Пример #1
0
        private void Logout()
        {
            HTMLDocument dom = (HTMLDocument)_transactionsBrowser.Document;
            IHTMLElement btn = dom.getElementById("LNKLOGOUT_new");

            btn?.click();
        }
Пример #2
0
        private void SelectAccount(AccountBasic account)
        {
            HTMLDocument dom         = (HTMLDocument)_transactionsBrowser.Document;
            object       accountsObj = dom.getElementById("ddlAccounts_m_ddl");

            if (accountsObj is IHTMLSelectElement accounts)
            {
                foreach (var option in accounts.options)
                {
                    var    utf8bytes = Encoding.UTF8.GetBytes(option.text);
                    String ascii     = Encoding.ASCII.GetString(utf8bytes);
                    var    ac        = ascii.TrimStart('?').TrimEnd('?').Split('-', '/');

                    if (ac.Length >= 2 && ac[1] == account.AccountNumber)
                    {
                        option.SetAttribute("selected", "selected");
                        account.BranchNumber = Convert.ToInt32(ac[0]);
                        account.Label        = $"{ac[0]}-{ac[1]}";
                    }
                    else
                    {
                        option.RemoveAttribute("selected");
                    }
                }
                ((HTMLSelectElement)accounts).FireEvent("onchange");

                IHTMLElement btn = dom.getElementById("btnDisplayDates");
                btn?.click();
            }
        }
 public void clickById(string id)
 {
     Application.Current.Dispatcher.Invoke((() =>
     {
         HTMLDocument doc = webbrowser.Document as HTMLDocument;
         IHTMLElement e = doc.getElementById(id);
         if (e != null)
         {
             e.click();
             Console.WriteLine("click on " + e);
         }
     }));
 }
Пример #4
0
 public void Click()
 {
     try
     {
         element.click();
     }
     catch (Exception e)
     {
         if (!(this is SUIHtmlAnchor))//Ignore anchor exception
         {
             throw;
         }
     }
 }
Пример #5
0
        /// <summary>
        /// 填报checkbox数据。
        /// </summary>
        /// <param name="value"></param>
        /// <param name="checkBoxGroup"></param>
        private void FillCheckBoxGroup(ref string value, Hashtable checkBoxGroup)
        {
            //存储checkbox中的"xxx其他"选项
            FillParameter otherCheckBox = null;

            string[] values = value == null ? null : value.Split(PZHFillManager.regularSeparator, StringSplitOptions.RemoveEmptyEntries);
            if (values == null || values.Length < 1)
            {
                return;
            }
            List <String> listValues = new List <String>(values);

            foreach (String key in checkBoxGroup.Keys)
            {
                FillParameter dElement = checkBoxGroup[key] as FillParameter;
                if (key.Contains("其他"))
                {
                    otherCheckBox = dElement;
                }
                if (listValues.Contains(key))
                {
                    dElement.Value = null;
                    IHTMLElement element = base.GetElement(dElement, _formIndex) as IHTMLElement;
                    if (element == null)
                    {
                        continue;
                    }
                    //element.@checked = true;
                    element.click();
                    if (dElement.CanDelete)
                    {
                        listValues.Remove(key);
                    }
                }
            }

            if (listValues != null && listValues.Count > 0)
            {
                otherCheckBox.Value = null;
                IHTMLElement element = base.GetElement(otherCheckBox, _formIndex) as IHTMLElement;
                if (element != null)
                {
                    //element.@checked = true;
                    //base.InvokeOnChange(element as IHTMLElement);
                    element.click();
                    base.InvokeChange2(element as IHTMLElement);
                }
            }
            value = (listValues == null || listValues.Count == 0) ? "" : String.Join(PZHFillManager.regularJoiner, listValues);
        }
Пример #6
0
        public bool ClickButton(InternetExplorer IE, HTMLDocument doc, string ID, string ElemType = "ID")
        {
            bool bResult = true;

#if (DEBUG)
            g_Util.DebugPrint("[ClickButton]" + ID);
#endif
            if (TotalWait(IE, doc, ID, ElemType) == false)
            {
                if (ElemType != "NAME")
                {
                    g_Util.DebugPrint("Element Waiting False. Skip this action.  " + ID);
                    return(true);
                }
            }

            if (ElemType == "ID" || ElemType == null)
            {
                IHTMLElement SelectedElement = doc.getElementById(ID);
                try
                {
                    SelectedElement.click();
                }
                catch (System.Exception e)
                {
                    g_Util.DebugPrint("Problem happen" + e);
                    bResult = false;
                }
            }
            else if (ElemType == "NAME")
            {
                IHTMLElementCollection SelectedElement = doc.getElementsByName(ID);

                foreach (IHTMLElement elem in SelectedElement)
                {
                    try
                    {
                        elem.click();
                        break;
                    }
                    catch (System.Exception e)
                    {
                        g_Util.DebugPrint("[Exception] " + e);
                        bResult = false;
                    }
                }
            }

            return(bResult);
        }
Пример #7
0
        public void Click()
        {
            object         refObj   = null;
            IHTMLDocument4 document = node.document as IHTMLDocument4;
            IHTMLElement3  element  = (IHTMLElement3)node;

            IHTMLEventObj eventObject = document.CreateEventObject(ref refObj);
            object        eventRef    = eventObject;

            element.FireEvent("onMouseDown", ref eventRef);
            element.FireEvent("onMouseUp", ref eventRef);
            node.click();
            parent.WaitForLoadToComplete();
        }
