public static HtmlString CompileBundleAndMinifyStyles(this HtmlHelper helper, string name, IEnumerable<string> paths) { var html = new HtmlString(string.Empty); if (paths != null && paths.Any()) { BundleTable.EnableOptimizations = true; BundleTable.Bundles.IgnoreList.Clear(); BundleTable.Bundles.FileSetOrderList.Clear(); BundleTable.Bundles.FileExtensionReplacementList.Clear(); var sitePath = helper.SitePath(); var styles = paths.ToArray(); var virtualPath = string.Format("~/styles/css/{0}", helper.UrlHelper().Encode(name)); var bundle = new TypesetBundle(virtualPath); bundle.Transforms.Add(new SassCompile()); bundle.Transforms.Add(new LessCompile()); bundle.Transforms.Add(new CssMinify()); bundle.IncludeLocalAndRemote(helper.ViewContext.HttpContext, helper.SitePath(), styles); BundleTable.Bundles.Add(bundle); var scriptTag = new TagBuilder("link"); scriptTag.Attributes.Add("type", "text/css"); scriptTag.Attributes.Add("rel", "stylesheet"); scriptTag.Attributes.Add("href", BundleTable.Bundles.ResolveBundleUrl(virtualPath)); html = new HtmlString(scriptTag.ToString(TagRenderMode.SelfClosing)); } return html; }
public static HtmlString CompileBundleAndMinifyScripts(this HtmlHelper helper, string name, IEnumerable<string> paths) { var html = new HtmlString(string.Empty); if (paths != null && paths.Any()) { BundleTable.EnableOptimizations = true; BundleTable.Bundles.IgnoreList.Clear(); BundleTable.Bundles.FileSetOrderList.Clear(); BundleTable.Bundles.FileExtensionReplacementList.Clear(); var scripts = paths.ToArray(); var virtualPath = string.Format("~/scripts/javascript/{0}", helper.UrlHelper().Encode(name)); var bundle = new TypesetBundle(virtualPath); bundle.IncludeLocalAndRemote(helper.ViewContext.HttpContext, helper.SitePath(), scripts); bundle.Transforms.Add(new CoffeeScriptCompile()); bundle.Transforms.Add(new JsMinify()); BundleTable.Bundles.Add(bundle); var scriptTag = new TagBuilder("script"); scriptTag.Attributes.Add("type", "text/javascript"); scriptTag.Attributes.Add("src", BundleTable.Bundles.ResolveBundleUrl(virtualPath)); html = new HtmlString(scriptTag.ToString()); } return html; }
public override StringCollection GetParameters(bool getFirstItem) { StringCollection l = new StringCollection(); Parse cells = row.Leaf; if (!getFirstItem) cells = cells.More; while (cells != null) { string str = cells.Body; HtmlString htmlStr = null; try { htmlStr = new HtmlString(str); } catch (System.Exception) { throw new System.Exception("Caughts fit exception, str = " + str); } string cellText = htmlStr.ToPlainText(); ReplaceSymbols(ref cellText); cells.SetBody(cellText); l.Add(cellText); cells = cells.More; } return l; }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "ul"; output.TagMode = TagMode.StartTagAndEndTag; var actionNames = ControllerType.GetTypeInfo().DeclaredMethods .Where(methodInfo => methodInfo.IsPublic) .Select(methodInfo => methodInfo.Name); var controllerName = ControllerType.Name; if (controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)) { controllerName = controllerName.Substring(0, controllerName.Length - "Controller".Length); } foreach (var action in actionNames) { if (!string.Equals(action, Exclude, StringComparison.OrdinalIgnoreCase)) { var displayName = action; if (string.Equals(action, "Index", StringComparison.OrdinalIgnoreCase)) { displayName = controllerName; } var liElement = new HtmlString($"<li><a href='{_urlHelper.Action(action, controllerName)}'>{displayName}</a></li>"); output.Content.Append(liElement); } } }
internal void ExecuteInternal() { // See comments in GetSafeExecuteStartPageThunk(). _safeExecuteStartPageThunk(() => { Output = new StringWriter(CultureInfo.InvariantCulture); Execute(); Markup = new HtmlString(Output.ToString()); }); }
public void FromEncodedText_DoesNotEncodeOnWrite() { // Arrange var expectedText = "Hello"; // Act var content = new HtmlString(expectedText); // Assert Assert.Equal(expectedText, content.ToString()); }
public void ToString_ReturnsText() { // Arrange var expectedText = "Hello"; var content = new HtmlString(expectedText); // Act var result = content.ToString(); // Assert Assert.Equal(expectedText, result); }
/// <summary> /// Renders the RouteJs script tag. /// </summary> /// <returns>A script tag to load RouteJs</returns> public HtmlString Render() { if (_scriptTag == null) { // Script tag has not been built yet, compute the hash and create it. var hash = ComputeHash(); var environment = _env.IsProduction() ? MINIFIED_MODE : null; var url = _urlHelper.Action("Routes", "RouteJs", new { hash, environment }); _scriptTag = new HtmlString($"<script src=\"{url}\"></script>"); } return _scriptTag; }
public void WriteTo_WritesToTheSpecifiedWriter() { // Arrange var expectedText = "Some Text"; var content = new HtmlString(expectedText); var writer = new StringWriter(); // Act content.WriteTo(writer, new HtmlTestEncoder()); // Assert Assert.Equal(expectedText, writer.ToString()); writer.Dispose(); }
public void ViewComponent_Content_SetsResultContentAndEncodedContent() { // Arrange var viewComponent = new TestViewComponent(); var expectedContent = "TestContent&"; var expectedEncodedContent = new HtmlString(HtmlEncoder.Default.Encode(expectedContent)); // Act var actualResult = viewComponent.Content(expectedContent); // Assert Assert.IsType<ContentViewComponentResult>(actualResult); Assert.Same(expectedContent, actualResult.Content); }
public void AppendHtml_AddsHtmlContentRazorValue() { // Arrange var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name", pageSize: 32); var content = new HtmlString("hello-world"); // Act buffer.AppendHtml(content); // Assert var page = Assert.Single(buffer.Pages); Assert.Equal(1, page.Count); Assert.Same(content, page.Buffer[0].Value); }
public string Decorate(string theInput) { var result = new StringBuilder(); var input = new HtmlString(theInput); result.Append(input.Leader); result.Append(mySetUpHead); result.Append(input.Head); result.Append(myTearDownHead); result.Append(input.Middle); result.Append(mySetUp); result.Append(input.Body); result.Append(myTearDown); result.Append(input.Trailer); return result.ToString(); }
public TestPageDecoration(string theSetUp, string theTearDown) { mySetUp = string.Empty; mySetUpHead = string.Empty; myTearDown = string.Empty; myTearDownHead = string.Empty; if (theSetUp.Length > 0) { var setUp = new HtmlString(theSetUp); mySetUp = setUp.Body; mySetUpHead = setUp.Head; } if (theTearDown.Length > 0) { var tearDown = new HtmlString(theTearDown); myTearDown = tearDown.Body; myTearDownHead = tearDown.Head; } }
public static void AddAlert(this Controller controller, AlertTypeEnum alertType, string title, HtmlString body, bool dismissable) { controller.AddAlert(alertType, new HtmlString(System.Net.WebUtility.HtmlEncode(title)), body, dismissable); }
/// <summary> /// Wraps an HtmlString in a div class=form-group /// </summary> /// <param name="content"></param> /// <returns></returns> public static HtmlString AddFormGroup(this HtmlString content) { return(content.ToString().AddFormGroup()); }
public static IHtmlString LabelEx(this HtmlHelper helper, string target, string text) { HtmlString str = new HtmlString("<label for=" + target + ">" + text + "</label>"); return(new MvcHtmlString(str.ToString())); }
/// <summary> /// TODO /// </summary> /// /// <param name="name">TODO</param> /// /// <param name="html">TODO</param> /// /// <remarks> /// TODO /// </remarks> /// public void AddAttribute(string name, HtmlString html) { this.mHtmlTextWriter.AddAttribute(name, (string)html, false); }
public string GetPagerHtml() { if (PagerHtml != null) { return(PagerHtml.ToString()); } if (TotalRows == 0) { return("No record found"); } //create dropdownlist var pageSelector = new TagBuilder("select"); if (!Container.UsePostBack) { pageSelector.MergeAttribute("onchange", "javascript:window.location.href=this.value;"); } else { pageSelector.MergeAttribute("onchange", "$(\"#" + Container.GridID + "_page" + "\").val($(this).val());$(this).parents(\"form:first\").submit();"); } for (int i = 1; i <= PageCount; i++) { var option = new TagBuilder("option"); option.SetInnerText(i.ToString()); if (!Container.UsePostBack) { option.MergeAttribute("value", HttpContext.Current.Request.Path + "?" + GetPageQuery(i)); } else { option.MergeAttribute("value", i.ToString()); } if (i == CurrentPage) { option.MergeAttribute("selected", "selected"); } pageSelector.InnerHtml += option.ToString(); } var pager = new TagBuilder("div"); var next = GetPagerNav(NextPage, "Next"); var last = GetPagerNav(PageCount, "Last"); var first = GetPagerNav(1, "First"); var prev = GetPagerNav(PrevPage, "Prev"); //create first, prev, next, last if (TotalRows > RowsPerPage) { if (CurrentPage == 1) { pager.InnerHtml = " Records (" + TotalRows.ToString() + ") " + pageSelector.ToString() + " of " + PageCount.ToString() + " " + next + " " + last; } if (Math.Ceiling((double)TotalRows / RowsPerPage) == CurrentPage) { pager.InnerHtml = first + " " + prev + " Records (" + TotalRows.ToString() + ") " + pageSelector.ToString() + " of " + PageCount.ToString(); } if ((CurrentPage > 1) && CurrentPage < Math.Ceiling((double)TotalRows / RowsPerPage)) { pager.InnerHtml = first + " " + prev + " Records (" + TotalRows.ToString() + ") " + pageSelector.ToString() + " of " + PageCount.ToString() + " " + next + " " + last; } } else { pager.InnerHtml = " Records (" + TotalRows.ToString() + ") " + pageSelector.ToString() + " of " + PageCount.ToString(); } PagerHtml = new HtmlString(pager.ToString()); return(PagerHtml.ToString()); }
public ActionResult ComparisonData(FormCollection form) { //傳入查詢條件 log.Info("start project id=" + Request["id"] + ",TypeCode1=" + Request["typeCode1"] + ",typecode2=" + Request["typeCode2"] + ",SystemMain=" + Request["SystemMain"] + ",Sytem Sub=" + Request["SystemSub"] + ",Form Name=" + Request["formName"]); string iswage = "N"; //取得備標品項與詢價資料 try { if (null != Request["formName"] && "" != Request["formName"]) { if (null != Request["isWage"]) { iswage = Request["isWage"]; } DataTable dt = service.getComparisonDataToPivot(Request["id"], Request["typeCode1"], Request["typeCode2"], Request["SystemMain"], Request["SystemSub"], iswage, Request["formName"]); @ViewBag.ResultMsg = "共" + dt.Rows.Count + "筆"; string htmlString = "<table class='table table-bordered'><tr>"; //處理表頭 for (int i = 1; i < 6; i++) { log.Debug("column name=" + dt.Columns[i].ColumnName); htmlString = htmlString + "<th>" + dt.Columns[i].ColumnName + "</th>"; } //處理供應商表頭 Dictionary <string, COMPARASION_DATA> dirSupplierQuo = service.dirSupplierQuo; log.Debug("Column Count=" + dt.Columns.Count); for (int i = 7; i < dt.Columns.Count; i++) { log.Debug("column name=" + dt.Columns[i].ColumnName); string[] tmpString = dt.Columns[i].ColumnName.Split('|'); //<a href="/Inquiry/SinglePrjForm/@item.FORM_ID" target="_blank">@item.FORM_ID</a> decimal tAmount = (decimal)dirSupplierQuo[tmpString[1]].TAmount; string strAmout = string.Format("{0:C0}", tAmount); htmlString = htmlString + "<th><table><tr><td>" + tmpString[0] + '(' + tmpString[2] + ')' + "<br/><button type='button' class='btn btn-xs' onclick=\"clickSupplier('" + tmpString[1] + "','" + iswage + "')\"><span class='fas fa-check'></span></button>" + "<button type='button' class='btn btn-xs'><a href='/Inquiry/SinglePrjForm/" + tmpString[1] + "'" + " target='_blank'><span class='fas fa-tasks' aria-hidden='true'></span></a></button>" + "<button type='button' class='btn btn-xs' onclick=\"chaneFormStatus('" + tmpString[1] + "','註銷')\"><span class='fas fa-times' aria-hidden='true'></span></a></button>" + "</td><tr><td style='text-align:center;background-color:yellow;' >" + strAmout + "</td></tr></table></th>"; } htmlString = htmlString + "</tr>"; //處理資料表 foreach (DataRow dr in dt.Rows) { htmlString = htmlString + "<tr>"; for (int i = 1; i < 5; i++) { htmlString = htmlString + "<td>" + dr[i] + "</td>"; } //單價欄位 <input type='text' id='[email protected]_ITEM_ID' name='[email protected]_ITEM_ID' size='5' /> //decimal price = decimal.Parse(dr[5].ToString()); if (dr[5].ToString() != "") { log.Debug("data row col 5=" + (decimal)dr[5]); htmlString = htmlString + "<td><input type='text' id='cost_" + dr[1] + "' name='cost_" + dr[1] + "' size='5' value='" + String.Format("{0:N0}", (decimal)dr[5]) + "' /></td>"; } else { htmlString = htmlString + "<td></td>"; } //String.Format("{0:C}", 0); //處理報價資料 for (int i = 7; i < dt.Columns.Count; i++) { if (dr[i].ToString() != "") { htmlString = htmlString + "<td><button class='btn-link' onclick=\"clickPrice('" + dr[1] + "', '" + dr[i] + "','" + iswage + "')\">" + String.Format("{0:N0}", (decimal)dr[i]) + "</button> </td>"; } else { htmlString = htmlString + "<td></td>"; } } htmlString = htmlString + "</tr>"; } htmlString = htmlString + "</table>"; //產生畫面 IHtmlString str = new HtmlString(htmlString); ViewBag.htmlString = str; } else { if (null != Request["isWage"]) { iswage = Request["isWage"]; } DataTable dt = service.getComparisonDataToPivot(Request["id"], Request["typeCode1"], Request["typeCode2"], Request["SystemMain"], Request["SystemSub"], iswage, Request["formName"]); @ViewBag.ResultMsg = "共" + dt.Rows.Count + "筆"; string htmlString = "<table class='table table-bordered'><tr>"; //處理表頭 for (int i = 1; i < 6; i++) { log.Debug("column name=" + dt.Columns[i].ColumnName); htmlString = htmlString + "<th>" + dt.Columns[i].ColumnName + "</th>"; } //處理供應商表頭 Dictionary <string, COMPARASION_DATA> dirSupplierQuo = service.dirSupplierQuo; log.Debug("Column Count=" + dt.Columns.Count); for (int i = 6; i < dt.Columns.Count; i++) { log.Debug("column name=" + dt.Columns[i].ColumnName); string[] tmpString = dt.Columns[i].ColumnName.Split('|'); //<a href="/Inquiry/SinglePrjForm/@item.FORM_ID" target="_blank">@item.FORM_ID</a> decimal tAmount = (decimal)dirSupplierQuo[tmpString[1]].TAmount; string strAmout = string.Format("{0:C0}", tAmount); htmlString = htmlString + "<th><table><tr><td>" + tmpString[0] + '(' + tmpString[2] + ')' + "<br/><button type='button' class='btn btn-xs' onclick=\"clickSupplier('" + tmpString[1] + "','" + iswage + "')\"><span class='fas fa-check'></span></button>" + "<button type='button' class='btn btn-xs'><a href='/Inquiry/SinglePrjForm/" + tmpString[1] + "'" + " target='_blank'><span class='fas fa-tasks'></span></a></button>" + "<button type='button' class='btn btn-xs' onclick=\"chaneFormStatus('" + tmpString[1] + "','註銷')\"><span class='fas fa-times'></span></a></button>" + "</td><tr><td style='text-align:center;background-color:yellow;' >" + strAmout + "</td></tr></table></th>"; } htmlString = htmlString + "</tr>"; //處理資料表 foreach (DataRow dr in dt.Rows) { htmlString = htmlString + "<tr>"; for (int i = 1; i < 5; i++) { htmlString = htmlString + "<td>" + dr[i] + "</td>"; } //單價欄位 <input type='text' id='[email protected]_ITEM_ID' name='[email protected]_ITEM_ID' size='5' /> //decimal price = decimal.Parse(dr[5].ToString()); if (dr[5].ToString() != "") { log.Debug("data row col 5=" + (decimal)dr[5]); htmlString = htmlString + "<td><input type='text' id='cost_" + dr[1] + "' name='cost_" + dr[1] + "' size='5' value='" + String.Format("{0:N0}", (decimal)dr[5]) + "' /></td>"; } else { htmlString = htmlString + "<td></td>"; } //String.Format("{0:C}", 0); //處理報價資料 for (int i = 6; i < dt.Columns.Count; i++) { if (dr[i].ToString() != "") { htmlString = htmlString + "<td><button class='btn btn-link' onclick=\"clickPrice('" + dr[1] + "', '" + dr[i] + "','" + iswage + "')\">" + String.Format("{0:N0}", (decimal)dr[i]) + "</button> </td>"; } else { htmlString = htmlString + "<td></td>"; } } htmlString = htmlString + "</tr>"; } htmlString = htmlString + "</table>"; //產生畫面 IHtmlString str = new HtmlString(htmlString); ViewBag.htmlString = str; } } catch (Exception e) { log.Error(e.StackTrace); ViewBag.htmlString = e.Message; } return(PartialView()); }
public void Process_DoesNotResolveNonTildeSlashValues_InHtmlString(HtmlString url) { // Arrange var tagHelperOutput = new TagHelperOutput( tagName: "a", attributes: new TagHelperAttributeList { { "href", url } }, getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null)); var urlHelperMock = new Mock<IUrlHelper>(); urlHelperMock .Setup(urlHelper => urlHelper.Content(It.IsAny<string>())) .Returns("approot/home/index.html"); var urlHelperFactory = new Mock<IUrlHelperFactory>(); urlHelperFactory .Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())) .Returns(urlHelperMock.Object); var tagHelper = new UrlResolutionTagHelper(urlHelperFactory.Object, new HtmlTestEncoder()); var context = new TagHelperContext( allAttributes: new TagHelperAttributeList( Enumerable.Empty<TagHelperAttribute>()), items: new Dictionary<object, object>(), uniqueId: "test"); // Act tagHelper.Process(context, tagHelperOutput); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal("href", attribute.Name, StringComparer.Ordinal); var attributeValue = Assert.IsType<HtmlString>(attribute.Value); Assert.Equal(url.ToString(), attributeValue.ToString(), StringComparer.Ordinal); Assert.Equal(HtmlAttributeValueStyle.DoubleQuotes, attribute.ValueStyle); }
// GET: /<controller>/ public IActionResult Index() { string result = string.Empty; var graph = new UndirectedSparseGraph <string>(); // Add vertices var verticesSet1 = new string[] { "a", "b", "c", "d", "e", "f", "s", "v", "x", "y", "z" }; graph.AddVertices(verticesSet1); result = result + "Vertices: " + "'a', 'b', 'c', 'd', 'e', 'f', 's', 'v', 'x', 'y', 'z'" + "\n\n"; // Add edges // Connected Component #1 // the vertex "e" won't be connected to any other vertex // Connected Component #2 graph.AddEdge("a", "s"); graph.AddEdge("a", "d"); graph.AddEdge("s", "x"); graph.AddEdge("x", "d"); // Connected Component #3 graph.AddEdge("b", "c"); graph.AddEdge("b", "v"); graph.AddEdge("c", "f"); graph.AddEdge("c", "v"); graph.AddEdge("f", "b"); // Connected Component #4 graph.AddEdge("y", "z"); result = result + "Edges: "; result = result + graph.ToReadable() + "\r\n\n"; // Get connected components var connectedComponents = ConnectedComponents.Compute(graph); connectedComponents = connectedComponents.OrderBy(item => item.Count).ToList(); result = result + "# of Connected Components: " + connectedComponents.Count() + "\n"; result = result + "Components are: \n"; foreach (var items in connectedComponents) { string edge = string.Empty; foreach (var item in items) { edge = edge + item + " -> "; } result = result + edge.Remove(edge.Length - 4) + "\n"; } HtmlString html = StringHelper.GetHtmlString(result); return(View(html)); }
internal void WriteHtml(HtmlString html) { m_htmlTextWriter.Write(html); }
/// <summary> /// Initializes a new instance of the <see cref="PlainTextString"/> class /// and specifies initial text for the object to contain. /// </summary> /// /// <param name="htmlText">Initial value of the object.</param> /// /// <remarks> /// The <P>htmlText</P> will be converted to plain text by a call to <Mth>HttpUtility.HtmlDecode</Mth>. /// </remarks> /// internal PlainTextString(HtmlString htmlText) { m_plainText = HttpUtility.HtmlDecode(htmlText); }
internal void AddAttribute(HtmlTextWriterAttribute key, HtmlString html) { m_htmlTextWriter.AddAttribute(key, (string)html, false); }
internal void AddAttribute(string name, HtmlString html) { m_htmlTextWriter.AddAttribute(name, (string)html, false); }
/// <summary> /// Constructor. /// </summary> /// <param name="name">Name of the attribute, as it is encoded in the HTML.</param> /// <param name="value">Value of the attribute, as it is encoded in the HTML.</param> /// <param name="quoteChar">The quote character, will be '\0', '\'', or '"'. '\0' means no quote char.</param> /// <param name="lineNumber">The line number of the attribute.</param> /// <param name="linePosition">The line position of the attribute.</param> internal AttributeNode(HtmlString name, HtmlString value, char quoteChar, int lineNumber, int linePosition) { m_Name = name; m_Value = value; QuoteChar = quoteChar; LineNumber = lineNumber; LinePosition = linePosition; }
// GET: /<controller>/ public IActionResult Index() { string result = string.Empty; // KEYED PRIORITY QUEUE PriorityQueue <int, int, int> keyedPriorityQueue = new PriorityQueue <int, int, int>(10); for (int i = 0; i < 20; ++i) { keyedPriorityQueue.Enqueue(i, i, (i / 3) + 1); } result = result + "Enqueue Keys: "; foreach (var key in keyedPriorityQueue.Keys) { result = result + key + ","; } var keyedPQHighest = keyedPriorityQueue.Dequeue(); result = result + "\nAfter Dequeue, Keyed PQ Highest = " + keyedPQHighest + "\n\n"; // Integer-index priority-queue string alphabet = "abcdefghijklmnopqrstuvwxyz"; result = result + "Alphabets: " + "abcdefghijklmnopqrstuvwxyz" + "\n"; MinPriorityQueue <string, int> priorityQueue = new MinPriorityQueue <string, int>((uint)alphabet.Length); for (int i = 0; i < alphabet.Length; ++i) { priorityQueue.Enqueue(alphabet[i].ToString(), (i / 3) + 1); } var PQMin = priorityQueue.DequeueMin(); result = result + "PQ Min = " + PQMin + "\n\n"; // Processes with priorities MinPriorityQueue <Process, int> sysProcesses = new MinPriorityQueue <Process, int>(); var process1 = new Process( id: 432654, action: new Action(() => System.Console.Write("I am Process #1.\r\n1 + 1 = " + (1 + 1))), desc: "Process 1"); result = result + "Id: " + process1.Id + "\nI am Process #1: 1 + 1 = " + (1 + 1) + "\n\n"; var process2 = new Process( id: 123456, action: new Action(() => System.Console.Write("Hello, World! I am Process #2")), desc: "Process 2"); result = result + "Id: " + process2.Id + "\nHello, World! I am Process #2" + "\n\n"; var process3 = new Process( id: 345098, action: new Action(() => System.Console.Write("I am Process #3")), desc: "Process 3"); result = result + "Id: " + process3.Id + "\nI am Process #3" + "\n\n"; var process4 = new Process( id: 109875, action: new Action(() => System.Console.Write("I am Process #4")), desc: "Process 4"); result = result + "Id: " + process4.Id + "\nI am Process #4" + "\n\n"; var process5 = new Process( id: 13579, action: new Action(() => System.Console.Write("I am Process #5")), desc: "Process 5"); result = result + "Id: " + process5.Id + "\nI am Process #5" + "\n\n"; var process6 = new Process( id: 24680, action: new Action(() => System.Console.Write("I am Process #6")), desc: "Process 6"); result = result + "Id: " + process6.Id + "\nI am Process #6" + "\n\n"; sysProcesses.Enqueue(process1, 1); sysProcesses.Enqueue(process2, 10); sysProcesses.Enqueue(process3, 5); sysProcesses.Enqueue(process4, 7); sysProcesses.Enqueue(process5, 3); sysProcesses.Enqueue(process6, 6); var leastPriorityProcess = sysProcesses.PeekAtMinPriority(); result = result + "First, Least Priority Process.Id = " + leastPriorityProcess.Id + "\n"; sysProcesses.DequeueMin(); leastPriorityProcess = sysProcesses.PeekAtMinPriority(); result = result + "After the second DequeueMin(), Least Priority Process.Id = " + leastPriorityProcess.Id + "\n"; sysProcesses.DequeueMin(); leastPriorityProcess = sysProcesses.PeekAtMinPriority(); result = result + "After the third DequeueMin(), Least Priority Process.Id = " + leastPriorityProcess.Id + "\n"; sysProcesses.DequeueMin(); leastPriorityProcess = sysProcesses.PeekAtMinPriority(); result = result + "After the forth DequeueMin(), Least Priority Process.Id = " + leastPriorityProcess.Id + "\n"; leastPriorityProcess.Action(); HtmlString html = StringHelper.GetHtmlString(result); return(View(html)); }
public void PartialWithViewDataAndModel_InvokesPartialAsyncWithPassedInViewDataAndModel() { // Arrange var expected = new HtmlString("value"); var passedInModel = new object(); var passedInViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()); var helper = new Mock<IHtmlHelper>(MockBehavior.Strict); helper.Setup(h => h.PartialAsync("test", passedInModel, passedInViewData)) .Returns(Task.FromResult((IHtmlContent)expected)) .Verifiable(); // Act var actual = helper.Object.Partial("test", passedInModel, passedInViewData); // Assert Assert.Same(expected, actual); helper.Verify(); }
/// <summary> /// Removes the given <paramref name="classValue"/> from the <paramref name="tagHelperOutput"/>'s /// <see cref="TagHelperOutput.Attributes"/>. /// </summary> /// <param name="tagHelperOutput">The <see cref="TagHelperOutput"/> this method extends.</param> /// <param name="classValue">The class value to remove.</param> /// <param name="htmlEncoder">The current HTML encoder.</param> public static void RemoveClass( this TagHelperOutput tagHelperOutput, string classValue, HtmlEncoder htmlEncoder) { if (tagHelperOutput == null) { throw new ArgumentNullException(nameof(tagHelperOutput)); } var encodedSpaceChars = SpaceChars.Where(x => !x.Equals('\u0020')).Select(x => htmlEncoder.Encode(x.ToString())).ToArray(); if (SpaceChars.Any(classValue.Contains) || encodedSpaceChars.Any(value => classValue.IndexOf(value, StringComparison.Ordinal) >= 0)) { throw new ArgumentException(Resources.ArgumentCannotContainHtmlSpace, nameof(classValue)); } if (!tagHelperOutput.Attributes.TryGetAttribute("class", out TagHelperAttribute classAttribute)) { return; } var currentClassValue = ExtractClassValue(classAttribute, htmlEncoder); if (string.IsNullOrEmpty(currentClassValue)) { return; } var encodedClassValue = htmlEncoder.Encode(classValue); if (string.Equals(currentClassValue, encodedClassValue, StringComparison.Ordinal)) { tagHelperOutput.Attributes.Remove(tagHelperOutput.Attributes["class"]); return; } if (!currentClassValue.Contains(encodedClassValue)) { return; } var listOfClasses = currentClassValue.Split(SpaceChars, StringSplitOptions.RemoveEmptyEntries) .SelectMany(perhapsEncoded => perhapsEncoded.Split(encodedSpaceChars, StringSplitOptions.RemoveEmptyEntries)) .ToList(); if (!listOfClasses.Contains(encodedClassValue)) { return; } listOfClasses.RemoveAll(x => x.Equals(encodedClassValue)); if (listOfClasses.Any()) { var joinedClasses = new HtmlString(string.Join(" ", listOfClasses)); tagHelperOutput.Attributes.SetAttribute(classAttribute.Name, joinedClasses); } else { tagHelperOutput.Attributes.Remove(tagHelperOutput.Attributes["class"]); } }
/// <summary> /// Clears the cached hash /// </summary> public static void ClearCache() { _scriptTag = null; }
/// <summary> /// TODO /// </summary> /// /// <param name="html">TODO</param> /// /// <remarks> /// TODO /// </remarks> /// public void WriteHtml(HtmlString html) { this.mHtmlTextWriter.Write(html); }
public void PartialWithModel_InvokesPartialAsyncWithPassedInModel() { // Arrange var expected = new HtmlString("value"); var model = new object(); var helper = new Mock<IHtmlHelper>(MockBehavior.Strict); helper.Setup(h => h.PartialAsync("test", model, null)) .Returns(Task.FromResult((IHtmlContent)expected)) .Verifiable(); // Act var actual = helper.Object.Partial("test", model); // Assert Assert.Same(expected, actual); helper.Verify(); }
/// <summary> /// 获取支付Html /// </summary> public void GetPaymentHtml(PaymentTransaction transaction, ref HtmlString html) { throw new NotImplementedException(); }
public static HtmlString ToEscapedJSHtmlString(this HtmlString htmlString) { return(new HtmlString($@"{htmlString.Value.Replace("/", "\\/")}")); }
/// <summary> /// Register an HTML block to be included in the page once /// </summary> /// <param name="html">Html helper</param> /// <param name="id">An id for the HTML block</param> /// <param name="htmlBlock">The HTML block as an MvcHtmlString</param> /// <returns>Empty string</returns> public static string RegisterHtmlBlock(this IHtmlHelper html, string id, HtmlString htmlBlock) { RegisterInclude(() => IncludesManager.Instance.Htmls, id, htmlBlock.ToString(), new List <string>()); return(""); }
/// <summary> /// Initializes a new instance of the <see cref="PlainTextString"/> class /// and specifies initial text for the object to contain. /// </summary> /// /// <param name="htmlText">Initial value of the object.</param> /// /// <remarks> /// The <P>htmlText</P> will be converted to plain text by a call to <Mth>HttpUtility.HtmlDecode</Mth>. /// </remarks> /// public PlainTextString(HtmlString htmlText) { this.mPlaintext = HttpUtility.HtmlDecode(htmlText); }
public NeptunePageDetailsViewData(HtmlString neptunePageContent) { NeptunePageContent = neptunePageContent; }
public void Titled_SetsHtmlContentTitle() { IHtmlContent expected = new HtmlString("HtmlContent Title"); IHtmlContent actual = column.Titled(expected).Title; Assert.Same(expected, actual); }
// GET: /<controller>/ public IActionResult Index() { string result = string.Empty; var graph = new UndirectedDenseGraph <string>(); var verticesSet1 = new string[] { "a", "z", "s", "x", "d", "c", "f", "v" }; graph.AddVertices(verticesSet1); graph.AddEdge("a", "s"); graph.AddEdge("a", "z"); graph.AddEdge("s", "x"); graph.AddEdge("x", "d"); graph.AddEdge("x", "c"); graph.AddEdge("d", "f"); graph.AddEdge("d", "c"); graph.AddEdge("c", "f"); graph.AddEdge("c", "v"); graph.AddEdge("v", "f"); var allEdges = graph.Edges.ToList(); // TEST REMOVE nodes v and f graph.RemoveVertex("v"); graph.RemoveVertex("f"); // TEST RE-ADD REMOVED NODES AND EDGES graph.AddVertex("v"); graph.AddVertex("f"); graph.AddEdge("d", "f"); graph.AddEdge("c", "f"); graph.AddEdge("c", "v"); graph.AddEdge("v", "f"); result = ("[*] Undirected Dense Graph: " + "\n\n") + "Graph nodes and edges: \n" + (graph.ToReadable() + "\n\n"); // RE-TEST REMOVE AND ADD NODES AND EDGES graph.RemoveEdge("d", "c"); graph.RemoveEdge("c", "v"); graph.RemoveEdge("a", "z"); result = result + "After removing edges (d-c), (c-v), (a-z):" + "\n"; result = result + graph.ToReadable() + "\n\n"; graph.RemoveVertex("x"); result = result + "After removing node(x):" + "\n"; result = result + graph.ToReadable() + "\n\n"; graph.AddVertex("x"); graph.AddEdge("s", "x"); graph.AddEdge("x", "d"); graph.AddEdge("x", "c"); graph.AddEdge("d", "c"); graph.AddEdge("c", "v"); graph.AddEdge("a", "z"); result = result + "Re-added the deleted vertices and edges to the graph." + "\n"; result = result + graph.ToReadable() + "\n\n"; // BFS result = result + "Walk the graph using BFS:" + "\n"; graph.BreadthFirstWalk("s"); result = result + "output: (s) (a) (x) (z) (d) (c) (f) (v)." + "\n"; result = result + "\n\n"; result = result + "***************************************************\r\n"; graph.Clear(); result = result + "Cleared the graph from all vertices and edges.\r\n"; var verticesSet2 = new string[] { "a", "b", "c", "d", "e", "f" }; result = result + "Vertices Set 2: " + "a, b, c, d, e, f" + "\n\n"; graph.AddVertices(verticesSet2); graph.AddEdge("a", "b"); graph.AddEdge("a", "d"); graph.AddEdge("b", "e"); graph.AddEdge("d", "b"); graph.AddEdge("d", "e"); graph.AddEdge("e", "c"); graph.AddEdge("c", "f"); graph.AddEdge("f", "f"); result = result + "[*] NEW Undirected Dense Graph: " + "\n"; result = result + "Graph nodes and edges:\n"; result = result + "graph.ToReadable()" + "\n\n"; result = result + "Walk the graph using DFS:\n"; graph.DepthFirstWalk(); result = result + "output: (a) (b) (e) (d) (c) (f)\n"; HtmlString html = StringHelper.GetHtmlString(result); return(View(html)); }
public UserDefinedView(string id, HtmlString value) { this.ElementId = id; this.SanitizedHTML = value; }
public static void AddAlert(this Controller controller, AlertTypeEnum alertType, HtmlString title, HtmlString body) { controller.AddAlert(alertType, title, body, false); }
private string GenerateThumbnailName(TempUploadedFile file) { string encodedFilename = new HtmlString(file.Name).ToString(); return(string.Format("{0}_{1}.png", encodedFilename, DateTime.Now.Ticks)); }
public static void AddAlert(this Controller controller, AlertTypeEnum alertType, HtmlString title, HtmlString body, bool dismissable) { controller.AddAlert(new Alert() { Type = alertType, Title = title, Body = body, Dismissable = dismissable }); }
/// <summary> /// Handle admin tabstrip created event /// </summary> /// <param name="eventMessage">Event message</param> public void HandleEvent(AdminTabStripCreated eventMessage) { if (eventMessage?.Helper == null) { return; } //we need customer details page var tabsElementId = "customer-edit"; if (!eventMessage.TabStripName.Equals(tabsElementId)) { return; } //check whether the payment plugin is installed and is active var worldpayPaymentMethod = _paymentService.LoadPaymentMethodBySystemName(WorldpayPaymentDefaults.SystemName); if (!(worldpayPaymentMethod?.PluginDescriptor?.Installed ?? false) || !worldpayPaymentMethod.IsPaymentMethodActive(_paymentSettings)) { return; } //get the view model if (!(eventMessage.Helper.ViewData.Model is CustomerModel customerModel)) { return; } //check whether a customer exists and isn't guest var customer = _customerService.GetCustomerById(customerModel.Id); if (customer == null || customer.IsGuest()) { return; } //try to get stored in Vault customer var vaultCustomer = _worldpayPaymentManager.GetCustomer(customer.GetAttribute <string>(WorldpayPaymentDefaults.CustomerIdAttribute)); //prepare model var model = new WorldpayCustomerModel { Id = customerModel.Id, CustomerExists = vaultCustomer != null, WorldpayCustomerId = vaultCustomer?.CustomerId }; //compose script to create a new tab var worldpayCustomerTabElementId = "tab-worldpay"; var worldpayCustomerTab = new HtmlString($@" <script> $(document).ready(function() {{ $(` <li> <a data-tab-name='{worldpayCustomerTabElementId}' data-toggle='tab' href='#{worldpayCustomerTabElementId}'> {_localizationService.GetResource("Plugins.Payments.Worldpay.WorldpayCustomer")} </a> </li> `).appendTo('#{tabsElementId} .nav-tabs:first'); $(` <div class='tab-pane' id='{worldpayCustomerTabElementId}'> { eventMessage.Helper.Partial("~/Plugins/Payments.Worldpay/Views/Customer/_CreateOrUpdate.Worldpay.cshtml", model).RenderHtmlContent() .Replace("</script>", "<\\/script>") //we need escape a closing script tag to prevent terminating the script block early } </div> `).appendTo('#{tabsElementId} .tab-content:first'); }}); </script>"); //add this tab as a block to render on the customer details page eventMessage.BlocksToRender.Add(worldpayCustomerTab); }
public static HtmlString AddLabel(this HtmlString content, string label, int?labelCols = null, int?inputCols = null) { return(content.ToString().AddLabel(label, labelCols, inputCols)); }
/// <summary> /// Initializes a new instance based on the specified <paramref name="control"/> and <paramref name="token"/>. /// </summary> /// <param name="control">An instance of <see cref="GridControl"/> representing the control.</param> /// <param name="token">An instance of <see cref="JToken"/> representing the value of the control.</param> public GridControlHtmlValue(GridControl control, JToken token) : base(control, token) { HtmlValue = new HtmlString(Value); }
private static Dictionary <string, string> ToAttributesDictionary(HtmlString htmlString) { return(htmlString.ToString().Split(' ').Select(x => x.Split('=')).ToDictionary(x => x[0], val => val.Length == 1 ? "" : val[1].Trim('\'', '"'))); }
public async Task Process() { //create content IHtmlContent res = null; var model = tag.For.Model as IEnumerable; if (model == null) res = new HtmlString(string.Empty); else { int i = 0; var sb = new StringWriter(); foreach (var row in model) { var rowType = options.GetServerRow(row); if (rowType == null) continue; if (options.Type == GridType.Immediate) (await rowType.InvokeDisplay(row, RowPrefix(i, rowType), helpers)).WriteTo(sb, HtmlEncoder.Default); else (await rowType.InvokeEdit(row, RowPrefix(i, rowType), helpers)).WriteTo(sb, HtmlEncoder.Default); i++; } res = new HtmlString(sb.ToString()); } // //Create Layout options var layoutOptions = new DefaultServerGridLayoutOptions( helpers, options.Rows, options.Toolbars, options.LayoutTemplate, options.SubTemplates, res, options.Type, options.Id, options.FullName, options.ErrorMessages??defaultMessages, options.CssClass, tag.Caption, tag.LocalizationType); // //Invoke Layout var fres = await options.LayoutTemplate.Invoke(tag.For, layoutOptions, helpers); output.TagName = string.Empty; output.Content.SetHtmlContent(fres); }
/// <summary> /// Initializes a new instance of the <see cref="ChromiumWebBrowser"/> class. /// **Important** - When using this constructor the <see cref="Control.Dock"/> property /// will default to <see cref="DockStyle.Fill"/>. /// </summary> /// <param name="html">html string to be initially loaded in the browser.</param> /// <param name="requestContext">(Optional) Request context that will be used for this browser instance, if null the Global /// Request Context will be used.</param> public ChromiumWebBrowser(HtmlString html, IRequestContext requestContext = null) : this(html.ToDataUriString(), requestContext) { }
/// <summary> /// Clears the cached hash /// </summary> public static void ClearCache() { _scriptTag = null; }
protected override void RenderWebPart(HtmlTextWriter output) { tb.AddTimer(); if (SPContext.Current.ViewContext.View != null) { foreach (System.Web.UI.WebControls.WebParts.WebPart wp in WebPartManager.WebParts) { try { if (wp.ToString() == "Microsoft.SharePoint.WebPartPages.XsltListViewWebPart" || wp.ToString() == "Microsoft.SharePoint.WebPartPages.ListViewWebPart") { wp.Visible = false; } } catch { } } } if (activation != 0) { output.Write(act.translateStatus(activation)); return; } if (!bHasPeriods) { output.WriteLine("There are no periods setup for this TimeSheet. Please contact your system administrator"); return; } output.WriteLine(@"<style> .GMBodyRight { border-right: 1px solid #DDD!important; } .GMBodyRight .GMCell { border-left: 1px solid #DDD!important; border-bottom: 1px solid #DDD!important; overflow: visible; } .GMCellHeader, .GMCellHeaderPanel, .GMCell, .GMCellPanel { border-bottom: 1px solid #DDD!important; } .Totals { font-weight: bold; } .GMFootRight { border-left: 2px solid #ccc } .GMFootRight .GMCell { border-left: 1px solid #DDD!important; border-bottom: 1px solid #DDD!important; } .HideCol0StopWatch { background-position: 0px center !important; } .TSBold { font-weight: bold !important; } .GMPx0xx { background: none; opacity: 1; } #ddlFilterControl .caret {display:none;} </style>"); string sUserId = ""; if (!string.IsNullOrEmpty(Page.Request["Delegate"])) { SPUser user = TimesheetAPI.GetUser(SPContext.Current.Web, Page.Request["Delegate"]); sUserId = user.ID.ToString(); } bCanEditViews = SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.ManageWeb); string url = SPContext.Current.Web.Url; if (url == "/") { url = ""; } string curUrl = Page.Request.RawUrl.ToString(); if (curUrl.Contains("?")) { curUrl = curUrl.Substring(0, curUrl.IndexOf("?") + 1); } foreach (string key in Page.Request.QueryString.AllKeys) { if (key.ToString().ToLower() != "newperiod" && key.ToString().ToLower() != "delegate") { curUrl += key + "=" + Page.Request.QueryString[key] + "&"; } } int counter = 0; bool IsDefaultAvailable = false; foreach (KeyValuePair <string, Dictionary <string, string> > key in views.Views) { try { if (key.Value["Default"].ToLower() == "true") { sCurrentView = key.Key; sCurrentViewId = "V" + counter; IsDefaultAvailable = true; } } catch { } counter++; } if (!IsDefaultAvailable) { counter = 0; foreach (KeyValuePair <string, Dictionary <string, string> > key in views.Views) { try { sCurrentView = key.Key; sCurrentViewId = "V" + counter; } catch { } counter++; } } curUrl = curUrl.Trim('&').Trim('?'); System.Globalization.CultureInfo cInfo = new System.Globalization.CultureInfo(1033); IFormatProvider culture = new System.Globalization.CultureInfo(cInfo.Name, true); System.Globalization.CultureInfo nInfo = new System.Globalization.CultureInfo(SPContext.Current.Web.Locale.LCID); output.WriteLine(@"<script language=""javascript""> var TSObject" + sFullGridId + @" = new Object(); TSObject" + sFullGridId + @".canSave = true; TSObject" + sFullGridId + @".id = '" + sFullGridId + @"'; TSObject" + sFullGridId + @".Periods = '" + sPeriodList + @"'; TSObject" + sFullGridId + @".PeriodName = '" + sPeriodName + @"'; TSObject" + sFullGridId + @".PeriodId = " + sPeriodId + @"; TSObject" + sFullGridId + @".UserId = '" + sUserId + @"'; TSObject" + sFullGridId + @".DecimalSeparator='" + nInfo.NumberFormat.NumberDecimalSeparator + @"'; TSObject" + sFullGridId + @".GroupSeparator='" + nInfo.NumberFormat.NumberGroupSeparator + @"'; TSObject" + sFullGridId + @".IsCurPeriod = " + bIsCurrentTimesheetPeriod.ToString().ToLower() + @"; TSObject" + sFullGridId + @".CurPeriodId = " + iCurPeriodId + @"; TSObject" + sFullGridId + @".CurPeriodName = '" + sCurPeriodName + @"'; TSObject" + sFullGridId + @".PreviousPeriod = " + iPreviousPeriod + @"; TSObject" + sFullGridId + @".NextPeriod = " + iNextPeriod + @"; TSObject" + sFullGridId + @".TSURL = '" + curUrl + @"'; TSObject" + sFullGridId + @".Status = '" + sStatus + @"'; TSObject" + sFullGridId + @".Locked = " + bTsLocked.ToString().ToLower() + @"; TSObject" + sFullGridId + @".DisableApprovals = " + settings.DisableApprovals.ToString().ToLower() + @"; TSObject" + sFullGridId + @".Delegates = '" + sDelegates.Replace("'", @"`") + @"'; TSObject" + sFullGridId + @".DelegateId = '" + Page.Request["Delegate"] + @"'; TSObject" + sFullGridId + @".Views = " + views.ToJSON() + @"; TSObject" + sFullGridId + @".CurrentView = '" + sCurrentView + @"'; TSObject" + sFullGridId + @".Qualifier = '" + Qualifier + @"'; TSObject" + sFullGridId + @".CurrentViewId = '" + sCurrentViewId + @"'; TSObject" + sFullGridId + @".CanEditViews = " + bCanEditViews.ToString().ToLower() + @"; TSColType = " + TSColType + @"; TSNotes = " + TSNotes + @"; TSTypeObject = " + TSTypeObject + @"; TSCols = " + TSCols + @"; TSDCols = " + TSDCols + @"; siteId = '" + SPContext.Current.Web.ID + @"'; siteUrl = '" + url + @"'; siteColUrl = '" + (SPContext.Current.Site.ServerRelativeUrl == "/" ? "" : SPContext.Current.Site.ServerRelativeUrl) + @"'; periodId = '" + sPeriodId + @"'; GridType = '" + GridType + @"'; curServerDate = (new Date()).getTime() - (new Date('" + DateTime.Now.ToString("MMMM dd, yyyy H:mm:ss", culture) + @"')).getTime(); TGSetEvent('OnRenderFinish', 'TS" + sFullGridId + @"', TSRenderFinish); TGSetEvent('OnReady', 'TS" + sFullGridId + @"', TSReady); TGSetEvent('OnLoaded', 'TS" + sFullGridId + @"', TSOnLoaded); </script> "); //output.WriteLine(@"<div align=""center"" id=""TSLoader" + sFullGridId + @""" width=""100%""><img style=""vertical-align:middle;"" src=""/_layouts/images/gears_anv4.gif""/> Loading Items...</div>"); StringBuilder sb = new StringBuilder("<select class=\"form-control\" onchange=\"changePeriodCommand('" + curUrl + "',this,'" + Page.Request["Delegate"] + "')\">"); var arrPeriods = sPeriodList.Split(','); for (var i = 0; i < arrPeriods.Length; i++) { var arrPeriod = arrPeriods[i].Split('|'); if (arrPeriod[1] != sPeriodName) { sb.Append("<option value=" + arrPeriod[0] + ">" + arrPeriod[1] + "</option>"); } else { sb.Append("<option value=" + arrPeriod[0] + " selected>" + arrPeriod[1] + "</option>"); } } sb.Append("</select>"); var str = new HtmlString(sb.ToString()); if (GridType == 0) { output.WriteLine(@" <div id=""tsnav"" style=""display:none""> <nav class=""navbar navbar-default navbar-static"" role=""navigation""> <div> <div class=""collapse navbar-collapse""> <ul class=""nav navbar-nav"" class=""ts-nav-list""> <li class=""nav-btn nav-text-wrapper"" style=""float:left;padding-right:20px;padding: 0px""> <div class=""nav-label"">Status:</div> <div class=""text"" id=""mytimesheetstatus"">" + sStatus + @"</div> </li> <li class=""nav-btn nav-text-wrapper"" style=""padding: 0px; float:left""> <div class=""nav-label"">Current Period: </div>"); if (iPreviousPeriod != 0) { output.WriteLine(@" <span class=""icon-arrow-left-17 icon"" onclick=""javascript:previousPeriodCommand('" + curUrl + "','" + iPreviousPeriod + "','" + Page.Request["Delegate"] + @"')""></span> "); } else { output.WriteLine(@" <span class=""icon-arrow-left-17 icon disabled""></span> "); } output.WriteLine(@"<div class=""nav-select"">" + str.ToHtmlString() + @" </div>"); if (iNextPeriod != 0) { output.WriteLine(@" <span class=""icon-arrow-right-17 icon"" onclick=""javascript:nextPeriodCommand('" + curUrl + "','" + iNextPeriod + "','" + Page.Request["Delegate"] + @"')""></span> "); } else { output.WriteLine(@" <span class=""icon-arrow-right-17 icon disabled""></span> "); } output.WriteLine(@"</li> </ul> </div> </div> </nav> </div>"); output.Write("<div style=\"height:300px;width:100%;overflow:hidden;display:inline-block\" id=\"gridouter\">"); output.WriteLine("<div style=\"width:100%;height:100%\">"); output.WriteLine(@"<treegrid Data_Url=""" + url + @"/_vti_bin/WorkEngine.asmx"" Data_Timeout=""0"" Data_Method=""Soap"" Data_Function=""Execute"" Data_Namespace=""workengine.com"" Data_Param_Function=""timesheet_GetTimesheetGrid"" Data_Param_Dataxml=""" + sDataParam + @""" Layout_Url=""" + url + @"/_vti_bin/WorkEngine.asmx"" Layout_Timeout=""0"" Layout_Method=""Soap"" Layout_Function=""Execute"" Layout_Namespace=""workengine.com"" Layout_Param_Function=""timesheet_GetTimesheetGridLayout"" Layout_Param_Dataxml=""" + sLayoutParam + @""" Check_Url=""" + url + @"/_vti_bin/WorkEngine.asmx"" Check_Timeout=""0"" Check_Method=""Soap"" Check_Function=""Execute"" Check_Namespace=""workengine.com"" Check_Param_Function=""timesheet_GetTimesheetUpdates"" Check_Param_Dataxml=""" + sLayoutParam + @""" Check_Interval=""0"" Check_Repeat=""0"" Upload_Url=""" + url + @"/_layouts/epmlive/savemytimesheet.aspx" + (Page.Request["Delegate"] != null? "?Delegate=" + Page.Request["Delegate"]:"") + @""" Upload_Type=""Body,Cfg"" Upload_Flags=""AllCols,Accepted"" Debug="""" SuppressMessage=""3""></treegrid>"); output.WriteLine("</div>"); output.WriteLine("</div>"); } else if (GridType == 1) { RenderApprovalToolbar(output); output.WriteLine(@" <div id=""tsnav"" style=""display:none""> <nav class=""navbar navbar-default navbar-static"" role=""navigation""> <div> <div class=""collapse navbar-collapse""> <ul class=""nav navbar-nav"" style=""list-style-type: none;padding-top: 10px; margin:0px;padding: 0px; ""> <li class=""nav-btn nav-text-wrapper"" style=""float:left;padding: 0px; ""> <div class=""nav-label"">Current Period: </div>"); if (iPreviousPeriod != 0) { output.WriteLine(@" <span class=""icon-arrow-left-17 icon"" onclick=""javascript:previousPeriodCommand('" + curUrl + "','" + iPreviousPeriod + "','" + Page.Request["Delegate"] + @"')""></span> "); } else { output.WriteLine(@" <span class=""icon-arrow-left-17 icon disabled""></span> "); } output.WriteLine(@"<div class=""nav-select"">" + str.ToHtmlString() + @" </div>"); if (iNextPeriod != 0) { output.WriteLine(@" <span class=""icon-arrow-right-17 icon"" onclick=""javascript:nextPeriodCommand('" + curUrl + "','" + iNextPeriod + "','" + Page.Request["Delegate"] + @"')""></span> "); } else { output.WriteLine(@" <span class=""icon-arrow-right-17 icon disabled""></span> "); } output.WriteLine(@"</li> </ul> </div> </div> </nav> </div>"); output.Write("<div style=\"height:300px;width:100%;overflow:hidden;display:inline-block\" id=\"gridouter\">"); output.WriteLine("<div style=\"width:100%;height:100%\">"); output.WriteLine(@"<treegrid Data_Url=""" + url + @"/_vti_bin/WorkEngine.asmx"" Data_Timeout=""0"" Data_Method=""Soap"" Data_Function=""Execute"" Data_Namespace=""workengine.com"" Data_Param_Function=""timesheet_GetTimesheetApprovalsGrid"" Data_Param_Dataxml=""" + sDataParam + @""" Layout_Url=""" + url + @"/_vti_bin/WorkEngine.asmx"" Layout_Timeout=""0"" Layout_Method=""Soap"" Layout_Function=""Execute"" Layout_Namespace=""workengine.com"" Layout_Param_Function=""timesheet_GetTimesheetGridLayout"" Layout_Param_Dataxml=""" + sLayoutParam + @""" Page_Url=""" + url + @"/_layouts/15/epmlive/timesheetapprovalpage.aspx?Period=" + sPeriodId + @""" SuppressMessage=""3"" ></treegrid>"); output.WriteLine("</div>"); output.WriteLine("</div>"); } output.WriteLine(@"<div align=""center"" id=""divMessage" + sFullGridId + @""" width=""100%"" class=""dialog""><img style=""vertical-align:middle;"" src=""/_layouts/images/gears_anv4.gif""/> <span id=""spnMessage" + sFullGridId + @""">Saving Timesheet...</span></div>"); output.Write("<div id='NotesDiv' style='z-index:999;position: absolute; margin-left: 65px; display:none; width:150px;height:110px;border: 1px solid #666;background-color:#FFFFFF;cursor:pointer' onClick='stopProp(event);'><textarea id='txtNotes' style='z-index:999;width:140px;height:60px;border:0px;margin-bottom:5px;resize: none; outline: 0;' onkeyup='stopProp(event);' onclick='stopProp(event);' onkeypress='stopProp(event);'"); if (bTsLocked) { output.Write(" disabled='disabled'"); } output.Write("></textarea><br><input type=\"button\" value=\"OK\" onCLick=\"SaveNotes(event);stopProp(event);\" style=\"float:right\"></div>"); output.WriteLine(@"<div id=""viewNameDiv"" style=""display:none;width:200;padding:10px""> View Name:<br /> <input type=""text"" class=""ms-input"" name=""viewname"" id=""viewname""/><br /><br /> <div><input type=""checkbox"" name=""chkViewDefault"" id=""chkViewDefault"" /> Default View </div><br /><br /> <input type=""button"" value=""OK"" onclick=""validate()"" class=""ms-ButtonHeightWidth"" style=""width:100px"" target=""_self"" /> <input type=""button"" value=""Cancel"" onclick=""SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancel clicked'); return false;"" class=""ms-ButtonHeightWidth"" style=""width:100px"" target=""_self"" /> </div>"); output.WriteLine(@"<script language=""javascript"">"); output.WriteLine("function LoadTSGrid" + sFullGridId + "(){ LoadTSGrid('" + sFullGridId + "');}"); output.WriteLine("SP.SOD.executeOrDelayUntilScriptLoaded(LoadTSGrid" + sFullGridId + ", 'EPMLive.js');"); output.WriteLine("initmb();"); output.WriteLine("function clickTab(){"); output.WriteLine("SelectRibbonTab('Ribbon.MyTimesheetTab', true);"); //output.WriteLine("var wp = document.getElementById('MSOZoneCell_WebPart" + this.Qualifier + "');"); //output.WriteLine("fireEvent(wp, 'mouseup');"); output.WriteLine("}"); output.WriteLine("function validate(){"); output.WriteLine("if(document.getElementById('viewname').value.replace(/^\\s+|\\s+$/, '') == ''){"); output.WriteLine("alert('Please enter a view name - view names cannot be blank.')"); output.WriteLine("return false;"); output.WriteLine("}"); output.WriteLine("else{"); output.WriteLine("SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, document.getElementById('viewname').value + '|' + document.getElementById('chkViewDefault').checked); return false;"); output.WriteLine("}"); output.WriteLine("}"); //output.Write("SP.SOD.executeOrDelayUntilScriptLoaded(clickTab, \"MyTimesheetContextualTabPageComponent.js\");"); output.WriteLine(@"var viewNameDiv = document.getElementById(""viewNameDiv"");"); output.WriteLine("</script>"); tb.StopTimer(); tb.WriteTimers(output); }
/// <summary> /// TODO /// </summary> /// /// <param name="key">TODO</param> /// /// <param name="html">TODO</param> /// /// <remarks> /// TODO /// </remarks> /// public void AddAttribute(HtmlTextWriterAttribute key, HtmlString html) { this.mHtmlTextWriter.AddAttribute(key, (string)html, false); }
// GET: /<controller>/ public IActionResult Index() { string result = string.Empty; string[] V; IEnumerable <WeightedEdge <string> > E; DirectedWeightedSparseGraph <string> graph; DijkstraShortestPaths <DirectedWeightedSparseGraph <string>, string> dijkstra; // Init graph object graph = new DirectedWeightedSparseGraph <string>(); // Init V V = new string[6] { "r", "s", "t", "x", "y", "z" }; result = result + "Initial Verrtices: 'r', 's', 't', 'x', 'y', 'z'" + "\n"; // Insert V graph.AddVertices(V); result = result + "# of vertices: " + V.Length + "\n"; // Insert E var status = graph.AddEdge("r", "s", 7); status = graph.AddEdge("r", "t", 6); status = graph.AddEdge("s", "t", 5); status = graph.AddEdge("s", "x", 9); status = graph.AddEdge("t", "x", 10); status = graph.AddEdge("t", "y", 7); status = graph.AddEdge("t", "z", 5); status = graph.AddEdge("x", "y", 2); status = graph.AddEdge("x", "z", 4); status = graph.AddEdge("y", "z", 1); // Get E E = graph.Edges; //Debug.Assert(graph.EdgesCount == 10, "Wrong Edges Count."); result = result + "# of edges: " + graph.EdgesCount + "\n\n"; // // PRINT THE GRAPH result = result + "[*] DIJKSTRA ON DIRECTED WEIGHTED GRAPH:\r\n"; result = result + "Graph representation:"; result = result + graph.ToReadable() + "\r\n\n"; // Init DIJKSTRA dijkstra = new DijkstraShortestPaths <DirectedWeightedSparseGraph <string>, string>(graph, "s"); result = result + "dijkstra.HasPathTo('r') is " + dijkstra.HasPathTo("r") + "\n"; result = result + "dijkstra.HasPathTo('z') is " + dijkstra.HasPathTo("z") + "\n\n"; // Get shortest path to Z var pathToZ = string.Empty; foreach (var node in dijkstra.ShortestPathTo("z")) { pathToZ = String.Format("{0}({1}) -> ", pathToZ, node); } pathToZ = pathToZ.TrimEnd(new char[] { ' ', '-', '>' }); result = result + "Shortest path to node 'z': " + pathToZ + "\r\n"; var pathToY = string.Empty; foreach (var node in dijkstra.ShortestPathTo("y")) { pathToY = String.Format("{0}({1}) -> ", pathToY, node); } pathToY = pathToY.TrimEnd(new char[] { ' ', '-', '>' }); result = result + "Shortest path to node 'y': " + pathToY + "\r\n\n"; ///***************************************************************************************/ //// Clear the graph and insert new V and E to the instance //graph.Clear(); //V = new string[] { "A", "B", "C", "D", "E" }; //// Insert new values of V //graph.AddVertices(V); //Debug.Assert(graph.VerticesCount == V.Length, "Wrong Vertices Count."); //// Insert new value for edges //status = graph.AddEdge("A", "C", 7); //Debug.Assert(status == true); //status = graph.AddEdge("B", "A", 19); //Debug.Assert(status == true); //status = graph.AddEdge("B", "C", 11); //Debug.Assert(status == true); //status = graph.AddEdge("C", "E", 5); //Debug.Assert(status == true); //status = graph.AddEdge("C", "D", 15); //Debug.Assert(status == true); //status = graph.AddEdge("D", "B", 4); //Debug.Assert(status == true); //status = graph.AddEdge("E", "D", 13); //Debug.Assert(status == true); //Debug.Assert(graph.EdgesCount == 7, "Wrong Edges Count."); //// //// PRINT THE GRAPH //Console.Write("[*] DIJKSTRA ON DIRECTED WEIGHTED GRAPH - TEST 01:\r\n"); //Console.WriteLine("Graph representation:"); //Console.WriteLine(graph.ToReadable() + "\r\n"); //// Init DIJKSTRA //dijkstra = new DijkstraShortestPaths<DirectedWeightedSparseGraph<string>, string>(graph, "A"); //var pathToD = string.Empty; //foreach (var node in dijkstra.ShortestPathTo("D")) // pathToD = String.Format("{0}({1}) -> ", pathToD, node); //pathToD = pathToD.TrimEnd(new char[] { ' ', '-', '>' }); //Console.WriteLine("Shortest path from 'A' to 'D': " + pathToD + "\r\n"); //Console.WriteLine("*********************************************\r\n"); ///***************************************************************************************/ var dijkstraAllPairs = new DijkstraAllPairsShortestPaths <DirectedWeightedSparseGraph <string>, string>(graph); var vertices = graph.Vertices; result = result + "Dijkstra All Pairs Shortest Paths: \r\n"; foreach (var source in vertices) { foreach (var destination in vertices) { var shortestPath = string.Empty; if (dijkstraAllPairs.ShortestPath(source, destination) != null) { foreach (var node in dijkstraAllPairs.ShortestPath(source, destination)) { shortestPath = String.Format("{0}({1}) -> ", shortestPath, node); } shortestPath = shortestPath.TrimEnd(new char[] { ' ', '-', '>' }); result = result + "Shortest path from '" + source + "' to '" + destination + "' is: " + shortestPath + "\r\n"; } } } //Console.ReadLine(); HtmlString html = StringHelper.GetHtmlString(result); return(View(html)); }
//gridIdentifier, columnHeaders, columnFieldNames, events, public static HtmlString CollectionGrid <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression, HtmlString formFields, IDictionary <string, string> columnHeaderAndFieldName, string gridUniqueIdentifier, string idFieldName) { JavaScriptSerializer serializer = new JavaScriptSerializer(); TModel model = (TModel)html.ViewContext.ViewData.ModelMetadata.Model; ICollection collection = (ICollection)expression.Compile().Invoke(model); TagBuilder grid = new TagBuilder("div"); grid.AddCssClass("s-grid"); grid.MergeAttribute("data-column-headers", serializer.Serialize(columnHeaderAndFieldName.Keys.ToArray())); grid.MergeAttribute("data-column-field-names", serializer.Serialize(columnHeaderAndFieldName.Values.ToArray())); grid.MergeAttribute("data-grid-unique-identifier", gridUniqueIdentifier); grid.MergeAttribute("data-id-field-name", idFieldName); foreach (var item in collection) { TagBuilder tableRow = new TagBuilder("div"); tableRow.AddCssClass("model-data table-data-row"); tableRow.MergeAttribute("data-all", serializer.Serialize(item)); grid.InnerHtml += tableRow.ToString(); } //create div with form TagBuilder form = new TagBuilder("div"); form.AddCssClass("model-form"); form.InnerHtml += formFields.ToHtmlString(); grid.InnerHtml += form.ToString(); grid.InnerHtml += html.Partial("CollectionGridLayout").ToHtmlString(); //combine all of them in one div with supportive data attributes and let the client-side //js do its work of re-arranging these divs return(new HtmlString(grid.ToString(TagRenderMode.Normal))); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { await base.ProcessAsync(context, output); // ignore, if already has integrity if (context.AllAttributes.ContainsName("integrity")) { return; } // get resource address var attribute = context.TagName switch { "script" => context.AllAttributes["src"], "link" => context.AllAttributes["href"], _ => throw new NotSupportedException($"Tag '{context.TagName}' is not supported for sub-resource integrity.") }; var content = attribute.Value switch { string value => value, HtmlString htmlString => htmlString.Value, _ => null }; if (content == null) { return; } if (content.StartsWith("//", StringComparison.OrdinalIgnoreCase)) { content = ViewContext.HttpContext.Request.Scheme + ":" + content; } // ignore same site if (!content.Contains("://", StringComparison.OrdinalIgnoreCase)) { return; } // ignore malformed URIs if (!Uri.TryCreate(content, UriKind.Absolute, out var uri)) { return; } // calculate hash or get from cache var key = $"SRI_{content}"; var integrity = await MemoryCache.GetOrCreateAsync(key, async cacheEntry => { cacheEntry.SetAbsoluteExpiration(DateTimeOffset.MaxValue); cacheEntry.SetPriority(CacheItemPriority.High); using var http = HttpClientFactory.CreateClient(); try { using var stream = await http.GetStreamAsync(uri); using var hashAlgorithm = SHA256.Create(); var hash = await hashAlgorithm.ComputeHashAsync(stream); var encoded = Convert.ToBase64String(hash); var value = $"sha256-{encoded}"; return(value); } catch (HttpRequestException ex) { Logger.LogWarning(ex, ex.Message); return(null); } }); if (integrity == null) { return; } output.Attributes.Add("integrity", integrity); output.Attributes.Add("crossorigin", "anonymous"); } }
public HelperResult GetExtendedHtml( string tableStyle = "table table-striped table-bordered table-hover footable toggle-square", string headerStyle = "webgrid-header", string footerStyle = "webgrid-footer", string rowStyle = null, string alternatingRowStyle = null, string selectedRowStyle = null, string caption = null, bool displayHeader = true, bool fillEmptyRows = false, string emptyRowCellValue = null, IEnumerable <WebGridColumnHelper> columns = null, IEnumerable <string> exclusions = null, WebGridPagerModes mode = WebGridPagerModes.Numeric | WebGridPagerModes.NextPrevious, string firstText = null, string previousText = null, string nextText = null, string lastText = null, int numericLinksCount = 5, Object htmlAttributes = null, bool displayTotalItems = true, string totalItemsText = "Total items") { HtmlString result; AdminPages adminPages = new AdminPages(); AdminPage adminPage = adminPages.GetPageByCurrentAction(); if (adminPages.IsPermissionGranted(adminPage.PageId, PermissionCode.Read)) { WebGrid webGrid = this; IHtmlString webGridHtml = webGrid.GetHtml(tableStyle, headerStyle, footerStyle, rowStyle, alternatingRowStyle, selectedRowStyle, caption, displayHeader, fillEmptyRows, emptyRowCellValue, columns, exclusions, mode, firstText, previousText, nextText, lastText, numericLinksCount, htmlAttributes); string webGridHtmlString = webGridHtml.ToString(); HtmlDocument htmlDocument = new HtmlDocument(); //TH Attributes htmlDocument.LoadHtml(webGridHtmlString); HtmlNodeCollection htmlNodeCollection = htmlDocument.DocumentNode.SelectSingleNode("//thead/tr").SelectNodes("th"); int i = 0; foreach (WebGridColumnHelper c in columns) { if (c.ThAttributes.IsNotNull()) { HtmlNode htmlNodeTh = HtmlNode.CreateNode(htmlNodeCollection[i].OuterHtml.Insert(3, " " + c.ThAttributes + " ")); htmlNodeCollection[i].ParentNode.ReplaceChild(htmlNodeTh, htmlNodeCollection[i]); } if (c.DataHide.IsNotNull()) { HtmlNode htmlNodeTh = HtmlNode.CreateNode(htmlNodeCollection[i].OuterHtml.Insert(3, " data-hide=\"" + c.DataHide.ToString().ToLower().Split('_').ToCSV(',') + "\" ")); htmlNodeCollection[i].ParentNode.ReplaceChild(htmlNodeTh, htmlNodeCollection[i]); } i++; } webGridHtmlString = htmlDocument.DocumentNode.OuterHtml; //Sort icon if (webGrid.SortColumn.IsNotEmptyOrWhiteSpace()) { htmlDocument.LoadHtml(webGridHtmlString); HtmlNode htmlNodeAnchor = htmlDocument.DocumentNode.SelectSingleNode("//a[contains(@href,'sort=" + webGrid.SortColumn + "')]"); if (htmlNodeAnchor != null) { string imgSortDirection; if (webGrid.SortDirection == SortDirection.Ascending) { imgSortDirection = "imgSortDirectionASC"; } else { imgSortDirection = "imgSortDirectionDESC"; } HtmlNode htmlNodeIcon = HtmlNode.CreateNode("<div class=\"" + imgSortDirection + "\"></div>"); htmlNodeAnchor.ParentNode.AppendChild(htmlNodeIcon); // Fix a bug http://stackoverflow.com/questions/759355/image-tag-not-closing-with-htmlagilitypack if (HtmlNode.ElementsFlags.ContainsKey("img")) { HtmlNode.ElementsFlags["img"] = HtmlElementFlag.Closed; } else { HtmlNode.ElementsFlags.Add("img", HtmlElementFlag.Closed); } webGridHtmlString = htmlDocument.DocumentNode.OuterHtml; } } //Total Row Count htmlDocument.LoadHtml(webGridHtmlString); HtmlNode htmlNodeTFoot = htmlDocument.DocumentNode.SelectSingleNode("//tfoot/tr/td"); if (htmlNodeTFoot != null) { string pager = webGrid.Pager(numericLinksCount: 10, mode: WebGridPagerModes.All).ToString(); if (displayTotalItems) { pager = "<span class=\"pager-total-items-text\">" + totalItemsText + ":</span> <span class=\"pager-total-items-value\">" + webGrid.TotalRowCount.ToString() + "</span><span class=\"pager-pagination\">" + pager + "</span>"; } htmlNodeTFoot.InnerHtml = pager; // Fix a bug http://stackoverflow.com/questions/759355/image-tag-not-closing-with-htmlagilitypack if (HtmlNode.ElementsFlags.ContainsKey("img")) { HtmlNode.ElementsFlags["img"] = HtmlElementFlag.Closed; } else { HtmlNode.ElementsFlags.Add("img", HtmlElementFlag.Closed); } webGridHtmlString = htmlDocument.DocumentNode.OuterHtml; } result = new HtmlString(webGridHtmlString); } else { result = new HtmlString("<span class=\"label label-danger\">" + Resources.Strings.InsufficientPermissions + "</span>"); } return(new HelperResult(writer => { writer.Write(result); })); }
public FancyTreeNode(HtmlString title, string key, bool expanded) { Title = title.ToString(); Key = key; Expanded = expanded; }
private static void ValidateHtmlString(HtmlString expected, HtmlString actual) { Assert.IsNotNull(actual); Assert.AreEqual(expected.ToString(), actual.ToString()); }
/// <summary> /// Initializes a new <see cref="ContentViewComponentResult"/>. /// </summary> /// <param name="content">Content to write. The content be HTML encoded when output.</param> public ContentViewComponentResult([NotNull] string content) { Content = content; EncodedContent = new HtmlString(WebUtility.HtmlEncode(content)); }
/// <summary> /// TODO /// </summary> /// /// <param name="html">TODO</param> /// /// <remarks> /// TODO /// </remarks> /// public void WriteHtml(HtmlString html) { m_htmlTextWriter.Write(html); }