Ejemplo n.º 1
0
 public static string RenderView(string pathToView, object model, ControllerContext controllerContext)
 {
     var st = new StringWriter();
     var razor = new RazorView(controllerContext, pathToView, null, false, null);
     razor.Render(new ViewContext(controllerContext, razor, new ViewDataDictionary(model), new TempDataDictionary(), st), st);
     return st.ToString();
 }
Ejemplo n.º 2
0
    } // End of the UnprotectCookieValue method

    /// <summary>
    /// Get a 404 not found page
    /// </summary>
    /// <returns>A string with html</returns>
    public static string GetHttpNotFoundPage()
    {
        // Create the string to return
        string htmlString = "";

        // Get the current domain
        Domain currentDomain = Tools.GetCurrentDomain();

        // Get the error page
        StaticPage staticPage = StaticPage.GetOneByConnectionId(5, currentDomain.front_end_language);
        staticPage = staticPage != null ? staticPage : new StaticPage();

        // Get the translated texts
        KeyStringList tt = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC");

        // Create the Route data
        System.Web.Routing.RouteData routeData = new System.Web.Routing.RouteData();
        routeData.Values.Add("controller", "home");

        // Create the controller context
        System.Web.Mvc.ControllerContext context = new System.Web.Mvc.ControllerContext(new System.Web.Routing.RequestContext(new HttpContextWrapper(HttpContext.Current), routeData), new Annytab.Webshop.Controllers.homeController());

        // Create the bread crumb list
        List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(2);
        breadCrumbs.Add(new BreadCrumb(tt.Get("start_page"), "/"));
        breadCrumbs.Add(new BreadCrumb(staticPage.link_name, "/home/error/404"));

        // Set form values
        context.Controller.ViewBag.BreadCrumbs = breadCrumbs;
        context.Controller.ViewBag.CurrentCategory = new Category();
        context.Controller.ViewBag.TranslatedTexts = tt;
        context.Controller.ViewBag.CurrentDomain = currentDomain;
        context.Controller.ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language);
        context.Controller.ViewBag.StaticPage = staticPage;
        context.Controller.ViewBag.PricesIncludesVat = HttpContext.Current.Session["PricesIncludesVat"] != null ? Convert.ToBoolean(HttpContext.Current.Session["PricesIncludesVat"]) : currentDomain.prices_includes_vat;

        // Render the view
        using (StringWriter stringWriter = new StringWriter(new StringBuilder(), CultureInfo.InvariantCulture))
        {
            string viewPath = currentDomain.custom_theme_id == 0 ? "/Views/home/error.cshtml" : "/Views/theme/error.cshtml";
            System.Web.Mvc.RazorView razor = new System.Web.Mvc.RazorView(context, viewPath, null, false, null);
            razor.Render(new System.Web.Mvc.ViewContext(context, razor, context.Controller.ViewData, context.Controller.TempData, stringWriter), stringWriter);
            htmlString += stringWriter.ToString();
        }

        //// Create the web page
        //notFoundString += "<html><head>";
        //notFoundString += "<meta charset=\"utf-8\">";
        //notFoundString += "<title>" + staticPage.title + "</title></head>";
        //notFoundString += "<body><div style=\"text-align:center;margin:200px auto auto auto;\"><h1>" + staticPage.title + "</h1>";
        //notFoundString += "<p>" + staticPage.main_content + "</p>";
        //notFoundString += "<a href=\"/\">" + tt.Get("start_page") + "</a></div></body>";
        //notFoundString += "</html>";

        // Return the string
        return htmlString;

    } // End of the GetHttpNotFoundPage method
Ejemplo n.º 3
0
 public static string GetRazorViewAsString(string filePath)
 {
     var st = new StringWriter();
     var context = new HttpContextWrapper(HttpContext.Current);
     var routeData = new RouteData();
     var controllerContext = new ControllerContext(new RequestContext(context, routeData), new HomeController());
     var razor = new RazorView(controllerContext, filePath, null, false, null);
     razor.Render(new ViewContext(controllerContext, razor, new ViewDataDictionary(), new TempDataDictionary(), st), st);
     return st.ToString();
 }
        public TestViewContext(ControllerContext controllerContext, string viewName, RouteData routeData)
        {
            WriterOutput = new StringBuilder();

            Controller = controllerContext.Controller;
            View = new RazorView(controllerContext, viewName, "Layout", false, new string[] { });
            ViewData = new ViewDataDictionary();
            TempData = new TempDataDictionary();
            Writer = new StringWriter(WriterOutput);
            RouteData = routeData;
        }