Пример #8
0
        /// <summary>
        /// Pushes the values from the specified line in the item array to the selected line in
        /// the browser
        /// </summary>
        public static void PushToSelectedLine(int rowIndex, string[] items, IHTMLDocument3 doc3, DataGridView dgvText)
        {
            // Iterate over all of the INPUT elements to find those wanting the project hours
            IHTMLElementCollection allInputs = doc3.getElementsByTagName("input");

            for (int i = 0; i < allInputs.length; i++)
            {
                // We're looking for an INPUT whose id contains "reg_value" and not "IsDirty"
                // this is enough to get the INPUTS for the hours
                IHTMLElement e   = allInputs.item(i);
                int          pos = e.id.IndexOf("reg_value");
                if (pos > -1 && !e.id.Contains("IsDirty"))
                {
                    // Get the single digit index of this current INPUT - this matches to our column index
                    string id = e.id.Substring(pos + 9);
                    if (char.IsDigit(id[0]))
                    {
                        int   index          = int.Parse(id.Substring(0, 1)) + 1;
                        Color originalColour = dgvText.Rows[rowIndex].Cells[index].Style.BackColor;
                        dgvText.Rows[rowIndex].Cells[index].Style.BackColor = Color.Gold;
                        e.click();
                        System.Threading.Thread.Sleep(100);

                        var stringToInsert = items[index];
                        try
                        {
                            // Try to use agresso culture setting
                            decimal value = decimal.Parse(items[index], System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
                            stringToInsert = value.ToString(AgressoCulture.NumberFormat);
                        }
                        catch (Exception)
                        {
                            // Revert to old behaviour
                        }

                        e.innerText = stringToInsert;
                        IHTMLElement3 e3 = e as IHTMLElement3;
                        if (e3 != null)
                        {
                            e3.FireEvent("onchange");
                            Marshal.ReleaseComObject(e3);
                        }
                        dgvText.Rows[rowIndex].Cells[index].Style.BackColor = originalColour;
                    }
                }
                Marshal.ReleaseComObject(e);
            }
            Marshal.ReleaseComObject(allInputs);
        }
Пример #9
0
        private void Login()
        {
            HTMLDocument dom         = (HTMLDocument)_transactionsBrowser.Document;
            object       uidObj      = dom.getElementById("uid");
            object       passwordObj = dom.getElementById("password");

            if (uidObj is IHTMLInputElement uid &&
                passwordObj is IHTMLInputElement password)
            {
                uid.value      = _username;
                password.value = _password;
            }

            IHTMLElement btn = dom.getElementById("enter");

            btn?.click();
        }
        private static void FindAndUseLoginButton(IEnumerable <IHTMLElement> allElements)
        {
            var          keepBeingLoggedInCtrl = allElements.First(f => f.id == Constants.BoerseUserControls.CHECKBOX_REMEMBER_LOGIN);
            var          parent             = keepBeingLoggedInCtrl.parentElement.parentElement;
            IHTMLElement loginButtonElement = null;

            foreach (IHTMLElement childElement in parent.children)
            {
                var valueAttr = childElement.getAttribute("value");
                if (valueAttr != null && valueAttr == "Anmelden")
                {
                    loginButtonElement = childElement;
                    break;
                }
            }

            Thread.Sleep(1000);
            loginButtonElement.click();
        }
Пример #11
0
        private void SetupDates()
        {
            HTMLDocument dom         = (HTMLDocument)_transactionsBrowser.Document;
            object       accountsObj = dom.getElementById("ddlTransactionPeriod");

            if (accountsObj is IHTMLSelectElement accounts)
            {
                foreach (var option in accounts.options)
                {
                    if (option.value.Equals("004"))
                    {
                        option.SetAttribute("selected", "selected");
                    }
                    else
                    {
                        option.RemoveAttribute("selected");
                    }
                }
                ((HTMLSelectElement)accounts).FireEvent("onchange");
            }

            var now = DateTime.Now;

            object fromDateObj = dom.getElementById("dtFromDate_textBox");

            if (fromDateObj is IHTMLInputElement fromDate)
            {
                var startDate = now.AddYears(-2);
                fromDate.value = String.Format("{0}/{1}/{2}", startDate.Day, startDate.Month, startDate.Year % 100);
            }

            object toDateObj = dom.getElementById("dtToDate_textBox");

            if (toDateObj is IHTMLInputElement toDate)
            {
                toDate.value = String.Format("{0}/{1}/{2}", now.Day, now.Month, now.Year % 100);
            }

            IHTMLElement btn = dom.getElementById("btnDisplayDates");

            btn?.click();
        }
Пример #12
0
        /// <summary>
        /// Selects a line in the Agresso webpage using either the code and description, or just the code
        /// if the description is empty.
        /// </summary>
        public static void SelectAgressoLine(string code, string description, IHTMLDocument3 doc3)
        {
            IHTMLElement rowDivElement = null;

            try
            {
                // Get list of Agresso workorders that match the project code
                List <Tuple <string, string, string> > possibleMatches = GetIDsForProjectCode(code, doc3);

                // Determine which of those is the correct one.
                string idOfRowToSelect = string.Empty;
                if (possibleMatches.Count == 0)
                {
                    throw new ApplicationException("SelectAgressoLine - Failed to find any Agresso projects with a code of " + code);
                }
                else if (possibleMatches.Count == 1)
                {
                    idOfRowToSelect = possibleMatches[0].Item3;
                }
                else
                {
                    idOfRowToSelect = (from m in possibleMatches
                                       where String.Equals(description, m.Item2, StringComparison.OrdinalIgnoreCase)
                                       select m.Item3).FirstOrDefault();
                }
                if (string.IsNullOrEmpty(idOfRowToSelect))
                {
                    throw new ApplicationException("SelectAgressoLine - Failed to find any Agresso projects with a code of " + code + " and a description of " + description);
                }

                rowDivElement = doc3.getElementById(idOfRowToSelect);
                rowDivElement.click();
                System.Threading.Thread.Sleep(1000);
            }
            finally
            {
                if (rowDivElement != null)
                {
                    Marshal.ReleaseComObject(rowDivElement);
                }
            }
        }
Пример #13
0
        static void Main(string[] args)
        {
            string         baseUrl       = "http://localhost:2310/common/";
            int            maxIterations = 50;
            string         instanceId    = CreateIEInstance();
            var            ie            = instances[instanceId];
            IHTMLDocument3 doc           = null;

            for (int i = 0; i < maxIterations; i++)
            {
                Console.WriteLine("Iteration {0} of {1}", i + 1, maxIterations);
                ie.Navigate2(baseUrl + "xhtmlTest.html");
                System.Threading.Thread.Sleep(500);
                if (doc == null)
                {
                    doc = ie.Document;
                }

                IHTMLElement element = doc.getElementsByName("windowOne").item(0);
                element.click();
                while (instances.Keys.Count < 2)
                {
                    System.Threading.Thread.Sleep(100);
                }

                string popupId = instances.Keys.Except(new List <string>()
                {
                    instanceId
                }).First();

                CloseIEInstance(popupId);
                ie.Navigate2(baseUrl + "macbeth.html");
            }

            CloseIEInstance(instanceId);
            Console.WriteLine("Completed {0} iterations. Press <Enter> to end.", maxIterations);
            Console.ReadLine();
        }
Пример #14
0
        private void SendPost(string input, string id)
        {
            InternetExplorer explorer = new InternetExplorer();

            explorer.Visible = true;
            explorer.Navigate($@"{consaddpostlink}{id}");
            while (explorer.Busy)
            {
                Thread.Sleep(100);
            }

            HTMLDocument doc = (HTMLDocument)explorer.Document;

            IHTMLElement field = doc.getElementById("text").parentElement.children.item(1, null);

            field.innerText = input;

            IHTMLElement button = doc.getElementById("previewButton").parentElement.children.item(0, null);

            button.click();

            explorer.Quit();
        }
Пример #15
0
        public void RelocateWine(string sBarcode, string sBin)
        {
            EnsureLoggedIn();

            m_srpt.AddMessage($"Relocating wine {sBarcode}...");
            m_srpt.PushLevel();

            // navigate directly to the relocation page
            string sPage = $"{_s_InventoryScanPageRoot}&iInventoryList={sBarcode}";

            if (!m_wc.FNavToPage(sPage) || !m_wc.FWaitForNavFinish((doc2) => FHasWineInTableRowOnPage(doc2, sBarcode)))
            {
                throw new Exception("couldn't navigate to cellar page");
            }

            IHTMLDocument2 oDoc2 = m_wc.Document2;

            WebControl.FSetInputControlText(oDoc2, _s_CtlName_InventoryScanPageRoot_SetBin, sBin, false);

            m_wc.ResetNav();
            IHTMLElement ihe = WebControl.FindSubmitControlByValueText(oDoc2, _s_CtlName_InventoryScanPageRoot_Submit_BulkUpdate);

            if (ihe == null)
            {
                throw new Exception("no submit control?");
            }

            ihe.click();
            if (!m_wc.FWaitForNavFinish((doc2) => FHasCorrectBinInTableRowOnPage(doc2, sBin)))
            {
                throw new Exception($"failed to relocate wine {sBarcode} to {sBin}");
            }

            m_srpt.PopLevel();
            m_srpt.AddMessage("Relocate complete");
        }
Пример #16
0
        public virtual bool NodeClick()
        {
            try
            {
                if (pNode != null)
                {
                    pNode.click();
                    AjaxWatch();

                    if (m_IsRedirctionEnable && m_RedirectUrl.Count > 0)
                    {
                        log.Debug("NodeClick-Redirection:" + GetCurrentURL() + " >>>> " + m_RedirectUrl.Peek());
                        Navigate(m_RedirectUrl.Pop());
                    }
                    return(true);
                }
                return(false);
            }
            catch (Exception e)
            {
                log.Debug("NodeClick Error:", e);
                return(false);
            }
        }
Пример #17
0
        public void Search(string url, string searchinputid, string content, string submitid)
        {
            InternetExplorer browser = null;

            if (IsOpened(url, out browser))
            {
                HTMLDocument      doc    = (HTMLDocument)browser.Document;
                IHTMLInputElement input  = (IHTMLInputElement)doc.getElementById(searchinputid);
                IHTMLElement      submit = doc.getElementById(submitid);
                input.value = content.Trim();
                submit.click();
            }
            else
            {
                #region 网页没有打开,尝试打开
                OpenUrl(url, 1000);
                #endregion

                if (IsOpened(url, out browser))
                {
                    Search(url, searchinputid, content, submitid);
                }
            }
        }
Пример #18
0
        private void FillElement(FillParameter parameter, ref string value)
        {
            //if (parameter.Type != Matcher.TYPE_FORM)
            //{
            //    if (parameter.Value == "上传图片")
            //    {
            //        if (string.IsNullOrEmpty(value))
            //            return;
            //        string file = string.IsNullOrEmpty(base.DataFilePath) ? value : string.Format("{0}\\{1}", base.DataFilePath, value);
            //        if (System.IO.File.Exists(file) == false)
            //        {
            //            base.FillRecords.Add(new FillRecord(ElementType.File, RecordType.Failed, string.Format("文件{0}不存在", file), parameter.ParameterName));
            //            return;
            //        }
            //    }
            //}
            //base.FillElement(parameter, value);
            if (parameter == null)
            {
                return;
            }
            IHTMLElement element = null;

            if (parameter.ParameterName == null || base.DataTable.Contains(parameter.ParameterName) == false)
            {
                value = DefaultValue;
            }
            if (parameter.Type != Matcher.TYPE_FORM)
            {
                element = base.GetElement(parameter, _formIndex);
                if (element == null)
                {
                    this.FillRecords.Add(new FillRecord(GetElementType(parameter.Type), RecordType.Failed, "未找到此元素", parameter.ParameterName));
                    return;
                }
                else if (parameter.Value == "上传图片")
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return;
                    }
                    string file = string.IsNullOrEmpty(base.DataFilePath) ? value : string.Format("{0}\\{1}", base.DataFilePath, value);
                    if (System.IO.File.Exists(file) == false)
                    {
                        this.FillRecords.Add(new FillRecord(ElementType.File, RecordType.Failed, string.Format("文件{0}不存在", value), parameter.ParameterName));
                        return;
                    }
                }
                ((IHTMLElement2)element).focus();
            }
            if (string.IsNullOrEmpty(parameter.SplitExpr) == false && string.IsNullOrEmpty(value) == false)
            {
                Match match = Regex.Match(value, parameter.SplitExpr, RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    value = match.Groups["value"].Value;
                }
            }
            _currentFillValue = value;
            switch (parameter.Type)
            {
            case Matcher.TYPE_FORM:
                if (base.GetElement(parameter, -1) != null)
                {
                    _formIndex++;
                }
                break;

            case Matcher.TYPE_RADIO:
                IHTMLInputElement radioElement = element as IHTMLInputElement;
                radioElement.@checked = true;
                this.FillRecords[(int)ElementType.Radio].RecordCount++;
                break;

            case Matcher.TYPE_SELECT:
                if (FillSelectElement(parameter, ref value))
                {
                    this.FillRecords[(int)ElementType.Select].RecordCount++;
                }
                else
                {
                    this.FillRecords.Add(new FillRecord(ElementType.Select, RecordType.Failed, string.Format("下拉框中不包含选项 {0}", value), parameter.ParameterName));
                }
                break;

            case Matcher.TYPE_A:
                element.click();
                break;

            case Matcher.TYPE_FILE:
                value             = string.IsNullOrEmpty(base.DataFilePath) ? value : string.Format("{0}\\{1}", base.DataFilePath, value);
                _currentFillValue = value;
                if (System.IO.File.Exists(value))
                {
                    element.click();
                    this.FillRecords[(int)ElementType.File].RecordCount++;
                }
                break;

            case Matcher.TYPE_SUBMIT:
            case Matcher.TYPE_BUTTON:
            case "BUTTON/SUBMIT":
                IHTMLInputElement fileElement = element as IHTMLInputElement;
                element.click();
                break;

            case Matcher.TYPE_TEXTAREA:
                IHTMLTextAreaElement textAreaElement = element as IHTMLTextAreaElement;
                textAreaElement.value = value;
                this.FillRecords[(int)ElementType.Text].RecordCount++;
                break;

            case Matcher.TYPE_TEXT:
            case Matcher.TYPE_PASSWORD:
                IHTMLInputElement textElement = element as IHTMLInputElement;
                textElement.value = value;
                this.FillRecords[(int)ElementType.Text].RecordCount++;
                break;
            }
        }
Пример #19
0
        private void Download(IHTMLElement link)
        {
            link.click();
            AutoClosingMessageBox.Show("Parsing...", "Strange but true", 400);

            //var downloadElement = ((HTMLDocument) WebBrowser1.Document).getElementsByTagName("A").Cast<IHTMLElement>()
            //    .Where(x => x.innerHTML != null && x.innerHTML.Contains("rtsp://video9.cc.technion.ac.il")).ToList();
            //MessageBox.Show("got " + downloadElement.Count);
            //var frames = ((HTMLDocument) WebBrowser1.Document).frames.item(0);
            //Thread.Sleep(1000);
            var outer = ((HTMLDocument)WebBrowser1.Document).getElementById("fancybox-outer");
            //MessageBox.Show(outer.innerText);

            // Also get X button
            //var Xbutton = ((HTMLDocument) outer.document).getElementById("fancybox-close");

            var content = ((HTMLDocument)outer.document).getElementById("fancybox-content");
            //MessageBox.Show(content.innerText);

            var frames = ((HTMLDocument)content.document).frames;

            //MessageBox.Show("Frames Length: " + frames.length);

            //MessageBox.Show(frames.outerHTML);
            //MessageBox.Show(innerframe.outerHTML);
            //MessageBox.Show(innerframe2.length.ToString());
            AutoClosingMessageBox.Show("Parsing...", "Strange but true", 400);

            //for (int i = 0; i < 1000000; i++)
            //{
            //    i++;
            //}

            //int i = 0;

            object refObj = 0;
            //while (frames.length == 0)
            //{
            //    frames = ((HTMLDocument)content.document).frames;
            //}
            //MessageBox.Show(frames.length.ToString());
            IHTMLWindow2 currentFrame = (IHTMLWindow2)frames.item(ref refObj);
            //while (currentFrame == null)
            //{
            //    currentFrame = (IHTMLWindow2)frames.item(ref refObj);
            //}
            String toParse = currentFrame.document.body.innerHTML;

            //MessageBox.Show(ToParse);
            TitleInfo.Text = toParse;
            String localfilename = link.getAttribute("href").ToString();

            localfilename = localfilename.Split('/')[7];
            var fullfilename = Path.Combine(_downloadDir, localfilename);

            //MessageBox.Show(fullfilename);
            curFile = fullfilename;
            Regex filenameRegex = new Regex("href=\"rtsp://video9.cc.technion.ac.il:554/Courses\\S+\"");
            var   filename      = filenameRegex.Match(toParse).Value.TrimStart("href=".ToCharArray()).TrimStart('"').TrimEnd('"');

            // TODO: save parsed filename in variable and use it
            // Close the iframe element to prepare for next download
            //Xbutton?.click();
            //MessageBox.Show(filename);
            //MessageBox.Show(localfilename);
            msdl = new Process
            {
                StartInfo =
                {
                    FileName  = "msdl.exe",
                    Arguments = "-s2 " + filename + " -o " + fullfilename,
                    //WindowStyle = ProcessWindowStyle.Maximized,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    CreateNoWindow         = true,
                    UseShellExecute        = false
                }
            };

            //// hookup the eventhandlers to capture the data that is received
            //msdl.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
            //msdl.ErrorDataReceived += (sender, args) => sb.AppendLine(args.Data);

            //redirect the output

            // redirect title to one textbox and the rest overrides itself in another
            msdl.OutputDataReceived += SortOutputHandler;
            msdl.ErrorDataReceived  += SortOutputHandler;

            // TODO: disable all buttons
            foreach (var element in Controls.Children)
            {
                if (element is Button button)
                {
                    //MessageBox.Show(button.Name);
                    button.IsEnabled = false;
                }
            }
            //{
            //    if (element is Button button) {
            //        button.IsEnabled = false;
            //    }
            //}

            // Wipe text boxes
            DownloadInfo.Text = TitleInfo.Text = "";
            msdl.Start();
            // start our event pumps
            msdl.BeginOutputReadLine();
            msdl.BeginErrorReadLine();

            while (!msdl.HasExited)
            {
                DoEvents(); // This keeps your form responsive by processing events
            }

            // Clear text
            DownloadInfo.Text = TitleInfo.Text = "";

            // TODO: enable all buttons
            foreach (var element in Controls.Children)
            {
                if (element is Button button)
                {
                    button.IsEnabled = true;
                }
            }
            // TODO: click the x button to close the popup
            //// until we are done
            //msdl.WaitForExit();

            //// do whatever you need with the content of sb.ToString();

            //TitleInfo.Text = sb.ToString();

            //for (int i = 0; i < innerframe2.length; i++)
            //{
            //    object ref_index = i;
            //    IHTMLWindow2 currentFrame = (IHTMLWindow2)innerframe2.item(ref ref_index);
            //    if (currentFrame != null)
            //    {
            //        string ToParse = currentFrame.document.body.innerHTML;
            //        MessageBox.Show(ref_index + " " + ToParse);
            //    }
            //    //System.Windows.Forms.HtmlWindow frame = ((HTMLDocument)WebBrowser1.Document).getElementById("fancybox-").Document.Window.Frames["decrpt_ifr"];
            //    //HtmlElement body = frame.Document.GetElementById("tinymce");



            //    //if (WebBrowser1.CanGoBack) WebBrowser1.GoBack();
            //}
        }
