Advertisement
commodore73

struct to model markup fields

Jul 23rd, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.07 KB | None | 0 0
  1. namespace Root.Core.Models.Fields
  2. {
  3.     using System.Net;
  4.  
  5.     using HtmlAgilityPack;
  6.    
  7.     using Microsoft.AspNetCore.Html;
  8.     public readonly struct MarkupField
  9.     {
  10.         private readonly string _markup;
  11.  
  12.         public MarkupField(string markup)
  13.         {
  14.             _markup = markup;
  15.         }
  16.  
  17.         public static implicit operator MarkupField(string input)
  18.         {
  19.             return new MarkupField(input);
  20.         }
  21.    
  22.         public static implicit operator string(MarkupField input)
  23.         {
  24.             return input.ToString();
  25.         }
  26.  
  27.         public static implicit operator HtmlString(MarkupField input)
  28.         {
  29.             return new HtmlString(input.ToString());
  30.         }
  31.    
  32.         public HtmlString Value
  33.         {
  34.             get
  35.             {
  36.                 return new HtmlString(_markup);
  37.             }
  38.         }
  39.    
  40.         public override string ToString()
  41.         {
  42.             return WebUtility.HtmlEncode(_markup);
  43.         }
  44.  
  45.         public HtmlString OpenExternalsLinksInNewTabsOrWindows
  46.         {
  47.             get
  48.             {
  49.                 HtmlDocument doc = new HtmlDocument();
  50.                 doc.LoadHtml(_markup);
  51.                 HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a[@href]");
  52.      
  53.                 if (nodes == null)
  54.                 {
  55.                     return new HtmlString(_markup);
  56.                 }
  57.  
  58.                 foreach (HtmlNode node in (nodes))
  59.                 {
  60.                     string url = node.GetAttributeValue("href", string.Empty);
  61.  
  62.                     if (!url.StartsWith("/"))
  63.                     {
  64.                         string target = node.GetAttributeValue("target", string.Empty);
  65.  
  66.                         if (string.IsNullOrWhiteSpace(target))
  67.                         {
  68.                             node.Attributes.Add(doc.CreateAttribute("target", "_blank"));
  69.                         }
  70.                     }
  71.                 }
  72.  
  73.                 return new HtmlString(doc.DocumentNode.OuterHtml);
  74.             }
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement