示例#1
0
        private void DL_click(object sender, RoutedEventArgs e)
        {
            /// 20200329 transcribed from vb.net 20191020 created
            /// 存儲頁面
            log.Info("Enter DL_click due to download key pressed.");
            // configuration for 院所下載

            // 判斷所在的頁面
            HTMLDocument d = (HTMLDocument)vpnweb.Document;

            if (d?.getElementById("ContentPlaceHolder1_gvDownLoad") != null)
            {
                log.Info("  Clinic Download page found.");
                v = new VPN_Downloader(this, DownloadType.ClinicDownloader);
            }
            else if (d?.getElementById("cph_rptDownload") != null)
            {
                log.Info("  Special Download page found.");
                v = new VPN_Downloader(this, DownloadType.SpecialDownloader);
            }
            else
            {
                log.Info("  No download page found.");
                log.Info("Exit DL_click.");
                return;
            }
            /// 前往讀取第一頁
            v.Start();
            log.Info("Exit DL_click.");
        }
示例#2
0
        public void UpdateBrowser(ITextSnapshot snapshot)
        {
            // Generate the HTML document
            string html;

            try {
                _currentDocument = snapshot.ParseToMarkdown();
                html             = _documentRenderer.RenderStaticHtml(_currentDocument);
            } catch (Exception ex) {
                // We could output this to the exception pane of VS?
                // Though, it's easier to output it directly to the browser
                var message = ex.ToString().Replace("<", "&lt;").Replace("&", "&amp;");
                html = Invariant($"<p>{Resources.BrowserView_Error}:</p><pre>{message}</pre>");
            }

            _services.MainThread().Post(() => {
                var content = _htmlDocument?.getElementById("___markdown-content___");
                // Content may be null if the Refresh context menu option is used.  If so, reload the template.
                if (content != null)
                {
                    content.innerHTML = html;
                    // Adjust the anchors after and edit
                }
                else
                {
                    html = GetPageHtml(html);
                    Control.NavigateToString(html);
                }
                if (_htmlDocument != null)
                {
                    _documentRenderer.RenderCodeBlocks(_htmlDocument);
                }
            });
        }
示例#3
0
        private static void UpdateContent2(WebBrowser browser, string markdown)
        {
            HTMLDocument document = (HTMLDocument)browser.Document;
            IHTMLElement textArea = document?.getElementById("content");

            if (textArea == null)
            {
                browser.NavigateToString(markdown);
            }
            else
            {
                textArea.innerHTML = markdown;
            }
        }
        private void F_LoadCompleted(object sender, FrameLoadCompleteEventArgs e)
        {
            log.Debug($"++ Enter F_LoadCompleted from {e.Message}.");
            // 20200509 因為沒有先 -= F_LoadComplted, 造成了幽靈, 因此一定要 -= F_LoadComplted 在任何Exit之前.
            // 每次作業F_LoadCompleted只會被呼叫一次,沒有被洗掉的情形
            fm.FrameLoadComplete -= F_LoadCompleted;
            log.Debug($"@@ delete delegate F_LoadCompleted.");

            // 使用DocumentLoadCompletedButNotFrame, 會造成偶而不動作的症狀, 要找別的方式來處理沒插健保卡的判別
            // 方法

            if (e.Message == FrameLoadStates.DocumentLoadCompletedButNotFrame)
            {
                // 沒有lbluserID, 例如沒插健保卡
                // activate hotkeys 1
                Activate_Hotkeys();
                log.Debug($"++ Exit F_LoadCompleted (1/5). No NHI card inserted.");
                log.Info("===========================================================================");
                log.Info($" ");
                return;
            }
            /// 會有兩次
            /// 第一次讀完檔案會再執行javascript, 在local用來認證健保卡, 沒過就不會有第二次
            /// 如果認證OK, 會再透過javascript下載個案雲端資料, 觸發第二次
            /// 這段程式的目的:
            /// 1. 取得身分證字號
            /// 2. 讀取有哪些tab

            // 20210719: mark this line to simplify logging
            // log.Info($"Entered F_LoadCompleted");

            HTMLDocument d = (HTMLDocument)g.Document;
            // 確定身分證字號
            string strUID = MakeSure_UID(d.getElementById("ContentPlaceHolder1_lbluserID").innerText);

            // if (strUID = string.Empty) 離開
            if (strUID == string.Empty)
            {
                tb.ShowBalloonTip("醫療系統資料庫查無此人", "請與杏翔系統連動, 或放棄操作", BalloonIcon.Warning);

                // activate hotkeys 2
                Activate_Hotkeys();
                log.Debug($"++ Exit F_LoadCompleted (2/5). NHI card inserted but no such person.");
                log.Info("===========================================================================");
                log.Info($" ");
                return;
            }
            else
            {
                /// 表示讀卡成功
                /// show balloon with built-in icon
                tb.ShowBalloonTip("讀卡成功", $"身分證號: {strUID}", BalloonIcon.Info);
                log.Info($"  Successful NHI card read, VPN id: {strUID}.");

                /// 讀卡成功後做三件事: 讀特殊註記, 讀提醒, 開始準備讀所有資料

                /// 2. 讀取提醒, 如果有的話
                ///    這是在ContentPlaceHolder1_GV
                ///    也是個table
                IHTMLElement List_NHI_lab_reminder = d?.getElementById("ContentPlaceHolder1_GV");
                if (List_NHI_lab_reminder != null)
                {
                    HtmlDocument Html_NHI_lab_reminder = new HtmlDocument();
                    Html_NHI_lab_reminder.LoadHtml(List_NHI_lab_reminder?.outerHTML);

                    // 寫入資料庫
                    foreach (HtmlNode tr in Html_NHI_lab_reminder.DocumentNode.SelectNodes("//table/tbody/tr"))
                    {
                        HtmlDocument h_ = new HtmlDocument();
                        h_.LoadHtml(tr.InnerHtml);
                        HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                        if ((tds == null) || (tds.Count == 0))
                        {
                            continue;
                        }
                        string Lab_Name = string.Empty, Last_Date = string.Empty;
                        // tds[0] 是檢查(驗)項目類別名稱
                        Lab_Name = tds[0]?.InnerText;
                        // tds[1] 是最近1次檢查日期
                        Last_Date = tds[1]?.InnerText;

                        using (Com_clDataContext dc = new Com_clDataContext())
                        {
                            var q1 = from p1 in dc.tbl_NHI_lab_reminder
                                     where (p1.uid == strUID) && (p1.lab_name == Lab_Name) && (p1.last_date == Last_Date)
                                     select p1;
                            if (q1.Count() == 0)
                            {
                                tbl_NHI_lab_reminder newReminder = new tbl_NHI_lab_reminder()
                                {
                                    uid       = strUID,
                                    QDATE     = DateTime.Now,
                                    lab_name  = Lab_Name,
                                    last_date = Last_Date
                                };
                                dc.tbl_NHI_lab_reminder.InsertOnSubmit(newReminder);
                                dc.SubmitChanges();
                            }
                        };
                    }
                }

                /// 準備: 初始化, 欄位基礎資料/位置, 可在windows生成時就完成

                #region 準備 - 製造QueueOperation

                // Initialization
                QueueOperation?.Clear();
                ListRetrieved?.Clear();
                current_page = total_pages = 0;

                log.Info($"  start reading Operation(s).");
                // 讀取所有要讀的tab, 這些資料位於"ContentPlaceHolder1_tab"
                // IHTMLElement 無法轉型為 HTMLDocument
                // 20200429 tested successful
                IHTMLElement List_under_investigation = d?.getElementById("ContentPlaceHolder1_tab");
                // li 之下就是 a
                List <string> balloonstring = new List <string>();
                string        BalloonTip    = string.Empty;
                foreach (IHTMLElement hTML in List_under_investigation?.all)
                {
                    if (tab_id_wanted.Contains(hTML.id))
                    {
                        // 僅將要讀入的排入, 並沒有真的讀取資料
                        VPN_Operation vOP = VPN_Dictionary.Making_new_operation(hTML.id, strUID, DateTime.Now);
                        QueueOperation.Enqueue(vOP);
                        log.Info($"    讀入operation: {vOP.Short_Name}, [{strUID}]");
                        balloonstring.Add(vOP.Short_Name);
                    }
                }

                for (int i = 0; i < balloonstring.Count; i++)
                {
                    if (i == 0)
                    {
                        BalloonTip = balloonstring[i];
                    }
                    else if ((i % 3) == 0)
                    {
                        BalloonTip += $";\r\n{balloonstring[i]}";
                    }
                    else
                    {
                        BalloonTip += $"; {balloonstring[i]}";
                    }
                }
                log.Info($"  end of Reading Operation(s), 共{QueueOperation?.Count}個Operation(s).");

                #endregion 準備 - 製造QueueOperation

                #region 執行

                if (QueueOperation.Count > 0)
                {
                    // 流程控制, fm = framemonitor

                    // 載入第一個operation
                    //log.Info($"  the first operation loaded.");
                    current_op = QueueOperation.Dequeue();
                    tb.ShowBalloonTip($"開始讀取 [{current_op.UID}]", BalloonTip, BalloonIcon.Info);

                    // 判斷第一個operation是否active, (小心起見, 其實應該不可能不active)
                    // 不active就要按鍵
                    // 要注意class這個attribute是在上一層li層, 需把它改過來
                    if (d.getElementById(current_op.TAB_ID.Replace("_a_", "_li_")).className == "active")
                    {
                        // 由於此時沒有按鍵, 因此無法觸發LoadComplete, 必須人工觸發
                        fm.FrameLoadComplete += F_Data_LoadCompleted;
                        log.Debug($"@@ Add delegate F_Data_LoadCompleted.");
                        FrameLoadCompleteEventArgs ex = new FrameLoadCompleteEventArgs()
                        {
                            Message = FrameLoadStates.DirectCall
                        };
                        log.Debug($"++ Exit F_LoadCompleted (3/5). Goto F_Data_LoadCompleted by direct call.");
                        F_Data_LoadCompleted(this, ex);
                        return;
                    }
                    else
                    {
                        // 不active反而可以用按鍵, 自動會觸發F_Data_LoadCompleted
                        fm.FrameLoadComplete += F_Data_LoadCompleted;
                        log.Debug($"@@ Add delegate F_Data_LoadCompleted.");
                        // 20210719 有時候不fire
                        Thread.Sleep(150);
                        d.getElementById(current_op.TAB_ID).click();
                        log.Info($"[Action] push TAB {current_op.TAB_ID} Button.");
                        log.Debug($"++ Exit F_LoadCompleted (4/5). Go to next tab by pushing tab button.");
                        return;
                    }
                }
                else
                {
                    // 做個紀錄
                    // 一個都沒有
                    log.Info($"  no record at all.");
                    tb.ShowBalloonTip("沒有資料", "健保資料庫裡沒有資料可讀取", BalloonIcon.Info);
                    // 製作紀錄by rd
                    tbl_Query2 q = new tbl_Query2()
                    {
                        uid         = strUID,
                        QDATE       = DateTime.Now,
                        cloudmed_N  = 0,
                        cloudlab_N  = 0,
                        schedule_N  = 0,
                        op_N        = 0,
                        dental_N    = 0,
                        allergy_N   = 0,
                        discharge_N = 0,
                        rehab_N     = 0,
                        tcm_N       = 0
                    };
                    using (Com_clDataContext dc = new Com_clDataContext())
                    {
                        dc.tbl_Query2.InsertOnSubmit(q);
                        dc.SubmitChanges();
                    };

                    // activate hotkeys 3
                    Activate_Hotkeys();
                    log.Debug($"++ Exit F_LoadCompleted (5/5). NHI inserted and verified but completey no data.");
                    log.Info("===========================================================================");
                    log.Info($" ");
                }

                #endregion 執行
            }
        }
        public IHTMLElement findElement(HTMLDocument doc, IdentifierType identType, string identifier, IdentifierExpression identExp, string tagName)
        {
            IHTMLElement elem = null;
            IHTMLElementCollection elements;
            elements = null;
            switch (identType)
            {
                //If getElementByID does not work then try byExpression which is more thorough.
                case IdentifierType.Id:
                    IHTMLElement elementFound = doc.getElementById(identifier);
                    if ((elementFound != null) && (elementFound.id == identifier))
                        return elementFound;
                    else
                        return null;

                case IdentifierType.InnerHtml:
                    elements = GetElements(tagName, doc);

                    foreach (IHTMLElement el in elements)
                    {
                        if (el.innerHTML != null && el.innerHTML.Equals(identifier, StringComparison.OrdinalIgnoreCase))
                            return el;
                    }
                    break;

                case IdentifierType.InnerHtmlContains:
                    elements = GetElements(tagName, doc);

                    foreach (IHTMLElement el in elements)
                    {
                        if (el.innerHTML != null && el.innerHTML.IndexOf(identifier, 0, StringComparison.OrdinalIgnoreCase) > -1)
                            return el;
                    }
                    break;

                case IdentifierType.Expression:
                    elements = GetElements(tagName, doc);
                    return this.getElementByExp(identExp, elements);
            }

            return elem;
        }