Пример #20
0
        private void TimersTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            log.Info($"  Entered TimersTimer_Elapsed.");

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

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

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

                    Goto_next_page();

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

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

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

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

            log.Info($"  Exited TimersTimer_Elapsed.");
            return;
        }
Пример #21
0
 public void NavigateClick(IHTMLElement element)
 {
     Initialize();
     element.click();
 }
Пример #22
0
        protected void AnalysisWebInfo(object sender, ref object URL)
        {
            SetIE(IeVersion.标准ie8);
            #region  读取网站
            HTMLDocument myDoc = MyWebBrower.Document as HTMLDocument;
            //MessageBox.Show("1");

            if (URL.ToString().IndexOf("https://app.singlewindow.cn/cas/login?service=http") >= 0 && isrun == ProcessStatus.初始化)
            {
                //MessageBox.Show("2");


                IHTMLElement           submit = null;
                IHTMLElement           KEYTX  = null;
                IHTMLInputElement      txtkw  = myDoc.getElementsByName("Login") as IHTMLInputElement;
                IHTMLElementCollection inputs = myDoc.getElementsByTagName("Input");



                foreach (IHTMLElement item in inputs)
                {
                    if (item.outerHTML.IndexOf("password") > 0)
                    {
                        KEYTX = item;
                    }
                    if (item.outerHTML.IndexOf("loginbutton") > 0)
                    {
                        submit = item;
                        break;
                    }
                }

                if (KEYTX != null && KEYTX != null)
                {
                    KEYTX.setAttribute("Value", tsbPassword, 0);
                }
                if (submit != null && submit != null)
                {
                    //MessageBox.Show("32");
                    isrun = ProcessStatus.账号正确;
                    //linshi
                    //isrun = ProcessStatus.第二页面;

                    submit.click();
                }
            }
            if (URL.ToString().IndexOf("https://www.singlewindow.cn/") >= 0 && isrun == ProcessStatus.账号正确)
            {
                IHTMLElementCollection inputs = myDoc.getElementsByTagName("a");
                foreach (IHTMLElement item in inputs)
                {
                    if (item.outerHTML.IndexOf("https://app.singlewindow.cn/userserver/user/index") > 0)
                    {
                        MessageBox.Show("" + item.outerText);
                    }
                    if (item.outerHTML.IndexOf("http://www.chinaport.gov.cn/kafgk/hgzs/18058.htm") > 0)
                    {
                        MessageBox.Show("" + item.outerText);
                        isReadyForSearch = true;
                    }
                }
                isrun = ProcessStatus.检索页面;
            }
            #endregion
        }