Ejemplo n.º 5
0
 static void RenderMvcErrorView(HttpRequestBase request,
                                HttpResponseBase response,
                                string redirectPath,
                                Exception currentError)
 {
     var controllerContext = NewControllerContext(request);
     var view = new RazorView(controllerContext, redirectPath, null, false, null);
     var viewModel = new ErrorViewModel {Exception = currentError};
     var viewContext = new ViewContext(controllerContext, view, new ViewDataDictionary(viewModel), new TempDataDictionary(),
                                       response.Output);
     view.Render(viewContext, response.Output);
 }
Ejemplo n.º 6
0
        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {

            var view = new RazorView(controllerContext, 
                viewPath,
                layoutPath: masterPath, 
                runViewStartPages: true, 
                viewStartFileExtensions: 
                FileExtensions, 
                viewPageActivator: ViewPageActivator);

            return view;

            //return base.CreateView(controllerContext, viewPath, masterPath);
        }
Ejemplo n.º 7
0
        // RENDER VIEWS HELPERS
        public static string RazorRender(Controller context, string DefaultAction)
        {
            string Cache = string.Empty;
            var sb = new System.Text.StringBuilder();
            TextWriter tw = new System.IO.StringWriter(sb);

            RazorView view_ = new RazorView(context.ControllerContext, DefaultAction, null, false, null);
            view_.Render(
                new ViewContext(context.ControllerContext, view_, new ViewDataDictionary(), new TempDataDictionary(), tw),
                tw);

            Cache = sb.ToString();

            return Cache;
        }
Ejemplo n.º 8
0
    } // End of the UnprotectCookieValue method

    /// <summary>
    /// Get a 404 not found page
    /// </summary>
    /// <returns>A string with html</returns>
    public static string GetHttpNotFoundPage()
    {
        // Create the string to return
        string htmlString = "";

        // Get the current domain
        Domain currentDomain = Tools.GetCurrentDomain();

        // Get the error page
        StaticPage staticPage = StaticPage.GetOneByConnectionId(4, currentDomain.front_end_language);
        staticPage = staticPage != null ? staticPage : new StaticPage();

        // Get the translated texts
        KeyStringList tt = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC");

        // Create the Route data
        System.Web.Routing.RouteData routeData = new System.Web.Routing.RouteData();
        routeData.Values.Add("controller", "home");

        // Create the controller context
        System.Web.Mvc.ControllerContext context = new System.Web.Mvc.ControllerContext(new System.Web.Routing.RequestContext(new HttpContextWrapper(HttpContext.Current), routeData), new Annytab.Blogsite.Controllers.homeController());

        // Create the bread crumb list
        List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(2);
        breadCrumbs.Add(new BreadCrumb(tt.Get("start_page"), "/"));
        breadCrumbs.Add(new BreadCrumb(staticPage.link_name, "/home/error/404"));

        // Set form values
        context.Controller.ViewBag.BreadCrumbs = breadCrumbs;
        context.Controller.ViewBag.CurrentCategory = new Category();
        context.Controller.ViewBag.TranslatedTexts = tt;
        context.Controller.ViewBag.CurrentDomain = currentDomain;
        context.Controller.ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language);
        context.Controller.ViewBag.StaticPage = staticPage;

        // Render the view
        using (StringWriter stringWriter = new StringWriter(new StringBuilder(), CultureInfo.InvariantCulture))
        {
            string viewPath = currentDomain.custom_theme_id == 0 ? "/Views/home/error.cshtml" : "/Views/theme/error.cshtml";
            System.Web.Mvc.RazorView razor = new System.Web.Mvc.RazorView(context, viewPath, null, false, null);
            razor.Render(new System.Web.Mvc.ViewContext(context, razor, context.Controller.ViewData, context.Controller.TempData, stringWriter), stringWriter);
            htmlString += stringWriter.ToString();
        }

        // Return the string
        return htmlString;

    } // End of the GetHttpNotFoundPage method
Ejemplo n.º 9
0
 private void WriteContent(QueryCriteria criteria, object model, StringBuilder sb)
 {
     if (this.ControllerContext == null)
         throw new CriteriaRenderException(this, typeof(RazorWebContentRender).Name + " must have Controller context");
     try
     {
         RazorView view = new RazorView(ControllerContext.ControllerContext, GetTemplateVirtualPath(criteria), layoutPath, true, new string[] { "cshtml", "vbhtml" });
         StringWriter sw = new StringWriter(sb);
         //设置视图数据对象
         ControllerContext.ViewBag.Criteria = criteria;
         ControllerContext.ViewBag.Data = model;
         ViewContext viewContext = new ViewContext(ControllerContext.ControllerContext, view, ControllerContext.ViewData, ControllerContext.TempData, sw);
         view.Render(viewContext, viewContext.Writer);
     }
     catch (Exception e)
     {
         throw new CriteriaRenderException(this, "render criteria view has error!", e);
     }
 }
