public void expect_well_formed_link_with_elipsisrelativeurl_and_appropriate_baseurl() { // arrange var linkhelper = new LinkHelper(); // act var result = linkhelper.ParseLink(RelativeLinkWithElipsis, BaseLinkFromWhichElipsisLinksOccur); // assert Assert.That(result, Is.EqualTo("http://www.google.com/intl/en/policies/")); }
public void expect_well_formed_link_with_baseurl_and_relative_link() { // arrange var linkHelper = new LinkHelper(); // act var result = linkHelper.ParseLink(RelativeLink, BaseUrl); // assert Assert.That(result, Is.EqualTo(BaseUrlHost + RelativeLink)); }
public void expect_rejected_link_with_baseurl_and_javascript_link() { // arrange var linkhelper = new LinkHelper(); // act var result = linkhelper.ParseLink(JavascriptLink, BaseUrl); // assert Assert.That(result, Is.Empty); }
/// <summary> /// Cancel content /// </summary> private void CancelNewsCategory() { string url = LinkHelper.GetAdminLink("slider"); Response.Redirect(url); }
public override bool Match(InlineProcessor processor, ref StringSlice slice) { // Previous char must be a whitespace or a punctuation var previousChar = slice.PeekCharExtra(-1); if (!previousChar.IsAsciiPunctuation() && !previousChar.IsWhiteSpaceOrZero()) { return(false); } List <char> pendingEmphasis; // Check that an autolink is possible in the current context if (!IsAutoLinkValidInCurrentContext(processor, out pendingEmphasis)) { return(false); } var startPosition = slice.Start; var c = slice.CurrentChar; // Precheck URL switch (c) { case 'h': if (!slice.MatchLowercase("ttp://", 1) && !slice.MatchLowercase("ttps://", 1)) { return(false); } break; case 'f': if (!slice.MatchLowercase("tp://", 1)) { return(false); } break; case 'm': if (!slice.MatchLowercase("ailto:", 1)) { return(false); } break; case 'w': if (!slice.MatchLowercase("ww.", 1) || previousChar == '/') // We won't match http:/www. or /www.xxx { return(false); } break; } // Parse URL string link; if (!LinkHelper.TryParseUrl(ref slice, out link)) { return(false); } // If we have any pending emphasis, remove any pending emphasis characters from the end of the link if (pendingEmphasis != null) { for (int i = link.Length - 1; i >= 0; i--) { if (pendingEmphasis.Contains(link[i])) { slice.Start--; } else { if (i < link.Length - 1) { link = link.Substring(0, i + 1); } break; } } } // Post-check URL switch (c) { case 'h': if (string.Equals(link, "http://", StringComparison.OrdinalIgnoreCase) || string.Equals(link, "https://", StringComparison.OrdinalIgnoreCase)) { return(false); } break; case 'f': if (string.Equals(link, "ftp://", StringComparison.OrdinalIgnoreCase)) { return(false); } break; case 'm': if (string.Equals(link, "mailto:", StringComparison.OrdinalIgnoreCase) || !link.Contains("@")) { return(false); } break; case 'w': // We require at least two . if (link.Length <= "www.x.y".Length || link.IndexOf(".", 4, StringComparison.Ordinal) < 0) { return(false); } break; } int line; int column; var inline = new LinkInline() { Span = { Start = processor.GetSourcePosition(startPosition, out line, out column), }, Line = line, Column = column, Url = c == 'w' ? "http://" + link : link, IsClosed = true, }; inline.Span.End = inline.Span.Start + link.Length - 1; inline.UrlSpan = inline.Span; inline.AppendChild(new LiteralInline() { Span = inline.Span, Line = line, Column = column, Content = new StringSlice(slice.Text, startPosition, startPosition + link.Length - 1), IsClosed = true }); processor.Inline = inline; return(true); }
public void TestUrilizeNonAscii_Simple(string input, string expectedResult) { Assert.AreEqual(expectedResult, LinkHelper.Urilize(input, false)); }
private void Add() { string url = LinkHelper.GetAdminLink("edit_contentstatic"); Response.Redirect(url); }
public void clickOnActionButton() { LinkHelper.click(action_Button); }
/// <summary> /// Cancel content /// </summary> private void CancelFengShuiCategory() { string url = LinkHelper.GetAdminLink("fengshui"); Response.Redirect(url); }
public override bool Match(InlineProcessor processor, ref StringSlice slice) { // Previous char must be a whitespace or a punctuation var previousChar = slice.PeekCharExtra(-1); if (!previousChar.IsWhiteSpaceOrZero() && Options.ValidPreviousCharacters.IndexOf(previousChar) == -1) { return(false); } List <char> pendingEmphasis = _listOfCharCache.Get(); try { // Check that an autolink is possible in the current context if (!IsAutoLinkValidInCurrentContext(processor, pendingEmphasis)) { return(false); } var startPosition = slice.Start; int domainOffset = 0; var c = slice.CurrentChar; // Precheck URL switch (c) { case 'h': if (slice.MatchLowercase("ttp://", 1)) { domainOffset = 7; // http:// } else if (slice.MatchLowercase("ttps://", 1)) { domainOffset = 8; // https:// } else { return(false); } break; case 'f': if (!slice.MatchLowercase("tp://", 1)) { return(false); } domainOffset = 6; // ftp:// break; case 'm': if (!slice.MatchLowercase("ailto:", 1)) { return(false); } break; case 't': if (!slice.MatchLowercase("el:", 1)) { return(false); } domainOffset = 4; break; case 'w': if (!slice.MatchLowercase("ww.", 1)) // We won't match http:/www. or /www.xxx { return(false); } domainOffset = 4; // www. break; } // Parse URL if (!LinkHelper.TryParseUrl(ref slice, out string?link, out _, true)) { return(false); } // If we have any pending emphasis, remove any pending emphasis characters from the end of the link if (pendingEmphasis.Count > 0) { for (int i = link.Length - 1; i >= 0; i--) { if (pendingEmphasis.Contains(link[i])) { slice.Start--; } else { if (i < link.Length - 1) { link = link.Substring(0, i + 1); } break; } } } // Post-check URL switch (c) { case 'h': if (string.Equals(link, "http://", StringComparison.OrdinalIgnoreCase) || string.Equals(link, "https://", StringComparison.OrdinalIgnoreCase)) { return(false); } break; case 'f': if (string.Equals(link, "ftp://", StringComparison.OrdinalIgnoreCase)) { return(false); } break; case 't': if (string.Equals(link, "tel", StringComparison.OrdinalIgnoreCase)) { return(false); } break; case 'm': int atIndex = link.IndexOf('@'); if (atIndex == -1 || atIndex == 7) // mailto:@ - no email part { return(false); } domainOffset = atIndex + 1; break; } // Do not need to check if a telephone number is a valid domain if (c != 't' && !LinkHelper.IsValidDomain(link, domainOffset)) { return(false); } var inline = new LinkInline() { Span = { Start = processor.GetSourcePosition(startPosition, out int line, out int column), }, Line = line, Column = column, Url = c == 'w' ? ((Options.UseHttpsForWWWLinks ? "https://" : "http://") + link) : link, IsClosed = true, IsAutoLink = true, };
private SyndicationItem GetSyndicationItem(Store store, Product product, ProductCategory productCategory, int description, int isDetailLink) { if (productCategory == null) { return(null); } if (description == 0) { description = 300; } var productDetailLink = LinkHelper.GetProductLink(product, productCategory.Name); String detailPage = String.Format("http://{0}{1}", store.Domain.ToLower(), productDetailLink); if (isDetailLink == 1) { detailPage = String.Format("http://{0}{1}", store.Domain.ToLower(), "/products/productbuy/" + product.Id); } string desc = ""; if (description > 0) { desc = GeneralHelper.GeneralHelper.GetDescription(product.Description, description); } var uri = new Uri(detailPage); var si = new SyndicationItem(product.Name, desc, uri); if (product.UpdatedDate != null) { si.PublishDate = product.UpdatedDate.Value.ToUniversalTime(); } if (!String.IsNullOrEmpty(productCategory.Name)) { si.ElementExtensions.Add("products:category", String.Empty, productCategory.Name); } si.ElementExtensions.Add("guid", String.Empty, uri); if (product.ProductFiles.Any()) { List <BaseFileEntity> baseFileEntities = product.ProductFiles != null && product.ProductFiles.Any() ? product.ProductFiles.Cast <BaseFileEntity>().ToList() : new List <BaseFileEntity>(); var imageLiquid = new ImageLiquid(baseFileEntities, this.ImageWidth, this.ImageHeight); imageLiquid.ImageState = true; String imageSrcHtml = String.Format("http://{0}{1}", store.Domain.ToLower(), imageLiquid.SmallImageSource); try { SyndicationLink imageLink = SyndicationLink.CreateMediaEnclosureLink(new Uri(imageSrcHtml), "image/jpeg", 100); si.Links.Add(imageLink); } catch (Exception ex) { Logger.Error(ex, "GetSyndicationItem"); } } return(si); }
public override bool Match(InlineProcessor processor, ref StringSlice slice) { // The following methods are inspired by the "An algorithm for parsing nested emphasis and links" // at the end of the CommonMark specs. var c = slice.CurrentChar; int line; int column; var startPosition = processor.GetSourcePosition(slice.Start, out line, out column); bool isImage = false; if (c == '!') { isImage = true; c = slice.NextChar(); if (c != '[') { return(false); } } switch (c) { case '[': // If this is not an image, we may have a reference link shortcut // so we try to resolve it here var saved = slice; string label; SourceSpan labelSpan; // If the label is followed by either a ( or a [, this is not a shortcut if (LinkHelper.TryParseLabel(ref slice, out label, out labelSpan)) { if (!processor.Document.ContainsLinkReferenceDefinition(label)) { label = null; } } slice = saved; // Else we insert a LinkDelimiter slice.NextChar(); processor.Inline = new LinkDelimiterInline(this) { Type = DelimiterType.Open, Label = label, LabelSpan = processor.GetSourcePositionFromLocalSpan(labelSpan), IsImage = isImage, Span = new SourceSpan(startPosition, processor.GetSourcePosition(slice.Start - 1)), Line = line, Column = column }; return(true); case ']': slice.NextChar(); if (processor.Inline != null) { if (TryProcessLinkOrImage(processor, ref slice)) { return(true); } } // If we don’t find one, we return a literal slice node ]. // (Done after by the LiteralInline parser) return(false); } // We don't have an emphasis return(false); }
public void WhenUserClickOnTheTitleAndRecipientTextbox() { cRpage.ClickOnTheTitleTextBox(); cRpage.ClickOnRecipientTextBox(); LinkHelper.ClickLink(By.XPath("//mat-select[@id='mat-select-2']")); }
public Status Get() { Output = LinkHelper.GetRootLinks(); return(200); }
public async Task BulkOpen([Remainder] string str = "") { var boxes = await LootBoxDb.GetAll(Context.User.Id, Context.Guild.Id); if (boxes.Count == 0) { await Context.Channel.SendMessageAsync("", false, ToastieUtil.NoBoxEmbed(Context.User).Build()); return; } LootBox box = null; if (boxes.Count == 1) { box = boxes[0]; } else { var listMsg = await Context.Channel.SendMessageAsync(embed : ToastieUtil.BoxListEmbed(boxes, Context.User) .WithFooter("Times out in 23 seconds") .WithDescription("Enter the number of the Lootbox type you wish to open.") .Build()); var response = await NextMessageAsync( new Criteria <IMessage>() .AddCriterion(new EnsureSourceUserCriterion()) .AddCriterion(new EnsureSourceChannelCriterion()) .AddCriterion(new EnsureRangeCriterion(boxes.Count, Program.GetPrefix(Context))), new TimeSpan(0, 0, 23)); _ = listMsg.DeleteAsync(); int i = 0; try { i = int.Parse(response.Content); } catch { _ = Context.Message.DeleteAsync(); return; } _ = response.DeleteAsync(); box = boxes[i - 1]; } var type = LootboxStats.Lootboxes[box.Type]; var dialoague = await ReplyAsync(embed : new EmbedBuilderPrepared(Context.User).WithDescription($"How many {type.Emote} **{type.Name}** lootboxes do you wish to open?").Build()); var amountMsg = await NextMessageAsync( new Criteria <IMessage>() .AddCriterion(new EnsureSourceUserCriterion()) .AddCriterion(new EnsureSourceChannelCriterion()) .AddCriterion(new EnsureRangeCriterion(int.MaxValue, Program.GetPrefix(Context))), new TimeSpan(0, 0, 23)); int amount; try { amount = int.Parse(amountMsg.Content); } catch { _ = Context.Message.DeleteAsync(); return; } _ = dialoague.DeleteAsync(); try { await LootBoxDb.AddLootbox(Context.User.Id, box.Type, -amount, box.GuildId); } catch { await Context.Channel.SendMessageAsync("You tried."); return; } _ = amountMsg.DeleteAsync(); var msg = await Context.Channel.SendMessageAsync("", false, ToastieUtil.BoxOpeningEmbed(Context.User).Build()); await ProfileDb.IncrementLootboxOpened(Context.User.Id, amount); int waitms = 4200; int toasties = 0; var waifusFound = new List <Waifu>(); var waifus = UserInventoryDb.GetWaifus(Context.User.Id, Context.Guild.Id); bool isPremium = PremiumDb.IsPremium(Context.User.Id, ProType.Pro); for (int i = 0; i < amount; i++) { if (type.IsWaifu()) { var waifu = await ToastieUtil.UnboxWaifu(type, isPremium, Context.User.Id, Context.Guild.Id); while (waifu == null || waifus.Any(x => x.Name.Equals(waifu.Name)) || waifusFound.Any(x => x.Name.Equals(waifu.Name))) { waifu = await ToastieUtil.UnboxWaifu(type, isPremium, Context.User.Id, Context.Guild.Id); } waifusFound.Add(waifu); await UserInventoryDb.AddWaifu(Context.User.Id, waifu, Context.Guild.Id); } else { toasties += type.GetRandomToasties(); } } await BalanceDb.AddToasties(Context.User.Id, toasties, Context.Guild.Id); var bal = BalanceDb.GetToasties(Context.User.Id, Context.Guild.Id); await Task.Delay(waitms); var eb = new EmbedBuilder() .WithAuthor($"{Context.User} | {box.Type.ToString()} x{amount}", Context.User.GetAvatarUrl(), LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "cmd-embed-lootbox")) .WithColor(BasicUtil.RandomColor()) .WithThumbnailUrl("https://i.imgur.com/4JQmxa6.png"); string desc = $"You found **{toasties.ToString("n0")}** {ToastieUtil.RandomEmote()}!\nNow you have **{bal.ToString("n0")}** {ToastieUtil.RandomEmote()}!\n\n"; if (waifusFound.Any()) { desc += "**Waifus Found:**\n"; foreach (var w in waifusFound) { desc += $"`T{w.Tier}` **{w.Name}** - *{(w.Source.Length > 37 ? w.Source.Substring(0, 33) + "..." : w.Source)}*\n"; } } eb.WithDescription(desc.Length > 2000 ? desc.Substring(0, 1970) + "\n*And more...*" : desc); await msg.ModifyAsync(x => { x.Embed = eb.Build(); }); }
public async Task Open([Remainder] string str = "") { var boxes = await LootBoxDb.GetAll(Context.User.Id, Context.Guild.Id); if (boxes.Count == 0) { await Context.Channel.SendMessageAsync("", false, ToastieUtil.NoBoxEmbed(Context.User).Build()); return; } LootBox box = null; if (boxes.Count == 1) { box = boxes[0]; } else { var listMsg = await Context.Channel.SendMessageAsync(embed : ToastieUtil.BoxListEmbed(boxes, Context.User) .WithFooter("Times out in 23 seconds") .WithDescription("Enter the number of the Lootbox you wish to open.") .Build()); var response = await NextMessageAsync( new Criteria <IMessage>() .AddCriterion(new EnsureSourceUserCriterion()) .AddCriterion(new EnsureSourceChannelCriterion()) .AddCriterion(new EnsureRangeCriterion(boxes.Count, Program.GetPrefix(Context))), new TimeSpan(0, 0, 23)); _ = listMsg.DeleteAsync(); int i = 0; try { i = int.Parse(response.Content); } catch { _ = Context.Message.DeleteAsync(); return; } _ = response.DeleteAsync(); box = boxes[i - 1]; } var type = LootboxStats.Lootboxes[box.Type]; try { await LootBoxDb.AddLootbox(Context.User.Id, box.Type, -1, box.GuildId); } catch { await Context.Channel.SendMessageAsync("You tried."); return; } var msg = await Context.Channel.SendMessageAsync("", false, ToastieUtil.BoxOpeningEmbed(Context.User).Build()); await ProfileDb.IncrementLootboxOpened(Context.User.Id); int waitms = 4200; if (type.IsWaifu()) { bool isPremium = PremiumDb.IsPremium(Context.User.Id, ProType.Pro); var waifu = await ToastieUtil.UnboxWaifu(type, isPremium, Context.User.Id, Context.Guild.Id); while (UserInventoryDb.OwnsWaifu(Context.User.Id, waifu, Context.Guild.Id)) { waifu = await ToastieUtil.UnboxWaifu(type, isPremium, Context.User.Id, Context.Guild.Id); } await UserInventoryDb.AddWaifu(Context.User.Id, waifu, Context.Guild.Id); await Task.Delay(waitms); var embed = WaifuUtil.WaifuEmbedBuilder(waifu, Context).Build(); await msg.ModifyAsync(x => { x.Embed = embed; x.Content = $"{Context.User.Mention} Congratulations! You found **{waifu.Name}**!"; }); return; } var amountWon = type.GetRandomToasties(); await BalanceDb.AddToasties(Context.User.Id, amountWon, Context.Guild.Id); var bal = BalanceDb.GetToasties(Context.User.Id, Context.Guild.Id); await Task.Delay(waitms); await msg.ModifyAsync(x => { x.Embed = new EmbedBuilder() .WithAuthor($"{Context.User} | {box.Type.ToString()}", Context.User.GetAvatarUrl(), LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "cmd-embed-lootbox")) .WithColor(BasicUtil.RandomColor()) .WithThumbnailUrl("https://i.imgur.com/4JQmxa6.png") .WithDescription($"Congratulations! You found **{amountWon.ToString("n0")}** {ToastieUtil.RandomEmote()}!\nNow you have **{bal.ToString("n0")}** {ToastieUtil.RandomEmote()}!") .Build(); }); }
/// <summary> /// Process the inlines of the heading to create a unique identifier /// </summary> /// <param name="processor">The processor.</param> /// <param name="inline">The inline.</param> private void HeadingBlock_ProcessInlinesEnd(InlineProcessor processor, Inline?inline) { var identifiers = processor.Document.GetData(AutoIdentifierKey) as HashSet <string>; if (identifiers is null) { identifiers = new HashSet <string>(); processor.Document.SetData(AutoIdentifierKey, identifiers); } var headingBlock = (HeadingBlock)processor.Block !; if (headingBlock.Inline is null) { return; } // If id is already set, don't try to modify it var attributes = processor.Block !.GetAttributes(); if (attributes.Id != null) { return; } // Use internally a HtmlRenderer to strip links from a heading var stripRenderer = rendererCache.Get(); stripRenderer.Render(headingBlock.Inline); var headingText = stripRenderer.Writer.ToString() !; rendererCache.Release(stripRenderer); // Urilize the link headingText = (options & AutoIdentifierOptions.GitHub) != 0 ? LinkHelper.UrilizeAsGfm(headingText) : LinkHelper.Urilize(headingText, (options & AutoIdentifierOptions.AllowOnlyAscii) != 0); // If the heading is empty, use the word "section" instead var baseHeadingId = string.IsNullOrEmpty(headingText) ? "section" : headingText; // Add a trailing -1, -2, -3...etc. in case of collision var headingId = baseHeadingId; if (!identifiers.Add(headingId)) { var headingBuffer = new ValueStringBuilder(stackalloc char[ValueStringBuilder.StackallocThreshold]); headingBuffer.Append(baseHeadingId); headingBuffer.Append('-'); uint index = 0; do { index++; headingBuffer.Append(index); headingId = headingBuffer.AsSpan().ToString(); headingBuffer.Length = baseHeadingId.Length + 1; }while (!identifiers.Add(headingId)); headingBuffer.Dispose(); } attributes.Id = headingId; }
private bool TryProcessLinkOrImage(InlineProcessor inlineState, ref StringSlice text) { LinkDelimiterInline openParent = null; foreach (var parent in inlineState.Inline.FindParentOfType <LinkDelimiterInline>()) { openParent = parent; break; } if (openParent != null) { // If we do find one, but it’s not active, // we remove the inactive delimiter from the stack, // and return a literal text node ]. if (!openParent.IsActive) { inlineState.Inline = new LiteralInline() { Content = new StringSlice("["), Span = openParent.Span, Line = openParent.Line, Column = openParent.Column, }; openParent.ReplaceBy(inlineState.Inline); return(false); } // If we find one and it’s active, // then we parse ahead to see if we have // an inline link/image, reference link/image, // compact reference link/image, // or shortcut reference link/image var parentDelimiter = openParent.Parent; switch (text.CurrentChar) { case '(': string url; string title; SourceSpan linkSpan; SourceSpan titleSpan; if (LinkHelper.TryParseInlineLink(ref text, out url, out title, out linkSpan, out titleSpan)) { // Inline Link var link = new LinkInline() { Url = HtmlHelper.Unescape(url), Title = HtmlHelper.Unescape(title), IsImage = openParent.IsImage, LabelSpan = openParent.LabelSpan, UrlSpan = inlineState.GetSourcePositionFromLocalSpan(linkSpan), TitleSpan = inlineState.GetSourcePositionFromLocalSpan(titleSpan), Span = new SourceSpan(openParent.Span.Start, inlineState.GetSourcePosition(text.Start - 1)), Line = openParent.Line, Column = openParent.Column, }; openParent.ReplaceBy(link); // Notifies processor as we are creating an inline locally inlineState.Inline = link; // Process emphasis delimiters inlineState.PostProcessInlines(0, link, null, false); // If we have a link (and not an image), // we also set all [ delimiters before the opening delimiter to inactive. // (This will prevent us from getting links within links.) if (!openParent.IsImage) { MarkParentAsInactive(parentDelimiter); } link.IsClosed = true; return(true); } break; default: var labelSpan = SourceSpan.Empty; string label = null; bool isLabelSpanLocal = true; // Handle Collapsed links if (text.CurrentChar == '[') { if (text.PeekChar(1) == ']') { label = openParent.Label; labelSpan = openParent.LabelSpan; isLabelSpanLocal = false; text.NextChar(); // Skip [ text.NextChar(); // Skip ] } } else { label = openParent.Label; } if (label != null || LinkHelper.TryParseLabel(ref text, true, out label, out labelSpan)) { if (isLabelSpanLocal) { labelSpan = inlineState.GetSourcePositionFromLocalSpan(labelSpan); } if (ProcessLinkReference(inlineState, label, labelSpan, openParent, inlineState.GetSourcePosition(text.Start - 1))) { // Remove the open parent openParent.Remove(); if (!openParent.IsImage) { MarkParentAsInactive(parentDelimiter); } } else { return(false); } return(true); } break; } // We have a nested [ ] // firstParent.Remove(); // The opening [ will be transformed to a literal followed by all the childrens of the [ var literal = new LiteralInline() { Span = openParent.Span, Content = new StringSlice(openParent.IsImage ? "![" : "[") }; inlineState.Inline = openParent.ReplaceBy(literal); return(false); } return(false); }
protected void rptResult_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { PNK_Product data = e.Item.DataItem as PNK_Product; HtmlAnchor hypImg = e.Item.FindControl("hypImg") as HtmlAnchor; HtmlAnchor hypTitle = e.Item.FindControl("hypTitle") as HtmlAnchor; string link = UtilityLocal.GetPathTreeNameUrl(data.CategoryId, LangInt, LangId); int level = link.Count(i => i.Equals('/')); if (level == 1) { hypTitle.HRef = hypImg.HRef = LinkHelper.GetLink(UtilityLocal.GetPathTreeNameUrl(data.CategoryId, LangInt, LangId), LocalizationUtility.GetText("linkCate", Ci), LocalizationUtility.GetText("linktmp", Ci), data.ProductDesc.TitleUrl); } else if (level == 2) { hypTitle.HRef = hypImg.HRef = LinkHelper.GetLink(link, LocalizationUtility.GetText("linktmp", Ci), data.ProductDesc.TitleUrl); } else if (level == 3) { hypTitle.HRef = hypImg.HRef = LinkHelper.GetLink(link, data.ProductDesc.TitleUrl); //hypTitle.HRef = hypImg.HRef = LinkHelper.GetLink(pageName, LangId, cid, data.CategoryUrlDesc, data.ProductDesc.TitleUrl); } else if (level == 4) { hypTitle.HRef = hypImg.HRef = LinkHelper.GetLink(link, data.ProductDesc.TitleUrl); } HtmlImage img = e.Item.FindControl("img") as HtmlImage; img.Src = WebUtils.GetUrlImage(ConfigurationManager.AppSettings["ProductUpload"], data.Image); //img.Attributes.Add("data-lazysrc", WebUtils.GetUrlImage(ConfigurationManager.AppSettings["ProductUpload"], data.Image)); Literal ltrTitle = e.Item.FindControl("ltrTitle") as Literal; hypImg.Title = ltrTitle.Text = img.Alt = img.Attributes["title"] = data.ProductDesc.Title; Literal ltrBrief = e.Item.FindControl("ltrBrief") as Literal; ltrBrief.Text = data.ProductDesc.Brief; StringBuilder sbPrice = new StringBuilder(); StringBuilder sbPriceFrom = new StringBuilder(); StringBuilder sbDiscountPercent = new StringBuilder(); //Nếu không có giá giảm if (string.IsNullOrWhiteSpace(data.Post)) { string normalPrice = data.Website == "" ? "Call" : string.Format("$USD {0}", data.Website); sbPrice.Append("<div class=\"package-info\"><i class=\"icon-tag\"></i><span class=\"package-price\">" + normalPrice + "</span></div>"); sbDiscountPercent.Append("<div class=\"package-ribbon-wrapper\"><div class=\"hidden package-type normal-type\">Learn More</div><div class=\"clear\"></div><div class=\"hidden package-type-gimmick\"></div><div class=\"clear\"></div></div>"); } //Nếu có giá giảm else { string normalPrice = data.Website == "" ? "Call" : string.Format("$USD {0}", data.Website); decimal discountPercent = ((DBConvert.ParseDecimal(data.Website) - DBConvert.ParseDecimal(data.Post)) / DBConvert.ParseDecimal(data.Website)) * 100; sbPrice.Append("<div class=\"package-info last-minute\"><div class=\"package-info-inner\"><span class=\"discount-price\"><i class=\"icon-tag\"></i> $USD " + data.Post + "</span><span class=\"normal-price\">$USD " + data.Website + "</span></div></div>"); sbDiscountPercent.Append("<div class=\"package-ribbon-wrapper\"><div class=\"hidden package-type last-minute\"><span class=\"head\">Last Minute</span><span class=\"discount-text\">" + discountPercent + " Off</span></div><div class=\"clear\"></div><div class=\"hidden package-type-gimmick\"></div><div class=\"clear\"></div></div>"); //sbPriceFrom.Append("<div class=\"package-info last-minute\"><div class=\"package-info-inner\"><span class=\"discount-price\"><i class=\"icon-tag\"></i>Price from $USD " + data.Post + "</span></div></div>"); } Literal ltrPrice = e.Item.FindControl("ltrPrice") as Literal; ltrPrice.Text = sbPrice.ToString(); Literal ltrDiscountPercent = e.Item.FindControl("ltrDiscountPercent") as Literal; ltrDiscountPercent.Text = sbDiscountPercent.ToString(); Literal ltrPriceFrom = e.Item.FindControl("ltrPriceFrom") as Literal; //ltrPriceFrom.Text = sbPriceFrom.ToString(); //Literal ltrPriceNormal = e.Item.FindControl("ltrPriceNormal") as Literal; //ltrPriceNormal.Text = data.Website; //Literal ltrPriceDiscount = e.Item.FindControl("ltrPriceDiscount") as Literal; //ltrPriceDiscount.Text = data.Latitude; Literal ltrDate = e.Item.FindControl("ltrDate") as Literal; ltrDate.Text = data.Area == "" ? "Available all year round" : string.Format("{0}; {1}", data.Area, data.Code); } }
/// <summary> /// Cancel user /// </summary> private void CancelUser() { Response.Redirect(LinkHelper.GetAdminLink("user")); }
protected void Page_Load(object sender, EventArgs e) { hypHomePage.HRef = LinkHelper.GetLink("trang-chu"); }
public async Task Vote([Remainder] string str = "") { await Context.Channel.SendMessageAsync(embed : new EmbedBuilderPrepared(Context.User) .WithDescription($"Vote for Namiko on [Discord Bots]({LinkHelper.GetRedirectUrl(LinkHelper.Vote, "Vote", "cmd-vote")}) and receive a lootbox!") .Build()); }
public ActionResult Index() { IToDoListsRepository toDoListsRepository = new ToDoListsRepository(db); IWorkDonesRepository workDonesRepository = new WorkDonesRepository(db); IUsersRepository usersRepository = new UsersRepository(db); int page = !String.IsNullOrWhiteSpace(Request.QueryString["page"]) ? Convert.ToInt32(Request.QueryString["page"]) : 1; int pageSize = !String.IsNullOrWhiteSpace(Request.QueryString["pageSize"]) ? Convert.ToInt32(Request.QueryString["pageSize"]) : Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ResultsPerPage"]); string sortOrder = !String.IsNullOrWhiteSpace(Request.QueryString["sortOrder"]) ? Request.QueryString["sortOrder"] : "ASC"; string sortColumn = !String.IsNullOrWhiteSpace(Request.QueryString["sortColumn"]) ? Request.QueryString["sortColumn"] : "Deadline"; string ordering = sortColumn + " " + sortOrder; ordering = ordering.Trim(); IQueryable <ToDoListView> toDoLists = ToDoListView.GetToDoListView(toDoListsRepository.GetValid(), workDonesRepository.GetValid(), usersRepository.GetValid()) .OrderBy(ordering); string status = "obligations"; if (!String.IsNullOrWhiteSpace(Request.QueryString["Status"])) { status = Request.QueryString["Status"]; } ViewBag.dateFrom = Request.QueryString["dateFrom"] != null ? Request.QueryString["dateFrom"] : DateTime.Now.AddDays(-30).ToString("dd.MM.yyyy."); ViewBag.dateTo = Request.QueryString["dateTo"] != null ? Request.QueryString["dateTo"] : DateTime.Now.AddDays(30).ToString("dd.MM.yyyy."); ViewBag.FinishedStatuses = new SelectList(GeneratorView.GenerateFinishedStauses(), "Value", "Text", status); if (!String.IsNullOrWhiteSpace(Request.QueryString["searchString"])) { string searchString = Request.QueryString["searchString"].ToString(); toDoLists = toDoLists.Where(c => c.Name.Contains(searchString)); } if (status == "obligations") { toDoLists = toDoLists.Where(c => c.Finished == false || c.Finished == null); } else { if (status == "finished") { toDoLists = toDoLists.Where(c => c.Finished == true); } if (Request.QueryString["dateFrom"] != "") { DateTime dateFromDate = new DateTime(); dateFromDate = DateTime.ParseExact(ViewBag.dateFrom, "dd.MM.yyyy.", null); toDoLists = toDoLists.Where(c => c.Deadline >= dateFromDate); } if (Request.QueryString["dateTo"] != "") { DateTime dateToDate = new DateTime(); dateToDate = DateTime.ParseExact(ViewBag.dateTo, "dd.MM.yyyy.", null); toDoLists = toDoLists.Where(c => c.Deadline <= dateToDate); } } toDoLists = toDoLists.Page(page, pageSize); ViewData["numberOfRecords"] = toDoLists.Count(); int numberOfPages = ((int)ViewData["numberOfRecords"] + pageSize - 1) / pageSize; if (page > numberOfPages) { string url = LinkHelper.getQueryStringArray(new string[] { "page" }); return(Redirect("ToDoList?" + url + "page=" + numberOfPages)); } else { return(View("Index", toDoLists.ToList())); } }
public ObservableCollection <HeaderItem> CreateDocumentOutline(string md) { if (string.IsNullOrEmpty(md)) { return(null); } var syntax = Markdig.Markdown.Parse(md); var lines = StringUtils.GetLines(md); bool inFrontMatter = false; var list = new ObservableCollection <HeaderItem>(); foreach (var item in syntax) { var line = item.Line; var content = lines[line].TrimStart(' ', '#');; if (line == 0 && content == "---") { inFrontMatter = true; continue; } if (inFrontMatter && content == "---") { inFrontMatter = false; continue; } if (inFrontMatter) { continue; } if (item is HeadingBlock) { var heading = item as HeadingBlock; if (heading.Level > AppModel.Configuration.MaxDocumentOutlineLevel) { continue; } // underlined format if (line > 0 && (content.StartsWith("---") || content.StartsWith("==="))) { line--; content = lines[line].TrimStart(' ', '#'); } var headerItem = new HeaderItem() { Text = $"{content}", Level = heading.Level, Line = line, LinkId = LinkHelper.UrilizeAsGfm(content.TrimEnd()) }; list.Add(headerItem); } } return(list); }
/// <summary>Recursively processes a node converting HTML into PDF using tag workers.</summary> /// <param name="node">the node</param> private void Visit(INode node) { if (node is IElementNode) { IElementNode element = (IElementNode)node; element.SetStyles(cssResolver.ResolveStyles(element, context.GetCssContext())); if (!IsDisplayable(element)) { return; } ITagWorker tagWorker = context.GetTagWorkerFactory().GetTagWorker(element, context); if (tagWorker == null) { if (!ignoredTags.Contains(element.Name())) { logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.NO_WORKER_FOUND_FOR_TAG, (element) .Name())); } } else { context.GetState().Push(tagWorker); } if (tagWorker is HtmlTagWorker) { ((HtmlTagWorker)tagWorker).ProcessPageRules(node, cssResolver, context); } if (TagConstants.BODY.Equals(element.Name()) || TagConstants.HTML.Equals(element.Name())) { RunApplier(element, tagWorker); } context.GetOutlineHandler().AddOutlineAndDestToDocument(tagWorker, element, context); VisitPseudoElement(element, tagWorker, CssConstants.BEFORE); VisitPseudoElement(element, tagWorker, CssConstants.PLACEHOLDER); foreach (INode childNode in element.ChildNodes()) { if (!context.IsProcessingInlineSvg()) { Visit(childNode); } } VisitPseudoElement(element, tagWorker, CssConstants.AFTER); if (tagWorker != null) { tagWorker.ProcessEnd(element, context); LinkHelper.CreateDestination(tagWorker, element, context); context.GetOutlineHandler().SetDestinationToElement(tagWorker, element); context.GetState().Pop(); if (!TagConstants.BODY.Equals(element.Name()) && !TagConstants.HTML.Equals(element.Name())) { RunApplier(element, tagWorker); } if (!context.GetState().Empty()) { PageBreakApplierUtil.AddPageBreakElementBefore(context, context.GetState().Top(), element, tagWorker); tagWorker = ProcessRunningElement(tagWorker, element, context); bool childProcessed = context.GetState().Top().ProcessTagChild(tagWorker, context); PageBreakApplierUtil.AddPageBreakElementAfter(context, context.GetState().Top(), element, tagWorker); if (!childProcessed && !ignoredChildTags.Contains(element.Name())) { logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.WORKER_UNABLE_TO_PROCESS_OTHER_WORKER , context.GetState().Top().GetType().FullName, tagWorker.GetType().FullName)); } } else { if (tagWorker.GetElementResult() != null) { roots.Add(tagWorker.GetElementResult()); } } } element.SetStyles(null); } else { if (node is ITextNode) { String content = ((ITextNode)node).WholeText(); if (content != null) { if (!context.GetState().Empty()) { bool contentProcessed = context.GetState().Top().ProcessContent(content, context); if (!contentProcessed) { logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.WORKER_UNABLE_TO_PROCESS_IT_S_TEXT_CONTENT , context.GetState().Top().GetType().FullName)); } } else { logger.Error(iText.Html2pdf.LogMessageConstant.NO_CONSUMER_FOUND_FOR_CONTENT); } } } } }
/// <summary> /// ItemDataBound /// </summary> protected void rptResult_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { string img, alt, publishedTask; HtmlTableRow tr = (HtmlTableRow)e.Item.FindControl("trList"); HtmlInputText txt = null; if (e.Item.ItemIndex % 2 == 0) { tr.Attributes.Add("class", "even"); } else { tr.Attributes.Add("class", "old"); } try { PNK_ContentStatic data = (PNK_ContentStatic)e.Item.DataItem; //Role Literal ltr = null; ltr = (Literal)e.Item.FindControl("ltrchk"); ltr.Text = string.Format(@"<INPUT class='txt' TYPE='checkbox' ID='cb{0}' NAME='cid[]' value='{1}' onclick='isChecked(this.checked);' >", e.Item.ItemIndex, data.Id); //ltrNewsCategory ltr = (Literal)e.Item.FindControl("ltrNewsCategory"); //image if (data.Published == "1") { img = "tick.png"; alt = LocalizationUtility.GetText(ltrAdminPublish.Text); publishedTask = "unpublish"; } else { img = "publish_x.png"; alt = LocalizationUtility.GetText(ltrAdminPublish.Text); publishedTask = "publish"; } //Order txt = (HtmlInputText)e.Item.FindControl("txtOrder"); txt.Value = DBConvert.ParseString(data.Ordering); //Id HtmlInputButton btId = (HtmlInputButton)e.Item.FindControl("btId"); btId.Value = DBConvert.ParseString(data.Id); //Base img HtmlImage Image = (HtmlImage)e.Item.FindControl("Image"); Image.Src = WebUtils.GetUrlImage(ConfigurationManager.AppSettings["ContentStaticUpload"], data.Image); HtmlAnchor hypImage = (HtmlAnchor)e.Item.FindControl("hypImage"); //set link HyperLink hdflink = new HyperLink(); hdflink = (HyperLink)e.Item.FindControl("hdflink"); hypImage.HRef = hdflink.NavigateUrl = template_path + LinkHelper.GetAdminLink("edit_contentstatic", data.Id); ImageButton imgctr = (ImageButton)e.Item.FindControl("btnPublish"); imgctr.ImageUrl = string.Format("/Admin/images/{0}", img); imgctr.Attributes.Add("alt", alt); HtmlTableCell btn = (HtmlTableCell)e.Item.FindControl("tdbtn"); btn.Attributes.Add("onclick", string.Format(" return listItemTask('cb{0}', '{1}')", e.Item.ItemIndex, publishedTask)); //Name ltr = (Literal)e.Item.FindControl("ltrName"); hypImage.Title = ltr.Text = data.ContentStaticDesc.Title; } catch { } } }
public ObservableCollection <HeaderItem> CreateDocumentOutline(string md) { if (string.IsNullOrEmpty(md)) { return(null); } // create a full pipeline to strip out front matter/yaml var parser = new MarkdownParserMarkdig(); var builder = parser.CreatePipelineBuilder(); var syntax = Markdig.Markdown.Parse(md, builder.Build()); var list = new ObservableCollection <HeaderItem>(); foreach (var item in syntax) { var line = item.Line; if (item is HeadingBlock) { var heading = item as HeadingBlock; var inline = heading?.Inline?.FirstChild; if (inline == null) { continue; } StringBuilder sb = new StringBuilder(); foreach (var inl in heading.Inline) { if (inl is HtmlEntityInline) { var htmlEntity = inl as HtmlEntityInline; sb.Append(WebUtility.HtmlDecode(htmlEntity.Transcoded.ToString())); } else if (inl is CodeInline) { var codeInline = inl as CodeInline; sb.Append(WebUtility.HtmlDecode(codeInline.Content)); } else if (inl is LinkInline) { var link = inl as LinkInline; var textInline = link?.FirstOrDefault(l => l is LiteralInline)?.ToString(); if (textInline == null) { textInline = "-- non-text header --"; } sb.Append(WebUtility.HtmlDecode(textInline)); } else { sb.Append(inl.ToString()); } } var content = sb.ToString(); if (content.Contains("\n")) { continue; } if (heading.Level > AppModel.Configuration.MaxDocumentOutlineLevel) { continue; } var headerItem = new HeaderItem() { Text = content, Level = heading.Level, Line = line, LinkId = LinkHelper.UrilizeAsGfm(content.TrimEnd()) }; list.Add(headerItem); } } return(list); }
public void clickOnEditButton() { LinkHelper.click(editButton); }
/// <summary> /// Cancel content /// </summary> private void CancelContentStaticCategory() { string url = LinkHelper.GetAdminLink("contentstatic"); Response.Redirect(url); }
public void TestUrilizeOnlyAscii_Numeric(string input, string expectedResult) { Assert.AreEqual(expectedResult, LinkHelper.Urilize(input, true)); }
public void WhenUserSelectsEmailTemplateOption() { Thread.Sleep(5000); LinkHelper.ClickLink(By.XPath("//span[contains(text(),'Email Template')]")); //JavaScriptExecutor.ScrollToAndClick(By.XPath("//span[text()='Email Template']")); }
public void TestUrilizeNonAscii_NonValidCharactersForFragments(string input, string expectedResult) { Assert.AreEqual(expectedResult, LinkHelper.Urilize(input, false)); }
public void DownloadsPageView() { LinkHelper.ClickLink(_downloadsLink); }