public static void Test() { HTMLInputElement input = new HTMLInputElement(); input.OnChange += (ev) => { // Tests if ev.CurrentTarget.Value compiles Console.WriteLine("ev.CurrentTarget.Value: " + ev.CurrentTarget.Value); // Tests if ev.IsMouseEvent() compiles Console.WriteLine("IsMouseEvent: " + ev.IsMouseEvent()); }; HTMLAnchorElement anchor = new HTMLAnchorElement(); anchor.OnClick += (ev) => { // Tests if ev.CurrentTarget.Href compiles Console.WriteLine("ev.CurrentTarget.Href: " + ev.CurrentTarget.Href); }; // Test if Document.GetElementById<>() compiles HTMLDivElement div = Document.GetElementById <HTMLDivElement>("div1"); // Tests if Element is still a superclass of all the element classes and the following code compiles HTMLElement element; element = new HTMLInputElement(); element = new HTMLTextAreaElement(); }
public void DefaultAction() { if (Data.Type == EventTypes.Click) { WrappedObject tempTarget = Target; HTMLAnchorElement anchorElement = tempTarget as HTMLAnchorElement; tempTarget = tempTarget.Parent; while (anchorElement == null && tempTarget != null) { anchorElement = tempTarget as HTMLAnchorElement; tempTarget = tempTarget.Parent; } if (anchorElement != null) { string newHref = anchorElement.Href; if (newHref != null) { ContentWindow window = mdr.Runtime.Instance.GlobalContext as ContentWindow; Debug.Assert(window != null, "In handling the default action for Click Content Window cannot be retrived!"); if (window != null) { Location loc = window.Location; Debug.Assert(loc != null, "In handling the default action for Click Content Window location cannot be retrived!"); if (loc != null) { loc.Href = newHref; Debug.WriteLine("Setting href of window location to {0}", newHref); } } } } } }
public HTMLDivElement getItemBoxElement(HTMLAnchorElement linkEle) { if (linkEle == null) { return(null); } IHTMLElement parentEle = linkEle.parentElement;//"col seller" if (parentEle == null) { return(null); } IHTMLElement grandParentEle = parentEle.parentElement;//"class="row"" if (grandParentEle == null) { return(null); } IHTMLElement grandParentEle2 = grandParentEle.parentElement;//"item box" if (grandParentEle2 == null) { return(null); } return((HTMLDivElement)grandParentEle2); }
public void ClickAnchorWithValue(string anchorValue) { HTMLAnchorElement anchor = (HTMLAnchorElement)GetElementByValue("A", anchorValue); anchor.click(); WaitForComplete(); }
public static void Insertlink(IHTMLDocument2 m_pDoc2, HTMLDesignControl htmlDesigner) { string innerText = ""; if (m_pDoc2.selection.type == "Text")//如果选中的是文本 { IHTMLTxtRange searchRange = (IHTMLTxtRange)m_pDoc2.selection.createRange(); innerText = searchRange.htmlText;//获取文本的html代码 } if (m_pDoc2.selection.type == "Control")//如果选中的控件 { /* IHTMLTxtRange searchRange = (IHTMLTxtRange)m_pDoc2.selection.createRange(); * innerText = searchRange.htmlText;//获取文本的html代码*/ } frmInsertLinkCode insertLink = new frmInsertLinkCode(); HTMLAnchorElement linkEle = htmlDesigner.CurrentElement as HTMLAnchorElement; if (linkEle != null) {//给弹出的控件赋值 string hrefStr = linkEle.href.Replace("about:blank", "").Replace("about:", ""); if (hrefStr.IndexOf("#") > 0) { insertLink.linkUrl = hrefStr.Substring(0, hrefStr.IndexOf("#")); insertLink.BookMark = hrefStr.Substring(1 + hrefStr.IndexOf("#")); insertLink.linkTarget = linkEle.target; insertLink.LinkTip = linkEle.title; insertLink.AccessKey = linkEle.accessKey; } else { insertLink.linkUrl = hrefStr; } } if (insertLink.ShowDialog() == DialogResult.OK) { //从弹出的控件中取值 if ((m_pDoc2.selection.type == "None") && (htmlDesigner.LinkBe != null))//如果没有选中文本,则对当前链接进行更改,否则插入新链接 { htmlDesigner.LinkBe.Element.href = insertLink.linkUrl; htmlDesigner.LinkBe.Element.target = insertLink.linkTarget; htmlDesigner.LinkBe.Element.accessKey = insertLink.AccessKey; // htmlDesigner.LinkBe.Element.tabIndex = insertLink.BookMark; } else { m_pDoc2.selection.clear(); string linkURL = insertLink.linkUrl; string linkTarget = insertLink.linkTarget; string linkAccesskey = insertLink.AccessKey; string linkTip = insertLink.LinkTip; string linkBookMark = insertLink.BookMark; LINK link = new LINK(); string insertlinkhtml = link.LinkHtml(innerText, linkURL, linkTarget, linkTip, linkAccesskey, linkBookMark); AddToSelection(m_pDoc2, insertlinkhtml, ""); } } }
private static async Task Main() { var allTestItemDetails = GetTestsToRun().ToArray(); if (!allTestItemDetails.Any()) { document.body.appendChild(GetMessage("There were no tests found to run", hrefIfTextShouldLink: null, isSuccess: false)); return; } var testNamesToFilterTo = new HashSet <string>(GetAnyTestsSpecifiedInQueryString()); // If this is empty then ALL tests will be run var(summaryContentToDisplay, setStatus, setSuccessCount, setFailureCount, setSkippedCount) = GetRunningSummary(allTestItemDetails.Length, showSkippedCount: testNamesToFilterTo.Any()); // Only show the number of skipped tests if not running them all document.body.appendChild(summaryContentToDisplay); var failureContainer = document.createElement("div"); document.body.appendChild(failureContainer); var successContainer = document.createElement("div"); document.body.appendChild(successContainer); var skipped = new List <TestDetails>(); var successes = new List <TestDetails>(); var failures = new List <TestDetails>(); foreach (var testItemDetails in allTestItemDetails) { if (testNamesToFilterTo.Any() && !testNamesToFilterTo.Contains(testItemDetails.FullName) && !testNamesToFilterTo.Contains(testItemDetails.DisplayName)) { skipped.Add(testItemDetails); setSkippedCount(skipped.Count); } else if (ExecuteTest(testItemDetails, showDetailedInformation: testNamesToFilterTo.Any(), successContainer, failureContainer)) { successes.Add(testItemDetails); setSuccessCount(successes.Count); } else { failures.Add(testItemDetails); setFailureCount(failures.Count); } await Task.Delay(1); // Give the UI a chance to update if there have been tests that don't complete almost instantly } setStatus("Completed"); if (testNamesToFilterTo.Any()) { var runAllTestsLinks = new HTMLAnchorElement { href = GetHrefForDisablingFiltering() }; runAllTestsLinks.innerText = "Return to running all tests"; runAllTestsLinks.style.padding = "0 0.5rem"; runAllTestsLinks.style.color = "black"; document.body.appendChild(runAllTestsLinks); } }
public static HTMLAnchorElement A(Attributes init, params HTMLElement[] children) { var a = new HTMLAnchorElement(); init?.InitAnchorElement(a); AppendElements(a, children); return(a); }
public void ClickAnchor(string anchorId) { isDocumentComplete = false; HTMLAnchorElement input = GetAnchorElement(anchorId); input.click(); WaitForComplete(); }
// private void button5_Click(object sender, EventArgs e) { HTMLAnchorElement musicAnchor = (HTMLAnchorElement)w.GetElementByTAV("a", "href", "/music"); w.BeginPageLoading(); musicAnchor.click(); w.WaitForComplete(); }
private void InitBrowser() { Control = new WebBrowser(); Control.HorizontalAlignment = HorizontalAlignment.Stretch; Control.LoadCompleted += (s, e) => { Zoom(_zoomFactor); _htmlDocument = (HTMLDocument)Control.Document; _cachedHeight = _htmlDocument.body.offsetHeight; _htmlDocument.documentElement.setAttribute("scrollTop", _positionPercentage * _cachedHeight / 100); foreach (IHTMLElement link in _htmlDocument.links) { HTMLAnchorElement anchor = link as HTMLAnchorElement; if (anchor == null || anchor.protocol != "file:") { continue; } HTMLAnchorEvents_Event handler = anchor as HTMLAnchorEvents_Event; if (handler == null) { continue; } string file = anchor.pathname.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); if (!File.Exists(file)) { anchor.title = "The file does not exist"; return; } handler.onclick += () => { ProjectHelpers.OpenFileInPreviewTab(file); return(true); }; } }; // Open external links in default browser Control.Navigating += (s, e) => { if (e.Uri == null) { return; } e.Cancel = true; if (e.Uri.IsAbsoluteUri && e.Uri.Scheme.StartsWith("http")) { Process.Start(e.Uri.ToString()); } }; }
public void ClickAnchorWithParent(string parentControlId, string anchorId) { isDocumentComplete = false; anchorId = parentControlId + anchorId; HTMLAnchorElement input = GetAnchorElement(anchorId); input.click(); WaitForComplete(); }
public Link(string url, IComponent component, bool noUnderline = false) { _anchor = A(_(href: url), component.Render()); if (noUnderline) { _anchor.classList.add("tss-link-no-underline"); } }
private HTMLAnchorElement GetAnchorElement(HTMLDocument htmlDocument, string buttonText) { HTMLAnchorElement anchorElement = (HTMLAnchorElement)htmlDocument.CreateElement("a"); Text backwardText = htmlDocument.CreateTextNode(buttonText); anchorElement.SetAttribute("class", "button"); anchorElement.AppendChild(backwardText); return(anchorElement); }
public static void ClickLogin(WebUtil w) { HTMLAnchorElement loginElement = (HTMLAnchorElement)w.GetElementByValue("a", "href", "/login"); if (loginElement != null) { w.BeginPageLoading(); loginElement.click(); w.WaitForComplete(); //block main thread until loaded event is fired } }
public AnchorBasedActionView(LabelDescr lbl, string title = null) { if (lbl.Label == null && lbl.PreLabelIcon == null) { throw new Exception("cannot have labelless and icon less in the same time"); } _a = new HTMLAnchorElement { Href = "#", ClassName = GetType().FullNameWithoutGenerics(), Title = title ?? "" }; var preLabel = Document.CreateElement("div"); _a.AppendChild(preLabel); if (lbl.PreLabelIcon != null) { preLabel.AddClasses(lbl.PreLabelIcon.Item1.ToCssClassName()); preLabel.TextContent = lbl.PreLabelIcon.Item2; } var label = Document.CreateElement("div"); _a.AppendChild(label); label.TextContent = lbl.Label ?? ""; Enabled = true; //initialize css class _a.OnClick += ev => { Logger.Debug(GetType(), "handling onclick"); if (OnClickPreventsDefault) { ev.PreventDefault(); } if (ev.HasHtmlTarget() && !ShouldTriggerOnTarget(ev.HtmlTarget())) { return; } if (!Enabled || State.Type == ActionViewStateType.OperationRunning) { return; } Triggered?.Invoke(); }; }
public void NormalizeRemovesEmptyTextNodesNested() { var div = new HTMLDivElement(); var a = new HTMLAnchorElement(); a.AppendChild(new TextNode()); a.AppendChild(new TextNode("Not empty.")); div.AppendChild(a); div.AppendChild(new TextNode()); div.AppendChild(new HTMLDivElement()); div.AppendChild(new TextNode("Certainly not empty!")); div.AppendChild(new HTMLImageElement()); div.Normalize(); Assert.AreEqual(a.ChildNodes.Length, 1); }
static void AddNewSheetTab() { var tabControl = Document.GetElementById("TabControl"); _newSheetTab = new HTMLLIElement(); _newSheetTab.Id = "new-sheet"; var anchor = new HTMLAnchorElement(); anchor.ClassName = "new-sheet-anchor"; anchor.TextContent = "+"; anchor.Href = "#"; _newSheetTab.AppendChild(anchor); tabControl.AppendChild(_newSheetTab); }
public void NormalizeMergeTextNodes() { var div = new HTMLDivElement(); var a = new HTMLAnchorElement(); a.AppendChild(new TextNode()); a.AppendChild(new TextNode("Not empty.")); div.AppendChild(a); div.AppendChild(new TextNode()); div.AppendChild(new HTMLDivElement()); div.AppendChild(new TextNode("Certainly not empty!")); div.AppendChild(new TextNode("Certainly not empty!")); div.AppendChild(new TextNode("Certainly not empty!")); div.AppendChild(new TextNode("Certainly not empty!")); div.AppendChild(new HTMLImageElement()); div.Normalize(); Assert.AreEqual(div.ChildNodes.Length, 4); }
/// <summary> /// /// </summary> /// <param name="inputElement"></param> /// <param name="identifier"></param> /// <param name="value"></param> /// <returns></returns> private static wxAction GetLink(HtmlElement inputElement, string identifier, string value) { string name = "Captured Link"; HTMLAnchorElement iElement = inputElement.DomElement as HTMLAnchorElement; if (inputElement.OuterHtml.Contains("wmPopupOpen")) { name = "PopUp LINK"; } //if (iElement.target == null) // return null; if (identifier == String.Empty) { identifier = "innertext"; value = inputElement.InnerText; } return(new wxActLink("", identifier, value)); }
private static HTMLElement GetMessage(string text, string hrefIfTextShouldLink, bool isSuccess, string additionalInfo = null) { var wrapper = new HTMLDivElement(); wrapper.style.color = "white"; wrapper.style.backgroundColor = isSuccess ? "#0a0" : "#c00"; wrapper.style.border = "1px solid " + (isSuccess ? "#080" : "#900"); wrapper.style.borderRadius = "0.25rem"; wrapper.style.padding = "0.5rem 1rem"; wrapper.style.marginBottom = "0.5rem"; var messageContainer = new HTMLDivElement(); wrapper.appendChild(messageContainer); HTMLElement message; if (string.IsNullOrWhiteSpace(hrefIfTextShouldLink)) { message = new HTMLSpanElement(); } else { message = new HTMLAnchorElement { href = hrefIfTextShouldLink }; message.style.color = wrapper.style.color; message.style.textDecoration = "none"; } message.innerText = text; messageContainer.appendChild(message); if (!string.IsNullOrWhiteSpace(additionalInfo)) { var additionalMessage = new HTMLDivElement { innerText = additionalInfo }; additionalMessage.style.fontSize = "0.8rem"; wrapper.appendChild(additionalMessage); } return(wrapper); }
public static void eleClick(this WebBrowser wb, string tag, string data) { HtmlElementCollection eleCollection = wb.Document.GetElementsByTagName(tag); foreach (HtmlElement ele in eleCollection) { if (ele.InnerHtml.ToCString().ToLower() == data) { switch (tag) { case "a": HTMLAnchorElement ancele = (HTMLAnchorElement)ele.DomElement; ancele.click(); break; } break; } } }
/// <summary> /// Adjust the file-based anchors so that they are navigable on the local file system /// </summary> /// <remarks>Anchors using the "file:" protocol appear to be blocked by security settings and won't work. /// If we convert them to use the "about:" protocol so that we recognize them, we can open the file in /// the <c>Navigating</c> event handler.</remarks> private void AdjustAnchors() { try { foreach (IHTMLElement link in _htmlDocument.links) { HTMLAnchorElement anchor = link as HTMLAnchorElement; if (anchor != null && anchor.protocol == "file:") { string pathName = null, hash = anchor.hash; // Anchors with a hash cause a crash if you try to set the protocol without clearing the // hash and path name first. if (hash != null) { pathName = anchor.pathname; anchor.hash = null; anchor.pathname = String.Empty; } anchor.protocol = "about:"; if (hash != null) { // For an in-page section link, use "blank" as the path name. These don't work // anyway but this is the proper way to handle them. if (pathName == null || pathName.EndsWith("/")) { pathName = "blank"; } anchor.pathname = pathName; anchor.hash = hash; } } } } catch { // Ignore exceptions } }
public static void eleClick(this WebBrowser wb, string id) { HtmlElement ele = wb.Document.All[id]; if (ele.IsNotNull()) { switch (ele.TagName.ToLower()) { case "input": HTMLButtonElement btnele = (HTMLButtonElement)ele.DomElement; btnele.click(); break; case "a": HTMLAnchorElement ancele = (HTMLAnchorElement)ele.DomElement; ancele.click(); break; } } }
public static void Main() { var body = Document.Body; HTMLDivElement msg = new HTMLDivElement { Id = "MsgPanel" }; HTMLAnchorElement linkbtn = new HTMLAnchorElement { Href = "#", InnerHTML = "Click", OnClick = (ev) => { HTMLDivElement msgpanel = Document.GetElementById <HTMLDivElement>("MsgPanel"); msgpanel.InnerHTML = "MyText"; } }; body.AppendChild(linkbtn); body.AppendChild(msg); }
public static void GoToProfile(WebUtil w) { HTMLUListElement ullist = (HTMLUListElement)w.GetUList("ul", "class", "visible-menu"); HTMLAnchorElement anchor = null; int i = 0; foreach (HTMLLIElement element in ullist.getElementsByTagName("li")) { if (i == 0) { anchor = (HTMLAnchorElement)element.firstChild; i += 1; } } w.BeginPageLoading(); if (anchor != null) { anchor.click(); } w.WaitForComplete(); }
private void MainBrowser_LoadCompleted(object sender, NavigationEventArgs e) { HTMLDocument doc = (mshtml.HTMLDocument) this.MainBrowser.Document; foreach (IHTMLElement link in doc.links) { HTMLAnchorElement anchor = link as HTMLAnchorElement; if (anchor != null) { HTMLAnchorEvents_Event handler = anchor as HTMLAnchorEvents_Event; if (handler != null) { handler.onclick += new HTMLAnchorEvents_onclickEventHandler(delegate() { Console.WriteLine("You clicks the link: " + anchor.href); Process.Start(anchor.href); // MainBrowser.NavigateToString(mail.Message); return(true); }); } } } }
public bool searchBroswer(SHDocVw.WebBrowser wb, string keyword) { HTMLDocument document = ((HTMLDocument)wb.Document); currentDoc = document; IHTMLElement element = document.getElementById("q"); HTMLInputElement searchKW = (HTMLInputElement)element; //HTMLInputElementClass searchKW = (HTMLInputElementClass)element; searchKW.value = keyword; //Point docHeight = new Point(document.body.offsetLeft, document.body.offsetTop); //ClientToScreen((IntPtr)wb.HWND, ref docHeight); //var rectDoc = document.body.getBoundingClientRect(); //RECT rct; //if (!GetWindowRect((IntPtr)element.HWND, out rct)) //{ // MessageBox.Show("ERROR"); // return false; //} var elements = document.getElementsByTagName("button"); foreach (HTMLButtonElement searchBTN in elements) { // If there's more than one button, you can check the //element.InnerHTML to see if it's the one you want if (searchBTN.innerHTML.Contains("搜 索")) { int randX = rndGenerator.Next(0, searchBTN.offsetWidth - 1); int randY = rndGenerator.Next(0, searchBTN.offsetHeight - 1); var rect = searchBTN.getBoundingClientRect(); Point p = new Point(rect.left + randX, rect.top + randY); ClientToScreen((IntPtr)wb.HWND, ref p); //p = this.PointToScreen(p); SetCursorPos(p.X, p.Y); //Thread.Sleep(6000); searchBTN.click(); break; } } while (wb.Busy) { Thread.Sleep(100); } HTMLAnchorElement foundAnchorEle = null; var linkElements = document.getElementsByTagName("a"); foreach (HTMLAnchorElement linkEle in linkElements) { // If there's more than one button, you can check the //element.InnerHTML to see if it's the one you want if (linkEle.innerText == null) { continue; } if (linkEle.innerText.Contains(sellerNameTB.Text.Trim())) { //int randX = rndGenerator.Next(0, searchBTN.offsetWidth - 1); //int randY = rndGenerator.Next(0, searchBTN.offsetHeight - 1); //var rect = searchBTN.getBoundingClientRect(); //Point p = new Point(rect.left + randX, rect.top + randY); //ClientToScreen((IntPtr)wb.HWND, ref p); ////p = this.PointToScreen(p); //SetCursorPos(p.X, p.Y); ////Thread.Sleep(6000); //searchBTN.click(); foundAnchorEle = linkEle; break; } } if (foundAnchorEle == null) { return(false); } //if found first scroll the page if (compareCB.Checked == true) { //货比三家 randVisitOther(document); } #region //search load #endregion Thread.Sleep(1000); return(true); }
public static bool ProcessChunk(int TopicId, int n, List <Article> Forum, DateTime from, ref string TopicName) { bool foundNew = false; string fromStr = from.ToString("yyyy.MM.dd"); // STEP SHOULD BE 100!!! string page = GetHtml("http://forum.index.hu/Article/showArticle?na_start=" + n * 100 + "&na_step=100&t=" + TopicId.ToString()); IHTMLDocument2 doc = (IHTMLDocument2) new HTMLDocument(); doc.write(page); foreach (IHTMLElement el in doc.all) { if (el.tagName == "TITLE" && TopicName == "") // <table class="art"> { TopicName = el.innerText; } if (el.tagName == "TABLE" && el.className == "art") // <table class="art"> { Article art = new Article(); foreach (IHTMLElement ell in el.all) { if (ell.tagName == "SPAN" && ell.className == "art_nr") // ez a hozzaszolas sorszama { var id = ell.innerText; try { art.Id = int.Parse(id); } catch { art.Id = 0; } } else if (ell.tagName == "TD" && ell.className != null && ell.className.StartsWith("art_h_l")) // ez a user adatai { foreach (IHTMLElement inn in ell.all) { HTMLAnchorElement a = inn as HTMLAnchorElement; if (a != null) { string href = a.href; if (href != null && href.StartsWith("about:")) { if (href.StartsWith("about:/User/UserDescription?u=")) { art.UserName = a.innerText; art.UserId = int.Parse(href.Substring("about:/User/UserDescription?u=".Length)); } else if (href.StartsWith("about:/Article/viewArticle?a=")) { string s = href.Substring("about:/Article/viewArticle?a=".Length); art.RefId = int.Parse(s.Split('&')[0]); } } } } var msg = ell.innerText; // ez a user neve + datum egyben, ami jo is nekunk! string[] parts = msg.Split(' '); if (msg.Contains("napja") || msg.Contains("órája") || msg.Contains("perce")) { art.Date = parts[parts.Length - 3] + " " + parts[parts.Length - 2]; } else { art.Date = parts[parts.Length - 2]; } } else if (ell.tagName == "TR" && ell.className == "art_b") // ez a hozzaszolas maga { var msg = ell.innerText; if (msg != null) { art.Message = msg; } var mmm = ell.innerHTML; // "http://imgfrm.index.hu/imgfrm/5/8/6/2/MED_0014095862.png\"></P></DIV></TD>" string // "http://imgfrm.index.hu/imgfrm/5/8/6/2/BIG_0014095862.png')\" title=\"\" class=\"tn_img tn_img14095862 tn_img_10\" border=0 alt=\"\" // "http://imgfrm.index.hu/imgfrm/5/8/6/2/MED_0014095862.png\"></P></DIV></TD>" string int ix = ell.innerHTML.IndexOf("http://imgfrm.index.hu/"); while (ix != -1) { int iyPNG = ell.innerHTML.IndexOf(".png", ix + 1); int iyJPG = ell.innerHTML.IndexOf(".jpg", ix + 1); int iy = -1; if (iyPNG == -1) { iy = iyJPG; } else if (iyJPG == -1) { iy = iyPNG; } else if (iyJPG > iyPNG) { iy = iyPNG; } else { iy = iyJPG; } if (iy != -1) { string img = ell.innerHTML.Substring(ix, iy - ix + 4); if (!art.Imgs.Contains(img)) { art.Imgs.Add(img); } ix = ell.innerHTML.IndexOf("http://imgfrm.index.hu/", iy); } else { ix = -1; } } } else if (ell.tagName == "TR" && ell.className == "art_f") // ez az elozmeny { var msg = ell.innerText; int pos = msg.IndexOf('('); if (pos > 1) { int posEnd = msg.IndexOf(')', pos); art.ReplyToId = int.Parse(msg.Substring(pos + 1, posEnd - pos - 1)); } } } if (!art.Date.Contains('.') || (art.Date.CompareTo(fromStr) >= 0)) { Forum.Add(art); foundNew = true; } } } return(foundNew); }
public HTMLDivElement getItemBoxElement(HTMLAnchorElement linkEle) { if (linkEle == null) { return null; } IHTMLElement parentEle = linkEle.parentElement;//"col seller" if (parentEle == null) { return null; } IHTMLElement grandParentEle = parentEle.parentElement;//"class="row"" if (grandParentEle == null) { return null; } IHTMLElement grandParentEle2 = grandParentEle.parentElement;//"item box" if (grandParentEle2 == null) { return null; } return (HTMLDivElement)grandParentEle2; }
//TODO refactor this monster private static Tuple <HTMLElement, DataGridColumnControllerResult <InternalT> > Create <InternalT, OperT, ViewT>( Func <InternalT, OperT> toOper, ITransformationMediator listener, FilterDef <OperT>[] availableFilters, IEnumerable <AggregatorDef <OperT> > rawAvailableAggregators, IEnumerable <GrouperDef <OperT> > rawAvailableGroupers, Func <IReadWriteValue <OperT>, IReadWriteValueView <HTMLElement, ViewT> > paramEditor, OperT initialFilterValue, OperT invalidFilterValue, IComparer <OperT> sortingImpl) { var availableAggregators = rawAvailableAggregators.ToList(); var availableGroupers = rawAvailableGroupers.ToList(); AssureUnique(availableFilters, x => x.Label); AssureUnique(availableAggregators, x => x.Label); AssureUnique(availableGroupers, x => x.Label); LocalValue <AggregatorDef <OperT> > aggregateFunc = null; LocalValue <GrouperDef <OperT> > groupingFunc = null; LocalValue <GroupOrAggregate?> groupOrAggregateChoice = null; FilterDef <OperT> currentFilterImplOrNull = null; var filterLabelToImpl = new Dictionary <string, FilterDef <OperT> >(); availableFilters.ForEach(x => filterLabelToImpl.Add(x.Label, x)); AggregatorDef <OperT> currentAggrImplOrNull = null; var aggregLabelToImpl = new Dictionary <string, AggregatorDef <OperT> >(); availableAggregators.ForEach(x => aggregLabelToImpl.Add(x.Label, x)); GrouperDef <OperT> currentGrouperImplOrNull = null; var grouperLabelToImpl = new Dictionary <string, GrouperDef <OperT> >(); availableGroupers.ForEach(x => grouperLabelToImpl.Add(x.Label, x)); var filterParam = new LocalValue <OperT>(initialFilterValue, invalidFilterValue); HTMLElement controllerElem = new HTMLSpanElement { ClassName = Magics.CssClassFilterMainContainer }; var actionContainer = new HTMLSpanElement { ClassName = Magics.CssClassFilterActionContainer }; controllerElem.AppendChild(actionContainer); var groupOrAggregateChoiceView = new RadioBasedSingleChoice(); Element GetLabelTh() { var filterTh = controllerElem.ParentElement; var filterTr = filterTh.ParentElement; var thead = filterTr.ParentElement; var iCol = filterTr.IndexOfChild(filterTh); var labelTr = thead.GetChildAtOrNull(0); var labelTh = labelTr.GetChildAtOrNull(iCol); return(labelTh); } void MarkAsGrouped(bool activated) { Logger.Debug(typeof(DataGridColumnController), "markAsGrouped({0})", activated); controllerElem.ParentElement.AddOrRemoveClass(activated, Magics.CssClassActive); GetLabelTh().AddOrRemoveClass(activated, Magics.CssClassWithGrouping); controllerElem.ParentElement.AddOrRemoveClass(activated, Magics.CssClassWithGrouping); } void MarkAsAggregated(bool activated) { Logger.Debug(typeof(DataGridColumnController), "markAsAggregated({0})", activated); controllerElem.ParentElement.AddOrRemoveClass(activated, Magics.CssClassActive); GetLabelTh().AddOrRemoveClass(activated, Magics.CssClassWithAggregation); controllerElem.ParentElement.AddOrRemoveClass(activated, Magics.CssClassWithAggregation); } void MarkAsFiltered(bool activated) { Logger.Debug(typeof(DataGridColumnController), "markAsFiltered({0})", activated); controllerElem.ParentElement.AddOrRemoveClass(activated, Magics.CssClassActive); GetLabelTh().AddOrRemoveClass(activated, Magics.CssClassWithFilter); controllerElem.ParentElement.AddOrRemoveClass(activated, Magics.CssClassWithFilter); } var removeFilter = new HTMLAnchorElement { Target = "#", Title = I18n.Translate("Remove filter"), Text = FontAwesomeSolid.IconFilter }; removeFilter.AddClasses(Magics.CssClassFilterRemove, IconFontType.FontAwesomeSolid.ToCssClassName()); actionContainer.AppendChild(removeFilter); var removeFilterActionView = new InputTypeButtonActionView(removeFilter); LocalActionBuilder.Build(removeFilterActionView, () => { currentFilterImplOrNull = null; MarkAsFiltered(false); listener.UserFilterChangedHandler(ChangeOrRemove.Removed); }); var removeGrouping = new HTMLAnchorElement { Target = "#", Title = I18n.Translate("Remove grouping"), Text = FontAwesomeSolid.IconListUl }; removeGrouping.AddClasses(Magics.CssClassGroupingRemove, IconFontType.FontAwesomeSolid.ToCssClassName()); actionContainer.AppendChild(removeGrouping); var removeGroupingActionView = new InputTypeButtonActionView(removeGrouping); LocalActionBuilder.Build(removeGroupingActionView, async() => { currentGrouperImplOrNull = null; MarkAsGrouped(false); await groupOrAggregateChoice.DoChange(null, false, null, false); listener.UserGroupingChangedHandler(ChangeOrRemove.Removed); }); var removeAggregation = new HTMLAnchorElement { ClassName = Magics.CssClassAggregationRemove, Target = "#", Title = I18n.Translate("Remove aggregation"), Text = "Σ" }; actionContainer.AppendChild(removeAggregation); var removeAggregationActionView = new InputTypeButtonActionView(removeAggregation); LocalActionBuilder.Build(removeAggregationActionView, async() => { currentAggrImplOrNull = null; await groupOrAggregateChoice.DoChange(null, false, null, false); MarkAsAggregated(false); listener.UserAggregationChangedHandler(ChangeOrRemove.Removed); }); Action <string> groupingChangedHandler = async labelOrNull => { Logger.Debug(typeof(DataGridColumnController), "Setting grouping programmatically to {0}", labelOrNull); if (labelOrNull == null) { currentGrouperImplOrNull = null; MarkAsGrouped(false); await groupOrAggregateChoice.DoChange(null, false, null, false); return; } GrouperDef <OperT> grouper; if (!grouperLabelToImpl.TryGetValue(labelOrNull, out grouper)) { Logger.Debug(typeof(DataGridColumnController), "No such grouping func when looking by label"); return; } await groupingFunc.DoChange(grouper, false, null, false); currentGrouperImplOrNull = grouper; MarkAsGrouped(true); }; Action <string> aggregationChangedHandler = async labelOrNull => { Logger.Debug(typeof(DataGridColumnController), "Setting aggregation programmatically to {0}", labelOrNull); if (labelOrNull == null) { currentAggrImplOrNull = null; MarkAsAggregated(false); await groupOrAggregateChoice.DoChange(null, false, null, false); listener.UserAggregationChangedHandler(ChangeOrRemove.Removed); return; } if (!aggregLabelToImpl.TryGetValue(labelOrNull, out var aggr)) { Logger.Debug(typeof(DataGridColumnController), "No such aggregation func when looking by label"); return; } await aggregateFunc.DoChange(aggr, false, null, false); currentAggrImplOrNull = aggr; MarkAsAggregated(true); }; listener.InitUserSide(groupingChangedHandler, aggregationChangedHandler); var filterOper = new LocalValue <FilterDef <OperT> >(availableFilters.FirstOrDefault()); var filterOperView = new DropDownSelectBox("") { PermittedValues = filterLabelToImpl.Select(x => Tuple.Create(x.Key, x.Key)) }; filterOperView.BindReadWriteAndInitialize(filterOper, x => x != null ? Tuple.Create(x.Label, x.Label) : Tuple.Create("", ""), x => !string.IsNullOrEmpty(x.Item1) ? filterLabelToImpl[x.Item1] : null); controllerElem.AppendChild(filterOperView.Widget); var val = paramEditor(filterParam); controllerElem.AppendChild(val.Widget); filterParam.Changed += (_, __, newValue, ___, isUserChange) => { if (!isUserChange) { return; } currentFilterImplOrNull = filterOper.Value; MarkAsFiltered(true); listener.UserFilterChangedHandler(ChangeOrRemove.Changed); }; filterOper.Changed += (_, __, newValue, ___, isUserChange) => { if (!isUserChange) { return; } currentFilterImplOrNull = newValue; MarkAsFiltered(true); listener.UserFilterChangedHandler(ChangeOrRemove.Changed); }; { groupOrAggregateChoice = new LocalValue <GroupOrAggregate?>(null); groupOrAggregateChoiceView.Widget.ClassList.Add(Magics.CssClassGroupOrAggregate); groupOrAggregateChoiceView.PermittedValues = EnumExtensions.GetEnumValues <GroupOrAggregate>().Select(x => Tuple.Create(((int)x).ToString(), x.GetUserFriendlyName())); groupOrAggregateChoiceView.BindReadWriteAndInitialize(groupOrAggregateChoice, x => !x.HasValue ? null : Tuple.Create(((int)x).ToString(), x.Value.GetUserFriendlyName()), x => (x == null || string.IsNullOrEmpty(x.Item1)) ? null : (GroupOrAggregate?)Convert.ToInt32(x.Item1)); groupingFunc = new LocalValue <GrouperDef <OperT> >(availableGroupers.FirstOrDefault()); var groupingFuncView = new DropDownSelectBox(I18n.Translate("group by:")); groupingFuncView.Widget.ClassList.Add(Magics.CssClassGroupingFunc); groupingFuncView.PermittedValues = grouperLabelToImpl.Select(x => Tuple.Create(x.Key, x.Key)); groupingFuncView.BindReadWriteAndInitialize(groupingFunc, x => x != null ? Tuple.Create(x.Label, x.Label) : Tuple.Create("", ""), x => !string.IsNullOrEmpty(x.Item1) ? grouperLabelToImpl[x.Item1] : null); aggregateFunc = new LocalValue <AggregatorDef <OperT> >(availableAggregators.FirstOrDefault()); var aggregateFuncView = new DropDownSelectBox(I18n.Translate("aggregate by:")); aggregateFuncView.Widget.ClassList.Add(Magics.CssClassAggregateFunc); aggregateFuncView.PermittedValues = aggregLabelToImpl.Select(x => Tuple.Create(x.Key, x.Key)); aggregateFuncView.BindReadWriteAndInitialize(aggregateFunc, x => x != null ? Tuple.Create(x.Label, x.Label) : Tuple.Create("", ""), x => !string.IsNullOrEmpty(x.Item1) ? aggregLabelToImpl[x.Item1] : null); groupingFunc.Changed += (_, __, newValue, errors, isUserChange) => { if (!isUserChange) { return; } currentGrouperImplOrNull = newValue; MarkAsGrouped(newValue != null); listener.UserGroupingChangedHandler(newValue != null ? ChangeOrRemove.Changed : ChangeOrRemove.Removed); }; aggregateFunc.Changed += (_, __, newValue, errors, isUserChange) => { if (!isUserChange) { return; } currentAggrImplOrNull = newValue; MarkAsAggregated(newValue != null); listener.UserAggregationChangedHandler(newValue != null ? ChangeOrRemove.Changed : ChangeOrRemove.Removed); }; groupOrAggregateChoice.Changed += (_, __, newValue, ___, isUserChange) => { Logger.Debug(typeof(DataGridColumnController), "groupOrAggregateChoice changed to {0} by {1}", newValue, isUserChange); //if (!isUserChange) { // return; //} if (!newValue.HasValue) { return; } switch (newValue.Value) { case GroupOrAggregate.Aggregate: currentAggrImplOrNull = aggregateFunc.Value; MarkAsAggregated(true); listener.UserAggregationChangedHandler(ChangeOrRemove.Changed); break; case GroupOrAggregate.Group: currentGrouperImplOrNull = groupingFunc.Value; MarkAsGrouped(true); listener.UserGroupingChangedHandler(ChangeOrRemove.Changed); break; default: throw new Exception("unsupported GroupOrAggregate"); } }; controllerElem.AppendChild(groupOrAggregateChoiceView.Widget); controllerElem.AppendChild(groupingFuncView.Widget); controllerElem.AppendChild(aggregateFuncView.Widget); } DocumentUtil.AddMouseClickListener(controllerElem, ev => { if (!ev.HasHtmlTarget()) { return; } //find out if clicked item is a descendant of th if (ev.HtmlTarget().IsDescendantOf(controllerElem.ParentElement)) { controllerElem.ParentElement.ClassList.Add(Magics.CssClassActive); return; } controllerElem.ParentElement?.ClassList.Remove(Magics.CssClassActive); }); return(Tuple.Create(controllerElem, new DataGridColumnControllerResult <InternalT> { FilterImpl = x => currentFilterImplOrNull == null || currentFilterImplOrNull.FilterFunc(filterParam.Value, toOper(x)), AggregationImpl = x => currentAggrImplOrNull?.AggregatorFunc(x.Select(toOper)), GroupingImpl = x => currentGrouperImplOrNull?.GroupingFunc(x.Select(toOper)), SortingImpl = new CompareImpl <InternalT>((x, y) => sortingImpl.Compare(toOper(x), toOper(y))), IsGroupingActive = () => currentGrouperImplOrNull != null })); }
private async Task <bool> FindQualifyingElement(object sender, EnumerableRowCollection <DataRow> elementSearchProperties, IHTMLElement element) { var engine = (IAutomationEngineInstance)sender; foreach (DataRow seachCriteria in elementSearchProperties) { string searchPropertyName = (string)await seachCriteria.Field <string>("Property Name").EvaluateCode(engine); dynamic searchPropertyValue = await seachCriteria.Field <string>("Property Value").EvaluateCode(engine); string searchPropertyFound = seachCriteria.Field <string>("Match Found"); string innerHTML = element.innerHTML; string outerHTML = element.outerHTML; searchPropertyFound = "False"; try { //if (element.GetType().GetProperty(searchPropertyName) == null) if ((outerHTML == null) || (element.getAttribute(searchPropertyName) == null) || (Convert.IsDBNull(element.getAttribute(searchPropertyName)))) { return(false); } if (searchPropertyValue is string && searchPropertyName.ToLower() == "href") { try { HTMLAnchorElement anchor = (HTMLAnchorElement)element; if (anchor.href.Contains(searchPropertyValue)) { seachCriteria.SetField("Match Found", "True"); } else { seachCriteria.SetField("Match Found", "False"); } } catch (Exception ex) { throw ex; } } else { if (searchPropertyValue is int) { //int elementValue = (int)element.GetType().GetProperty(searchPropertyName).GetValue(element, null); int elementValue = (int)element.getAttribute(searchPropertyName); if (elementValue == searchPropertyValue) { seachCriteria.SetField("Match Found", "True"); } else { seachCriteria.SetField("Match Found", "False"); } } else { //string elementValue = (string)element.GetType().GetProperty(searchPropertyName).GetValue(element, null); string elementValue = (string)element.getAttribute(searchPropertyName); if ((elementValue != null) && (elementValue == searchPropertyValue)) { seachCriteria.SetField("Match Found", "True"); } else { seachCriteria.SetField("Match Found", "False"); } } } } catch (Exception ex) { throw ex; } } /*foreach (var seachCriteria in elementSearchProperties) * { * Console.WriteLine(seachCriteria.Field<string>("Property Value")); * }*/ return(elementSearchProperties.Where(seachCriteria => seachCriteria.Field <string>("Match Found") == "True").Count() == elementSearchProperties.Count()); }
/// <summary> /// Renders the menu and its settings. /// </summary> /// <param name="parent"></param> public void Render(Element parent) { // The menu's button in the toolbar and also the root element. var menu = (HTMLAnchorElement)window.document.createElement("A"); menu.href = "#"; menu.className = "menu " + _className; // The menu popup element _popup = (HTMLAnchorElement)window.document.createElement("A"); _popup.href = "#"; _popup.className = "popup"; // Shows the menu name as a title var title = (HTMLDivElement)window.document.createElement("H1"); title.innerHTML = _name; _popup.appendChild(title); if ((dynamic)_settings && (dynamic)_settings.length) { // Renders all of the menu settings foreach (var setting in _settings) { // Attach the changed event to the settings controls setting.changed += settingChanged; setting.render(_popup); } _popup.appendChild(window.document.createElement("BR")); // Button to apply the setting changes. var applyButton = (HTMLAnchorElement)window.document.createElement("A"); applyButton.innerHTML = "Apply"; applyButton.className = "button ok"; _popup.appendChild(applyButton); // Handling the mousedown event to ensure the click is captured on all browsers. applyButton.addEventListener("mousedown", (e) => { // Deselect menu to hide it menu.className = menu.className.replace(" selected", ""); // Save the changes. persistSettings(); }, false); // Button to exit the menu and discard changes var cancelButton = (HTMLAnchorElement)window.document.createElement("A"); cancelButton.innerHTML = "Cancel"; cancelButton.className = "button cancel"; _popup.appendChild(cancelButton); // Handling the mousedown event to ensure the click is captured on all browsers. cancelButton.addEventListener("mousedown", (e) => { menu.className = menu.className.replace(" selected", ""); }, false); } else { // Just in case a developer creates a menu with no settings _popup.appendChild(window.document.createTextNode("No settings available.")); } // Prevents the # from being appended to the URL menu.addEventListener("click", (e) => { e.preventDefault(); }, false); // Certain browsers will trigger the blur event unless we capture and dispose of the mousedown event menu.addEventListener("mousedown", (e) => { // Make sure nothing catches the event as this could close the menu. e.preventDefault(); // If the mouse event target occured inside the menu, then if (contains(menu, (Element)e.target)) return; // Check if the menu is open or closed if (menu.className.indexOf("selected") < 0) { // If closed, set the setting controls from the game settings object loadSettings(); // Showing the menu by setting the 'selected' CSS class menu.className += " selected"; } else { // Hiding the menu by removing the 'selected' CSS class menu.className = menu.className.replace(" selected", ""); } // Set the focus because when the popup is blurred, ir needs to close. _popup.focus(); }, false); // Catching the popup's blur event, this lets us close the popup no matter what gets clicked _popup.addEventListener("blur", (e) => { menu.className = menu.className.replace(" selected", ""); e.preventDefault(); }, false); menu.appendChild(_popup); parent.appendChild(menu); // Forcing the settings to load in order to save the default values, then persist them in local storage loadSettings(); persistSettings(); }