示例#6
0
        public bool ReadComboItem(InternetExplorer IE, HTMLDocument doc,
                                  string Depth1Txt, string Depth2Txt, string Depth3Txt, string Depth4Txt,
                                  int nCurDepth, int nLastDepth,
                                  string ID, string ID2, string ID3, string ID4, string Comment,
                                  ref List <Dictionary <KPMReadInfo, List <string> > > ReadList)
        {
            bool bResult = true;

#if (DEBUG)
            g_Util.DebugPrint("[ReadComboItem]");
#endif
            string[] IDAray     = { ID, ID2, ID3, ID4 };
            string[] ItemIDAray = { ID + "_items", ID2 + "_items", ID3 + "_items", ID4 + "_items" };

            TotalWait(IE, doc, IDAray[nCurDepth]);
            IHTMLElement SelectedElement = doc.getElementById(IDAray[nCurDepth]);
            SelectedElement.click();

            TotalWait(IE, doc, ItemIDAray[nCurDepth]);
            IHTMLElementCollection elemcoll = doc.getElementById(ItemIDAray[nCurDepth]).children as IHTMLElementCollection;

            Dictionary <KPMReadInfo, List <string> > LastList = null;
            List <string> TextList = null;
            KPMReadInfo   nInfo    = null;
            int           nLen     = elemcoll.length;
            foreach (IHTMLElement elem in elemcoll)
            {
                string ElemText = elem.innerText;

                if (nCurDepth < nLastDepth - 1)
                {
                    if (nCurDepth == 0)
                    {
                        Depth1Txt = ElemText;
                    }
                    else if (nCurDepth == 1)
                    {
                        Depth2Txt = ElemText;
                    }
                    else if (nCurDepth == 2)
                    {
                        Depth3Txt = ElemText;
                    }
                    else
                    {
                        Depth4Txt = ElemText;
                    }

                    elem.click();
                    TotalWait(IE, doc);

                    int nNextdepth = nCurDepth + 1;
                    ReadComboItem(IE, doc,
                                  Depth1Txt, Depth2Txt, Depth3Txt, Depth4Txt,
                                  nNextdepth, nLastDepth,
                                  ID, ID2, ID3, ID4, Comment,
                                  ref ReadList);
                }
                else
                {   // End. Let's add all texts.
                    if (nInfo == null)
                    {
                        nInfo           = new KPMReadInfo();
                        nInfo.Depth1    = Depth1Txt; nInfo.Depth2 = Depth2Txt;
                        nInfo.Depth3    = Depth3Txt; nInfo.Depth4 = Depth4Txt;
                        nInfo.nDepthCnt = nCurDepth;
                        nInfo.sDataType = Comment;
                    }
                    if (TextList == null)
                    {
                        TextList = new List <string>();
                    }
                    if (LastList == null)
                    {
                        LastList = new Dictionary <KPMReadInfo, List <string> >();
                    }

                    TextList.Add(ElemText);
                    g_Util.DebugPrint("\t[ReadComboItem] Text Add = (" + Depth1Txt + ")(" + Depth2Txt + ")(" + Depth3Txt + ")(" + Depth4Txt + ")-" + ElemText);
                }
            }
            if (LastList != null)
            {
                LastList.Add(nInfo, TextList);
                ReadList.Add(LastList);
            }
            return(bResult);
        }
示例#7
0
        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);
        }
示例#8
0
        public void OnDocumentComplete(object pDisp, ref object URL)
        {
            const string myUhc    = "https://www.myuhc.com/member/prewelcome.do?currentLanguageFromPreCheck=en";
            const string gnc      = "https://www.gnc.com/login?original=%2Faccount";
            const string wngstp   = "https://order.wingstop.com/user/login?url=%2F";
            string       apppId   = null;
            HTMLDocument document = (HTMLDocument)webBrowser.Document;

            if (document.url == myUhc)
            {
                apppId = "1";
            }
            else if (document.url == gnc)
            {
                apppId = "2";
            }
            else if (document.url == wngstp)
            {
                apppId = "3";
            }

            HttpClient client;
            string     url = "http://localhost:52566";

            client             = new HttpClient();
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.GetAsync("api/Tables/" + apppId).Result;

            if (response.IsSuccessStatusCode)
            {
                // Calls Web API information and
                string    resp = response.Content.ReadAsStringAsync().Result;
                LoginInfo lgIn = JsonConvert.DeserializeObject <LoginInfo>(resp);
                // Checks to see which website we're currently visiting
                if (myUhc == lgIn.url)
                {
                    IHTMLInputElement userName = (IHTMLInputElement)document.getElementById(lgIn.userIdPattern);
                    userName.defaultValue = lgIn.userId;
                    IHTMLInputElement password = (IHTMLInputElement)document.getElementById(lgIn.passwordPattern);
                    password.defaultValue = lgIn.password;
                    var links = document.getElementsByTagName("a");
                    foreach (IHTMLElement link in links)
                    {
                        if (link.getAttribute("className") == lgIn.submitPattern && link.innerText == "Login")
                        {
                            link.click();
                        }
                    }
                }
                else if (gnc == lgIn.url)
                {
                    IHTMLInputElement userName = (IHTMLInputElement)document.getElementById(lgIn.userIdPattern);
                    userName.defaultValue = lgIn.userId;
                    IHTMLInputElement password = (IHTMLInputElement)document.getElementById(lgIn.passwordPattern);
                    password.defaultValue = lgIn.password;

                    var links = document.getElementsByTagName("button");
                    foreach (IHTMLElement link in links)
                    {
                        if (link.getAttribute("type").Equals(lgIn.submitPattern))
                        {
                            link.click();
                        }
                    }
                }
                else if (wngstp == lgIn.url)
                {
                    IHTMLInputElement userName = (IHTMLInputElement)document.getElementById(lgIn.userIdPattern);
                    userName.defaultValue = lgIn.userId;
                    IHTMLInputElement password = (IHTMLInputElement)document.getElementById(lgIn.passwordPattern);
                    password.defaultValue = lgIn.password;
                    IHTMLElement clicky = document.getElementById(lgIn.submitPattern);
                    clicky.click();
                }
            }
        }
 public List<MetlConfiguration> parseConfig(MeTLConfigurationProxy server, HTMLDocument doc)
 {
     var authDataContainer = doc.getElementById("authData");
     if (authDataContainer == null)
     {
         return new List<MetlConfiguration>();
     }
     var html = authDataContainer.innerHTML;
     if (html == null)
     {
         return new List<MetlConfiguration>();
     }
     var xml = XDocument.Parse(html).Elements().ToList();
     var cc = getElementsByTag(xml, "clientConfig");
     var xmppDomain = getElementsByTag(cc, "xmppDomain").First().Value;
     var xmppUsername = getElementsByTag(cc, "xmppUsername").First().Value;
     var xmppPassword = getElementsByTag(cc, "xmppPassword").First().Value;
     var imageUrl = getElementsByTag(cc, "imageUrl").First().Value;
     return new List<MetlConfiguration>
     {
         new MetlConfiguration(server.name,server.imageUrl.ToString(),xmppDomain,xmppUsername,xmppPassword,server.host)
     };
 }