Пример #23
0
 void doWaitClick(IHTMLElement what)
 {
     what.click();
       //  Thread.Sleep(700);
 }
Пример #24
0
        private void mainWeb_LoadCompleted(object sender, NavigationEventArgs e)
        {
            if (styleSheetApplied)
            {
                return;
            }
            var document = mainWeb.Document as HTMLDocument;

            if (document == null)
            {
                return;
            }

            //抽取Flash,应用CSS样式
            IHTMLElement gameFrame = null;

            if (DataUtil.Game.gameServer == (int)GameInfo.ServersList.American || DataUtil.Game.gameServer == (int)GameInfo.ServersList.AmericanR18)
            {
                gameFrame = document.getElementById("game_frame");
                if (gameFrame != null)
                {
                    mainWeb.Navigate(Convert.ToString(gameFrame.getAttribute("src")));
                    return;
                }
                else
                {
                    gameFrame = document.getElementById("externalContainer");
                }
            }
            else
            {
                gameFrame = document.getElementById("game_frame");
            }
            if (gameFrame != null)
            {
                var target = gameFrame?.document as HTMLDocument;
                if (target != null)
                {
                    if (DataUtil.Game.gameServer == (int)GameInfo.ServersList.American || DataUtil.Game.gameServer == (int)GameInfo.ServersList.AmericanR18)
                    {
                        target.createStyleSheet().cssText = DataUtil.Config.sysConfig.userCSSAmerican;
                    }
                    else
                    {
                        target.createStyleSheet().cssText = DataUtil.Config.sysConfig.userCSS;
                    }
                    styleSheetApplied = true;
                    MiscHelper.AddLog("抽取Flash样式应用成功!", MiscHelper.LogType.System);
                }
            }

            //自动登录相关
            if (!loginSubmitted && DataUtil.Config.currentAccount.username != null && DataUtil.Config.currentAccount.username.Trim() != "")
            {
                IHTMLElement username = null;
                IHTMLElement password = null;
                if (DataUtil.Game.gameServer == (int)GameInfo.ServersList.American || DataUtil.Game.gameServer == (int)GameInfo.ServersList.AmericanR18)
                {
                    username = document.getElementById("s-email");
                    password = document.getElementById("s-password");
                }
                else
                {
                    username = document.getElementById("login_id");
                    password = document.getElementById("password");
                }

                if (username == null || password == null)
                {
                    return;
                }

                DESHelper des = new DESHelper();

                username.setAttribute("value", des.Decrypt(DataUtil.Config.currentAccount.username));
                password.setAttribute("value", des.Decrypt(DataUtil.Config.currentAccount.password));

                if (DataUtil.Config.currentAccount.username.Trim() == "" || DataUtil.Config.currentAccount.password == "")
                {
                    loginSubmitted = true;
                    return;
                }

                //点击登录按钮
                if (DataUtil.Game.gameServer == (int)GameInfo.ServersList.American || DataUtil.Game.gameServer == (int)GameInfo.ServersList.AmericanR18)
                {
                    IHTMLElement autoLogin = document.getElementById("autoLogin");
                    IHTMLElement login     = document.getElementById("login-button");
                    if (autoLogin != null)
                    {
                        autoLogin.click();
                    }
                    if (login != null)
                    {
                        login.click();
                        loginSubmitted = true;
                    }
                }
                else
                {
                    foreach (IHTMLElement element in document.all)
                    {
                        if (Convert.ToString(element.getAttribute("value")) == "ログイン")
                        {
                            element.click();
                            loginSubmitted = true;
                            break;
                        }
                    }
                }
            }
        }
        private async Task RunCommandActions(IHTMLElement element, object sender, InternetExplorer browserInstance)
        {
            var engine = (IAutomationEngineInstance)sender;

            switch (v_WebAction)
            {
            case "Fire onmousedown event":
                ((IHTMLElement3)element).FireEvent("onmousedown");
                break;

            case "Fire onmouseover event":
                ((IHTMLElement3)element).FireEvent("onmouseover");
                break;

            case "Invoke Click":
                element.click();
                IECreateBrowserCommand.WaitForReadyState(browserInstance);
                break;

            case "Left Click":
            case "Middle Click":
            case "Right Click":
                int elementXposition = FindElementXPosition(element);
                int elementYposition = FindElementYPosition(element);

                //inputs need to be validated

                string userXAdjustString = (from rw in v_WebActionParameterTable.AsEnumerable()
                                            where rw.Field <string>("Parameter Name") == "X Adjustment"
                                            select rw.Field <string>("Parameter Value")).FirstOrDefault();
                int userXAdjust = (int)await userXAdjustString.EvaluateCode(engine);

                string userYAdjustString = (from rw in v_WebActionParameterTable.AsEnumerable()
                                            where rw.Field <string>("Parameter Name") == "Y Adjustment"
                                            select rw.Field <string>("Parameter Value")).FirstOrDefault();
                int userYAdjust = (int)await userYAdjustString.EvaluateCode(engine);

                var ieClientLocation = User32Functions.GetWindowPosition(new IntPtr(browserInstance.HWND));

                var mouseX     = (elementXposition + ieClientLocation.left + 10) + userXAdjust;                                  // + 10 gives extra padding
                var mouseY     = (elementYposition + ieClientLocation.top + 90 + SystemInformation.CaptionHeight) + userYAdjust; // +90 accounts for title bar height
                var mouseClick = v_WebAction;

                User32Functions.SendMouseMove(mouseX, mouseY, v_WebAction);
                break;

            case "Set Attribute":
                string setAttributeName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                           where rw.Field <string>("Parameter Name") == "Attribute Name"
                                           select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string valueToSet = (from rw in v_WebActionParameterTable.AsEnumerable()
                                     where rw.Field <string>("Parameter Name") == "Value To Set"
                                     select rw.Field <string>("Parameter Value")).FirstOrDefault();

                valueToSet = (string)await valueToSet.EvaluateCode(engine);

                element.setAttribute(setAttributeName, valueToSet);
                break;

            case "Set Text":
                string setTextAttributeName = "value";

                string textToSet = (from rw in v_WebActionParameterTable.AsEnumerable()
                                    where rw.Field <string>("Parameter Name") == "Text To Set"
                                    select rw.Field <string>("Parameter Value")).FirstOrDefault();

                textToSet = (string)await textToSet.EvaluateCode(engine);

                element.setAttribute(setTextAttributeName, textToSet);
                break;

            case "Get Attribute":
                string attributeName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Attribute Name"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string variableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                       where rw.Field <string>("Parameter Name") == "Variable Name"
                                       select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string convertedAttribute = Convert.ToString(element.getAttribute(attributeName));

                convertedAttribute.SetVariableValue(engine, variableName);
                break;
            }
        }
