コード例 #1
0
ファイル: AllFramesProcessor.cs プロジェクト: koshdim/KoWatIn
        public AllFramesProcessor(HTMLDocument htmlDocument)
        {
            Elements = new List<INativeDocument>();
            _htmlDocument = htmlDocument;

            _iFrameElements = (IHTMLElementCollection)htmlDocument.all.tags("iframe");
        }
コード例 #2
0
        /// <summary>
        /// initializes a class instance using the WLW editor handle to 
        /// obtain access to the current HTML document through IHTMLDocument2
        /// </summary>
        public WLWEditorContent(IntPtr wlwEditorHandle)
        {
            _owner = wlwEditorHandle;

            // Everything else in this class depends upon successful initialization of _htmlDocument
            _htmlDocument = WLWEditorContent.getHtmlDocument2(wlwEditorHandle);
            _anchorCollection = this.getAnchorCollection();
        }
コード例 #3
0
ファイル: ElementTag.cs プロジェクト: pusp/o2platform
		public IHTMLElementCollection GetElementCollection(IHTMLElementCollection elements)
		{
			if (elements == null) return null;

			if (TagName == null) return elements;

			return (IHTMLElementCollection) elements.tags(TagName);
		}
コード例 #4
0
 public void UpdateElementsEvents(IHTMLElementCollection elements)
 {
     foreach (IHTMLElement3 element in elements)
     {
         //element.onmouseenter += new HTMLElementEvents_onmouseenterEventHandler(dd);
         //element.onmouseup += new HTMLElementEvents_onmouseupEventHandler(dd);
         //element.MouseEnter += new HtmlElementEventHandler(element_MouseEnter);
     }
 }
コード例 #5
0
        public AllFramesProcessor(HTMLDocument htmlDocument)
        {
            Elements = new List<INativeDocument>();

            frameElements = (IHTMLElementCollection) htmlDocument.all.tags("frame");

            // If the current document doesn't contain FRAME elements, it then
            // might contain IFRAME elements.
            if (frameElements.length == 0)
            {
                frameElements = (IHTMLElementCollection)htmlDocument.all.tags("iframe");
            }

            this.htmlDocument = htmlDocument;
        }
コード例 #6
0
ファイル: AllFramesProcessor.cs プロジェクト: pusp/o2platform
		public AllFramesProcessor(DomContainer domContainer, HTMLDocument htmlDocument)
		{
			elements = new ArrayList();

			frameElements = (IHTMLElementCollection) htmlDocument.all.tags(ElementsSupport.FrameTagName);

			// If the current document doesn't contain FRAME elements, it then
			// might contain IFRAME elements.
			if (frameElements.length == 0)
			{
				frameElements = (IHTMLElementCollection) htmlDocument.all.tags("IFRAME");
			}

			this._domContainer = domContainer;
			this.htmlDocument = htmlDocument;
		}
コード例 #7
0
ファイル: ElementTag.cs プロジェクト: pusp/o2platform
        public IHTMLElement GetElementById(IHTMLElementCollection elements, string id)
		{
			if (elements == null) return null;

            IHTMLElementCollection3 elementCollection3 = elements as IHTMLElementCollection3;
            
            if (elementCollection3 == null) return null;
            
            object item = elementCollection3.namedItem(id);
            IHTMLElement element = null;

            if ((item as IHTMLElement) != null) element = (IHTMLElement) item;
            else if ((item as IHTMLElementCollection) != null) element = (IHTMLElement)((IHTMLElementCollection)item).item(null, 0);

            if (element !=null && Compare(new IEElement(element))) return element;

            return null;
		}
コード例 #8
0
ファイル: AllFramesProcessor.cs プロジェクト: exaphaser/WatiN
        public AllFramesProcessor(HTMLDocument htmlDocument)
        {
            Elements = new List<INativeDocument>();
            _htmlDocument = htmlDocument;

            // Bug fix, trying to revert back to previous version
            // http://stackoverflow.com/questions/5882415/error-when-accessing-the-frames-in-watin-new-version-2-1
            //_iFrameElements = (IHTMLElementCollection)htmlDocument.all.tags("iframe");

            _iFrameElements = (IHTMLElementCollection)_htmlDocument.all.tags("frame");

            // If the current document doesn't contain FRAME elements, it then
            // might contain IFRAME elements.
            if (_iFrameElements.length == 0)
            {
                _iFrameElements = (IHTMLElementCollection)_htmlDocument.all.tags("iframe");
            }
        }
コード例 #9
0
        public void browser_fill()
        {
            if (webBrowser1.IsLoaded)
            {
                m_hec = (webBrowser1.Document as HTMLDocumentClass).getElementsByTagName("input");
                List<string> lstInput = new List<string>();
                foreach (HTMLInputElementClass he in m_hec)
                {
                    if (he.getAttribute("name").ToString() == "Email")
                    {

                        if (he.getAttribute("value") != null)
                        {
                            lstInput.Add(he.getAttribute("value").ToString());
                        }

                        else
                        {
                            lstInput.Add("");
                            he.setAttribute("value", username);
                        }
                    }

                    if (he.getAttribute("name").ToString() == "Passwd")
                    {

                        if (he.getAttribute("value") != null)
                        {
                            lstInput.Add(he.getAttribute("value").ToString());
                        }

                        else
                        {
                            lstInput.Add("");
                            he.setAttribute("value", password);
                        }
                    }

                }
            }
        }
コード例 #10
0
ファイル: HtmlTree.cs プロジェクト: cnboker/autorobo
 private void InspectFrameMouseEvent(mshtml.IHTMLElementCollection fc)
 {
     if (fc == null)
     {
         return;
     }
     if (fc.length > 0)
     {
         for (int i = 0; i < fc.length; i++)
         {
             object                  id              = (object)i;
             IHTMLWindow2            frameWindow     = (IHTMLWindow2)fc.item(id, 0);
             mshtml.HTMLDocument     frameDoc        = (mshtml.HTMLDocument)frameWindow.document;
             mshtml.DispHTMLDocument frameDispDoc    = (mshtml.DispHTMLDocument)frameDoc;
             DHTMLEventHandler       onmousedownhand = new DHTMLEventHandler(frameDoc);
             onmousedownhand.Handler += new DHTMLEvent(Mouse_Down);
             frameDispDoc.onmousedown = onmousedownhand;
             IHTMLElementCollection col = BrowserExtensions.GetFrames((IHTMLDocument2)frameDoc);
             InspectFrameMouseEvent(col);
         }
     }
 }