Ejemplo n.º 10
0
        public static void WriteErrorResponse(HttpContext context, object model, string filePath, string layoutPath, string layoutPathBody, string layoutPathModal, string title, string errorMsg)
        {
            var contextWrapper    = new HttpContextWrapper(context);
            var controllerContext = new ControllerContext(new RequestContext(contextWrapper, new RouteData()), new AjaxController());

            if (IsJsonRequest(contextWrapper.Request))
            {
                var razor = new RazorView(controllerContext, filePath, context.Request.Headers["isModal"] == "true" ? layoutPathModal : layoutPathBody, false, null);
                using (var stringWriter = new StringWriter())
                {
                    razor.Render(new ViewContext(controllerContext, razor, new ViewDataDictionary(model), new TempDataDictionary(), stringWriter), stringWriter);
                    context.Response.Write(new JavaScriptSerializer().Serialize(new JsonResponse(ResponseCode.Error)
                    {
                        ErrorMessage = errorMsg, Html = stringWriter.GetStringBuilder().ToString(), Url = context.Request.Path, Title = title
                    }));
                }
            }
            else
            {
                var razor = new RazorView(controllerContext, filePath, layoutPath, false, null);
                razor.Render(new ViewContext(controllerContext, razor, new ViewDataDictionary(model), new TempDataDictionary(), context.Response.Output), context.Response.Output);
                context.Response.ContentType = "text/html; charset=utf-8";
            }
        }
Ejemplo n.º 11
0
        public ActionResult Save(ComposePageModel pageModel)
        {
            Page page = new Page
            {
                FileId = pageModel.FileId,
                Title = pageModel.Title,
                Body = pageModel.Contents
            };

            // Ajax call, return Json message
            if (string.IsNullOrEmpty(page.FileId))
            {
                // unique stuff.
                page.FileId = Guid.NewGuid().ToString();
            }

            page.Body = page.Body ?? string.Empty;

            PageComp.Save(page);

            DateTime now =
                LocalTime.GetCurrentTime(TimeZoneInfo.FindSystemTimeZoneById(SettingsComp.GetSettings().Timezone));

            StringWriter sw = new StringWriter();
            IView view = new RazorView(this.ControllerContext, "~/Views/Shared/AutoSaveControl.cshtml", null, false, null);
            this.ViewData.Model = now;
            ViewContext viewContext = new ViewContext(this.ControllerContext, view, this.ViewData, this.TempData, sw);
            view.Render(viewContext, sw);

            // PartialViewResult result = RenderViewToString this.PartialView("AutoSaveControl", now);
            return Json(new SavePageResultModel { FileId = page.FileId, Content = sw.ToString() });
        }
 protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
 {
     var view = new RazorView(controllerContext, viewPath, masterPath, false, FileExtensions);
     return view;
 }
 protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
 {
     var view = new RazorView(controllerContext, partialPath, null, false, FileExtensions);
     return view;
 }
