Example #1
0
 public static HelperResult RenderSection(this WebPageBase page, string sectionName, Func <object, HelperResult> defaultContent)
 {
     if (page.IsSectionDefined(sectionName))
     {
         return(page.RenderSection(sectionName));
     }
     else
     {
         return(defaultContent(_o));
     }
 }
        public static TriggerContext Trig(this WebPageBase controller, Func <TriggerContext, TriggerContext> invocation = null)
        {
            var trig = TriggerContext.Current;

            if (invocation != null)
            {
                return(invocation(trig));
            }

            return(trig);
        }
Example #3
0
 /// <summary>
 /// Renders the section as layout region.
 /// </summary>
 /// <param name="webPage">The web page.</param>
 /// <param name="partialViewHtml">The partial view HTML.</param>
 /// <param name="sectionName">Name of the section.</param>
 private static void RenderSectionAsLayoutRegion(WebPageBase webPage, string partialViewHtml, string sectionName)
 {
     webPage.DefineSection(
         sectionName,
         () =>
     {
         Action <TextWriter> writerAction = tw => tw.Write(partialViewHtml);
         var result = new HelperResult(writerAction);
         webPage.Write(result);
     });
 }
Example #4
0
 public static HelperResult RedefineSection(this WebPageBase page, string sectionName, Func <object, HelperResult> defaultContent)
 {
     if (page.IsSectionDefined(sectionName))
     {
         page.DefineSection(sectionName, () => page.Write(page.RenderSection(sectionName)));
     }
     else if (defaultContent != null)
     {
         page.DefineSection(sectionName, () => page.Write(defaultContent(_o)));
     }
     return(new HelperResult(_ => { }));
 }
        public static T GetValueFor <T>(this WebPageBase webPageBase, string name, T defaultValue)
        {
            var nameKey = name.ToLower();

            if (webPageBase.Context.Items[nameKey] == null)
            {
                return(defaultValue);
            }
            var result = (T)webPageBase.Context.Items[nameKey];

            return(result);
        }
Example #6
0
        /// <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());
        }
Example #7
0
 protected override void ConfigurePage(WebPageBase parentPage)
 {
     if (parentPage == null)
     {
         return;
     }
     //Inject SetMembers Into New Context
     if (parentPage is IMacroContext)
     {
         var macroContext = (IMacroContext)parentPage;
         SetMembers(macroContext.Macro, macroContext.Node);
     }
 }
        private bool Validate(WebPageBase webPageBase)
        {
            var razorFunction = webPageBase as RazorFunction;

            if (razorFunction == null)
            {
                ShowWarning(GetText("EditRazorFunctionWorkflow.Validation.IncorrectBaseClass")
                            .FormatWith(typeof(RazorFunction).FullName));
                return(false);
            }


            return(true);
        }
Example #9
0
        /// <summary>
        /// Renders all *.cshtml pages under a specified directory.
        /// </summary>
        /// <param name="this"></param>
        /// <param name="path">The directory to search.</param>
        /// <param name="data">Optional data to pass to the pages.</param>
        public static HtmlString RenderPages(this WebPageBase @this, string path, params object[] data)
        {
            var sb            = new StringBuilder();
            var pageDirectory = Path.GetDirectoryName(@this.Request.MapPath(@this.VirtualPath));
            var dir           = Path.Combine(pageDirectory, path);

            foreach (var page in Directory.EnumerateFiles(dir, "*.cshtml", SearchOption.AllDirectories).OrderBy(x => x))
            {
                var relativePath = MakeRelative(pageDirectory, page);
                sb.Append(@this.RenderPage(relativePath, data).ToString());
            }

            return(new HtmlString(sb.ToString()));
        }
Example #10
0
        /// <exclude />
        protected override void ConfigurePage(WebPageBase parentPage)
        {
            base.ConfigurePage(parentPage);

            if (parentPage is CompositeC1WebPage parentC1Page)
            {
                if (parentC1Page._childPages == null)
                {
                    parentC1Page._childPages = new List <IDisposable>();
                }

                parentC1Page._childPages.Add(this);
            }
        }
Example #11
0
        public static WebPage CompileAndInstantiate(string virtualPath)
        {
            //Compile Razor - We Will Leave This To ASP.NET Compilation Engine & ASP.NET WebPages
            //Security in medium trust is strict around here, so we can only pass a virtual file path
            //ASP.NET Compilation Engine caches returned types
            //Changed From BuildManager As Other Properties Are Attached Like Context Path/
            var webPageBase = WebPageBase.CreateInstanceFromVirtualPath(virtualPath);
            var webPage     = webPageBase as WebPage;

            if (webPage == null)
            {
                throw new InvalidCastException("Context Must Implement System.Web.WebPages.WebPage");
            }
            return(webPage);
        }
