public static IHtmlContent UseChinaRegisterInfo(this RazorPage page) { var content = new HtmlContentBuilder(); var requestCultureFeature = page.Context.Features.Get <IRequestCultureFeature>(); if (requestCultureFeature == null) { return(content); } var requestCulture = requestCultureFeature.RequestCulture.UICulture.IetfLanguageTag; if (requestCulture == "zh") { content.SetHtmlContent("<a href='http://www.miitbeian.gov.cn' target='_blank'>辽ICP备17004979号-1</a>"); } return(content); }
// Get themed content page first, then default back to a non-themed content page search internal RazorPage GetPageByPathInfo(string pathInfo, IHttpRequest request) { RazorPage page = null; var theme = GetThemeName(request); if (!string.IsNullOrEmpty(theme) && !theme.EqualsIgnoreCase("default")) { // rebuild path info with theme info var pageName = Path.GetFileName(pathInfo); var pathInfoWithoutPage = pathInfo.Substring(0, pathInfo.LastIndexOf('/')).TrimEnd('/'); var themedPathInfo = string.Concat(pathInfoWithoutPage, "/", string.Format(ThemedViewPageNameFormat, theme.ToLowerInvariant(), pageName.ToLowerInvariant())); page = GetPageByPathInfo(themedPathInfo); } return(page ?? GetPageByPathInfo(pathInfo)); }
internal static async Task RenderAsync(RazorPage <dynamic> page) { var services = page.Context.RequestServices; var path = Path.ChangeExtension(page.ViewContext.ExecutingFilePath, ViewExtension); var fileProviderAccessor = services.GetRequiredService <ILiquidViewFileProviderAccessor>(); var isDevelopment = services.GetRequiredService <IHostEnvironment>().IsDevelopment(); var template = await ParseAsync(path, fileProviderAccessor.FileProvider, Cache, isDevelopment); var context = new TemplateContext(); await context.ContextualizeAsync(page, (object)page.Model); var options = services.GetRequiredService <IOptions <LiquidOptions> >().Value; var htmlEncoder = services.GetRequiredService <HtmlEncoder>(); await template.RenderAsync(options, services, page.Output, htmlEncoder, context); }
public static string SelectOptionsPorQuantidade(this RazorPage page, int quantidade, int valorSelecionado = 0) { var sb = new StringBuilder(); for (var i = 1; i <= quantidade; i++) { var selected = ""; if (i == valorSelecionado) { selected = "selected"; } sb.Append($"<option {selected} value='{i}'>{i}</option>"); } return(sb.ToString()); }
public static IHtmlContent UseAiurDashboardCss(this RazorPage page, bool includeCore = true) { var serviceLocation = page.Context.RequestServices.GetService <ServiceLocation>(); var builder = new HtmlContentBuilder() .AppendHtml($"<meta name=\"theme-color\" content=\"#0082c9\">"); if (includeCore) { return(builder .AppendStyleSheet($"{serviceLocation.UI}/dist/AiurCore.min.css") .AppendStyleSheet($"{serviceLocation.UI}/dist/AiurDashboard.min.css")); } else { return(builder .AppendStyleSheet($"{serviceLocation.UI}/dist/AiurDashboard.min.css")); } }
public static IHtmlContent UseDnsPrefetch(this RazorPage page) { var serviceLocation = page.Context.RequestServices.GetService <ServiceLocation>(); var builder = new HtmlContentBuilder(); string[] domains = { serviceLocation.API, serviceLocation.OSS, serviceLocation.CDN, serviceLocation.Account }; foreach (var domain in domains) { builder.AppendHtmlLine($@"<link rel='dns-prefetch' href='{domain}'>"); } return(builder); }
public void Dispose() { var content = this._page.EndTagHelperWritingScope(); var partResult = new HtmlString(content.GetContent()); var resource = new ResourceCollection { new ResourceEntity { Position = _position, Source = partResult } }; resource.Name = "Capture-" + partResult.Value.GetHashCode(); resource.Position = _position; _onRegisted(resource); _page = null; _onRegisted = null; }
public static HtmlString CssFrameworkSelector(RazorPage page) { var context = page.Context; var currentFramework = context.GetCurrentCssFramework(); var selector = new StringBuilder($"<select id='cssFrameworkSelector'>"); foreach (CssFramework framework in Enum.GetValues(typeof(CssFramework))) { var selected = framework == currentFramework ? "selected='selected'" : ""; var option = $"<option value='{framework}' {selected}>{framework}</option>"; selector.Append(option); } selector.Append("</select>"); return(new HtmlString(selector.ToString())); }
public IHtmlContent ToSource <T>(RazorPage <T> page) { if (Source != null) { return(Source); } if (UrlHelper == null) { UrlHelper = page.Context.RequestServices.GetService <IUrlHelperFactory>().GetUrlHelper(page.ViewContext); } if (HostingEnvironment == null) { HostingEnvironment = page.Context.RequestServices.GetService <IHostingEnvironment>(); } string source = null; if (System.Diagnostics.Debugger.IsAttached || HostingEnvironment.IsDevelopment()) { switch (SourceType) { case ResourceType.Script: source = string.Format(ScriptFormt, UrlHelper.Content(DebugSource)); break; case ResourceType.Style: source = string.Format(StyleFormt, UrlHelper.Content(DebugSource)); break; } } else { switch (SourceType) { case ResourceType.Script: source = string.Format(ScriptFormt, UseCNDSource ? CDNSource : UrlHelper.Content(ReleaseSource)); break; case ResourceType.Style: source = string.Format(StyleFormt, UseCNDSource ? CDNSource : UrlHelper.Content(ReleaseSource)); break; } } return(new HtmlString(source)); }
/// <summary> /// Writes the specified <paramref name="value"/> with HTML encoding to given <paramref name="content"/>. /// </summary> /// <param name="content">The <see cref="TagHelperContent"/> to write to.</param> /// <param name="encoder">The <see cref="HtmlEncoder"/> to use when encoding <paramref name="value"/>.</param> /// <param name="value">The <see cref="object"/> to write.</param> /// <returns><paramref name="content"/> after the write operation has completed.</returns> /// <remarks> /// <paramref name="value"/>s of type <see cref="Html.IHtmlContent"/> are written using /// <see cref="Html.IHtmlContent.WriteTo(TextWriter, HtmlEncoder)"/>. /// For all other types, the encoded result of <see cref="object.ToString"/> /// is written to the <paramref name="content"/>. /// </remarks> public static TagHelperContent Append(this TagHelperContent content, HtmlEncoder encoder, object value) { if (content == null) { throw new ArgumentNullException(nameof(content)); } if (encoder == null) { throw new ArgumentNullException(nameof(encoder)); } if (value == null) { // No real action but touch content to ensure IsModified is true. content.Append((string)null); return(content); } string stringValue; var htmlString = value as HtmlEncodedString; if (htmlString != null) { // No need for a StringWriter in this case. stringValue = htmlString.ToString(); } else { using (var stringWriter = new StringWriter()) { RazorPage.WriteTo(stringWriter, encoder, value); stringValue = stringWriter.ToString(); } } // In this case the text likely came directly from the Razor source. Since the original string is // an attribute value that may have been quoted with single quotes, must handle any double quotes // in the value. Writing the value out surrounded by double quotes. content.AppendHtml(stringValue.Replace("\"", """)); return(content); }
public override void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName) { httpRes.ContentType = ContentType.Html; if (RazorFormat == null) { RazorFormat = RazorFormat.Instance; } var contentPage = RazorPage ?? RazorFormat.FindByPathInfo(PathInfo); if (contentPage == null) { httpRes.StatusCode = (int)HttpStatusCode.NotFound; httpRes.EndHttpRequest(); return; } if (RazorFormat.WatchForModifiedPages) { RazorFormat.ReloadIfNeeeded(contentPage); } //Add good caching support //if (httpReq.DidReturn304NotModified(contentPage.GetLastModified(), httpRes)) // return; var model = Model; if (model == null) { httpReq.Items.TryGetValue("Model", out model); } if (model == null) { var modelType = RazorPage != null?RazorPage.GetRazorTemplate().ModelType : null; model = modelType == null || modelType == typeof(DynamicRequestObject) ? null : DeserializeHttpRequest(modelType, httpReq, httpReq.ContentType); } RazorFormat.ProcessRazorPage(httpReq, contentPage, model, httpRes); }
public static string FormataStatus(this RazorPage page, int tipoStatus) { if (tipoStatus == 1) { return("Aberto"); } if (tipoStatus == 2) { return("Fechado"); } if (tipoStatus == 3) { return("Pausado"); } return("Cancelado"); }
public string RenderToHtml(RazorPage razorPage, out IRazorView razorView, object model = null, string layout = null) { if (razorPage == null) { throw new ArgumentNullException("razorPage"); } var httpReq = new BasicRequest(); if (layout != null) { httpReq.Items[RazorPageResolver.LayoutKey] = layout; } razorView = PageResolver.ExecuteRazorPage(httpReq, httpReq.Response, model, razorPage); var ms = (MemoryStream)httpReq.Response.OutputStream; return(ms.ToArray().FromUtf8Bytes()); }
public string RenderToHtml(RazorPage razorPage, out IRazorView razorView, object model = null, string layout = null) { if (razorPage == null) { throw new ArgumentNullException(nameof(razorPage)); } var httpReq = new BasicRequest(); if (layout != null) { httpReq.Items[Keywords.Template] = layout; } var ms = (MemoryStream)httpReq.Response.OutputStream; razorView = PageResolver.ExecuteRazorPage(httpReq, ms, model, razorPage); return(ms.ReadToEnd()); }
public static HtmlString ScriptBlock(this RazorPage webPage, Func <dynamic, HelperResult> template) { var sb = new StringBuilder(); TextWriter tw = new StringWriter(sb); var encoder = (HtmlEncoder)webPage.ViewContext.HttpContext.RequestServices.GetService(typeof(HtmlEncoder)); if (webPage.Context.Request.Headers["x-requested-with"] != "XMLHttpRequest") { var scriptBuilder = webPage.Context.Items[SCRIPTBLOCK_BUILDER] as StringBuilder ?? new StringBuilder(); template.Invoke(null).WriteTo(tw, encoder); scriptBuilder.Append(sb.ToString()); webPage.Context.Items[SCRIPTBLOCK_BUILDER] = scriptBuilder; return(new HtmlString(string.Empty)); } template.Invoke(null).WriteTo(tw, encoder); return(new HtmlString(sb.ToString())); }
public RazorPage GetPage(string absolutePath, IHttpRequest request) // new method not in base class that looks for themed content page { RazorPage page = null; var theme = GetThemeName(request); if (!string.IsNullOrEmpty(theme) && !theme.EqualsIgnoreCase("default")) { var pageName = Path.GetFileName(absolutePath); if (pageName != null) { var pathInfoWithoutPage = absolutePath.Substring(0, absolutePath.LastIndexOf('/')).TrimEnd('/'); var themedPathInfo = string.Concat(pathInfoWithoutPage, "/", string.Format(ThemedViewPageNameFormat, theme.ToLowerInvariant(), pageName.ToLowerInvariant())); page = base.GetPage(themedPathInfo); } } // revert to non-themed fetcher if no themed page exists page = page ?? base.GetPage(absolutePath); return(page); }
private string GetFullyQualifiedPageName(RazorPage razorPage) { string escapedNs = Namespace.Escape(razorPage.Data.Namespace?.Text); string escapedClass = string.IsNullOrWhiteSpace(razorPage.Data.Class?.Text) ? "" : CSharp.Identifier(razorPage.Data.Class.Text.Trim()); if (escapedClass.Length == 0 && escapedNs.Length == 0) { return("<invalid>"); } else if (escapedNs.Length == 0) { return($"global::{escapedClass}"); } else if (escapedClass.Length == 0) { return($"{escapedNs}.<invalid>"); } else { return($"{escapedNs}.{escapedClass}"); } }
/// <summary> /// In layout pages, renders the content of a scripts section. /// </summary> /// <param name="razorPage">The RazorPage object.</param> /// <returns></returns> public static HtmlString RenderScripts(this RazorPage razorPage) { try { // Checks to see if the method is being called from _Layout pages. if (razorPage.PreviousSectionWriters != null) { razorPage.RenderSection("scripts", false); } } catch (InvalidOperationException ex) { throw new InvalidOperationException(Resources.Resources.FWRenderScripts_MethodCannotBeCalled, ex); } if (razorPage.ViewContext.ViewData["LayoutLateScripts"] is List <string> scripts) { return(new HtmlString(string.Join(' ', scripts))); } return(HtmlString.Empty); }
public static IHtmlContent UseAiurLogoutter(this RazorPage page) { var template = @"<div class='modal fade' id='exampleModal' tabindex='-1' role='dialog' aria-labelledby='exampleModalLabel' aria-hidden='true'> <div class='modal-dialog' role='document'> <form class='modal-content' action='/Home/Logoff' method='post'> <div class='modal-header'> <h5 class='modal-title' id='exampleModalLabel'>Ready to Leave?</h5> <button class='close' type='button' data-dismiss='modal' aria-label='Close'> <span aria-hidden='true'>×</span> </button> </div> <div class='modal-body'>Select 'Logout' below if you are ready to end your current session.</div> <div class='modal-footer'> <button class='btn btn-secondary' type='button' data-dismiss='modal'>Cancel</button> <input class='btn btn-primary' type='submit' value='Logout' /> </div> </form> </div> </div>"; return(new HtmlContentBuilder() .SetHtmlContent(template)); }
/// <summary> /// Write random lorem ipsum text to generate test content. /// credit : kEnobus https://stackoverflow.com/questions/4286487/is-there-any-lorem-ipsum-generator-in-c /// </summary> /// <param name="minWords"></param> /// <param name="maxWords"></param> /// <param name="minSentences"></param> /// <param name="maxSentences"></param> /// <param name="numLines"></param> /// <returns></returns> public static string LoremIpsum(this RazorPage page, int minWords, int maxWords, int minSentences, int maxSentences, int numLines) { var words = new[] { "lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "sed", "diam", "nonummy", "nibh", "euismod", "tincidunt", "ut", "laoreet", "dolore", "magna", "aliquam", "erat" }; var rand = new Random(); int numSentences = rand.Next(maxSentences - minSentences) + minSentences; int numWords = rand.Next(maxWords - minWords) + minWords; var sb = new StringBuilder(); for (int p = 0; p < numLines; p++) { for (int s = 0; s < numSentences; s++) { for (int w = 0; w < numWords; w++) { if (w > 0) { sb.Append(" "); } string word = words[rand.Next(words.Length)]; if (w == 0) { word = word.Substring(0, 1).Trim().ToUpper() + word.Substring(1); } sb.Append(word); } sb.Append(". "); } if (p < numLines - 1) { sb.AppendLine(); } } return(sb.ToString()); }
public IHtmlContent ToSource <T>(RazorPage <T> page) { if (Source != null) { return(Source); } IUrlHelper urlHelper = page.Context.RequestServices.GetService <IUrlHelperFactory>().GetUrlHelper(page.ViewContext); IHostingEnvironment hostingEnvironment = page.Context.RequestServices.GetService <IHostingEnvironment>(); if (CDN == null) { CDN = page.Context.RequestServices.GetService <IOptions <CDNOption> >(); } string source = null; if (System.Diagnostics.Debugger.IsAttached || hostingEnvironment.IsDevelopment()) { string debugSource = VersionSource(hostingEnvironment, DebugSource); switch (SourceType) { case ResourceType.Script: source = string.Format(ScriptFormt, urlHelper.Content(debugSource)); break; case ResourceType.Style: source = string.Format(StyleFormt, urlHelper.Content(debugSource)); break; } } else { string releaseSource = VersionSource(hostingEnvironment, ReleaseSource); switch (SourceType) { case ResourceType.Script: source = string.Format(ScriptFormt, UseCNDSource ? CDNSource : urlHelper.Content(releaseSource)); break; case ResourceType.Style: source = string.Format(StyleFormt, UseCNDSource ? CDNSource : urlHelper.Content(releaseSource)); break; } } return(new HtmlString(source)); }
internal static async Task RenderAsync(RazorPage <dynamic> page) { var services = page.Context.RequestServices; var path = Path.ChangeExtension(page.ViewContext.ExecutingFilePath, ViewExtension); var fileProviderAccessor = services.GetRequiredService <ILiquidViewFileProviderAccessor>(); var isDevelopment = services.GetRequiredService <IHostEnvironment>().IsDevelopment(); var template = await ParseAsync(path, fileProviderAccessor.FileProvider, Cache, isDevelopment); var context = Context; var htmlEncoder = services.GetRequiredService <HtmlEncoder>(); try { await context.EnterScopeAsync(page.ViewContext, (object)page.Model, scopeAction : null); await template.RenderAsync(page.Output, htmlEncoder, context); } finally { context.ReleaseScope(); } }
public static string FormataDocumento(this RazorPage page, int tipoPessoa, string documento) { return(tipoPessoa == 1 ? Convert.ToUInt64(documento).ToString(@"000\.000\.000\-00") : Convert.ToUInt64(documento).ToString(@"00\.000\.000\/0000\-00")); }
public static bool IfClaim(this RazorPage page, string claimName, string claimValue) { return(CustomAuthorization.ValidarClaimsUsuario(page.Context, claimName, claimValue)); }
public static string IfClaimShow(this RazorPage page, string claimName, string claimValue) { return(CustomAuthorization.ValidarClaimsUsuario(page.Context, claimName, claimValue) ? "" : "disabled"); }
public static string MensagemEstoque(this RazorPage page, int quantidade) { return(quantidade > 0 ? $"Apenas {quantidade} em estoque!" : "Produto esgotado!"); }
public static string FormatoMoeda(this RazorPage page, decimal valor) { return(valor > 0 ? string.Format(Thread.CurrentThread.CurrentCulture, "{0:C}", valor) : "Gratuito"); }
public static string GetCurrentEnumDescription <TEnum>(this RazorPage page, string currentEnumValue) where TEnum : Enum => GetEnumDescriptionAttribute <TEnum>().Where(enumDesc => enumDesc != null && enumDesc.Value.Equals(currentEnumValue)).SingleOrDefault()?.Description;
public static IEnumerable <SelectListItem> GetSelectItensFromEnum <TEnum>(this RazorPage page) where TEnum : Enum { IEnumerable <EnumDescriptionAttribute> descriptions = GetEnumDescriptionAttribute <TEnum>(); return(descriptions?.Where(w => w != null).Select(desc => new SelectListItem(desc.Description, desc.Value))); }
public static string ifClaimShow(this RazorPage page, string claimName, string claimValue) { return(CustomClains.ValidarAcesso(page.Context, claimName, claimValue) ? "" : "disabled"); }