Пример #26
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;
        }
Пример #27
0
        //填充参数
        protected virtual void FillElement(FillParameter parameter, string value)
        {
            if (parameter == null)
            {
                return;
            }
            IHTMLElement element = null;

            if (parameter.Type != Matcher.TYPE_FORM)
            {
                //查找元素,如果是null就是代表没有此元素
                element = GetElement(parameter, GetFormIndex(parameter));
                if (element == null)
                {
                    this.FillRecords.Add(new FillRecord(GetElementType(parameter.Type), RecordType.Failed, "未找到此元素", parameter.ParameterName));
                    return;
                }
                if (parameter.Type == Matcher.TYPE_FILE)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return;
                    }
                    value = File.Exists(value) ? value : (string.IsNullOrEmpty(DataFilePath) ? value : string.Format("{0}\\{1}", DataFilePath, value));
                    if (System.IO.File.Exists(value) == false)
                    {
                        this.FillRecords.Add(new FillRecord(ElementType.File, RecordType.Failed, string.Format("文件{0}不存在", value), parameter.ParameterName));
                        return;
                    }
                }
                ((IHTMLElement2)element).focus();
            }
            if (string.IsNullOrEmpty(parameter.SplitExpr) == false && string.IsNullOrEmpty(value) == false)
            {
                Match match = Regex.Match(value, parameter.SplitExpr, RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    value = match.Groups["value"].Value;
                }
            }
            _currentFillValue = value;
            switch (parameter.Type)
            {
            case Matcher.TYPE_FORM:
                UpdateFormIndex(parameter);
                break;

            case Matcher.TYPE_RADIO:
                IHTMLInputElement radioElement = element as IHTMLInputElement;
                radioElement.@checked = true;
                this.FillRecords[(int)ElementType.Radio].RecordCount++;
                break;

            case Matcher.TYPE_SELECT:
                IHTMLSelectElement selectElement = element as IHTMLSelectElement;
                if (FillSelectElement(selectElement, parameter, value))
                {
                    this.FillRecords[(int)ElementType.Select].RecordCount++;
                }
                else
                {
                    this.FillRecords.Add(new FillRecord(ElementType.Select, RecordType.Failed, string.Format("下拉框中不包含选项 {0}", value), parameter.ParameterName));
                }
                break;

            case Matcher.TYPE_A:
                element.click();
                break;

            case Matcher.TYPE_FILE:
                element.click();
                this.FillRecords[(int)ElementType.File].RecordCount++;
                break;

            case Matcher.TYPE_SUBMIT:
            case Matcher.TYPE_BUTTON:
            case "BUTTON/SUBMIT":
                IHTMLInputElement fileElement = element as IHTMLInputElement;
                element.click();
                break;

            case Matcher.TYPE_TEXTAREA:
            case Matcher.TYPE_TEXT:
            case Matcher.TYPE_PASSWORD:
                FillTextElement(element, value);
                break;
            }
        }