Example #12
0
        private static PartialViewMacroPage CompileAndInstantiate(string virtualPath)
        {
            //Compile Razor - We Will Leave This To ASP.NET Compilation Engine & ASP.NET WebPages
            //Security in medium trust is strict around here, so we can only pass a virtual file path
            //ASP.NET Compilation Engine caches returned types
            //Changed From BuildManager As Other Properties Are Attached Like Context Path/
            var webPageBase = WebPageBase.CreateInstanceFromVirtualPath(virtualPath);
            var webPage     = webPageBase as PartialViewMacroPage;

            if (webPage == null)
            {
                throw new InvalidCastException("All Partial View Macro views must inherit from " + typeof(PartialViewMacroPage).FullName);
            }
            return(webPage);
        }
Example #13
0
        public static bool GetValueFor(this WebPageBase webPageBase, string name, bool defaultValue)
        {
            var nameKey = name.ToLower();

            //if (webPageBase.PageData[nameKey] == null)
            //{
            //    return defaultValue;
            //}
            //return webPageBase.PageData[nameKey];
            if (webPageBase.Context.Items[nameKey] == null)
            {
                return(defaultValue);
            }
            return(webPageBase.Context.Items[nameKey].ToString().ToLower() == "true");
        }
Example #14
0
        public static Chunk BeginChunk(this WebPageBase page, string tag, string info, params string[] classes)
        {
            TagBuilder tagBuilder = null;

            if (!string.IsNullOrEmpty(tag))
            {
                tagBuilder = new TagBuilder(tag);
                tagBuilder.Attributes["data-virtualpath"] = VirtualPathUtility.ToAbsolute(page.VirtualPath);

                foreach (var @class in classes)
                {
                    tagBuilder.AddCssClass(@class);
                }
            }
            return(new Chunk(page, tagBuilder, info));
        }
        public WebPageHttpHandler(string virtualPath)
        {
            // create a new WebPage instance for use when processing the request
            this.Page = (WebPage)WebPageBase.CreateInstanceFromVirtualPath(virtualPath);

            Func <WebPageRenderingBase> func = null;

            if (func == null)
            {
                func = delegate
                {
                    return(StartPage.GetStartPage(this.Page, "_PageStart", System.Web.WebPages.WebPageHttpHandler.GetRegisteredExtensions()));
                };
            }
            this._startPage = new Lazy <WebPageRenderingBase>(func);
        }
        protected override void ConfigurePage(WebPageBase parentPage)
        {
            var baseViewPage = parentPage as WebViewPage;

            if (baseViewPage == null)
            {
                // TODO : review if this check is even necessary.
                // When this method is called by the framework parentPage should already be an instance of WebViewPage
                // Need to review what happens if this method gets called in Plan9 pointing at an MVC view
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, MvcResources.CshtmlView_WrongViewBase, parentPage.VirtualPath));
            }

            // Set ViewContext and ViewData here so that the layout page inherits ViewData from the main page
            ViewContext = baseViewPage.ViewContext;
            ViewData    = baseViewPage.ViewData;
            InitHelpers();
        }
Example #17
0
        // </2sic>

        #endregion

        #region BaseClass Overrides

        protected override void ConfigurePage(WebPageBase parentPage)
        {
            base.ConfigurePage(parentPage);

            // Child pages need to get their context from the Parent
            Context = parentPage.Context;

            // Return if parent page is not a SexyContentWebPage
            if (parentPage.GetType().BaseType != typeof(SexyContentWebPage))
            {
                return;
            }

            Html = ((SexyContentWebPage)parentPage).Html;
            Url  = ((SexyContentWebPage)parentPage).Url;
            AppAndDataHelpers = ((SexyContentWebPage)parentPage).AppAndDataHelpers;
        }
Example #18
0
        protected override void ConfigurePage(WebPageBase parentPage)
        {
            base.ConfigurePage(parentPage);

            // Child pages need to get their context from the Parent
            Context = parentPage.Context;

            // Return if parent page is not a SexyContentWebPage
            if (!(parentPage is SexyContentWebPage typedParent))
            {
                return;
            }

            Html = typedParent.Html;
            Url  = typedParent.Url;
            Sexy = typedParent.Sexy;
            DnnAppAndDataHelpers = typedParent.DnnAppAndDataHelpers;
        }