示例#10
0
        public void regExtension()
        {
            document = (HTMLDocument)webBrowser.Document;
            IHTMLElement e = document.getElementById("_BHO_");
            append(""+(e == null));

            if(e == null)
            {
                IHTMLElement body = document.body;
                body.insertAdjacentHTML("afterBegin", "<input id=\"_BHO_\" type=\"text\" value=\""+ DateTime.Now.ToString()+"\" />");
                append("regExtension");
                this.regExtFun();
                this.regExtJs();
            }
        }
示例#11
0
        public void libraryLinky()
        {
            try
            {
                string href = document.location.href;
                Regex  reg  = new Regex(@"/(dp|ASIN|product)/([\dX]{10})");
                Match  m    = reg.Match(href);
                string title;
                if (m.Success && m.Groups.Count == 3)
                {
                    string         isbn = m.Groups[2].Value;
                    HTMLDivElement div  = (HTMLDivElement)document.getElementById("btAsinTitle").parentElement.parentElement;
                    title = truncate(Regex.Replace(document.getElementById("btAsinTitle").innerHTML, "</?[^>]+>", ""));
                    addLoadingIcon((IHTMLDOMNode)div);
                    string url = "http://api.calil.jp/check?appkey=" + appkey + "&isbn=" + isbn + "&systemid=" + selectedSystemId + "&format=xml";
                    checkLibrary(url, (IHTMLDOMNode)div, isbn, title);
                }
                else if ((href.IndexOf("wishlist") != -1) || (href.IndexOf("/s?") != -1) || (href.IndexOf("/s/") != -1) || (href.IndexOf("/exec/") != -1) || (href.IndexOf("/gp/search") != -1) || (href.IndexOf("/gp/bestsellers/") != -1))
                {
                    IHTMLElementCollection objects = null;
                    if (href.IndexOf("wishlist") != -1)
                    {
                        objects = (IHTMLElementCollection)document.getElementsByTagName("span");
                    }
                    else
                    {
                        objects = (IHTMLElementCollection)document.getElementsByTagName("div");
                    }
                    if (objects != null)
                    {
                        IEnumerator objEnum = objects.GetEnumerator();
                        while (objEnum.MoveNext())
                        {
                            IHTMLElement obj = (IHTMLElement)objEnum.Current;
                            if (obj.className == null)
                            {
                                continue;
                            }
                            if (obj.className == "productTitle" || (obj.className == "title" && obj.parentElement.className == "data") || obj.className == "fixed-line")
                            {
                                IHTMLDOMChildrenCollection childs = null;
                                if (((IHTMLElement)obj).tagName.ToLower() == "span")
                                {
                                    childs = (IHTMLDOMChildrenCollection)((HTMLSpanElement)obj).childNodes;
                                }
                                else
                                {
                                    childs = (IHTMLDOMChildrenCollection)((HTMLDivElement)obj).childNodes;
                                }
                                IEnumerator childEnum = childs.GetEnumerator();
                                while (childEnum.MoveNext())
                                {
                                    if (((IHTMLElement)childEnum.Current).tagName.ToLower() == "a")
                                    {
                                        HTMLAnchorElement link = (HTMLAnchorElement)childEnum.Current;
                                        if (link != null)
                                        {
                                            reg = new Regex("<span title='(.+)'>");
                                            m   = reg.Match(link.innerHTML);
                                            if (m.Success && m.Groups.Count == 2)
                                            {
                                                title = truncate(stripTags(m.Groups[1].Value.Trim()));
                                            }
                                            else
                                            {
                                                title = truncate(stripTags(Regex.Replace(link.innerHTML, @"<\w[^>]*?>", "")));
                                            }

                                            reg = new Regex(@"/dp/([\dX]{10})/ref");
                                            m   = reg.Match(link.href);
                                            if (m.Success && m.Groups.Count == 2)
                                            {
                                                string isbn = m.Groups[1].Value;
                                                addLoadingIcon((IHTMLDOMNode)obj);
                                                string url = "http://api.calil.jp/check?appkey=" + appkey + "&isbn=" + isbn + "&systemid=" + selectedSystemId + "&format=xml";
                                                checkLibrary(url, (IHTMLDOMNode)obj, isbn, title);
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                AddErrorLog(ex);
                MessageBox.Show(ex.Message);
            }
        }
示例#12
0
        IHTMLElement FindElement(string xPath, HTMLDocument doc)
        {
            IHTMLElement theElement = null;

            try
            {
                string[] tmp = xPath.Split(new string[] { "##" }, StringSplitOptions.None);

                string elementAttributes = tmp[1];
                string[] attributes = elementAttributes.Split(new string[] { ";" }, StringSplitOptions.None);
                string attributeId = attributes[0].Replace(@"id=", "");
                string attributeName = attributes[1].Replace(@"name=", "");
                string attributeClass = attributes[2].Replace(@"class=", "");

                string[] xPathParts = tmp[0].Split('/');
                string elementTagName = xPathParts[xPathParts.Length - 1];
                if (elementTagName.Contains("["))
                {
                    elementTagName = elementTagName.Split('[')[0];
                }

                // try in first place the id (if it's unique)
                theElement = doc.getElementById(attributeId);
                if (theElement != null && !String.IsNullOrEmpty(attributeId))
                {
                    int c = 0;
                    IHTMLElementCollection possibleElements = doc.getElementsByTagName(elementTagName);
                    foreach (IHTMLElement possibleElement in possibleElements)
                    {
                        if (possibleElement.id == attributeId)
                        {
                            c++;
                        }
                    }

                    if (c > 1)
                    {
                        theElement = null;
                    }
                }

                if (theElement == null && !String.IsNullOrEmpty(attributeName))
                {
                    IHTMLElementCollection possibleElements = doc.getElementsByName(attributeName);
                    if (possibleElements.length == 1)
                    {
                        theElement = (IHTMLElement)possibleElements.item(null, 0);
                    }
                }

                // try next, the exact xpath
                try
                {
                    if (theElement == null)
                    {
                        IHTMLElementCollection possibleElements = doc.getElementsByTagName(elementTagName);
                        foreach (IHTMLElement possibleElement in possibleElements)
                        {
                            string possibleXPath = "";
                            try
                            {
                                possibleXPath = Utils.FindXPath(possibleElement);
                                //Utils.l(possibleXPath);
                            }
                            catch (Exception e) {
                                //Utils.l(e);
                            }

                            if (possibleXPath == xPath)
                            {
                                theElement = possibleElement;
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.l(ex);
                }

                try
                {
                    // next, try the path skipping attributes
                    if (theElement == null)
                    {
                        string cleanXPath = tmp[0];
                        IHTMLElementCollection possibleElements = doc.getElementsByTagName(elementTagName);
                        foreach (IHTMLElement possibleElement in possibleElements)
                        {
                            if (possibleElement.tagName == "INPUT") {
                                IHTMLInputElement tmpInput = (IHTMLInputElement)possibleElement;
                                if (tmpInput.type == "hidden" || tmpInput.type == "text" || tmpInput.type == "password")
                                {
                                    continue;
                                }
                            }

                            string possibleXPath = Utils.FindXPath(possibleElement);
                            string[] possibleTmp = possibleXPath.Split(new string[] { "##" }, StringSplitOptions.None);
                            string cleanPossibleXPath = possibleTmp[0];

                            if (cleanPossibleXPath == cleanXPath)
                            {
                                theElement = possibleElement;
                                break;
                            }
                        }
                    }
                }
                catch (Exception ee)
                {
                    Utils.l(ee);
                }

            }
            catch (Exception e)
            {
                Utils.l(e);
            }

            return theElement;
        }
示例#13
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);
            IHTMLElement       button  = doc.getElementById("btn_download");

            await Pause(5000); //Wait 5 Seconds.

            button.click();    //Click button

            string tempFile = $"{System.IO.Path.GetTempPath()}{Guid.NewGuid().ToString()}.lf.html";

            await JavaScriptProcessingTime(); //Wait 15 seconds.

            using (var output = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
            {
                byte[] buffer = ASCIIEncoding.UTF8.GetBytes(((HTMLDocument)browser.Document).documentElement.outerHTML);
                await output.WriteAsync(buffer, 0, buffer.Length);
            }

            UpdateStatus("Scanning Web page after link...");

            var   line  = string.Empty;
            var   input = new StreamReader(tempFile);
            Match match = null;

            while ((line = input.ReadLine()) != null) //Scan file for link.
            {
                if (line == "")
                {
                    continue;
                }
                match = _bourceUrlPattern.Match(line);

                if (match.Success)
                {
                    break;
                }
            }

            var sourceUrl = string.Empty;
            var response  = LinkFetchResult.SUCCESSFULL;

            if (match.Success)
            {
                sourceUrl = match.Groups[2].Value;
            }
            else
            {
                response = LinkFetchResult.FAILED;
            }
            return(new Tuple <string, LinkFetchResult>(sourceUrl, response));
        }
        // Recursive implementation of the above function.
        //
        private IHTMLElement GetElementByID(string id, HTMLDocument parentDoc)
        {
            string[] frameTags = new string[] {"FRAME", "IFRAME"};
            IHTMLElement element = null;

            // Try getting element directly from doc...
            //
            element = parentDoc.getElementById(id);

            // Otherwise, search all current frames.
            //
            foreach(string tag in frameTags)
            {
                if (element == null)
                {
                    FramesCollection frames = parentDoc.frames;

                    int i = 0;
                    while (i < frames.length && element == null)
                    {
                        // Get document from frame
                        //
                        object refID = i;
                        HTMLWindow2 frame = (HTMLWindow2)frames.item(ref refID);
                        HTMLDocument currentDocument = (HTMLDocument)frame.document;

                        // Wait for document to load
                        //
                        // TODO: Handle frames which can't access readyState
                        while (!currentDocument.readyState.Equals("complete")) { Thread.Sleep(500); }

                        // Get element
                        //
                        element = currentDocument.getElementById(id);

                        // Release COM objects as appropriate
                        //
                        Marshal.ReleaseComObject(frame);

                        // Check sub-frames and release appropriately
                        //
                        if (element == null)
                        {
                            // Check child frames
                            //
                            element = this.GetElementByID(id, currentDocument);

                            if (element == null)
                            {
                                Marshal.ReleaseComObject(currentDocument);
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }

                        i++;
                    }

                    Marshal.ReleaseComObject(frames);
                }
            }

            return element;
        }
示例#15
0
 private void WebBrowser_LoadCompleted(object sender, NavigationEventArgs e)
 {
     HTMLDocument doms        = (HTMLDocument)webBrowser.Document;
     IHTMLElement kw          = doms.getElementById("reportModal");
     var          cssSelector = CssPath(kw, true);
 }
示例#16
0
 private string[] GetRFFYDInfo()
 {
     string[] strArray = new string[3];
     try
     {
         HTMLDocument document = (HTMLDocument)this.axWebBrowser1.Document;
         if (!document.url.ToLower().Contains("default.aspx"))
         {
             return(null);
         }
         FramesCollection frames = document.parentWindow.frames;
         for (int i = 0; i < frames.length; i++)
         {
             object pvarIndex             = i;
             mshtml.IHTMLWindow2 window2  = (mshtml.IHTMLWindow2)frames.item(ref pvarIndex);
             FramesCollection    framess2 = window2.frames;
             string tagName = "";
             for (int j = 0; j < framess2.length; j++)
             {
                 object obj3 = j;
                 mshtml.IHTMLWindow2 window3   = (mshtml.IHTMLWindow2)framess2.item(ref obj3);
                 HTMLDocument        document2 = window3.document as HTMLDocument;
                 if (document2.url.Contains("InDoor.aspx"))
                 {
                     HTMLTextAreaElement element = document2.getElementById("txtCPH") as HTMLTextAreaElement;
                     HTMLTable           table   = document2.getElementById("GridView1") as HTMLTable;
                     bool flag = false;
                     foreach (HTMLTableRow row in table.rows)
                     {
                         foreach (HTMLTableCell cell in row.cells)
                         {
                             foreach (mshtml.IHTMLElement element2 in cell.getElementsByTagName("INPUT"))
                             {
                                 if ((element2.getAttribute("type", 0).ToString() == "checkbox") && (element2.getAttribute("checked", 0).ToString().ToUpper() == "TRUE"))
                                 {
                                     tagName = cell.tagName;
                                     flag    = true;
                                 }
                             }
                             if (flag)
                             {
                                 if (cell.cellIndex == 3)
                                 {
                                     strArray[0] = cell.innerText;
                                 }
                                 if (cell.cellIndex == 1)
                                 {
                                     strArray[1] = cell.innerText;
                                 }
                                 if (cell.cellIndex == 4)
                                 {
                                     strArray[2] = cell.innerText;
                                 }
                             }
                         }
                         if (flag)
                         {
                             break;
                         }
                     }
                 }
             }
         }
         return(strArray);
     }
     catch (Exception)
     {
         return(null);
     }
 }
示例#17
0
        private bool ExtractRegistrationLink(EmailMessage email)
        {
            string body;

            if (ConfigurationManager.AppSettings["debug_mode"] == "Y")
            {
                Console.WriteLine(DateTime.Now.ToString() + " DEBUG Email Subject ==> " + email.Subject.ToString());
            }

            //if (email.Subject.IndexOf(m_filtersubject) > 0)
            {
                body = email.Body;

                int linkStart = body.LastIndexOf("https://");
                int linkEnd   = body.LastIndexOf("</a>");

                if (linkEnd <= linkStart)
                {
                    return(false);
                }

                /* sample link => https://hatesting.brightidea.com/ct/ct_login.php?br=40F88B5D */

                string link = body.Substring(linkStart, linkEnd - linkStart);

                if (link.IndexOf("ct/ct_login.php?") < 0)
                {
                    return(false);
                }

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);
                request.Method = "GET";

                /*
                 *              IWebProxy proxy = request.Proxy;
                 *              // Print the Proxy Url to the console.
                 *              if (proxy != null)
                 *              {
                 *                  Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
                 *              }
                 *              else
                 *              {
                 *                  Console.WriteLine("Proxy is null; no proxy will be used");
                 *              }
                 */
                try
                {
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                    using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()))
                    {
                        string sPage = reader.ReadToEnd();
                        // Process the response text if you need to...
                        object[] oPageText = { sPage };

                        HTMLDocument   doc  = new HTMLDocument();
                        IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
                        doc2.write(oPageText);

                        HTMLInputElement screenEle = (HTMLInputElement)doc.getElementById("b_register_screen_name");
                        HTMLInputElement emailEle  = (HTMLInputElement)doc.getElementById("b_register_email");

                        response.Close();

                        if (screenEle is null || emailEle is null)
                        {
                            Console.WriteLine(DateTime.Now.ToString() + " ERROR Fail to extract the UserId and Email from " + link);
                            return(false);
                        }
                        if (ConfigurationManager.AppSettings["debug_mode"] == "Y")
                        {
                            Console.WriteLine(DateTime.Now.ToString() + " DEBUG Extracted values ==> " + screenEle.value + "," + emailEle.value + "," + link);
                        }

                        m_screen = screenEle.value;
                        m_email  = emailEle.value;
                        m_link   = link;
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(DateTime.Now.ToString() + " ERROR " + ex.Message);
                    return(false);
                }
            }
            //return false;
        }
示例#18
0
 private bool IsConfirmPage(HTMLDocument doc)
 {
     return(doc.getElementById(MODIFY_BUTTON) != null && doc.getElementById(CONFIRM_BUTTON) != null);
 }
示例#19
0
        private void GetTransactionsForSelectedAccount()
        {
            HTMLDocument dom   = (HTMLDocument)_transactionsBrowser.Document;
            object       ttObj = dom.getElementById("ctlActivityTable");

            var account = GetSelectedAccount();

            if (ttObj is IHTMLTable transactionsTable)
            {
                foreach (var rowObj in transactionsTable.rows)
                {
                    var row = (IHTMLTableRow)rowObj;
                    if (row.rowIndex == 0)
                    {
                        continue;
                    }

                    var transaction = new TransactionBasic();
                    foreach (var cellObj in row.cells)
                    {
                        var cell = (HTMLTableCell)cellObj;
                        switch (cell.cellIndex)
                        {
                        case 1:
                            var date = cell.innerText.Split('/');
                            transaction.PaymentDate = new DateTime(2000 + Convert.ToInt32(date[2]), Convert.ToInt32(date[1]), Convert.ToInt32(date[0]));
                            break;

                        case 2:
                            Encoding wind1252 = Encoding.GetEncoding(1255);
                            Encoding utf8     = Encoding.UTF8;

                            byte[] wind1252Bytes = wind1252.GetBytes(cell.innerText);
                            byte[] utf8Bytes     = Encoding.Convert(wind1252, utf8, wind1252Bytes);
                            string utf8String    = Encoding.UTF8.GetString(utf8Bytes);
                            transaction.Description = utf8String;
                            break;

                        case 3:
                            transaction.SupplierId = cell.innerText;
                            break;

                        case 4:
                            if (!String.IsNullOrWhiteSpace(cell.innerText))
                            {
                                transaction.Type   = TransactionType.Expense;
                                transaction.Amount = Convert.ToDecimal(cell.innerText);
                            }
                            break;

                        case 5:
                            if (!String.IsNullOrWhiteSpace(cell.innerText))
                            {
                                transaction.Type   = TransactionType.Income;
                                transaction.Amount = Convert.ToDecimal(cell.innerText);
                            }
                            break;

                        case 6:
                            transaction.CurrentBalance = Convert.ToDecimal(cell.innerText);
                            break;

                        default: break;
                        }
                    }

                    account.Transactions.Add(transaction);
                }
            }
        }
示例#20
0
        public void OnDocumentComplete(object pDisp, ref object URL)
        {
            /*
             * Проверка по адресу
             */
            string url = URL.ToString();
            bool matched = false;
            foreach (Regex reg in regulars)
            {
                if (reg.Match(url).Success)
                {
                    matched = true;
                    break;
                }
            };
            if (!matched)
            {
                return;
            }

            document = (HTMLDocument)webBrowser.Document;
            /*
             * скрипт уже подключён
             */
            if (document.getElementById(scriptElementId) != null)
            {
                return;
            };

            // создаем скрипт
            string source = vkpatch.Properties.Resources.vkpatch.ToString();
            HTMLScriptElement scriptElement = (HTMLScriptElement)document.createElement("script");
            scriptElement.text = source;
            scriptElement.id = "vkpatch";

            // выполняем инъекцию в head
            IHTMLElementCollection heads = document.getElementsByTagName("head");
            foreach (HTMLHeadElement head in heads)
            {
                head.appendChild((IHTMLDOMNode) scriptElement);
                break;
            }
        }
示例#21
0
        IHTMLElement FindElement(string xPath, HTMLDocument doc)
        {
            IHTMLElement theElement = null;

            try
            {
                string[] tmp = xPath.Split(new string[] { "##" }, StringSplitOptions.None);

                string   elementAttributes = tmp[1];
                string[] attributes        = elementAttributes.Split(new string[] { ";" }, StringSplitOptions.None);
                string   attributeId       = attributes[0].Replace(@"id=", "");
                string   attributeName     = attributes[1].Replace(@"name=", "");
                string   attributeClass    = attributes[2].Replace(@"class=", "");

                string[] xPathParts     = tmp[0].Split('/');
                string   elementTagName = xPathParts[xPathParts.Length - 1];
                if (elementTagName.Contains("["))
                {
                    elementTagName = elementTagName.Split('[')[0];
                }


                // try in first place the id (if it's unique)
                theElement = doc.getElementById(attributeId);
                if (theElement != null && !String.IsNullOrEmpty(attributeId))
                {
                    int c = 0;
                    IHTMLElementCollection possibleElements = doc.getElementsByTagName(elementTagName);
                    foreach (IHTMLElement possibleElement in possibleElements)
                    {
                        if (possibleElement.id == attributeId)
                        {
                            c++;
                        }
                    }

                    if (c > 1)
                    {
                        theElement = null;
                    }
                }


                if (theElement == null && !String.IsNullOrEmpty(attributeName))
                {
                    IHTMLElementCollection possibleElements = doc.getElementsByName(attributeName);
                    if (possibleElements.length == 1)
                    {
                        theElement = (IHTMLElement)possibleElements.item(null, 0);
                    }
                }


                // try next, the exact xpath
                try
                {
                    if (theElement == null)
                    {
                        IHTMLElementCollection possibleElements = doc.getElementsByTagName(elementTagName);
                        foreach (IHTMLElement possibleElement in possibleElements)
                        {
                            string possibleXPath = "";
                            try
                            {
                                possibleXPath = Utils.FindXPath(possibleElement);
                                //Utils.l(possibleXPath);
                            }
                            catch (Exception e) {
                                //Utils.l(e);
                            }

                            if (possibleXPath == xPath)
                            {
                                theElement = possibleElement;
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.l(ex);
                }


                try
                {
                    // next, try the path skipping attributes
                    if (theElement == null)
                    {
                        string cleanXPath = tmp[0];
                        IHTMLElementCollection possibleElements = doc.getElementsByTagName(elementTagName);
                        foreach (IHTMLElement possibleElement in possibleElements)
                        {
                            if (possibleElement.tagName == "INPUT")
                            {
                                IHTMLInputElement tmpInput = (IHTMLInputElement)possibleElement;
                                if (tmpInput.type == "hidden" || tmpInput.type == "text" || tmpInput.type == "password")
                                {
                                    continue;
                                }
                            }

                            string   possibleXPath      = Utils.FindXPath(possibleElement);
                            string[] possibleTmp        = possibleXPath.Split(new string[] { "##" }, StringSplitOptions.None);
                            string   cleanPossibleXPath = possibleTmp[0];

                            if (cleanPossibleXPath == cleanXPath)
                            {
                                theElement = possibleElement;
                                break;
                            }
                        }
                    }
                }
                catch (Exception ee)
                {
                    Utils.l(ee);
                }
            }
            catch (Exception e)
            {
                Utils.l(e);
            }

            return(theElement);
        }
示例#22
0
        private async void ParsingTables(string o)
        {
            tb.ShowBalloonTip($"讀取完成 [{current_op?.UID}]", "開始解析與寫入資料庫", BalloonIcon.Info);
            log.Info($"[Info] all HTML loaded into memory. start to analyze. [{current_op?.UID}]");

            // Count = 0 代表最後一個 tab
            // 20200504 這裡一個BUG, 漏了把F_DATA_Loadcompleted刪掉,以至於不斷重複多次. ******

            /// 確定是最後一個tab這段程式到此結束
            /// 4. Parsing & Saving to SQL: async
            ///     4-1. 多工同時處理, 快速
            ///     4-2. 依照欄位資料/位置 Parsing
            ///     4-3. 存入SQL
            ///     4-4. 製作Query
            /// 查核機制?
            log.Debug($"[Start] async process, {current_op?.UID}");
            List <Response_DataModel> rds = await VPN_Dictionary.RunWriteSQL_Async(ListRetrieved);

            log.Debug($"[End] async process, {current_op?.UID}");

            /// 1. 讀取特殊註記, 如果有的話
            ///    這是在ContentPlaceHolder1_tab02
            ///    是個table
            // 每當刷新後都要重新讀一次
            // d 是parent HTML document
            HTMLDocument d = (HTMLDocument)g.Document;

            IHTMLElement Special_remark  = d?.getElementById("ContentPlaceHolder1_tab02");
            string       _special_remark = Special_remark?.innerText;

            // 製作紀錄by rd
            try
            {
                short?med_N = (short?)(from p1 in rds
                                       where p1.SQL_Tablename == SQLTableName.Medicine
                                       select p1.Count).Sum(),
                     lab_N = (short?)(from p1 in rds
                                      where p1.SQL_Tablename == SQLTableName.Laboratory
                                      select p1.Count).Sum(),
                     schedule_N = (short?)(from p1 in rds
                                           where p1.SQL_Tablename == SQLTableName.Schedule_report
                                           select p1.Count).Sum(),
                     op_N = (short?)(from p1 in rds
                                     where p1.SQL_Tablename == SQLTableName.Operations
                                     select p1.Count).Sum(),
                     dental_N = (short?)(from p1 in rds
                                         where p1.SQL_Tablename == SQLTableName.Dental
                                         select p1.Count).Sum(),
                     allergy_N = (short?)(from p1 in rds
                                          where p1.SQL_Tablename == SQLTableName.Allergy
                                          select p1.Count).Sum(),
                     discharge_N = (short?)(from p1 in rds
                                            where p1.SQL_Tablename == SQLTableName.Discharge
                                            select p1.Count).Sum(),
                     rehab_N = (short?)(from p1 in rds
                                        where p1.SQL_Tablename == SQLTableName.Rehabilitation
                                        select p1.Count).Sum(),
                     tcm_N = (short?)(from p1 in rds
                                      where p1.SQL_Tablename == SQLTableName.TraditionalChineseMedicine_detail
                                      select p1.Count).Sum();
                Com_clDataContext dc = new Com_clDataContext();
                tbl_Query2        q  = new tbl_Query2()
                {
                    uid    = ListRetrieved.First().UID,
                    QDATE  = ListRetrieved.First().QDate,
                    EDATE  = DateTime.Now,
                    remark = _special_remark
                };
                q.cloudmed_N  = med_N;
                q.cloudlab_N  = lab_N;
                q.schedule_N  = schedule_N;
                q.op_N        = op_N;
                q.dental_N    = dental_N;
                q.allergy_N   = allergy_N;
                q.discharge_N = discharge_N;
                q.rehab_N     = rehab_N;
                q.tcm_N       = tcm_N;
                dc.tbl_Query2.InsertOnSubmit(q);
                dc.SubmitChanges();
                log.Info($"[Final Step]Successfully write into tbl_Query2. From: {ListRetrieved.First().UID}, [{ListRetrieved.First().QDate}]");
                tb.ShowBalloonTip($"寫入完成 [{current_op?.UID}]", "已寫入資料庫", BalloonIcon.Info);
            }
            catch (Exception ex)
            {
                log.Error($"[Final Step]Failed to write into tbl_Querry2. From:  {ListRetrieved.First().UID}, [{ListRetrieved.First().QDate}] Error: {ex.Message}");
            }

            // 更新顯示資料
            string tempSTR = s.m.Label1.Text;

            s.m.Label1.Text = string.Empty;
            s.m.Label1.Text = tempSTR;
            s.m.Web_refresh();

            // activate hotkeys 4
            Activate_Hotkeys();

            log.Debug(o);
            log.Info("===========================================================================");
            log.Info($" ");
        }
示例#23
0
        private void button1_Click(object sender, EventArgs e)
        {
            ////// Create a new instance of the Firefox driver.

            ////// Notice that the remainder of the code relies on the interface,
            ////// not the implementation.

            ////// Further note that other drivers (InternetExplorerDriver,
            ////// ChromeDriver, etc.) will require further configuration
            ////// before this example will work. See the wiki pages for the
            ////// individual drivers at http://code.google.com/p/selenium/wiki
            ////// for further information.
            ////IWebDriver driver = new FirefoxDriver();

            //////Notice navigation is slightly different than the Java version
            //////This is because 'get' is a keyword in C#
            ////driver.Navigate().GoToUrl("http://www.google.com/");

            ////// Find the text input element by its name
            ////IWebElement query = driver.FindElement(By.Name("q"));

            ////// Enter something to search for
            ////query.SendKeys("Cheese");

            ////// Now submit the form. WebDriver will find the form for us from the element
            ////query.Submit();

            ////// Google's search is rendered dynamically with JavaScript.
            ////// Wait for the page to load, timeout after 10 seconds
            ////WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            ////wait.Until((d) => { return d.Title.ToLower().StartsWith("cheese"); });

            ////// Should see: "Cheese - Google Search"
            ////System.Console.WriteLine("Page title is: " + driver.Title);

            //////Close the browser
            ////driver.Quit();
            //string IELocation = @"%ProgramFiles%\Internet Explorer\iexplore.exe";
            //IELocation = System.Environment.ExpandEnvironmentVariables(IELocation);

            //Console.WriteLine("Launching IE ");
            //Process p = Process.Start(IELocation, @"http://www.baidu.com");
            //Thread.Sleep(3000);

            //Console.WriteLine("Attaching to IE ... ");
            //InternetExplorer ie = null;

            //string ieWindowName = "空白页";
            //if (p != null)
            //{
            //    //Console.WriteLine("Process handle is: " + p.MainWindowHandle.ToString());
            //    SHDocVw.ShellWindows allBrowsers = new ShellWindowsClass();
            //    Console.WriteLine("Number of active IEs :" + allBrowsers.Count.ToString());
            //    if (allBrowsers.Count != 0)
            //    {
            //        SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
            //        foreach (SHDocVw.InternetExplorer ieVW in shellWindows)
            //        {
            //            // 判斷視窗是否為 iexplore
            //            if (Path.GetFileNameWithoutExtension(ieVW.FullName).ToLower().Equals("iexplore"))
            //            {
            //                ie = ieVW;
            //                break;
            //            }
            //        }


            //        //for (int i = 0; i < allBrowsers.Count; i++)
            //        //{
            //        //    //IWebBrowser2 iwb2 = allBrowsers.Item(i) as IWebBrowser2;

            //        //    InternetExplorer eitem = (InternetExplorer)allBrowsers.Item(i);
            //        //    int l = eitem.HWND;
            //        //    int j = 0;
            //        //    j++;
            //        //    if (eitem.HWND == (int)p.MainWindowHandle.ToInt32())
            //        //    {
            //        //        ie = eitem;
            //        //        break;
            //        //    }
            //        //}
            //    }
            //    else
            //        throw new Exception("Faul to find IE");
            //}
            //else
            //    throw new Exception("Fail to launch IE");

            ////var ie = new SHDocVw.InternetExplorer();
            ////ie.Visible = true;
            ////object o = null;
            ////Console.WriteLine("打开百度首页...");
            ////ie.Navigate(@"http://www.baidu.com", ref o, ref o, ref o, ref o);
            //Thread.Sleep(1000);

            //HTMLDocument doc = (HTMLDocument)ie.Document;

            //Console.WriteLine("网站标题:" + doc.title);

            //Console.WriteLine("输入搜索关键字:飞苔博客");
            //var keyEle = doc.getElementById("kw");
            //keyEle.setAttribute("value", "飞苔博客", 0);

            //Console.WriteLine("点击[百度一下]按钮,进行搜索");
            //var btnSubmit = doc.getElementById("su");
            //btnSubmit.click();
            //Thread.Sleep(500);

            //Console.WriteLine("网站标题:" + doc.title);
            ////var relatedSearchResultEle = doc.getElementsByTagName("SPAN").Cast<ihtmlelement>().Where(ele => ele.className == "nums").FirstOrDefault();
            //Console.WriteLine("百度相关搜索结果:");
            //p.Close();
            ////Console.WriteLine(relatedSearchResultEle.innerHTML);
            object o = null;

            SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorerClass();

            SHDocVw.WebBrowser wb = (SHDocVw.WebBrowser)ie;
            wb.Visible    = true;
            wb.FullScreen = true;
            //Do anything else with the window here that you wish
            wb.Navigate("http://www.taobao.com/", ref o, ref o, ref o, ref o);
            while (wb.Busy)
            {
                Thread.Sleep(100);
            }
            HTMLDocument          document = ((HTMLDocument)wb.Document);
            IHTMLElement          element  = document.getElementById("q");
            HTMLInputElementClass email    = (HTMLInputElementClass)element;

            email.value = "包装盒子";

            var elements = document.getElementsByTagName("button");

            foreach (HTMLButtonElementClass element1 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 (element1.innerHTML.Contains("搜 索"))
                {
                    element1.click();
                }
            }
            //for (int i = 0; i < count; i++)
            //{

            //    //去抓標籤名字有a的,像是連結<a href=xx>這種

            //    //奇怪的是這個方法如果要抓一些標籤都抓不到,像是<td><tr>那些=.=

            //    //所以那些我是用另外的方法抓的,等下會講
            //    if (document.all[i].TagName.ToLower().Equals("button"))
            //    {

            //        //GetAttribute就是去取得標籤的屬性的內容,例:

            //        //<a href ="我是屬性的內容" target=_blank>,不過有些屬性取不到,像是class

            //        if (doc.All[i].GetAttribute("type").Contains("submit"))
            //        {                             //InnerText就是取得標籤中間的內容,<標籤>內容</標籤>
            //            //richTextContent1.AppendText(doc.All[i].InnerText);
            //            //richTextContent1.AppendText(doc.All[i].GetAttribute("href"));
            //            //richTextContent1.AppendText(Environment.NewLine);

            //            ////另外這個函式可以去更改HTML裡面屬性的內容
            //            //XXX.SetAttribute("value", "Hello");
            //            int j = i;
            //            j++;
            //        }
            //    }
            //}
            IHTMLElement           search    = document.getElementById(@"tag:BUTTON&value:搜 索");
            HTMLButtonElementClass searchEle = (HTMLButtonElementClass)search;

            searchEle.click();
            //email = null;
            //element = document.getElementById("Passwd");
            //HTMLInputElementClass pass = (HTMLInputElementClass)element;
            //pass.value = "pass";
            //pass = null;
            //element = document.getElementById("signIn");
            //HTMLInputElementClass subm = (HTMLInputElementClass)element;
            //subm.click();
            //subm = null;
            //while (wb.Busy) { Thread.Sleep(100); }
            //wb.Navigate("https://adwords.google.co.uk/o/Targeting/Explorer?", ref o, ref o, ref o, ref o);
            //while (wb.Busy) { Thread.Sleep(100); }
            //string connString = "SERVER=localhost;" +
            //        "DATABASE=test;" +
            //        "UID=root;";

            ////create your mySQL connection
            //MySqlConnection cnMySQL = new MySqlConnection(connString);
            ////create your mySql command object
            //MySqlCommand cmdMySQL = cnMySQL.CreateCommand();
            ////create your mySQL reeader object
            //MySqlDataReader reader;
            ////open the mySQL connection
            //cnMySQL.Open();
            //int j = 1;
            //cmdMySQL.CommandText = "SELECT * FROM `emails1` WHERE `send`>'" + j + "' order by `send` asc limit 0,1";
            //reader = cmdMySQL.ExecuteReader();
            //reader.Read();
            //j = (int)reader.GetValue(1);
            HTMLElementCollection col = default(HTMLElementCollection);

            document = ((HTMLDocument)wb.Document);
            col      = (HTMLElementCollection)document.getElementsByTagName("textarea");
            //the error happens here in this typecast


            //Console.WriteLine(j);
            wb.Quit();
        }
示例#24
0
        public static List <string> Extract_Tag_with_IHTMLDocument(string tagName, string source)
        {
            //prepare nodename and its attributes
            List <string[]> res = TagProcessing.NodenameAndAttributes(tagName);

            List <string> list_sonuc = new List <string>();
            Stopwatch     stopwatch  = new Stopwatch();

            stopwatch.Start();
            HTMLDocument   doc  = new HTMLDocument();
            IHTMLDocument2 doc2 = (IHTMLDocument2)doc;

            doc2.clear();
            doc2.designMode = "On";
            doc2.write(source);

            stopwatch.Stop();
            preProcessTime = stopwatch.Elapsed.TotalMilliseconds;
            stopwatch.Restart();
            if (null != doc)
            {
                string[] nodename = res[0];
                nodename[0] = nodename[0].ToUpper(new CultureInfo("en-US", false));

                for (int i = 1; i < res.Count; i++)
                {
                    string[] att = res[i];
                    if (att[0] == "id")
                    {
                        //id means only one record
                        list_sonuc.Add(doc.getElementById(att[1]).innerHTML);
                        stopwatch.Stop();
                        searchTime = stopwatch.Elapsed.TotalMilliseconds;
                        return(list_sonuc);
                    }
                }

                foreach (IHTMLElement element in doc.getElementsByTagName(nodename[0]))
                {
                    bool sonuc = true;
                    for (int i = 1; i < res.Count; i++)
                    {
                        string[] att = res[i];
                        if (att[0] == "class")
                        {
                            if (element.className != att[1])
                            {
                                sonuc = false;
                                break;
                            }
                        }
                        else
                        {
                            if (element.innerHTML != null)
                            {
                                string tag_temp = element.outerHTML.Substring(0, element.outerHTML.IndexOf(">"));
                                if (!(tag_temp.Contains(att[0]) && tag_temp.Contains(att[1])))
                                {
                                    sonuc = false;
                                    break;
                                }
                            }
                            else
                            {
                                sonuc = false;
                                break;
                            }
                        }
                    }

                    if (sonuc)
                    {
                        list_sonuc.Add(element.innerHTML);
                    }
                }
            }
            else
            {
                stopwatch.Stop();
                searchTime = stopwatch.Elapsed.TotalMilliseconds;
                return(null);
            }


            stopwatch.Stop();
            searchTime = stopwatch.Elapsed.TotalMilliseconds;
            return(list_sonuc);
        }
示例#25
0
        public static void FillSelect(HTMLDocument document, string id, string value, string converted, bool fireOnchange = false)
        {
            IHTMLSelectElement element = (IHTMLSelectElement)document.getElementById(id);

            FillSelect(element, value, converted, fireOnchange);
        }
示例#26
0
        bool LR_click(IHTMLEventObj pEvtObj)
        {
            IHTMLElement gg = pEvtObj.srcElement;

            feed_id = gg.getAttribute("feedid");
            string feed_link = gg.getAttribute("feedlink");


            mshtml.IHTMLElementCollection feed_div = document.getElementById(feed_id).all;


            foreach (mshtml.IHTMLElement elem1 in feed_div)
            {
                // bejárja a címsor(lista)
                if (Conf.cimsor_class.Contains(elem1.className))
                {
                    foreach (IHTMLElement cim_elem in elem1.all)
                    {
                        if (Conf.cimsor_elem_class.Contains(cim_elem.className))
                        {
                            cim_elemek.Add(cim_elem.innerText);
                        }
                    }
                }
                else if (Conf.intro_class.Contains(elem1.className))
                {
                    intro = elem1.innerHTML;
                }
                else if (Conf.user_ikon_class.Contains(elem1.className))
                {
                    user_ikon_sourci = elem1.getAttribute("src");
                }
                else if (Conf.feed_image_class.Contains(elem1.className))
                {
                    feed_image_sourci = elem1.getAttribute("src");
                }
                else if (Conf.feed_image_szoveg_class.Contains(elem1.className))
                {
                    feed_image_szoveg = elem1.innerHTML;
                }
            }
            int i = 1;
            IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)document.body).createControlRange();

            foreach (mshtml.IHTMLImgElement img in doc.images)
            {
                string sourci = img.src;
                //
                if (sourci == user_ikon_sourci || sourci == feed_image_sourci)
                {
                    Bitmap ujkep = GetImage(img);
                    ujkep.Save(@"d:\Temp\hh" + i + ".jpg");
                    byte[] bite         = BitmapToArray(ujkep);
                    string base64String = Convert.ToBase64String(bite);


                    string URI = "http://like.infolapok.hu";

                    string myParameters = "param1=value1&param2=value2&param3=" + base64String;

                    using (WebClient wc = new WebClient())
                    {
                        wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                        string HtmlResult = wc.UploadString(URI, myParameters);
                        Console.WriteLine(" a válasz: {0}", HtmlResult);
                    }

                    // string ff= Encoding.ASCII.GetString(responseArray);


                    i++;
                }
            }

            bool kk = true;

            return(kk);
        }
 /// <summary>
 /// Checks if current page is the page with confirm information i.e. amount paid and entered bank account number.
 /// </summary>
 /// <param name="doc">HTML document (current page)</param>
 /// <returns>true if current page is the page with confirm information or false otherwise</returns>
 private bool IsConfirmPage(HTMLDocument doc)
 {
     return(doc.getElementById("f_Beneficiary") != null && doc.getElementById(BENEFICIARY_LIST) == null);
 }
        static void Main(string[] args)
        {
            #region arguments
            Dictionary <String, String> argsDict = new Dictionary <string, string>();
            foreach (String arg in args)
            {
                string param = arg.Substring(0, 2);
                if (param == "-H")
                {
                    Console.WriteLine("This is the Helper of MonitorePublicWebPage:");
                    Console.WriteLine("To set URL use: -U=https://site.com where https://site.com is your web page;");
                    Console.WriteLine("To set Which element need to monitor use: -W=A to all page or -W=E to an element;");
                    Console.WriteLine("To set the element use: -E=element where the first character indicate '#' for id and '.' for className;");
                    Console.WriteLine("To set the tries in the internet error use: -T=3;");
                    Console.WriteLine("To set the time in interations use: -P=10 where 10 is in seconds;");
                    return;
                }
                argsDict.Add(param, arg.Substring(3, arg.Length - 3));
            }
            #endregion

            #region which is the public URL
            String urlAddress = "";
            while (true)
            {
                Console.Write("Which is the public page URL? ");

                urlAddress = argsDict.ContainsKey("-U") ? argsDict["-U"] : Console.ReadLine();

                if (argsDict.ContainsKey("-U"))
                {
                    Console.WriteLine(urlAddress);
                }

                if (CheckURLValid(urlAddress))
                {
                    break;
                }
                else
                {
                    if (argsDict.ContainsKey("-U"))
                    {
                        argsDict.Remove("-U");
                    }
                    Console.WriteLine("The url '" + urlAddress + "' is invalid. Try again;");
                }
            }
            #endregion

            #region what i need look in the page
            char whatElem = '\0';
            while (true)
            {
                whatElem = argsDict.ContainsKey("-W") ? argsDict["-W"][0] : '\0';
                if (whatElem != 'A' && whatElem != 'E')
                {
                    if (argsDict.ContainsKey("-W"))
                    {
                        Console.WriteLine("The which element '" + whatElem + "' is invalid. Try again;");
                        argsDict.Remove("-W");
                    }

                    try
                    {
                        Console.Write("All Page (A), Element (E)? ");
                        whatElem = Console.ReadLine()[0];
                        if (whatElem != 'E' && whatElem != 'A')
                        {
                            Console.WriteLine("The which element '" + whatElem + "' is invalid. Try again;");
                        }
                        else
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        //ignore and try again
                    }
                }
                else
                {
                    if (argsDict.ContainsKey("-W"))
                    {
                        Console.Write("All Page (A), Element (E)? ");
                        Console.WriteLine(whatElem);
                    }
                    break;
                }
            }
            #endregion

            #region what is the element indicator
            String element = null;
            if (whatElem == 'E')
            {
                while (true)
                {
                    element = argsDict.ContainsKey("-E") ? argsDict["-E"] : null;
                    if (element[0] != '#' || element[0] != '.' || element.Length < 2)
                    {
                        if (argsDict.ContainsKey("-W"))
                        {
                            Console.WriteLine("The element '" + element + "' is invalid. Try again;");
                            argsDict.Remove("-E");
                        }
                        else
                        {
                            try
                            {
                                Console.Write("Which id (#)id or (.)class of the element? ");
                                element = Console.ReadLine();
                                if (element[0] != '#' || element[0] != '.')
                                {
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                //ignore and try again
                            }
                        }
                    }
                    else
                    {
                        if (argsDict.ContainsKey("-E"))
                        {
                            Console.Write("Which id (#)id or (.)class of the element? ");
                            Console.WriteLine(element);
                        }
                        break;
                    }
                }
            }
            #endregion

            #region tries default
            int triesDefault;
            if (!argsDict.ContainsKey("-T") || !int.TryParse(argsDict["-T"], out triesDefault))
            {
                triesDefault = 3;
            }
            #endregion

            #region period default
            int periodDefault;
            if (!argsDict.ContainsKey("-P") || !int.TryParse(argsDict["-P"], out periodDefault))
            {
                periodDefault = 10;
            }
            #endregion

            #region notificationIcon
            new Thread(() =>
            {
                NotifyIcon trayIcon = new NotifyIcon();
                trayIcon.Text       = "Monitore Public Web Page";
                trayIcon.Icon       = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);

                ContextMenu trayMenu    = new ContextMenu();
                menuItemExit            = new MenuItem("Sair");
                menuItemHideShow        = new MenuItem("Esconder/Mostrar");
                menuItemHideShow.Click += MenuItemHideShow_Click;
                menuItemExit.Click     += MenuItemExit_Click;
                trayMenu.MenuItems.Add(menuItemExit);
                trayMenu.MenuItems.Add(menuItemHideShow);
                trayIcon.ContextMenu = trayMenu;
                trayIcon.Visible     = true;
                Application.Run();
            }).Start();

            #endregion

            #region program execution
            int    tries   = 0;
            string data    = null;
            bool   changed = false;
            while (true)
            {
                try
                {
                    HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(urlAddress);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Stream       receiveStream = response.GetResponseStream();
                        StreamReader readStream    = null;

                        if (response.CharacterSet == null)
                        {
                            readStream = new StreamReader(receiveStream);
                        }
                        else
                        {
                            readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                        }

                        string readedData   = readStream.ReadToEnd();
                        string selectedData = null;
                        if (whatElem == 'A')
                        {
                            selectedData = readedData;
                        }
                        else
                        {
                            HTMLDocument   doc  = new HTMLDocument();
                            IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
                            doc2.write(readedData);
                            String indicator = element.Substring(1, element.Length - 1);
                            if (element[0] == '#')
                            {
                                IHTMLElement htmlElem = doc.getElementById(indicator);
                                selectedData = htmlElem.innerHTML;
                            }
                            else
                            {
                                foreach (IHTMLElement htmlElem in doc.all)
                                {
                                    if (htmlElem.getAttribute("className") == indicator)
                                    {
                                        if (htmlElem.id != null)
                                        {
                                            element = "#" + htmlElem.id;
                                        }
                                        selectedData = htmlElem.innerHTML;
                                        break;
                                    }
                                }
                            }
                        }

                        response.Close();
                        readStream.Close();

                        if (data == null)
                        {
                            data = selectedData;
                            Console.WriteLine(DateTime.Now + ": Read data, Chars:" + data.Length + ";");
                        }
                        else
                        {
                            if (data.Length != selectedData.Length)
                            {
                                changed = true;
                                break;
                            }
                            else
                            {
                                Console.WriteLine(DateTime.Now + ": Same; Read data, Chars:" + data.Length + ";");
                            }
                        }
                    }
                    tries = 0;
                } catch (Exception ex)
                {
                    tries++;
                    //ignore and try again
                }
                if (tries >= triesDefault)
                {
                    break;
                }
                Thread.Sleep(periodDefault * 1000);
            }
            #endregion

            if (changed)
            {
                System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"alert.wav");
                player.PlayLooping();
                player.Play();
                Console.WriteLine("There is some alteration. Type any key to open browser...");
                Console.ReadKey();
                System.Diagnostics.Process.Start(urlAddress);
            }
            else
            {
                Console.WriteLine("There is an error on internet.");
            }

            Console.ReadKey();
        }
示例#29
0
        public virtual void Login(LoginEntity model)
        {
            InternetExplorer browser = null;

            if (IsOpened(model.URL, out browser))
            {
                #region 网页已经打开,绑定数据
                BindData(browser, model);
                #endregion

                #region 提交
                HTMLDocument doc = (HTMLDocument)browser.Document;
                if (model.SUBMITID != null && model.SUBMITID != "")
                {
                    IHTMLElement login = doc.getElementById(model.SUBMITID);
                    if (login != null)
                    {
                        login.click();
                    }
                }
                else if (model.SUBMITCLASS != null && model.SUBMITCLASS != "")
                {
                    bool clicked = false;
                    IHTMLElementCollection login2 = doc.getElementsByTagName("INPUT");
                    IHTMLElementCollection login1 = doc.getElementsByTagName("A");
                    foreach (IHTMLElement l in login2)
                    {
                        if (l.className == model.SUBMITCLASS)
                        {
                            l.click();
                            clicked = true;
                            break;
                        }
                    }
                    if (!clicked)
                    {
                        foreach (IHTMLElement l in login1)
                        {
                            if (l.className == model.SUBMITCLASS)
                            {
                                l.click();
                                clicked = true;
                                break;
                            }
                        }
                    }
                }
                #endregion
            }
            else
            {
                #region 网页没有打开,尝试打开
                OpenUrl(model.URL);
                #endregion

                #region 如果已经打开,执行登录,如果没打开,则认为已经登录过
                if (IsOpened(model.URL, out browser))
                {
                    Login(model);
                }
                #endregion
            }
            return;
        }
示例#30
0
        protected override bool IsUserLogged(PaymentRequest request)
        {
            HTMLDocument doc = request.Document;

            return(doc.getElementById("inteligomenu") != null && doc.getElementById("leftmenucontener") != null);
        }
示例#31
0
        private void NavigateToFragment(string fragmentId)
        {
            IHTMLElement element = _htmlDocument.getElementById(fragmentId);

            element.scrollIntoView(true);
        }
示例#32
0
        /// <summary>
        /// Retrieves and saves Events information
        /// </summary>
        /// <param name="urlEvents"></param>
        private void GetEvents(string eventsUrl, ILog logger)
        {
            HTMLDocument document = JobUtils.LoadDocument(eventsUrl);

            string rssRoot = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <?xml-stylesheet href=\"http://www.w3.org/2000/08/w3c-synd/style.css\" type=\"text/css\"?> <!-- generator=\"ICMS GemWeb v1.1\" --> <rdf:RDF  xmlns=\"http://purl.org/rss/1.0/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"     xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:ev=\"http://www.w3.org/2001/xml-events\">#####1</rdf:RDF>";
            string rssItem = "<item rdf:about=\"#####2\" image=\"#####5\" > <dc:format>text/html</dc:format> <date>#####3</date> <title>#####4</title> <description>#####6</description> </item>";
            string strRssContent = "", strRssDetailsContent = "";

            // Find original content placeholder
            IHTMLElement contentBox = document.getElementById("contentboxsub");

            // Iterate over all <TR>'s
            foreach (IHTMLElement el in (IHTMLElementCollection)contentBox.all)
            {
                string strDate = "", strTitle = "", strDetailID = "", strDetailUrl = "", strRssItem = "";
                if (el.tagName.ToLower() == "tr")
                {
                    IHTMLElement date = JobUtils.FindElement(el, "td span");
                    if (date != null)
                    {
                        strDate = date.innerHTML;
                    }

                    IHTMLElement title = JobUtils.FindElement(el, "span a");
                    if (title != null)
                    {
                        // Process title
                        strTitle     = title.innerText;
                        strDetailUrl = title.getAttribute("href").ToString();
                        int infoPos = strDetailUrl.IndexOf("_id=") + 4;
                        int ampPos  = strDetailUrl.IndexOf("&", infoPos);
                        if (ampPos < 0)
                        {
                            ampPos = strDetailUrl.Length;
                        }
                        strDetailID = strDetailUrl.Substring(infoPos, ampPos - infoPos);

                        // Save Details content
                        strDetailUrl = strDetailUrl.Replace("about:blank", JobUtils.GetConfigValue("sourceWebRoot"));
                        JobUtils.SaveEventsDetailsContent(strDetailUrl, strDetailID + ".data", logger);
                    }

                    if ((title == null) || (date == null))
                    {
                        continue;
                    }

                    strRssItem  = rssItem.Replace("#####2", strDetailUrl);
                    strRssItem  = strRssItem.Replace("#####4", strTitle);
                    strRssItem  = strRssItem.Replace("#####5", "");
                    strRssItem  = strRssItem.Replace("#####3", strDate);
                    strRssItem  = strRssItem.Replace("#####6", "");
                    strRssItem += "\\\n";

                    strRssContent += strRssItem;

                    strRssDetailsContent += (strDetailUrl + "   \n");
                }
            }

            strRssContent = rssRoot.Replace("#####1", strRssContent);

            // Updated processed content
            strRssContent = strRssContent.Replace('"', '\'');
            strRssContent = "RSSData.Content = \"" + strRssContent + "\";";

            JobUtils.SaveData(strRssContent, "events.rss", logger);
        }
示例#33
0
        private void F_Pager_LoadCompleted(object sender, FrameLoadCompleteEventArgs e)
        {
            log.Debug($"++ Entered F_Pager_LoadCompleted from {e.Message}");
            if (e.Message == FrameLoadStates.DocumentLoadCompletedButNotFrame)
            {
                return;
            }
            log.Debug($"@@ delete delegate F_Pager_LoadComplated. [{current_op?.UID}]");
            fm.FrameLoadComplete -= F_Pager_LoadCompleted;

            // 每當刷新後都要重新讀一次
            // d 是parent HTML document
            HTMLDocument d = (HTMLDocument)g.Document;
            // f 是frame(0) HTML document
            HTMLDocument f = d.frames.item(0).document.body.document;

            // 讀取資料
            foreach (Target_Table tt in current_op.Target)
            {
                // 這裡不用管多table, 因為多table只發生在管制藥那裏
                ListRetrieved.Add(new VPN_Retrieved(tt.Short_Name, tt.Header_Want, f.getElementById(tt.TargetID).outerHTML, current_op.UID, current_op.QDate));

                SaveHTML($"{tt.Short_Name}_{current_op.UID}", f.getElementById(tt.TargetID).outerHTML);
            }
            log.Info($"[Action] Reading HTML: {current_op.Short_Name}, [{current_op.UID}]. page: {current_page}/{total_pages}");

            // 判斷是否最後一頁, 最後一tab
            if ((current_page == total_pages) && (QueueOperation.Count == 0))
            {
                // 兩個出口之一, 最後一個tab, 另一個出口是, 最後一個tab, 同時有其他page且為最後一頁,
                // 另一個在F_Data_LoadCompleted

                // 最後一頁
                // 處理index
                current_page = total_pages = 0;

                // 20200506: current_op 歸零似乎是不行的
                //current_op = null;
                // 20210719: 將QDATE設定為1901/1/1, 是傳達這是最後一頁了, 設定在F_Pager_LoadCompleted
                // 20210719: 移除這個愚蠢的方法
                //current_op.QDate = DateTime.Parse("1901/01/01");

                //// 這是沒有用的add delegate, 但是為了平衡, 避免可能的錯誤
                //fm.FrameLoadComplete += F_Data_LoadCompleted;
                //log.Info("  add delegate F_Data_LoadCompleted.");

                //// 沒有按鍵無法直接觸發, 只好直接呼叫
                //FrameLoadCompleteEventArgs ex = new FrameLoadCompleteEventArgs()
                //{
                //    Message = FrameLoadStates.DirectCall
                //};
                //F_Data_LoadCompleted(this, ex);
                // 此段程式的一個出口點

                // 20210719: 讀完實體資料就開始解析HTML吧
                string o = $"++ Exit F_Pager_LoadCompleted (1/3). last page, last tab, go to finalization directly. [{current_op.UID}]";
                ParsingTables(o);

                return;
            }
            else if (current_page == total_pages)
            {
                // 最後一頁
                // 處理index
                current_page = total_pages = 0;
                // 轉軌
                fm.FrameLoadComplete += F_Data_LoadCompleted;
                log.Debug($"@@ add delegate F_Data_LoadCompleted. [{current_op.UID}]");
                Thread.Sleep(150);
                // 下一個tab
                log.Info($"[Action]  {current_op.TAB_ID} tab key pressed.");
                current_op = QueueOperation.Dequeue();
                log.Debug($"++ Exit F_Pager_LoadCompleted (2/3). last page, go to next tab by clicking. [{current_op.UID}]");
                d.getElementById(current_op.TAB_ID).click();
                // 此段程式的一個出口點
                return;
            }
            else
            {
                current_page++;
                // 按鍵到下一頁, 此段程式到此結束
                // HOW TO ?????????????????????????????????????????
                // 如何下一頁, 可能要用invokescript
                // 按鈕機制
                fm.FrameLoadComplete += F_Pager_LoadCompleted;
                log.Debug($"@@ add delegate F_Pager_LoadCompleted. [{current_op.UID}]");
                Thread.Sleep(150);
                log.Info($"[Action] 下一頁按下去了.(多頁) [{current_op.UID}]");
                log.Debug($"++ Exit F_Pager_LoadCompleted (3/3). go to next page by clicking. [{current_op.UID}]");
                foreach (IHTMLElement a in f.getElementById("ContentPlaceHolder1_pg_gvList").all)
                {
                    if (a.innerText == ">")
                    {
                        a.click();
                    }
                }
                // 此段程式的一個出口點
                return;
            }
        }
示例#34
0
        public void loadFiles(XmlNode xn,HTMLDocument document)
        {
            try
            {

                /*动态加载JavaScript文件
                * 需先判断是否已经加载项目;如未加载再加入该模块
                * 
                */

                XmlNodeList jsFiles = xn.SelectNodes("js");
                foreach (XmlNode jsFile in jsFiles)
                {
                    XmlElement jsxe = (XmlElement)jsFile;

                    if (document.getElementById(jsxe.GetAttribute("keyID")) == null)
                    {                        
                        IHTMLElement script = document.createElement("script");
                        script.setAttribute("src", jsxe.InnerText, 0);
                        script.setAttribute("type", "text/javascript", 0);
                        script.setAttribute("defer", jsxe.GetAttribute("defer"), 0);
                        script.setAttribute("id", jsxe.GetAttribute("keyID"), 0); 
                        script.setAttribute("charset", "utf-8", 0);
                        IHTMLDOMNode head = (IHTMLDOMNode)document.getElementsByTagName("head").item(0, 0);
                        head.appendChild((IHTMLDOMNode)script);

                    }
                }

                /*动态加载CSS文件
                 * 需先判断是否已经加载项目;如未加载再加入该模块
                 * 
                 */

                XmlNodeList cssFiles = xn.SelectNodes("css");
                foreach (XmlNode cssFile in cssFiles)
                {
                    XmlElement cssxe = (XmlElement)cssFile;

                    if (document.getElementById(cssxe.GetAttribute("keyID")) == null)
                    {
                        
                        IHTMLElement css = document.createElement("link");
                        css.setAttribute("rel", "stylesheet", 0);
                        css.setAttribute("type", "text/css", 0);
                        css.setAttribute("href", cssxe.InnerText, 0);
                        css.setAttribute("id", cssxe.GetAttribute("keyID"), 0);
                        IHTMLDOMNode head = (IHTMLDOMNode)document.getElementsByTagName("head").item(0, 0);
                        head.appendChild((IHTMLDOMNode)css);

                        //document.createStyleSheet(cssxe.InnerText, 1);//方法二
                    }
                }
            }
            catch (Exception e)
            {
                //alert(e.Message);
                throw e;
            }

        }
示例#35
0
        public bool SetComboItem(InternetExplorer IE, HTMLDocument doc, string ParentID, string SubID, string InputValue)
        {
            bool bResult = true;

            if (InputValue != null)
            {
#if (DEBUG)
                g_Util.DebugPrint("[SetComboItem]" + ParentID + ", " + InputValue);
#endif
                TotalWait(IE, doc, ParentID);
                IHTMLElement SelectedElement = doc.getElementById(ParentID);
                try
                {
                    SelectedElement.click();
                }
                catch (System.Exception e)
                {
                    g_Util.DebugPrint("[Exception] " + e);
                    bResult = false;
                    return(bResult);
                }

                TotalWait(IE, doc, SubID);
                IHTMLElementCollection elemcoll = doc.getElementById(SubID).children as IHTMLElementCollection;

                bool bFind = false;
                foreach (IHTMLElement elem in elemcoll)
                {
                    //System.Diagnostics.Debug.WriteLine(" elem.GetType() ===> " + elem.GetType().ToString());
                    //System.Diagnostics.Debug.WriteLine(" tagName == " + elem.tagName);
                    //System.Diagnostics.Debug.WriteLine(" innerText == " + elem.innerText);
                    //System.Diagnostics.Debug.WriteLine(" outerHTML == " + elem.outerHTML);
                    //if (elem.getAttribute("id") != null)
                    //{
                    //    System.Diagnostics.Debug.WriteLine(" id == " + elem.getAttribute("id"));
                    //}

                    if (elem.innerText == InputValue)
                    {
                        try
                        {
                            elem.click();
                        }
                        catch (System.Exception e)
                        {
                            g_Util.DebugPrint("[Exception] " + e);
                            bResult = false;
                            return(bResult);
                        }

                        TotalWait(IE, doc);
                        bFind = true;
                    }
                    //System.Diagnostics.Debug.WriteLine(" ==================================================");
                }

                if (bFind == false)
                {
                    g_Util.DebugPrint("No Item in List. Input Value = " + InputValue);
                }
            }

            return(bResult);
        }