Пример #28
0
 public void InvokeClick(IHTMLElement HtmlElement)
 {
     HtmlElement.click();
 }
Пример #29
0
        private void RunCommandActions(IHTMLElement element, object sender, InternetExplorer browserInstance)
        {
            if (v_WebAction == "Fire onmousedown event")
            {
                ((IHTMLElement3)element).FireEvent("onmousedown");
            }
            else if (v_WebAction == "Fire onmouseover event")
            {
                ((IHTMLElement3)element).FireEvent("onmouseover");
            }
            else if (v_WebAction == "Invoke Click")
            {
                element.click();
                IEBrowserCreateCommand.WaitForReadyState(browserInstance);
            }
            else if ((v_WebAction == "Left Click") || (v_WebAction == "Middle Click") || (v_WebAction == "Right Click"))
            {
                int elementXposition = FindElementXPosition(element);
                int elementYposition = FindElementYPosition(element);

                //inputs need to be validated

                int userXAdjust = Convert.ToInt32((from rw in v_WebActionParameterTable.AsEnumerable()
                                                   where rw.Field <string>("Parameter Name") == "X Adjustment"
                                                   select rw.Field <string>("Parameter Value")).FirstOrDefault());

                int userYAdjust = Convert.ToInt32((from rw in v_WebActionParameterTable.AsEnumerable()
                                                   where rw.Field <string>("Parameter Name") == "Y Adjustment"
                                                   select rw.Field <string>("Parameter Value")).FirstOrDefault());

                var ieClientLocation = User32Functions.GetWindowPosition(new IntPtr(browserInstance.HWND));

                SendMouseMoveCommand newMouseMove = new SendMouseMoveCommand();

                newMouseMove.v_XMousePosition = ((elementXposition + ieClientLocation.left + 10) + userXAdjust).ToString();                                                       // + 10 gives extra padding
                newMouseMove.v_YMousePosition = ((elementYposition + ieClientLocation.top + 90 + System.Windows.Forms.SystemInformation.CaptionHeight) + userYAdjust).ToString(); // +90 accounts for title bar height
                newMouseMove.v_MouseClick     = v_WebAction;
                newMouseMove.RunCommand(sender);
            }
            else if (v_WebAction == "Set Attribute")
            {
                string attributeName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Attribute Name"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string valueToSet = (from rw in v_WebActionParameterTable.AsEnumerable()
                                     where rw.Field <string>("Parameter Name") == "Value To Set"
                                     select rw.Field <string>("Parameter Value")).FirstOrDefault();

                valueToSet = valueToSet.ConvertToUserVariable(sender);

                element.setAttribute(attributeName, valueToSet);
            }
            else if (v_WebAction == "Set Text")
            {
                string attributeName = "value";

                string textToSet = (from rw in v_WebActionParameterTable.AsEnumerable()
                                    where rw.Field <string>("Parameter Name") == "Text To Set"
                                    select rw.Field <string>("Parameter Value")).FirstOrDefault();

                textToSet = textToSet.ConvertToUserVariable(sender);

                element.setAttribute(attributeName, textToSet);
            }
            else if (v_WebAction == "Get Attribute")
            {
                string attributeName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Attribute Name"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string variableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                       where rw.Field <string>("Parameter Name") == "Variable Name"
                                       select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string convertedAttribute = Convert.ToString(element.getAttribute(attributeName));

                convertedAttribute.StoreInUserVariable(sender, variableName);
            }
        }