Ejemplo n.º 14
0
        private void RenderRazorView(ControllerContext context, RazorView razorView)
        {
            using (StringWriter sw = new StringWriter())
            {
                BaseControl.SectionsStack.Push(new List<string>());
                ViewContext viewContext = new ViewContext(context, razorView, this.ViewData, this.TempData, sw);

                RequestManager.SuppressAjaxRequestMarker();

                razorView.Render(viewContext, sw);
                string result = sw.GetStringBuilder().ToString();

                RequestManager.ResumeAjaxRequestMarker();
                var idsToRender = BaseControl.SectionsStack.Pop();

                StringBuilder sb = new StringBuilder();
                sb.Append("<Ext.Net.RazorItems>[");
                foreach (var item in idsToRender)
                {
                    sb.Append(Transformer.NET.Net.CreateToken(typeof(Transformer.NET.AnchorTag), new Dictionary<string, string>{                        
                               {"id", item}         
                            }));
                    sb.Append(",");
                }
                if (idsToRender.Count > 0)
                {
                    sb.Remove(sb.Length - 1, 1);
                }
                sb.Append("]</Ext.Net.RazorItems>");

                sb.Append("<Ext.Net.RazorBeforeScript>");
                sb.Append("<#:anchor id='ext.net.global.script.before' />");                
                sb.Append("</Ext.Net.RazorBeforeScript>");

                sb.Append("<Ext.Net.RazorRenderToItems>");                
                sb.Append(Transformer.NET.Net.CreateToken(typeof(Transformer.NET.AnchorTag), new Dictionary<string, string>{                        
                    {"id", "init_script"}         
                }));                
                sb.Append("</Ext.Net.RazorRenderToItems>");

                sb.Append("<Ext.Net.RazorAfterScript>");
                sb.Append("<#:anchor id='ext.net.global.script.after' />");
                sb.Append("</Ext.Net.RazorAfterScript>");

                var config = MVC.MvcResourceManager.SharedConfig;
                config.RenderScripts = ResourceLocationType.None;
                config.RenderStyles = ResourceLocationType.None;
                MVC.MvcResourceManager.SharedConfig = config;

                List<ResourceItem> resources = null;

                if (HttpContext.Current.Items[Ext.Net.ResourceManager.GLOBAL_RESOURCES] != null)
                {
                    resources = (List<ResourceItem>)HttpContext.Current.Items[Ext.Net.ResourceManager.GLOBAL_RESOURCES];
                }                

                sb.Insert(0, result);                

                result = Ext.Net.ExtNetTransformer.Transform(sb.ToString());

                var items = "";
                var html = RazorItems_RE.Replace(result, delegate(Match m){
                    items = m.Groups[1].Value;
                    return "";
                });

                var renderToItems = "";
                html = RazorRenderToItems_RE.Replace(html, delegate(Match m)
                {
                    renderToItems = m.Groups[1].Value;
                    return "";
                });

                var beforeScript = "";
                html = RazorBeforeScript_RE.Replace(html, delegate(Match m)
                {
                    beforeScript = m.Groups[1].Value;
                    return "";
                });

                var afterScript = "";
                html = RazorAfterScript_RE.Replace(html, delegate(Match m)
                {
                    afterScript = m.Groups[1].Value;
                    return "";
                });

                sb.Length = 0;                

                if (!string.IsNullOrWhiteSpace(html))
                {
                    string[] lines = html.Split(new string[] { "\r\n", "\n", "\r", "\t" }, StringSplitOptions.RemoveEmptyEntries);

                    if (lines.Length > 0)
                    {
                        html = JSON.Serialize(lines).ConcatWith(".join('')");
                        html = html.Replace("</script>", "<\\/script>");
                        sb.AppendFormat("Ext.net.append({0},{1});", this.RenderMode == Ext.Net.RenderMode.RenderTo ? string.Concat("Ext.net.getEl('", this.ContainerId, "')") : "Ext.getBody()", html);
                    }
                }

                if (beforeScript.IsNotEmpty())
                {
                    sb.Append(beforeScript);
                }                

                if (this.RenderMode == Ext.Net.RenderMode.AddTo || this.RenderMode == Ext.Net.RenderMode.InsertTo)
                {
                    sb.AppendFormat("Ext.net.addTo({0}, {1});", JSON.Serialize(this.ContainerId), items);
                }
                else if (this.RenderMode == RenderMode.Replace)
                {
                    sb.Append("Ext.net._renderTo(arguments[0]," + items + ");");
                }
                else
                {
                    sb.AppendFormat("Ext.net.renderTo({0}, {1});", JSON.Serialize(this.ContainerId), items);
                }

                if (renderToItems.IsNotEmpty())
                {
                    sb.Append(renderToItems);
                }

                if (afterScript.IsNotEmpty())
                {
                    sb.Append(afterScript);
                }

                if (this.RenderMode == RenderMode.Replace)
                {
                    var elementGet = this.ContainerId.Contains(".") ? this.ContainerId : "Ext.getCmp({0})".FormatWith(JSON.Serialize(this.ContainerId));
                    sb.Insert(0, elementGet + ".replace(function(){");
                    sb.Append("});");
                }
                

                this.RenderScript(context, this.RegisterRazorResources(sb.ToString(), resources));
            }
        }