コード例 #11
0
        /// <summary>
        /// 웹에 이미지를 폴더에 저장한다.
        /// </summary>
        /// <param name="FolderPath"></param>
        public void AllImage_Save(string FolderPath)
        {
            string strElName;

            mshtml.IHTMLElement2     body2        = (mshtml.IHTMLElement2)HTMLDoc.body;
            mshtml.IHTMLControlRange controlRange = (mshtml.IHTMLControlRange)body2.createControlRange();
            IHTMLElementCollection   imgs         = HTMLDoc.images;


            foreach (mshtml.HTMLImg objImg in imgs)
            {
                controlRange.add((mshtml.IHTMLControlElement)objImg);
                controlRange.execCommand("Copy", false, System.Reflection.Missing.Value);
                controlRange.remove(0);
                strElName = objImg.nameProp;

                if (Clipboard.GetDataObject() != null)
                {
                    IDataObject data = Clipboard.GetDataObject();

                    if (data.GetDataPresent(DataFormats.Bitmap))
                    {
                        Image image = (Image)data.GetData(DataFormats.Bitmap, true);
                        if (strElName.Substring(strElName.IndexOf(".") + 1).ToLower() == "jpg")
                        {
                            image.Save(FolderPath + strElName, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                        else if (strElName.Substring(strElName.IndexOf(".") + 1).ToLower() == "gif")
                        {
                            image.Save(FolderPath + strElName, System.Drawing.Imaging.ImageFormat.Gif);
                        }
                        else if (strElName.Substring(strElName.IndexOf(".") + 1).ToLower() == "png")
                        {
                            image.Save(FolderPath + strElName, System.Drawing.Imaging.ImageFormat.Png);
                        }
                    }
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// Retrieve a Cell by Index in the row
        /// </summary>
        /// <param name="index"> The cell index as it appear in the Index property of the HTMLTd element</param>
        /// <example>
        /// <code>
        ///    HTMLTd cell;
        ///    HTMLTr mailRow = Browser.This.CurrentPage.FindByID("TABLE", "gaia_table")["TBODY", 1]["TR", 3] as HTMLTr;
        ///    for (int idx = 0; idx &lt; mailRow.NumberOfCells; idx++)
        ///    {
        ///		   if (mailRow.Cell(idx).InnerText.Contains("Email"))
        ///		   {
        ///
        ///		   }
        ///    }
        /// </code>
        /// </example>
        /// <returns>HTMlTd with requested index, or null if index not found</returns>
        public HTMLTd Cell(int index)
        {
            if (index <= NumberOfCells)
            {
                IHTMLElementCollection tblCells = ((IHTMLTableRow)htmlElement).cells;
                HTMLTd[] cellArr = new HTMLTd[tblCells.length];
                //for (int idx = 0; idx < cellArr.Length; idx++)
                //	  cellArr[idx] = Cell(idx);
                int idx = 0;
                foreach (IHTMLElement cel in tblCells)
                {
                    cellArr[idx++] = new HTMLTd(cel);
                }

                return(cellArr[index]);
            }

            else
            {
                return(null);
            }
        }
コード例 #13
0
        private Analysis GetAnalysis()
        {
            var dom = (HTMLDocument)WebBrowser.Document;

            if (dom != null)
            {
                IHTMLElementCollection elems = dom.getElementsByTagName("INPUT");
                foreach (HTMLInputElement elem in elems)
                {
                    string value = elem.getAttribute("value");
                    string name  = elem.getAttribute("name");
                    if (!string.IsNullOrEmpty(name))
                    {
                        CurrentState.CurrentAnalysis.AddData(name, value);
                    }
                }
            }
            CurrentState.CurrentAnalysis.Template = CurrentState.CurrentTemplate;
            CurrentState.CurrentAnalysis.Person   = CurrentState.CurrentPerson;

            return(CurrentState.CurrentAnalysis);
        }
コード例 #14
0
ファイル: FormTest.cs プロジェクト: zidane0522/CSharpStudy
        private void button2_Click(object sender, EventArgs e)
        {
            IHTMLDocument2 hdoc = doc.DomDocument as IHTMLDocument2;
            IHTMLWindow2   win  = hdoc.parentWindow as mshtml.IHTMLWindow2;

            var d = win.execScript(@"function sucdd(){ return popUpWin;}", "javascript");
            HTMLWindow2Class       dddd     = doc.InvokeScript("sucdd") as HTMLWindow2Class;
            IHTMLDocument2         popupdoc = dddd.document;
            IHTMLElementCollection eleclt   = popupdoc.all.tags("span") as IHTMLElementCollection;

            foreach (IHTMLElement item in eleclt)
            {
                if (item.innerText != null)
                {
                    if (item.innerText.Contains("问题十四"))
                    {
                        item.click();
                    }
                }
            }
            //IHTMLElement ele=eleclt.item
        }
コード例 #15
0
        private static List <T1> populateVar <T, T1>(IHTMLElementCollection elementCollection) //, List<T> targetList)
        {
            var targetList = new List <T1>();

            try
            {
                foreach (IHTMLElement element in elementCollection)
                {
                    var t = (T1)typeof(T).ctor(element);
                    if (t != null)
                    {
                        targetList.Add(t);
                    }
                }
                return(targetList);
            }
            catch (Exception ex)
            {
                "ex: {0}".format(ex.Message).error();
                return(null);
            }
        }
コード例 #16
0
ファイル: XslGenerator.cs プロジェクト: leonchen09/poc
        private void MatchingControlBookmarks(Stack <KeyValuePair <IHTMLDOMNode, PartBookmark> > controlMarkupStack, IHTMLDOMNode htmlNode)
        {
            IHTMLElement2          htmlElement = htmlNode as IHTMLElement2;
            IHTMLElementCollection anchors     = htmlElement.getElementsByTagName("A");

            foreach (IHTMLElement anchor in anchors)
            {
                PartBookmark bookmark = ParseToPartBookmark(anchor);

                if (bookmark != null && bookmark.IsControlBookmark)
                {
                    IHTMLDOMNode node = anchor as IHTMLDOMNode;

                    if (controlMarkupStack.Count == 0)
                    {
                        controlMarkupStack.Push(new KeyValuePair <IHTMLDOMNode, PartBookmark>(node, bookmark));
                    }
                    else
                    {
                        KeyValuePair <IHTMLDOMNode, PartBookmark> previous = controlMarkupStack.Peek();

                        bool isMatch = (previous.Value.Type == BookmarkType.StartForeach && bookmark.Type == BookmarkType.EndForeach) ||
                                       (previous.Value.Type == BookmarkType.StartIf && bookmark.Type == BookmarkType.EndIf);

                        isMatch = isMatch && previous.Key.parentNode == node.parentNode;

                        if (isMatch)
                        {
                            controlMarkupStack.Pop();
                        }
                        else
                        {
                            controlMarkupStack.Push(new KeyValuePair <IHTMLDOMNode, PartBookmark>(node, bookmark));
                        }
                    }
                }
            }
        }
コード例 #17
0
 /// <summary>
 /// Safely sets the value of given HTML element (IHTMLInputElement or IHTMLTextAreaElement).
 /// If any other element will be passed this request will be ignored.
 /// </summary>
 /// <param name="element">IHTMLInputElement or IHTMLTextAreaElement whose value is to be set</param>
 /// <param name="value">String value</param>
 /// <param name="args">optional params for firing event on Select element</param>
 public static int SetElementValue(Object element, String value, params Object[] args)
 {
     if (element != null)
     {
         if (element is IHTMLInputElement)
         {
             ((IHTMLInputElement)element).value = value;
         }
         else if (element is IHTMLSelectElement)
         {
             IHTMLElement select = element as IHTMLElement;
             Dictionary <String, List <int> > options = GetOptionsMap(select);
             if (options.ContainsKey(value.ToLower()))
             {
                 ((IHTMLSelectElement)element).selectedIndex = options[value.ToLower()][0];
                 if (args.Length > 0)
                 {
                     ((IHTMLElement3)element).FireEvent("onchange", ref args[0]);
                 }
                 return(options[value.ToLower()].Count);
             }
             return(-1);
         }
         else if (element is IHTMLTextAreaElement)
         {
             ((IHTMLTextAreaElement)element).value = value;
         }
         else if (element is IHTMLElementCollection)
         {
             IHTMLElementCollection col = element as IHTMLElementCollection;
             if (col.length > 0)
             {
                 return(SetElementValue(col.item(null, 0), value, args));
             }
         }
     }
     return(0);
 }
コード例 #18
0
        public string GetUserID(string strUserName)
        {
            IHTMLElementCollection Tags = this.htmlDoc.getElementsByTagName("tr");
            string strUserId            = "";

            foreach (IHTMLElement cTag in Tags)
            {
                if (cTag.innerHTML.Substring(0, 7).ToUpper().Equals("<TD ID="))
                {
                    if (cTag.innerText.IndexOf(strUserName) >= 0)
                    {
                        int pos = cTag.innerHTML.IndexOf("incrementAssignation(this,");
                        if (pos > 0)
                        {
                            strUserId = cTag.innerHTML.Substring(pos + 27, 3);
                            strUserId = strUserId.Replace("'", "");
                            break;
                        }
                    }
                }
            }
            return(strUserId);
        }
コード例 #19
0
        /// <summary>
        /// Helper function to build up the list of form field elements
        /// </summary>
        private void verifyFieldElements(IHTMLDocument2 document)
        {
            if (fieldElements == null)
            {
                fieldElements = new ArrayList();

                IHTMLElementCollection allElements      = document.all;
                IHTMLElementCollection inputElements    = (IHTMLElementCollection)allElements.tags(ElementsSupport.InputTagName);
                IHTMLElementCollection textareaElements = (IHTMLElementCollection)allElements.tags("textarea");

                // Merge the two collections
                for (int i = 0; i < inputElements.length; i++)
                {
                    IHTMLElement node = (IHTMLElement)inputElements.item(i, null);
                    fieldElements.Add(node);
                }
                for (int i = 0; i < textareaElements.length; i++)
                {
                    IHTMLElement node = (IHTMLElement)textareaElements.item(i, null);
                    fieldElements.Add(node);
                }
            }
        }
コード例 #20
0
 private void webBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
 {
     try
     {
         var docs = webBrowser.Document as HTMLDocument;
         if (docs != null)
         {
             IHTMLElementCollection elementCollection = docs.getElementsByTagName("title");
             if (elementCollection != null && elementCollection.length > 0)
             {
                 foreach (IHTMLElement element in elementCollection)
                 {
                     lblTitleStatus.Text = element.innerText;
                     break;
                 }
             }
         }
     }
     catch (Exception generalException)
     {
         System.Windows.MessageBox.Show(generalException.Message);
     }
 }
コード例 #21
0
        /// <summary>
        /// IEで検索ボタンを押下する処理
        /// </summary>
        /// <param name="IE"></param>
        private void ClickIESearchButton(InternetExplorer IE, string storeName)
        {
            var doc = IE.Document as mshtml.IHTMLDocument3;

            // 検索テキストタグ取得
            IHTMLElement searchText = doc.getElementById("idWord");

            // 検索文字列入力
            searchText.innerText = storeName;

            // 検索ボタン押下
            doc.getElementById("idWord");
            IHTMLElementCollection elementCollection = doc.getElementsByTagName("input");

            foreach (IHTMLElement element in elementCollection)
            {
                string outerHtml = element.outerHTML;
                if (outerHtml.IndexOf("検索") > 0)
                {
                    element.click();
                }
            }
        }
コード例 #22
0
        public virtual void ModifyDOM(IHTMLDocument2 document, bool addEventHandler)
        {
            ((IHTMLDocument3)document).documentElement.insertAdjacentHTML("afterBegin", "<script language='javascript' type='text/css'>window.onerror = function(e){return true;}</script>");
            ((IHTMLDocument3)document).documentElement.insertAdjacentHTML("afterBegin", "<script language='javascript'>window.alert = function () { }</script>");

            IHTMLDocument3 doc = (IHTMLDocument3)document;

            IHTMLElementCollection linkElements = doc.getElementsByTagName("LINK");

            foreach (IHTMLLinkElement linkElement in linkElements)
            {
                linkElement.disabled = true;
            }

            //Also disable style elements, so that @import inside styles won't trigger download.
            IHTMLElementCollection styleElements = doc.getElementsByTagName("STYLE");

            foreach (IHTMLStyleElement styleElement in styleElements)
            {
                styleElement.disabled = true;
            }

            //BrowserOptions.NoFrameDownload seems to work only for FRAME elements and not the IFRAME elements.
            IHTMLElementCollection iframeElements = doc.getElementsByTagName("IFRAME");

            foreach (IHTMLElement iframeElement in iframeElements)
            {
                //iframeElement.setAttribute("src", "about:blank");
            }

            if (addEventHandler)
            {
                HTMLWindowEvents2_Event onErrorEvent = (HTMLWindowEvents2_Event)document.parentWindow;

                onErrorEvent.onerror += myHTMLWindowEvents2_onerror;
            }
        }
コード例 #23
0
        public static void tidySpan(IHTMLDocument2 idoc2)
        {
            IHTMLElementCollection elements = (IHTMLElementCollection)(idoc2).all;
            string       pstylestr          = "";
            string       estylestr          = "";
            string       pinnstr            = "";
            string       einnstr            = "";
            IHTMLElement pele = null;
            IHTMLElement eele = null;

            foreach (IHTMLElement element in elements)
            {
                if (element.tagName == "SPAN")
                {
                    string outstr = element.outerHTML;
                    pele      = eele;
                    eele      = element;
                    pinnstr   = einnstr;
                    einnstr   = element.innerText;
                    pstylestr = estylestr;
                    if (outstr.IndexOf("style") > 0)
                    {
                        estylestr = outstr.Substring(outstr.IndexOf("style"), outstr.IndexOf(">") - outstr.IndexOf("style"));
                        if (estylestr == pstylestr)
                        {
                            eele.innerText = pinnstr + element.innerText;
                            pele.innerText = "";
                            einnstr        = eele.innerText;
                        }
                    }
                    else
                    {
                        eele.outerHTML = eele.innerHTML;
                    }
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// 이미지 이름으로 찾는다.
        /// </summary>
        /// <param name="imgName">이미지파일명이나 herf 경로</param>
        /// <returns></returns>
        public Image Image_Get(string imgName)
        {
            string strElName;

            mshtml.IHTMLElement2     body2        = (mshtml.IHTMLElement2)HTMLDoc.body;
            mshtml.IHTMLControlRange controlRange = (mshtml.IHTMLControlRange)body2.createControlRange();
            IHTMLElementCollection   imgs         = HTMLDoc.images;

            Image image = null;

            foreach (mshtml.HTMLImg objImg in imgs)
            {
                if (objImg.nameProp != imgName && objImg.href != imgName)
                {
                    continue;
                }


                controlRange.add((mshtml.IHTMLControlElement)objImg);
                controlRange.execCommand("Copy", false, System.Reflection.Missing.Value);
                controlRange.remove(0);
                strElName = objImg.nameProp;

                if (Clipboard.GetDataObject() != null)
                {
                    IDataObject data = Clipboard.GetDataObject();

                    if (data.GetDataPresent(DataFormats.Bitmap))
                    {
                        image = (Image)data.GetData(DataFormats.Bitmap, true);
                    }
                }
            }

            return(image);
        }
コード例 #25
0
        public Object[] GetElementsByTagName(String tag)
        {
            IHTMLElement[] result = null;
            if (!String.IsNullOrEmpty(tag) && this._document != null)
            {
                try
                {
                    tag = tag.ToUpper().Trim();
                    IHTMLDocument3 doc3 = this._document as IHTMLDocument3;
                    if (doc3 != null)
                    {
                        if (!_tagElements.TryGetValue(tag, out result))
                        {
                            IHTMLElementCollection elements = doc3.getElementsByTagName(tag);
                            result = new IHTMLElement[elements.length];
                            for (int i = 0; i < elements.length; i++)
                            {
                                try
                                {
                                    result[i] = elements.item(i, i) as IHTMLElement;
                                }
                                catch
                                {
                                }
                            }
                            _tagElements.Add(tag, result);
                        }
                    }
                }
                catch
                {
                }
            }

            return(result);
        }
コード例 #26
0
        public HTMLUListElement GetUList(string tagName, string attName, string attValue)
        {
            HTMLDocument document = ((HTMLDocument)IE.Document);
            IHTMLElement el       = null;

            IHTMLElementCollection tags = document.getElementsByTagName(tagName);

            IEnumerator enumerator = tags.GetEnumerator();

            while (enumerator.MoveNext())
            {
                HTMLUListElement element = (HTMLUListElement)enumerator.Current;
                if (element.getAttributeNode(attName) != null)  // are class
                {
                    if (element.getAttributeNode(attName).nodeValue != null &&
                        element.getAttributeNode(attName).nodeValue.ToString() == attValue)
                    {
                        ///MessageBox.Show("found the element");
                        return(element);
                    }
                }
            }
            return(null);
        }
コード例 #27
0
            public void DoDelete()
            {
                if (_realExtendedEntry.sourceIndex == 0)                //this "real" entry is deleted
                {
                    return;
                }

                using (IUndoUnit undo = _editorContext.CreateInvisibleUndoUnit())
                {
                    IHTMLElementCollection extendedEntryElements = _document.getElementsByName(PostBodyEditingElementBehavior.EXTENDED_ENTRY_ID);
                    foreach (IHTMLElement element in extendedEntryElements)
                    {
                        if (element.sourceIndex != _realExtendedEntry.sourceIndex)
                        {
                            if (element.sourceIndex > -1)                            //just in case its already been deleted
                            {
                                (element as IHTMLDOMNode).removeNode(true);
                            }
                        }
                    }

                    undo.Commit();
                }
            }
コード例 #28
0
        private string GetLcsDescription(string lcsId)
        {
            if (string.IsNullOrWhiteSpace(lcsId) == false)
            {
                WebClient client = new WebClient();
                client.Headers.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
                client.UseDefaultCredentials = true;

                string htmlContent = client.DownloadString(this.LCS_BUG_URI + lcsId);

                // Obtain the document interface
                IHTMLDocument2 htmlDocument = (IHTMLDocument2) new mshtml.HTMLDocument();

                // Construct the document
                htmlDocument.write(htmlContent);

                // Extract all elements
                IHTMLElementCollection allElements = htmlDocument.all;

                bool bugTitlefound = false;
                foreach (IHTMLElement element in allElements)
                {
                    if (element.outerText == "Bug Title")
                    {
                        bugTitlefound = true;
                    }
                    if (bugTitlefound &&
                        string.IsNullOrWhiteSpace(element.outerText) == false &&
                        element.outerText != "Bug Title")
                    {
                        return(element.outerText);
                    }
                }
            }
            return(string.Empty);
        }
コード例 #29
0
        private void TimersTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            log.Info($"  Entered TimersTimer_Elapsed.");

            m.Dispatcher.Invoke((Action)(() =>
            {
                HTMLDocument d = (HTMLDocument)m.vpnweb.Document;

                // dispatcher的問題, 要叫用就要在這裡面
                if (GOTO_NEXT_PAGE)
                {
                    GOTO_NEXT_PAGE = false;

                    log.Info($"    _timer1 stopped. this pages finished.");
                    this._timer1.Stop();

                    Goto_next_page();

                    log.Info($"  Exited TimersTimer_Elapsed.");
                    return;
                }

                log.Info($"    Now dealing with page {current_page}/{total_pages}.");
                log.Info($"    Now dealing with line {current_line}.");
                IHTMLElement gvDownLoad = d.getElementById(DOM_FOR_ACTUAL_DATA);
                IHTMLElementCollection trs_ = gvDownLoad.all;
                IHTMLElementCollection trs = trs_.tags("tr");
                IHTMLElement tr = trs.item(current_line, null);
                IHTMLElement a = tr.children[4].children[0];
                a.click();
                log.Info($"    button click: {a.innerHTML}");

                System.Threading.ThreadStart th_begin = new System.Threading.ThreadStart(Work_todo);
                System.Threading.Thread thr = new System.Threading.Thread(th_begin)
                {
                    IsBackground = true,
                    Name = "PressS"
                };
                thr.Start();

                // 判斷是否這一頁讀完了? 是否最後一頁了?
                if ((queue_files.Count == 0) && (current_page == total_pages))
                {
                    // 這頁讀完, 且所有頁都讀完了.
                    log.Info($"    _timer1 stopped. all pages finished.");
                    m.Refresh_Table();
                    tb.ShowBalloonTip("結束", "完成所有頁面讀取", BalloonIcon.Info);
                    this._timer1.Stop();
                }
                else if (queue_files.Count == 0)
                {
                    // 這頁讀完, 但還有下一頁.
                    GOTO_NEXT_PAGE = true;
                }
                else
                {
                    current_line = queue_files.Dequeue();
                    log.Info($"    go to next line: {current_line}.");
                }
            }));

            log.Info($"  Exited TimersTimer_Elapsed.");
            return;
        }
コード例 #30
0
        private bool PerformAutomationTask(IHTMLElementCollection col, AutomationTasks task, string elemname, string data)
        {
            bool bret = false;

            if (col == null) return bret;

            foreach (IHTMLElement elem in col)
            {
                if (elem != null)
                {
                    switch (task)
                    {
                        case AutomationTasks.ClickButton:
                            {
                                IHTMLInputElement btn = elem as IHTMLInputElement;
                                if ((btn != null) &&
                                    (btn.name == elemname))
                                {
                                    elem.click();
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.ClickLink:
                            {
                                IHTMLAnchorElement anchor = elem as IHTMLAnchorElement;
                                if( (anchor != null) &&
                                    (anchor.name == elemname))
                                {
                                    elem.click();
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.EnterData:
                            {
                                IHTMLInputElement inputelem = elem as IHTMLInputElement;
                                if( (inputelem != null) &&
                                    (inputelem.name == elemname) )
                                {
                                    inputelem.value = data;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.EnterDataTextArea:
                            {
                                IHTMLTextAreaElement txtarea = elem as IHTMLTextAreaElement;
                                if ((txtarea != null) &&
                                    (txtarea.name == elemname))
                                {
                                    txtarea.value = data;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SelectListItem:
                            {
                                IHTMLSelectElement selelem = elem as IHTMLSelectElement;
                                if( (selelem != null) &&
                                    (selelem.name == elemname) )
                                {
                                    selelem.value = data;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SelectRadioButton:
                            {
                                IHTMLInputElement inputelem = elem as IHTMLInputElement;
                                if( (inputelem != null) &&
                                    (inputelem.name == elemname) )
                                {
                                    inputelem.checkeda = true;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SubmitForm:
                            {
                                IHTMLFormElement form = elem as IHTMLFormElement;
                                if ((form != null) &&
                                    (form.name == elemname))
                                {
                                    form.submit();
                                    return true;
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } //End foreach

            return bret;
        }
コード例 #31
0
        public static void CreatePDF(System.IO.Stream stream, string htmlMarkup)
        {
            if (null == stream || string.IsNullOrEmpty(htmlMarkup))
            {
                return;
            }

            System.IO.MemoryStream m        = new System.IO.MemoryStream();
            iText.Document         document = new iText.Document();
            iText.pdf.PdfWriter    writer   = iText.pdf.PdfWriter.GetInstance(document, m);

            HTMLDocument pseudoDoc = new HTMLDocument();

            ((IHTMLDocument2)pseudoDoc).write(htmlMarkup);

            document.Open();

            IHTMLElementCollection children = (IHTMLElementCollection)pseudoDoc.getElementById("pdfContainer").children;

            foreach (IHTMLElement el in children)
            {
                IHTMLElement theEl = el;

                if (null == theEl.className)
                {
                    continue;
                }

                string className = theEl.className.ToLowerInvariant();

                if (className == "ignore" || string.IsNullOrEmpty(className))
                {
                    continue;
                }

                string tagName = theEl.tagName.ToLowerInvariant();

                string innerText = theEl.innerText;

                if (string.IsNullOrEmpty(innerText))
                {
                    theEl     = (IHTMLElement)((IHTMLElementCollection)el.children).item(null, 0);
                    tagName   = theEl.tagName.ToLowerInvariant();
                    innerText = theEl.innerText;
                }

                if (tagName == "div" || tagName == "span")
                {
                    document.Add(new iText.Paragraph(innerText));
                    continue;
                }

                if (tagName == "hr")
                {
                    if (className == "pagebreak")
                    {
                        document.NewPage();
                    }
                    else
                    {
                        iText.pdf.PdfPTable t = new iText.pdf.PdfPTable(1);
                        t.HorizontalAlignment             = iText.Element.ALIGN_CENTER;
                        t.WidthPercentage                 = 100f; // this would be the 100 from setHorizontalLine
                        t.SpacingAfter                    = 5f;
                        t.SpacingBefore                   = 0f;
                        t.DefaultCell.UseVariableBorders  = true;
                        t.DefaultCell.VerticalAlignment   = iText.Element.ALIGN_MIDDLE;
                        t.DefaultCell.HorizontalAlignment = iText.Element.ALIGN_CENTER;
                        t.DefaultCell.Border              = iText.Image.BOTTOM_BORDER; // This generates the line
                        t.DefaultCell.BorderWidth         = 1f;                        // this would be the 1 from setHorizontalLine
                        t.DefaultCell.Padding             = 0;
                        t.AddCell("");
                        document.Add(t);
                    }
                }

                if (tagName == "img")
                {
                    iText.Image img = iText.Image.GetInstance(theEl.getAttribute("src", 0).ToString());
                    img.ScaleToFit(document.PageSize.Width - 100, document.PageSize.Height - 100);
                    document.Add(img);
                    continue;
                }
            }

            pseudoDoc.close();
            pseudoDoc = null;

            document.Close();

            writer.Flush();

            byte[] data = m.GetBuffer();

            try
            {
                stream.Write(data, 0, data.Length);
                stream.Flush();
                stream.Close();
            }
            catch
            {
                throw;
            }
            finally
            {
                Array.Clear(data, 0, data.Length);
                data     = null;
                document = null;
                writer   = null;
                m.Dispose();
                m = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
コード例 #32
0
 private static void ResetPaths(string attributeName, IHTMLElementCollection elements, string baseUrl)
 {
     foreach (IHTMLElement element in elements)
     {
         ResetPath(attributeName, element, baseUrl);
     }
 }
コード例 #33
0
ファイル: IEDriver.cs プロジェクト: DougThompson/AutomateIE
        /// <summary>
        /// Try to get an element by the ID, index, and/or name
        /// </summary>
        /// <param name="elems"></param>
        /// <param name="index"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private IHTMLElement GetElementById(IHTMLElementCollection elems, int index, string name)
        {
            // If there is no document, then throw exception -- sometimes the driver loses the IE instance
            if (IE.Document == null)
            {
                printTestResult(textBox1, "Error", Color.Red, String.Format("{0}   Document is null!{1}", Environment.NewLine, Environment.NewLine));
                throw new Exception("Document is null!");
            }

            IHTMLElement result;
            int i = 0;
            foreach (IHTMLElement htmlElement in elems)
            {
                // if the index == -1, then grab the first one
                // Otherwise, check to see if we've counted enough repeated elements
                if (index < 0 | i == index)
                {
                    // Now, get either the id or name, and check if the name (if provided) matches
                    string elemID = htmlElement.id ?? (htmlElement.getAttribute("name") == null ? "" : htmlElement.getAttribute("name").ToString());
                    if (elemID.EndsWith(name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        result = htmlElement;
                        return result;
                    }
                }
                else
                    i++;
            }

            // Not found, so print out error and stop
            printTestResult(textBox1, "Error", Color.Red, String.Format("{0}   Element not found in current collection.{1}", Environment.NewLine, Environment.NewLine));
            throw new Exception("Element not found in current collection.");
        }
コード例 #34
0
        public sealed override async Task <Tuple <string, LinkFetchResult> > GetSourceLink(string url)
        {
            var ie = new IE();

            ie.Navigate2(url);

            while (ie.ReadyState != SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE)
            {
            }

            SHDocVw.WebBrowser browser = ((SHDocVw.WebBrowser)ie);
            HTMLDocument       doc     = ((HTMLDocument)browser.Document); //Get Document

            IHTMLElementCollection searchHash = (IHTMLElementCollection)doc.getElementsByName("hash");

            string hash      = string.Empty;
            string timestamp = string.Empty;

            foreach (IHTMLElement element in searchHash)
            {
                if (element == null)
                {
                    break;
                }
                if ((string)element.getAttribute("name") == "hash")
                {
                    hash = element.getAttribute("value");
                }
            }

            IHTMLElementCollection searchTimestamp = (IHTMLElementCollection)doc.getElementsByName("timestamp");

            foreach (IHTMLElement element in searchTimestamp)
            {
                if (element == null)
                {
                    break;
                }
                if ((string)element.getAttribute("name") == "timestamp")
                {
                    timestamp = element.getAttribute("value");
                }
            }

            /* PREPARE POST DATA */

            var stringData = $"hash={HttpUtility.UrlEncode(hash)}&timestamp={HttpUtility.UrlEncode(timestamp)}";
            var byteData   = Encoding.ASCII.GetBytes(stringData);

            /* PREPARE HTTP CLIENT */
            var request = (HttpWebRequest)WebRequest.Create(url);

            request.Method        = "POST";
            request.UserAgent     = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = byteData.Length;

            /* SEND POST DATA ASYNC */

            Stream requestStream = await request.GetRequestStreamAsync();

            await requestStream.WriteAsync(byteData, 0, byteData.Length);

            requestStream.Close();

            /* RECIVE RESPONSE ASYNC */
            var response     = ((HttpWebResponse)await request.GetResponseAsync()).GetResponseStream();
            var streamReader = new StreamReader(response, Encoding.Default);

            var responseString = await streamReader.ReadToEndAsync();

            /* PARSE STRING TO DOC  */
            UpdateStatus("Scanning Web page after link");
            var docTemp = (IHTMLDocument2)doc;

            docTemp.write(responseString);

            /* SEARCH DOWNLOAD LINK */
            var contentElement = GetStreamContent(doc);

            var sourceURL     = string.Empty;
            var fetchResponse = LinkFetchResult.SUCCESSFULL;

            if (contentElement != null)
            {
                UpdateStatus("Starting download...");
                sourceURL = contentElement.getAttribute("data-url"); //Get data-url attribute
            }
            else
            {
                fetchResponse = LinkFetchResult.FAILED;
                UpdateStatus("Source link not found");
            }

            ie.Quit();
            return(new Tuple <string, LinkFetchResult>(sourceURL, fetchResponse));
        }
コード例 #35
0
        void Navigate()
        {
            try
            {
                Encoding       encode  = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(urlTextBox.Text);
                request.Method    = "GET";
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome Safari/537.36";
                request.KeepAlive = false;
                IAsyncResult iar1 = request.BeginGetResponse(null, null);
                try
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(iar1))
                    {
                        if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
                        {
                            string       temp   = Path.GetTempFileName();
                            BinaryReader br     = new BinaryReader(response.GetResponseStream());
                            byte[]       buffer = new byte[4096];
                            MemoryStream ms     = new MemoryStream();
                            int          n      = 0;
                            do
                            {
                                n = br.Read(buffer, 0, buffer.Length);
                                ms.Write(buffer, 0, n);
                            } while (n > 0);
                            br.Dispose();
                            buffer = ms.ToArray();
                            ms.Close();

                            String html = Encoding.ASCII.GetString(buffer);
                            try
                            {
                                Match match = Regex.Match(html, @"<meta[^>]*charset[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                if (match.Success)
                                {
                                    string[] ss      = match.Value.Split(new string[] { "charset=" }, StringSplitOptions.RemoveEmptyEntries);
                                    string   charset = ss[ss.Length - 1].Split(new char[] { '"', ' ' }, StringSplitOptions.RemoveEmptyEntries)[0];
                                    encode = Encoding.GetEncoding(charset);
                                }
                            }
                            catch
                            {
                            }


                            html = encode.GetString(buffer);
                            // http://bytes.com/topic/c-sharp/answers/228303-using-mshtml-parsing-html-files-c
                            try
                            {
                                // http://stackoverflow.com/questions/2505957/using-regex-to-remove-script-tags
                                // http://go4answers.webhost4life.com/Example/regex-match-body-tag-help-111595.aspx
                                Match match = Regex.Match(html, @"<body[^>]*>(.*?)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                if (match.Success)
                                {
                                    html = match.Value;
                                    HTMLDocument   doc  = new HTMLDocument();
                                    IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
                                    doc2.write(new object[] { html });

                                    IHTMLDOMNode dom = (IHTMLDOMNode)doc2;

                                    IHTMLElementCollection scripts = ((IHTMLElement2)doc2.body).getElementsByTagName("script");
                                    foreach (IHTMLElement script in scripts)
                                    {
                                        // http://stackoverflow.com/questions/554233/removing-htmlelement-objects-programmatically-using-c-sharp
                                        IHTMLDOMNode node = script as IHTMLDOMNode;
                                        node.parentNode.removeChild(node);
                                    }

                                    IHTMLElementCollection imgs = ((IHTMLElement2)doc2.body).getElementsByTagName("img");
                                    foreach (IHTMLElement img in imgs)
                                    {
                                        IHTMLDOMNode node = img as IHTMLDOMNode;
                                        IHTMLElement el   = img as IHTMLElement;
                                        string       src  = el.getAttribute("src");
                                        if (removeImageCheckBox.Checked || !src.StartsWith("http"))
                                        {
                                            node.parentNode.removeChild(node);
                                        }
                                    }

                                    if (removeHyperlinkCheckBox.Checked)
                                    {
                                        IHTMLElementCollection @as = ((IHTMLElement2)doc2.body).getElementsByTagName("a");
                                        foreach (IHTMLElement a in @as)
                                        {
                                            IHTMLDOMNode node = a as IHTMLDOMNode;
                                            node.parentNode.removeChild(node);
                                        }
                                    }

                                    html = doc2.body.innerHTML;
                                }
                            }
                            catch
                            {
                            }
                            html = String.Format("<html><body>{0}</body></html>", html);
                            File.WriteAllText(temp, html, encode);

                            // http://stackoverflow.com/questions/5362591/how-to-display-the-string-html-contents-into-webbrowser-control
                            //webBrowser1.DocumentText = html;

                            // http://www.c-sharpcorner.com/uploadfile/d2dcfc/convert-html-to-word-then-word-to-pdf-with-C-Sharp/
                            object           missing = System.Reflection.Missing.Value;
                            Word.Application word    = new Word.Application();
                            // http://bytes.com/topic/c-sharp/answers/243445-word-interop-quickly-inserting-html-files-into-word-doc
                            word.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
                            Word.Document document = word.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                            // http://www.cprogramdevelop.com/3434569/
                            document.ActiveWindow.View.Type = Word.WdViewType.wdWebView;
                            //word.Options.Pagination = false;
                            //word.ScreenUpdating = false;
                            word.Visible = true;

                            // http://charliedigital.com/2010/09/29/inserting-html-into-word-documents/
                            // http://msdn.microsoft.com/en-us/library/bb217015%28office.12%29.aspx
                            // http://msdn.microsoft.com/en-us/library/office/ff191763(v=office.15).aspx
                            document.Range().InsertFile(temp, missing, false, false, false);
                            //Clipboard.SetText(html, TextDataFormat.Text);
                            //word.Selection.PasteSpecial(missing, missing, missing, missing, Word.WdPasteDataType.wdPasteHTML, missing, missing);

                            word.Activate();
                        }
                        else
                        {
                        }
                    }
                }
                catch (WebException e4)
                {
                    if (e4.Message == "要求已經中止: 無法建立 SSL/TLS 的安全通道。")
                    {
                        if (retry > 0)
                        {
                            retry--;
                            // https://peacemeditation.ljm.org.tw/page.aspx?id=982
                            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
                            Navigate();
                        }
                        else
                        {
                            throw e4;
                        }
                    }
                    else
                    {
                        throw e4;
                    }
                }
                catch (Exception e2)
                {
                    throw e2;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
コード例 #36
0
        private void Vpn_PageData()
        {
            log.Info($"Entered Vpn_PageData.");
            log.Info($"  Currently on page {current_page}/{total_pages}.");

            #region write in sql table

            /// 取得gvList
            HTMLDocument d          = (HTMLDocument)m.vpnweb.Document;
            IHTMLElement gvDownLoad = d.getElementById(DOM_FOR_ACTUAL_DATA);
            log.Info($"[{DOM_FOR_ACTUAL_DATA}] is read.");

            /// 讀取
            /// 20200503 我發現Html Agility Pack不能click
            /// 只好第一層是ihtmlelement
            IHTMLElementCollection trs_ = gvDownLoad.all;
            IHTMLElementCollection trs  = trs_.tags("tr");
            DateTime current_time       = DateTime.Now;

            // 使用item這個方法可以將集合中的元素取出
            // 第一個參數代表的是順序,但是在msdn中標示為name
            // 第二個參數msdn中標示為index,但經過測試後,指的並不是順序,所以目前無法確定他的用途
            // 如果有知道的朋友,也請跟我說一下

            // current_line = 0 是標題行
            /// 20200503 我發現Html Agility Pack不能click
            /// 只好第一層是ihtmlelement

            VPN_files.Clear();
            for (current_line = 1; current_line < trs.length; current_line++)
            {
                IHTMLElement tr = trs.item(current_line, null);
                HtmlDocument h_ = new HtmlDocument();
                h_.LoadHtml(tr.innerHTML);
                HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                tbl_download result = _td_parcer(tds);

                using (NHIDataContext dc = new NHIDataContext())
                {
                    var q = from p in dc.tbl_download
                            where (p.f_name == result.f_name) && (p.SDATE == result.SDATE)
                            select p;
                    if (q.Count() == 0)
                    {
                        result.QDATE = current_time;
                        dc.tbl_download.InsertOnSubmit(result);
                        dc.SubmitChanges();
                        log.Info($"    [{result.f_name}] added to SQL server");
                    }
                }
            }

            #endregion write in sql table

            #region download files

            // making queue_files
            foreach (KeyValuePair <int, string> v in VPN_files)
            {
                if (!Local_files.Contains(v.Value))
                {
                    queue_files.Enqueue(v.Key);
                    log.Info($"    {v.Key}: {v.Value} enqueued.");
                }
            }

            if ((queue_files.Count == 0) && (current_page == total_pages))
            {
                // 這頁讀完, 且所有頁都讀完了.
                m.Refresh_Table();
                tb.ShowBalloonTip("結束", "完成所有頁面讀取", BalloonIcon.Info);
            }
            else if (queue_files.Count == 0)
            {
                log.Info($"    Nothing enqueued on page {current_page}/{total_pages}");
                Goto_next_page();
            }
            else
            {
                // 有東西才需要執行

                tb.ShowBalloonTip("計時器開始", $"一共{queue_files.Count}個檔案要下載", BalloonIcon.Info);
                // initialization
                current_line = 0;
                current_line = queue_files.Dequeue();

                // execution
                this._timer1 = new System.Timers.Timer
                {
                    Interval = 6000
                };
                this._timer1.Elapsed += new System.Timers.ElapsedEventHandler(TimersTimer_Elapsed);

                log.Info($"    _timer1 started.");
                this._timer1.Start();
            }

            #endregion download files

            log.Info("Exited Vpn_PageData.");
        }
コード例 #37
0
 private bool AllTransactionsProcessed(IHTMLElementCollection coll)
 {
     if (_transacOnPage == 0)
     {
         foreach (IHTMLElement el in coll) //count how many transactions on page
         {
             if (el.title == "Zobacz szczegóły transakcji")
             {
                 _transacOnPage++;
             }
         }
     }
     else if (_aktualnaTranzakcja == _transacOnPage) //wyjscie z petli
     {
         _status = mBankStatus.KoniecListy;
         return true;
     }
     
     return false;
 }
コード例 #38
0
 private IHTMLInputElement _get_selected_option(IHTMLElementCollection options)
 {
     foreach (IHTMLInputElement o in options)
         if (o.@checked == true)
             return o;
     return null;
 }
コード例 #39
0
        private IHTMLElement FindFormItem(IHTMLElementCollection elements, string name, int index)
        {
            IHTMLElement retVal = null;

            // loop
            foreach (IHTMLElement el in elements)
            {
                if ( (el is HTMLInputElementClass) || (el is HTMLButtonElementClass) || (el is HTMLSelectElementClass) || (el is HTMLTextAreaElementClass) )
                {
                    int itemCount = ((IHTMLElementCollection)el.children).length;

                    if ( itemCount > 0 )
                    {
                        FindItemFromCollection(el,index);
                    }
                    else
                    {
                        IHTMLElement el2 = (IHTMLElement)el;
                        if ( name == (string)el2.getAttribute("name",0) )
                        {
                            retVal = (IHTMLElement)el2;
                            break;
                        }
                    }
                }
                else
                {
                    // get children
                    //retVal = FindFormItem((IHTMLElementCollection)el.children,name,index);
                }
            }

            return retVal;
        }
コード例 #40
0
ファイル: Dorm.cs プロジェクト: carpedm20/UNIST-robot
 static IEnumerable<IHTMLElement> ElementsByClass(IHTMLElementCollection doc, string classname)
 {
     foreach (IHTMLElement e in doc)
         if (e.className == classname)
             yield return e;
 }
コード例 #41
0
 private static void AddAttributesToList(string attributeName, IHTMLElementCollection elements, ArrayList resources)
 {
     foreach (IHTMLElement element in elements)
     {
         AddAttributeToList(attributeName, element, resources);
     }
 }
コード例 #42
0
 private IHTMLElement getElementByExp(IdentifierExpression exp, IHTMLElementCollection elements)
 {
     foreach (IHTMLElement el in elements)
     {
         if (((bool)exp.IsMatch(el, BrowserType.InternetExplorer)))
             return el;
         else
         {
             //special case for the closing </li> tags
             string tagCheck = exp._identifierExpression;
             if (tagCheck.EndsWith("</li>"))
             {
                 el.innerHTML = el.innerHTML.Replace("\r\n", "</li>");
                 if (((bool)exp.IsMatch(el, BrowserType.InternetExplorer)))
                     return el;
             }
         }
     }
     return null;
 }
コード例 #43
0
 public HTMLInterface(string html)
 {
     HtmlDocument = (IHTMLElementCollection)HTMLToDom(html).body.children;
 }
コード例 #44
0
        public static int GetRadioElementIndex(IHTMLDocument2 doc, IHTMLElement ele, string itemName, string tagStr)
        {
            int  num  = 0;
            bool flag = false;

            if (ele != null)
            {
                ElementTag iD = ElementTag.ID;
                if (!string.IsNullOrEmpty(tagStr))
                {
                    iD = (ElementTag)WindowUtil.StringToInt(tagStr);
                }
                if (iD != ElementTag.ID)
                {
                    IHTMLElementCollection o = (IHTMLElementCollection)doc.all.tags("input");
                    foreach (IHTMLElement element in o)
                    {
                        if (IsElementMatchType(element, "radio") && IsElementMatch(element, iD, itemName, ""))
                        {
                            if (ele == element)
                            {
                                flag = true;
                                break;
                            }
                            num++;
                        }
                    }
                    if (o != null)
                    {
                        Marshal.ReleaseComObject(o);
                    }
                    if (!flag)
                    {
                        o = (IHTMLElementCollection)doc.all.tags("label");
                        foreach (IHTMLElement element2 in o)
                        {
                            if (element2.getAttribute("htmlFor", 0) != null)
                            {
                                string str = element2.getAttribute("htmlFor", 0).ToString();
                                if (!string.IsNullOrEmpty(str))
                                {
                                    IHTMLElement element3 = doc.all.item(str, Missing.Value) as IHTMLElement;
                                    if (((element3 != null) && IsElementMatchType(element3, "radio")) && IsElementMatch(element2, iD, itemName, ""))
                                    {
                                        if (ele == element2)
                                        {
                                            flag = true;
                                            break;
                                        }
                                        num++;
                                    }
                                }
                            }
                        }
                        if (o != null)
                        {
                            Marshal.ReleaseComObject(o);
                        }
                    }
                }
            }
            if (!flag)
            {
                num = 0;
            }
            return(num);
        }
コード例 #45
0
 public HTMLInterface(IHTMLElementCollection lElementCollection)
 {
     HtmlDocument = lElementCollection;
 }
コード例 #46
0
ファイル: Utils.cs プロジェクト: pusp/o2platform
		/// <summary>
		/// Converts the HTML element collection to an array list.
		/// </summary>
		/// <param name="elementCollection">The element collection.</param>
		/// <returns>an array list with all the elements found in the element collection</returns>
		internal static ArrayList IHtmlElementCollectionToArrayList(IHTMLElementCollection elementCollection)
		{
			ArrayList elements = new ArrayList();
			int length = elementCollection.length;

			for (int index = 0; index < length; index++)
			{
				elements.Add(elementCollection.item(index, null));
			}

			return elements;
		}
コード例 #47
0
        private void WebBrowserLogin()
        {
            Debug.WriteLine("Login URL\r\n\r\n{0}\r\n", (object)_loginBrowserHtmlDocument.location.href);

            // Wait for login.live.com page
            Debug.WriteLine("Waiting for host to switch to login.live.com");
            bool success = TimedOutOperation(kLoginPageReadyTimeout, kOperationRetryDelay, () => {
                try {
                    return
                    (_loginBrowserHtmlDocument.location.host.EndsWith("login.live.com") &&
                     _loginBrowserHtmlDocument.location.pathname.StartsWith("/oauth20_authorize.srf"));
                } catch (Exception) {
                    return(false);
                }
            });

            if (!success)
            {
                throw new LoginException("Failed waiting for login.live.com login page");
            }

            // Wait for login page to load
            Debug.WriteLine("Wait until login.live.com login page is loaded");
            success = TimedOutOperation(kLoginPageReadyTimeout, kOperationRetryDelay, () => _loginBrowserHtmlDocument.readyState == "complete");
            if (!success)
            {
                throw new LoginException("Unable to load the login.live.com login page");
            }

            IHTMLElementCollection passwdElementCollection = null;

            success = TimedOutOperation(kLoginPageReadyTimeout, kOperationRetryDelay, () => {
                passwdElementCollection = _loginBrowserHtmlDocument.getElementsByName("passwd");
                return(passwdElementCollection.length == 1);
            });

            if (!success)
            {
                throw new LoginException("Unable to get password field element");
            }

            // Get the login page elements
            Debug.WriteLine("Get the login page elements");
            HTMLInputElementClass passwordInputElement = null;
            HTMLInputElementClass signInButtonElement  = null;

            success = TimedOutOperation(kLoginPageReadyTimeout, kOperationRetryDelay, () => {
                passwordInputElement = (HTMLInputElementClass)((IHTMLElementCollection3)passwdElementCollection).namedItem("passwd");
                signInButtonElement  = (HTMLInputElementClass)_loginBrowserHtmlDocument.getElementById("idSIButton9");

                return(passwdElementCollection != null && signInButtonElement != null);
            });

            if (!success)
            {
                throw new LoginException("Unable to get login form elements");
            }

            // Update password
            LoginBrowserSetInputFieldValue(passwordInputElement, _password);

            // Click Sign In button
            Debug.WriteLine("Click Sign In button");
            signInButtonElement.click();
        }
コード例 #48
0
ファイル: IEDriver.cs プロジェクト: DougThompson/AutomateIE
        /// <summary>
        /// Try to get an element by the text of the element
        /// </summary>
        /// <param name="elems"></param>
        /// <param name="text"></param>
        /// <param name="caseSensitive"></param>
        /// <returns></returns>
        private IHTMLElement GetElementByText(IHTMLElementCollection elems, string text, bool caseSensitive)
        {
            // If there is no document, then throw exception -- sometimes the driver loses the IE instance
            if (IE.Document == null)
            {
                printTestResult(textBox1, "Error", Color.Red, String.Format("{0}   Document is null!{1}", Environment.NewLine, Environment.NewLine));
                throw new Exception("Document is null!");
            }

            // Start checking each element for the text and use case sensitivity, if requested
            IHTMLElement result;
            foreach (IHTMLElement htmlElement in elems)
            {
                string elemText = htmlElement.innerText;
                if (caseSensitive)
                {
                    if (elemText.Equals(text))
                    {
                        result = htmlElement;
                        return result;
                    }
                }
                else
                {
                    if (elemText.Equals(text, StringComparison.InvariantCultureIgnoreCase))
                    {
                        result = htmlElement;
                        return result;
                    }
                }
            }

            // Not found, so print out error and stop
            printTestResult(textBox1, "Error", Color.Red, String.Format("{0}   Element not found in current collection.{1}", Environment.NewLine, Environment.NewLine));
            throw new Exception("Element not found in current collection.");
        }
コード例 #49
0
 private void AllLayerTransferRecursion(ref List<IHTMLElement> elist, IHTMLElementCollection ec)
 {            
     foreach (IHTMLElement e in ec)
     {
         elist.Add(e);
         if (ec != null && ec.length > 0)
             AllLayerTransferRecursion(ref elist, (IHTMLElementCollection)e.children);
     }
 }
コード例 #50
0
        private void NavigateIEShell(string url, string title)
        {
            try
            {
                _logger.Trace("navigate the url. URL: " + url);

                var newBrowser = (SHDocVw.WebBrowser)(new SHDocVw.InternetExplorer());

                Uri uri = new Uri(url);
                SHDocVw.ShellWindows shellWindows = new ShellWindows();

                if (shellWindows != null && ieProcessID != 0 && shellWindows.Cast <SHDocVw.IWebBrowser2>().Any(x => x.HWND == ieProcessID))
                {
                    _logger.Trace("The exist window found to the machine");

                    var windows = shellWindows.Cast <SHDocVw.IWebBrowser2>().SingleOrDefault(x => x.HWND == ieProcessID);

                    if (windows.Document != null)
                    {
                        _logger.Trace("Going to retrieve the document from the browser.");

                        HTMLDocument htmlDoc = (HTMLDocument)windows.Document;

                        _logger.Trace("The document has been retrieved from the browser window.");
                        _logger.Trace("Going to inject the script to navigate the page.");

                        //IHTMLElementCollection nodes = htmlDoc.getElementsByTagName("script");
                        //if (nodes != null && nodes.length > 0)
                        //{
                        //    _logger.Trace("The script tag found in the document.");
                        //    foreach (IHTMLScriptElement scriptElement in nodes)
                        //    {
                        //        scriptElement.text = scriptElement.text + "window.location='" + url + "';";
                        //        _logger.Trace("Script injected successfully.");
                        //        break;
                        //    }
                        //}
                        //else
                        //{
                        //_logger.Trace("The script tag not found in the document.");

                        var scriptErrorSuppressed = (IHTMLScriptElement)htmlDoc.createElement("SCRIPT");
                        scriptErrorSuppressed.type = "text/javascript";
                        //scriptErrorSuppressed.text = "window.location='" + url + "';";
                        scriptErrorSuppressed.text = " window.open('" + url + "', '_self','" + title + "');";

                        IHTMLElementCollection headElement = htmlDoc.getElementsByTagName("head");
                        foreach (IHTMLElement elem in headElement)
                        {
                            var head = (HTMLHeadElement)elem;
                            head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);
                            _logger.Trace("Script injected successfully.");
                            break;
                        }
                        //}
                    }
                    else
                    {
                        _logger.Warn("The document is null to the window");
                    }

                    //_logger.Trace("Going to navigate the URL in the old window - " + windows.HWND);

                    //windows.Navigate(url);

                    //_logger.Trace("The URL navigated in the old window.");
                }
                else
                {
                    _logger.Trace("The existing window is not found. So going to open new window.");

                    var newBrowser = (SHDocVw.WebBrowser)(new SHDocVw.InternetExplorer());
                    //newBrowser.Name = "HimmsMainWindow";

                    _logger.Trace("Going to navigate the URL in the new window.");

                    newBrowser.Navigate(url);
                    var inptr = new IntPtr(newBrowser.HWND);
                    ieProcessID = newBrowser.HWND;
                    ShowWindow(inptr, 9);

                    _logger.Trace("The URL navigated in the new window.");
                }
            }
            catch (Exception generalException)
            {
                _logger.Error("Error occurred as " + generalException.Message);
                _logger.Trace("Error Trace : " + generalException.StackTrace);
            }
        }
コード例 #51
0
        /// <summary>
        /// a class="primary-nav-link"
        /// </summary>
        /// <param name="tagName"></param>
        /// <param name="attName"></param>
        /// <param name="attValue"></param>
        /// <returns></returns>

        public IHTMLElement GetElementByTAV(string tagName, string attName, string attValue)
        {
            HTMLDocument document = ((HTMLDocument)IE.Document);
            IHTMLElement el       = null;

            IHTMLElementCollection tags = document.getElementsByTagName(tagName);

            IEnumerator enumerator = tags.GetEnumerator();

            while (enumerator.MoveNext())
            {
                IHTMLElement element = (IHTMLElement)enumerator.Current;
                if (element.getAttribute(attName, 0).ToString().Contains(attValue))
                {
                    return(element);
                }
            }
            if (el == null)
            {
                IHTMLFramesCollection2 frames = (IHTMLFramesCollection2)document.frames;
                try
                {
                    object o = null;
                    for (int i = 0; i < frames.length; i++)
                    {
                        o = i;
                        IHTMLWindow2 fr  = (IHTMLWindow2)frames.item(ref o);
                        HTMLDocument doc = (HTMLDocument)fr.document;
                        tags = doc.getElementsByTagName(tagName);

                        enumerator = tags.GetEnumerator();

                        while (enumerator.MoveNext())
                        {
                            IHTMLElement element = (IHTMLElement)enumerator.Current;

                            bool go = false;
                            try
                            {
                                go = element.getAttribute(attName, 0).ToString().Contains(attValue);
                            }
                            catch { }
                            if (go)
                            {
                                return(element);
                            }

                            //if (element.innerText == elementValue)
                            //{
                            //    return element;
                            //}
                        }
                    }
                }
                catch (Exception ex)
                {
                    string x = ex.Message;
                }
            }
            return(null);
        }
コード例 #52
0
        /// <summary>
        /// Recursively parses the element tag collection to an ArrayList.
        /// </summary>
        /// <param name="list"> The list where the items are added.</param>
        /// <param name="coll"> The element collection.</param>
        /// <returns> An ArrayList with the parsed tags.</returns>
        private ArrayList ParseTags(ArrayList list, IHTMLElementCollection coll)
        {
            foreach (object obj in coll)
            {
                if (
                    (obj is mshtml.HTMLInputButtonElementClass)
                    ||
                    (obj is mshtml.HTMLSelectElementClass)
                    ||
                    (obj is mshtml.HTMLTextAreaElementClass)
                    ||
                    (obj is mshtml.HTMLInputElementClass)
                    )
                {
                    // Add to ArrayList
                    list.Add(obj);
                    continue;
                } else {
                    // else get items and loop again
                    IHTMLElementCollection children = (IHTMLElementCollection)((IHTMLElement)obj).children;
                    if ( children.length > 0 )
                    {
                        ParseTags(list, children);
                    }
                }
            }

            return list;
        }
コード例 #53
0
 //加入所有元素(包括子对象)
 private List<IHTMLElement> AllLayerTransefer(IHTMLElementCollection ec)
 {
     List<IHTMLElement> elist = new List<IHTMLElement>();
     AllLayerTransferRecursion(ref elist, ec);
     return elist;
 }
コード例 #54
0
        /// <summary>
        /// Loads document information into the Tree
        /// Uses each node.Tag to store information
        /// </summary>
        /// <param name="pWB">An instance of csExWB.cEXWB</param>
        public void LoadDocumentInfo(csExWB.cEXWB pWB)
        {
            treeDocInfo.Nodes.Clear();
            txtDocInfo.Clear();
            IHTMLDocument2 doc2 = null;

            //First fill in the main document information
            TreeNode root = treeDocInfo.Nodes.Add("Main Document");

            TreeNode node    = root.Nodes.Add("HTML");
            TreeNode subnode = node.Nodes.Add("Title");

            subnode.Tag = pWB.GetTitle(true);
            doc2        = (IHTMLDocument2)pWB.WebbrowserObject.Document;
            subnode     = node.Nodes.Add("URL");
            subnode.Tag = doc2.url;
            subnode     = node.Nodes.Add("Domain");
            subnode.Tag = doc2.domain;
            subnode     = node.Nodes.Add("Protocol");
            subnode.Tag = doc2.protocol;
            subnode     = node.Nodes.Add("Cookie");
            subnode.Tag = doc2.cookie;
            subnode     = node.Nodes.Add("Referrer");
            subnode.Tag = doc2.referrer;
            subnode     = node.Nodes.Add("Last Modified");
            subnode.Tag = doc2.lastModified;
            subnode     = node.Nodes.Add("Source");
            subnode.Tag = pWB.GetSource(true);
            subnode     = node.Nodes.Add("Text");
            subnode.Tag = pWB.GetText(true);

            //or pWB.GetImages(true);
            IHTMLElementCollection elems = (IHTMLElementCollection)doc2.images;

            subnode = node.Nodes.Add("Images");
            IHTMLImgElement img = null;
            string          str = string.Empty;

            foreach (IHTMLElement elem in elems)
            {
                if (elem != null)
                {
                    img  = (IHTMLImgElement)elem;
                    str += Environment.NewLine + img.src;
                }
            }
            subnode.Tag = str;

            //
            //Other collections
            //

            //elems = (IHTMLElementCollection)doc2.anchors;
            //subnode = node.Nodes.Add("Links");

            //elems = (IHTMLElementCollection)doc2.scripts;
            //subnode = node.Nodes.Add("Java Scripts");

            //IHTMLMetaElement meta = null;
            //IHTMLElementCollection col = (IHTMLElementCollection)pWB.GetElementsByTagName(true, "meta");
            //foreach (IHTMLElement elem in col)
            //{
            //    meta = (IHTMLMetaElement)elem;
            //    if (meta != null)
            //    {
            //        AllForms.m_frmLog.AppendToLog("\r\nhttpEquiv=" + meta.httpEquiv + "\r\nname=" + meta.name +
            //            "\r\nurl=" + meta.url + "\r\ncharset=" + meta.charset + "\r\ncontent=" + meta.content);
            //    }
            //    meta = null;
            //}

            //If frameset, we add the frames
            if (pWB.IsFrameset())
            {
                TreeNode            framenode = root.Nodes.Add("FRAMES");
                List <IWebBrowser2> frames    = pWB.GetFrames();
                foreach (IWebBrowser2 wb in frames)
                {
                    node        = framenode.Nodes.Add("HTML");
                    subnode     = node.Nodes.Add("Title");
                    subnode.Tag = pWB.GetTitle(wb);
                    doc2        = (IHTMLDocument2)wb.Document;
                    subnode     = node.Nodes.Add("URL");
                    subnode.Tag = doc2.url;
                    subnode     = node.Nodes.Add("Domain");
                    subnode.Tag = doc2.domain;
                    subnode     = node.Nodes.Add("Protocol");
                    subnode.Tag = doc2.protocol;
                    subnode     = node.Nodes.Add("Cookie");
                    subnode.Tag = doc2.cookie;
                    subnode     = node.Nodes.Add("Referrer");
                    subnode.Tag = doc2.referrer;
                    subnode     = node.Nodes.Add("Last Modified");
                    subnode.Tag = doc2.lastModified;
                    subnode     = node.Nodes.Add("Source");
                    subnode.Tag = pWB.GetSource(wb);
                    subnode     = node.Nodes.Add("Text");
                    subnode.Tag = pWB.GetText(wb);
                }
            }

            //Expand the root
            root.Expand();
        }
コード例 #55
0
ファイル: cEXWB.cs プロジェクト: aldoblack/webknowledge
        private bool PerformAutomationTask(IHTMLElementCollection col, AutomationTasks task, string elemname, string data)
        {
            bool bret = false;

            if (col == null) return bret;

            foreach (IHTMLElement elem in col)
            {
                if (elem != null)
                {
                    switch (task)
                    {
                        case AutomationTasks.ClickButton:
                            {
                                IHTMLInputElement btn = elem as IHTMLInputElement;
                                if ((btn != null) &&
                                    ((elem.id == elemname) ||(btn.name == elemname))
                                    )
                                {
                                    elem.click();
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.ClickLink:
                            {
                                IHTMLAnchorElement anchor = elem as IHTMLAnchorElement;
                                if( (anchor != null) &&
                                    ((elem.id == elemname) ||(anchor.name == elemname))
                                    )
                                {
                                    elem.click();
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.EnterData:
                            {
                                IHTMLInputElement inputelem = elem as IHTMLInputElement;
                                if( (inputelem != null) &&
                                    ((elem.id == elemname) ||(inputelem.name == elemname))
                                    )
                                {
                                    inputelem.value = data;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.EnterDataTextArea:
                            {
                                IHTMLTextAreaElement txtarea = elem as IHTMLTextAreaElement;
                                if ((txtarea != null) &&
                                    ((elem.id == elemname) ||(txtarea.name == elemname))
                                    )
                                {
                                    txtarea.value = data;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SelectListItem:
                            {
                                IHTMLSelectElement selelem = elem as IHTMLSelectElement;
                                if( (selelem != null) &&
                                    ((elem.id == elemname) || (selelem.name == elemname))
                                    )
                                {
                                    //data can be value or text of the htmloptionelement
                                    // Obtain the number of option objects in the select object.
                                    int icount = selelem.length;
                                    IHTMLOptionElement optelem = null;
                                    for (int i = 0; i < icount; i++)
                                    {
                                        optelem = selelem.item(i, i) as IHTMLOptionElement;
                                        if (optelem != null)
                                        {
                                            if ((optelem.text == data) ||
                                                (optelem.value == data))
                                            {
                                                optelem.selected = true;
                                                return true;
                                            }
                                        }
                                    }
                                    return false;
                                }
                            }
                            break;
                        case AutomationTasks.SelectRadioButton:
                            {
                                IHTMLInputElement inputelem = elem as IHTMLInputElement;
                                if( (inputelem != null) && 
                                    ((elem.id == elemname) ||(inputelem.name == elemname))
                                    )
                                {
                                    inputelem.checkeda = true;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SubmitForm:
                            {
                                IHTMLFormElement form = elem as IHTMLFormElement;
                                if ((form != null) &&
                                   ((elem.id == elemname) ||(form.name == elemname))
                                    )
                                {
                                    form.submit();
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SelectRadioButton2:
                            {
                                IHTMLInputElement inputelem = elem as IHTMLInputElement;
                                if ((inputelem != null) &&
                                   (((elem.id == elemname) || (inputelem.name == elemname)) &&
                                    (inputelem.value == data))
                                    )
                                {
                                    inputelem.checkeda = true;
                                    return true;
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } //End foreach

            return bret;
        }
コード例 #56
0
ファイル: HtmlElement.cs プロジェクト: 15835229565/winforms-1
        public HtmlElementCollection GetElementsByTagName(string tagName)
        {
            IHTMLElementCollection iHTMLElementCollection = ((IHTMLElement2)NativeHtmlElement).GetElementsByTagName(tagName);

            return(iHTMLElementCollection != null ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager));
        }
コード例 #57
0
 //只加入当前层元素
 private List<IHTMLElement> SingleLayerTransefer(IHTMLElementCollection ec)
 {
     List<IHTMLElement> elist = new List<IHTMLElement>();
     foreach (IHTMLElement e in ec)
         elist.Add(e);            
     return elist;
 }