Example #19
0
        protected override WebPageBase CreatePageFromVirtualPath(WebPageBase basePage, string path)
        {
            WebViewPage page = base.CreatePageFromVirtualPath(basePage, path) as WebViewPage;
            if (page == null)
            {
                throw new InvalidOperationException(string.Format(
                    CultureInfo.CurrentCulture, 
                    "Wrong base type for view: {0}", path));
            }
            WebViewPage page2 = basePage as WebViewPage;
            if (page2 == null)
            {
                throw new InvalidOperationException();
            }
//            page.ViewContext = page2.ViewContext;
//            page.ViewData = page2.ViewData;
//            page.InitHelpers();
            return page;
        }
Example #20
0
        // </2sic>

        #endregion

        #region BaseClass Overrides

        protected override void ConfigurePage(WebPageBase parentPage)
        {
            base.ConfigurePage(parentPage);

            // Child pages need to get their context from the Parent
            Context = parentPage.Context;

            // Return if parent page is not a SexyContentWebPage
            if (!(parentPage is SexyContentWebPage))
            {
                return;                                         // 2016-02-22 believe this is necessary with dnn 8 because this razor uses a more complex inheritance with Type<T>
            }
            //if (parentPage.GetType().BaseType != typeof(SexyContentWebPage)) return;

            Html = ((SexyContentWebPage)parentPage).Html;
            Url  = ((SexyContentWebPage)parentPage).Url;
            Sexy = ((SexyContentWebPage)parentPage).Sexy;
            AppAndDataHelpers = ((SexyContentWebPage)parentPage).AppAndDataHelpers;
        }
        private static string RenderTemplate(string virtualPath, dynamic model)
        {
            var page        = WebPageBase.CreateInstanceFromVirtualPath(virtualPath);
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var pageContext = new WebPageContext(httpContext, page, model);

            using (var writer = new StringWriter())
            {
                if (page is WebPage)
                {
                    page.ExecutePageHierarchy(pageContext, writer);
                }
                else
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The webpage at '{0}' must inherit from System.Web.WebPages.WebPage", virtualPath));
                }

                return(writer.ToString());
            }
        }
Example #22
0
        // </2sic>


        #endregion

        #region BaseClass Overrides

        protected override void ConfigurePage(WebPageBase parentPage)
        {
            base.ConfigurePage(parentPage);

            // Child pages need to get their context from the Parent
            Context = parentPage.Context;

            // Return if parent page is not a SexyContentWebPage
            if (!(parentPage is SexyContentWebPage typedParent))
            {
                return;
            }

            Html = typedParent.Html;
            // Deprecated 2019-05-27 2dm - I'm very sure this isn't used anywhere or by anyone.
            // reactivate if it turns out to be used, otherwise delete ca. EOY 2019
            //Url = typedParent.Url;
            Sexy = typedParent.Sexy;
            DnnAppAndDataHelpers = typedParent.DnnAppAndDataHelpers;
        }
        private StringWriter RenderTemplate(string virtualPath, dynamic model)
        {
            var page        = WebPageBase.CreateInstanceFromVirtualPath(virtualPath);
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var pageContext = new WebPageContext(httpContext, page, model);

            var writer = new StringWriter();

            if (page is WebPage)
            {
                page.ExecutePageHierarchy(pageContext, writer);
            }
            else
            {
                var razorEngine = new RazorEngine(virtualPath, null, null);
                razorEngine.Render <dynamic>(writer, model);
            }

            return(writer);
        }
Example #24
0
        protected override void ConfigurePage(WebPageBase parentPage)
        {
            base.ConfigurePage(parentPage);

            // Child pages need to get their context from the Parent
            Context = parentPage.Context;

            // Return if parent page is not a SexyContentWebPage
            if (!(parentPage is RazorComponentBase typedParent))
            {
                return;
            }

            // Forward the context
            Html    = typedParent.Html;
            DynCode = typedParent.DynCode;
            try
            {
                Log.Add("@RenderPage:" + VirtualPath);
            } catch { /* ignore */ }
        }