Пример #30
0
 public void submitClick(IHTMLElement submitElement)
 {
     this.BeginPageLoading();
     submitElement.click();
     this.WaitForComplete();
 }
Пример #31
0
        private void RegCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            wb_.DocumentCompleted -= RegCompleted;

            // Input Reg Info.
            IHTMLDocument2   doc  = (IHTMLDocument2)wb_.Document.DomDocument;
            IHTMLFormElement form = doc.forms.item("main");

            IDictionary <string, string> info = GetRegInfo();

            // Account
            {
                IHTMLInputElement accEle = form.item("username");
                accEle.value = info["username"];
            }

            // Pwd
            {
                IHTMLInputElement pwdEle = form.item("password");
                pwdEle.value = info["password"];
                IHTMLInputElement pwdConfirmEle = form.item("password2");
                pwdConfirmEle.value = info["password"];
            }

            // Real Name
            {
                IHTMLInputElement aliasEle = form.item("alias");
                aliasEle.value = info["alias"];
            }

            // PwdSecurityQuestion
            {
                IHTMLSelectElement qEle = form.item("question");
                qEle.selectedIndex = int.Parse(info["question"]);
            }

            // PwdSecurityAnswer
            {
                IHTMLInputElement aEle = form.item("answer");
                aEle.value = info["answer"];
            }

            // Sex
            // Use default value.
            //{
            //    IHTMLSelectElement sexEle = form.item("answer");
            //    sexEle.selectedIndex = int.Parse(info["answer"]);
            //}

            //  CreditCard Pwd
            {
                IHTMLSelectElement aEle = form.item("drpAuthCodea");
                aEle.selectedIndex = int.Parse(info["drpAuthCodea"]);

                IHTMLSelectElement bEle = form.item("drpAuthCodeb");
                bEle.selectedIndex = int.Parse(info["drpAuthCodeb"]);

                IHTMLSelectElement cEle = form.item("drpAuthCodec");
                cEle.selectedIndex = int.Parse(info["drpAuthCodec"]);

                IHTMLSelectElement dEle = form.item("drpAuthCoded");
                dEle.selectedIndex = int.Parse(info["drpAuthCoded"]);
            }

            // BirthDay
            {
                IHTMLSelectElement yearEle = form.item("year11");
                yearEle.selectedIndex = int.Parse(info["year11"]);

                IHTMLSelectElement monthEle = form.item("maoth11");
                monthEle.selectedIndex = int.Parse(info["month11"]);

                IHTMLSelectElement dayEle = form.item("day11");
                dayEle.selectedIndex = int.Parse(info["day11"]);
            }

            // All use default.
            // Nation
            {
                IHTMLInputElement nationEle = form.item("contory");
            }

            // City
            {
                IHTMLInputElement cityEle = form.item("city");
            }
            // KnownWay
            {
                //...
            }
            // Agreement
            {
            }


            // Submit
            {
                IHTMLElement submitEle = form.item("submitBtn");
                submitEle.click();
            }
        }