Ejemplo n.º 15
0
    } // End of the UnprotectCookieValue method

    /// <summary>
    /// Get a 404 not found page
    /// </summary>
    /// <returns>A string with html</returns>
    public static string GetHttpNotFoundPage()
    {
        // Create the string to return
        string htmlString = "";

        // Get the current domain
        Domain currentDomain = Tools.GetCurrentDomain();

        // Get the error page
        StaticPage staticPage = StaticPage.GetOneByConnectionId(5, currentDomain.front_end_language);
        staticPage = staticPage != null ? staticPage : new StaticPage();

        // Get the translated texts
        KeyStringList tt = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC");

        // Create the Route data
        System.Web.Routing.RouteData routeData = new System.Web.Routing.RouteData();
        routeData.Values.Add("controller", "home");

        // Create the controller context
        System.Web.Mvc.ControllerContext context = new System.Web.Mvc.ControllerContext(new System.Web.Routing.RequestContext(new HttpContextWrapper(HttpContext.Current), routeData), new Annytab.Webshop.Controllers.homeController());

        // Create the bread crumb list
        List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(2);
        breadCrumbs.Add(new BreadCrumb(tt.Get("start_page"), "/"));
        breadCrumbs.Add(new BreadCrumb(staticPage.link_name, "/home/error/404"));

        // Set form values
        context.Controller.ViewBag.BreadCrumbs = breadCrumbs;
        context.Controller.ViewBag.CurrentCategory = new Category();
        context.Controller.ViewBag.TranslatedTexts = tt;
        context.Controller.ViewBag.CurrentDomain = currentDomain;
        context.Controller.ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language);
        context.Controller.ViewBag.StaticPage = staticPage;
        context.Controller.ViewBag.PricesIncludesVat = HttpContext.Current.Session["PricesIncludesVat"] != null ? Convert.ToBoolean(HttpContext.Current.Session["PricesIncludesVat"]) : currentDomain.prices_includes_vat;

        // Render the view
        using (StringWriter stringWriter = new StringWriter(new StringBuilder(), CultureInfo.InvariantCulture))
        {
            string viewPath = currentDomain.custom_theme_id == 0 ? "/Views/home/error.cshtml" : "/Views/theme/error.cshtml";
            System.Web.Mvc.RazorView razor = new System.Web.Mvc.RazorView(context, viewPath, null, false, null);
            razor.Render(new System.Web.Mvc.ViewContext(context, razor, context.Controller.ViewData, context.Controller.TempData, stringWriter), stringWriter);
            htmlString += stringWriter.ToString();
        }

        //// Create the web page
        //notFoundString += "<html><head>";
        //notFoundString += "<meta charset=\"utf-8\">";
        //notFoundString += "<title>" + staticPage.title + "</title></head>";
        //notFoundString += "<body><div style=\"text-align:center;margin:200px auto auto auto;\"><h1>" + staticPage.title + "</h1>";
        //notFoundString += "<p>" + staticPage.main_content + "</p>";
        //notFoundString += "<a href=\"/\">" + tt.Get("start_page") + "</a></div></body>";
        //notFoundString += "</html>";

        // Return the string
        return htmlString;

    } // End of the GetHttpNotFoundPage method
        private static void RenderCustomErrorView(HttpApplication httpApplication, string viewPath,
                                                  HttpStatusCode httpStatusCode,
                                                  Exception currentError)
        {
            try
            {
                // We need to render the view now.
                // This means we need a viewContext ... which requires a controller.
                // So we instantiate a fake controller which does nothing
                // and then work our way to rendering the view.
                var errorController = new FakeErrorController();
                var controllerContext =
                    new ControllerContext(httpApplication.Context.Request.RequestContext, errorController);
                var view = new RazorView(controllerContext, viewPath, null, false, null);
                var viewModel = new ErrorViewModel
                                {
                                    Exception = currentError
                                };
                var tempData = new TempDataDictionary();
                var viewContext = new ViewContext(controllerContext, view,
                                                  new ViewDataDictionary(viewModel), tempData,
                                                  httpApplication.Response.Output);
                view.Render(viewContext, httpApplication.Response.Output);

                // Lets make sure we set the correct Error Status code :)
                httpApplication.Response.StatusCode = (int) httpStatusCode;
            }
            catch (Exception exception)
            {
                // Damn it! Something -really- crap just happened. 
                // eg. the path to the redirect might not exist, etc.
                string errorMessage =
                    string.Format(
                        "An error occured while trying to Render the custom error view which you provided, for this HttpStatusCode. ViewPath: {0}; Message: {1}",
                        string.IsNullOrEmpty(viewPath) ? "--no view path was provided!! --" : viewPath,
                        exception.Message);

                RenderFallBackErrorViewBecauseNoneWasProvided(httpApplication,
                                                              HttpStatusCode.InternalServerError,
                                                              new InvalidOperationException(errorMessage, currentError));
            }
        }
Ejemplo n.º 17
0
 protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
 {
     var view = new RazorView(controllerContext, viewPath, masterPath, true,
         ViewEngineFileLocations.FileExtensions, ViewPageActivator);
     return view;
 }