Example #25
0
            public Chunk(WebPageBase page, TagBuilder tagBuilder, string info)
            {
                _page       = page;
                _tagBuilder = tagBuilder;
                _info       = info;


                if (tagBuilder == null)
                {
                    return;
                }


                if (HttpContext.Current.IsDebuggingEnabled)
                {
                    page.Output.WriteLine("<!-- BEGIN {0} -->", page.VirtualPath);
                }

                page.Output.WriteLine(Environment.NewLine + tagBuilder.ToString(TagRenderMode.StartTag));
                tagBuilder.ToString(TagRenderMode.Normal);
            }
        /// <summary>
        /// Executes the razor page.
        /// </summary>
        /// <param name="virtualPath">The virtual path.</param>
        /// <param name="setParameters">Delegate to set the parameters.</param>
        /// <param name="resultType">The type of the result.</param>
        /// <param name="functionContextContainer">The function context container</param>
        /// <returns></returns>
        public static object ExecuteRazorPage(
            string virtualPath, 
            Action<WebPageBase> setParameters,
            Type resultType,
            FunctionContextContainer functionContextContainer)
        {
            WebPageBase webPage = null;
            try
            {
                webPage = WebPageBase.CreateInstanceFromVirtualPath(virtualPath);

                return ExecuteRazorPage(webPage, setParameters, resultType, functionContextContainer);
            }
            finally
            {
                if (webPage is IDisposable)
                {
                    (webPage as IDisposable).Dispose();
                }
            }
        }
Example #27
0
        protected override void InitializeParameters()
        {
            WebPageBase razorPage = null;

            try
            {
                using (BuildManagerHelper.DisableUrlMetadataCachingScope())
                {
                    razorPage = WebPage.CreateInstanceFromVirtualPath(VirtualPath);
                }

                if (!(razorPage is RazorFunction))
                {
                    throw new InvalidOperationException($"Failed to initialize function from cache. Path: '{VirtualPath}'");
                }

                Parameters = FunctionBasedFunctionProviderHelper.GetParameters(razorPage as RazorFunction, typeof(RazorFunction), VirtualPath);
            }
            finally
            {
                (razorPage as IDisposable)?.Dispose();
            }
        }
        public static string Lang(this WebPageBase page, String key)
        {
            var pagePath = page.VirtualPath;
            var pageName = pagePath.Substring(pagePath.LastIndexOf('/'), pagePath.Length - pagePath.LastIndexOf('/')).TrimStart('/');
            var filePath = page.Server.MapPath(pagePath.Substring(0, pagePath.LastIndexOf('/') + 1)) + "App_LocalResources";

            string lang       = System.Globalization.CultureInfo.CurrentCulture.Name;
            string resxKey    = string.Empty;
            string def_resKey = string.Format(@"{0}\{1}.resx", filePath, pageName);
            string lng_resKey = string.Format(@"{0}\{1}.{2}.resx", filePath, pageName, lang);

            resxKey = File.Exists(lng_resKey) ? lng_resKey : def_resKey;
            IEnumerable <DictionaryEntry> resxs = GetResx(resxKey);

            if (resxs != null)
            {
                return((string)resxs.FirstOrDefault(x => x.Key.ToString() == key).Value);
            }
            else
            {
                return("");
            }
        }
Example #29
0
        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application </param>
        public void Init(HttpApplication context)
        {
            const string errorPage = "~/Views/Shared/Error.cshtml";

            // When ever an error occurs on the Http Application, we'll now handle it, here.
            context.Error += (sender, e) =>
            {
                HttpContext.Current.ClearError();

                IWebObjectFactory webObjectFactory = BuildManager.GetObjectFactory(errorPage, true);

                WebPageBase webPageBase = webObjectFactory.CreateInstance() as WebPageBase;

                if (webPageBase == null)
                {
                    throw new InvalidOperationException("Failed to create an instance of the following page: " + errorPage);
                }

                var wrapper        = new HttpContextWrapper(HttpContext.Current);
                var webPageContext = new WebPageContext(wrapper, null, null);

                webPageBase.ExecutePageHierarchy(webPageContext, HttpContext.Current.Response.Output);
            };
        }
Example #30
0
 public static IFluentAdapter <TModel> Fluent <TModel>(this HtmlHelper htmlHelper, WebPageBase webPageBase, TModel model)
 {
     if (webPageBase == null)
     {
         throw new ArgumentNullException(nameof(webPageBase));
     }
     return(new FluentWebpagesAdapter <TModel>(webPageBase.Output, model));
 }
Example #31
0
 public static HelperResult RedefineSection(this WebPageBase page,
                                            string sectionName)
 {
     return(RedefineSection(page, sectionName, defaultContent: null));
 }