Exemple #1
0
        private void InstallHTMLHooks(Win32HookMsgEventArgs evt)
        {
            String       searchCondition   = String.Format("{0}!=1", CatStudioConstants.HOOKED_BY_REC_ATTR);
            IElementList rootElemNotHooked = this.twebstBrowser.FindAllElements("html", searchCondition);

            try
            {
                for (int i = 0; i < rootElemNotHooked.length; ++i)
                {
                    IElement       crntElem = rootElemNotHooked[i];
                    IHTMLDocument3 doc3     = (IHTMLDocument3)crntElem.nativeElement.document;
                    IHTMLWindow2   wnd      = ((IHTMLDocument2)doc3).parentWindow;

                    doc3.attachEvent("onclick", new HtmlHandler(this.OnHtmlClick, wnd));
                    doc3.attachEvent("onmouseup", new HtmlHandler(this.OnHtmlMouseUp, wnd));
                    crntElem.SetAttribute(CatStudioConstants.HOOKED_BY_REC_ATTR, "1");
                }

                InstallHTMLHooksForOnchange();
            }
            catch
            {
                // Can not properly install html hooks.
            }
        }
Exemple #2
0
        public void setupRollcallPage(bool showPictures)
        {
            IHTMLDocument3 rollpageFrame = parseFrameDocument(ROLLCALL_FRAME);

            signAllStudents(false);
            setShowingAllStudentPictures(showPictures);
        }
Exemple #3
0
        public void loadStylesheet()
        {
            string appDir = Program.appDir, dataDir = Program.dataDir,
                   themeName = Program.glob.para("messageView__theme", "Default");
            string style = "", style2 = "";

            try {
                style = File.ReadAllText(appDir + "style-global.txt");
                if (File.Exists(appDir + "themes/" + themeName + ".txt"))
                {
                    style2 = File.ReadAllText(appDir + "themes/" + themeName + ".txt");
                }
                else if (File.Exists(dataDir + "style.txt") && themeName == "Custom")
                {
                    style2 = File.ReadAllText(dataDir + "style.txt");
                }
            } catch (Exception e) {
                Console.WriteLine("Error loading stylesheet: " + e.Message);
            }
            try {
                IHTMLDocument3    doc     = (IHTMLDocument3)this.Document.DomDocument;
                IHTMLStyleElement styleEl = (IHTMLStyleElement)doc.getElementById("st");
                styleEl.styleSheet.cssText = style + "\n" + style2;
            } catch (Exception e) {
                Console.WriteLine("Error applying stylesheet: " + e.Message);
            }
        }
Exemple #4
0
        public IHTMLElement GetElementByXPath(String xPath)
        {
            String[]     path = xPath.Split('/');
            int          dept = 0;
            int          idx  = GetSplitKey(path[dept++]);
            IHTMLElement element;

            if (idx == 0)
            {
                IHTMLDocument3 doc3 = (IHTMLDocument3)document;
                element = doc3.documentElement;
            }
            else
            {
                element = ((IHTMLDocument3)subFrameDocument[idx - 1]).documentElement;
            }

            while (element != null)
            {
                idx = GetSplitKey(path[dept]);
                if (idx >= element.children.Length)
                {
                    return(null);
                }
                element = element.children[idx];
                dept++;
                if (path.Length == dept)
                {
                    return(element);
                }
            }
            return(null);
        }
Exemple #5
0
            /// <summary>
            /// Callback to indicate that consent screen has been rendered and is ready to be analyzed.
            /// </summary>
            /// <param name="sender">Reference to the browser.</param>
            /// <param name="args">Event arguments.</param>
            private void OnConsentDisplayed(object sender, EventArgs args)
            {
                IHTMLDocument3 document     = this.StopTimerAndGetDocument(sender);
                IHTMLElement   buttonAccept = document.getElementById("submit_approve_access") as IHTMLElement;

                buttonAccept.click();
            }
Exemple #6
0
        public void signStudent(Student student, bool signed)
        {
            IHTMLDocument2 htmlDoc       = (IHTMLDocument2)webBrowser.Document.DomDocument;
            IHTMLDocument3 rollpageFrame = parseFrameDocument(ROLLCALL_FRAME);
            var            inputElms     = rollpageFrame.getElementsByTagName("td")
                                           .OfType <IHTMLElement>().ToList();

            foreach (var elm in inputElms)
            {
                var html = elm.innerHTML == null ? null : elm.innerHTML.Trim();
                if (html != null && Regex.IsMatch(html, REGEX_HTML_IS_STUDENT_TD) &&
                    html.Contains(student.studentId))
                {
                    if (signed)
                    {
                        elm.innerHTML = elm.innerHTML.Replace("CHECKED", "");
                    }
                    else
                    {
                        elm.setAttribute("checked", "checked");
                    }
                    break;
                }
            }
        }
Exemple #7
0
        public void CreateMapPathCsv(String filename)
        {
            FileInfo fileinfo = new FileInfo(filename);

            if (fileinfo.Exists)
            {
                fileinfo.Delete();
            }
            using (FileStream fs = fileinfo.OpenWrite())
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (StreamWriter sw = new StreamWriter(bs, Encoding.UTF8))
                    {
                        IHTMLDocument3 doc3 = (IHTMLDocument3)mainDom;
                        sw.WriteLine("key, number, tagname, id, classname, html");
                        WriteCSV(sw, this, doc3.documentElement, 0);

                        int index = 1;
                        IList <IHTMLDocument> subFrame = this.GetSubDocument();
                        foreach (IHTMLDocument frame in subFrame)
                        {
                            IHTMLDocument3 framedoc3 = frame as IHTMLDocument3;
                            WriteCSV(sw, this, framedoc3.documentElement, index++);
                        }
                    }
                }
            }
        }
Exemple #8
0
        // GET: api/Users
        public IHttpActionResult GetUser(PublicModel publicModel)
        {
            SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer();

            ie.Navigate("https://login.taobao.com/member/login.jhtml?redirectURL=https%3A%2F%2Fai.taobao.com%2F%3Fpid%3Dmm_112599953_14918079_77950911");
            ie.Visible = true;

            IHTMLDocument3 doc = (IHTMLDocument3)ie.Document;

            doc.getElementById("TPL_username_1").innerText = "肖梓璇35834616";
            doc.getElementById("TPL_password_1").innerText = "xiao4563515";
            doc.getElementById("J_SubmitStatic").click();


            ie.Navigate("http://i.taobao.com/my_taobao.htm");
            ie.Visible = true;

            ie.Navigate(" https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm?spm=a1z02.1.972272805.d4919663.73d2782d6TTeTm&action=itemlist/BoughtQueryAction&event_submit_do_query=1&tabCode=waitRate");
            ie.Visible = true;
            doc.getElementById("rateOrder").click();
            var ss = doc.documentElement.outerText = "1111";


            var userList = db.User.ToList();
            var data     = Newtonsoft.Json.JsonConvert.SerializeObject(userList);

            return(Json(data));
        }
        /// <summary>
        /// Handle the HTMLElementEvents event.
        /// </summary>
        /// <param name="e"></param>
        ///

        void SetDragHandler()
        {
            //To avoid set handler repeatedly, remove previous handler.
            //DateTime tm1 = DateTime.Now;
            try
            {
                document          = ieInstance.Document as IHTMLDocument3;
                rootElementEvents = document.documentElement as HTMLElementEvents2_Event;

                rootElementEvents.ondragstart -=
                    new HTMLElementEvents2_ondragstartEventHandler(Events_Ondragstart);
                rootElementEvents.ondragstart +=
                    new HTMLElementEvents2_ondragstartEventHandler(Events_Ondragstart);
                rootElementEvents.ondragover -=
                    new HTMLElementEvents2_ondragoverEventHandler(Events_Ondragover);
                rootElementEvents.ondragover +=
                    new HTMLElementEvents2_ondragoverEventHandler(Events_Ondragover);
                rootElementEvents.ondragend -=
                    new HTMLElementEvents2_ondragendEventHandler(Events_Ondragend);
                rootElementEvents.ondragend +=
                    new HTMLElementEvents2_ondragendEventHandler(Events_Ondragend);
            }
            catch
            {
                //MessageBox.Show("set failed");
            }
            //TimeSpan s = DateTime.Now - tm1;
            //MessageBox.Show(s.TotalMilliseconds.ToString());
        }
Exemple #10
0
        public IHTMLElement GetElementByXPath(String xPath)
        {
            String[]     pathList = xPath.Split('/');
            int          idx      = 0;
            int          tagIndex = GetSplitKey(pathList[idx++]);
            IHTMLElement element;

            if (tagIndex == 0)
            {
                IHTMLDocument3 doc3 = (IHTMLDocument3)mainDom;
                element = doc3.documentElement;
            }
            else
            {
                element = ((IHTMLDocument3)subFrame[tagIndex - 1]).documentElement;
            }

            while (element != null)
            {
                tagIndex = GetSplitKey(pathList[idx]);
                if (tagIndex >= element.children.Length)
                {
                    return(null);
                }
                element = element.children[tagIndex];
                idx++;
                if (pathList.Length == idx)
                {
                    break;
                }
            }
            return(element);
        }
        void m_timer_Tick(object sender, EventArgs e)
        {
            m_timer.Stop();
            this.richTextBox1.Clear();
            //Enum child windows
            winenum.enumerate(m_Dialog);
            //Get the control names
            m_Ctls  = winenum.GetControlsClassNames();
            m_Count = m_Ctls.Count;

            this.richTextBox1.AppendText("HTMLDialog total child windows count =" + m_Count.ToString() + "\r\n");

            for (m_Counter = 0; m_Counter < m_Count; m_Counter++)
            {
                this.richTextBox1.AppendText(m_Ctls[m_Counter].ToString() + "\r\n");
                //Find IE_Server
                if ((m_Ctls[m_Counter] != null) &&
                    (m_Ctls[m_Counter].ToString().Equals("Internet Explorer_Server", StringComparison.CurrentCultureIgnoreCase))
                    )
                {
                    //subscribe to documentelement events
                    //so we can handle key + unload events
                    m_IE = (IntPtr)Int32.Parse(winenum.GetControlsHwnds()[m_Counter].ToString());
                    this.richTextBox1.AppendText("Internet Explorer_Server HWND =" + m_IE.ToString() + "\r\n");
                    if (m_IE != IntPtr.Zero)
                    {
                        m_pDoc2 = winenum.GetIEHTMLDocument2FromWindowHandle(m_IE);
                        IHTMLDocument3 doc3 = m_pDoc2 as IHTMLDocument3;
                        if (doc3 != null)
                        {
                            if (m_docelemevents.ConnectToHtmlElementEvents(doc3.documentElement))
                            {
                                this.richTextBox1.AppendText("Subscribed to Document events = OK\r\n");
                            }
                            else
                            {
                                this.richTextBox1.AppendText("Subscribed to Document events = FAILED\r\n");
                            }
                        }
                        if (m_pDoc2 != null)
                        {
                            m_pWin2 = m_pDoc2.parentWindow as IHTMLWindow2;
                            if (m_pWin2 != null)
                            {
                                if (m_docwinevents.ConnectToHtmlWindowEvents(m_pWin2))
                                {
                                    this.richTextBox1.AppendText("Subscribed to Window events = OK\r\n");
                                }
                                else
                                {
                                    this.richTextBox1.AppendText("Subscribed to Window events = FAILED\r\n");
                                }
                            }
                        }
                    }
                    break;
                }
            }
            winenum.clear();
        }
Exemple #12
0
            /// <summary>
            /// Stops the timer and reads the DOM document.
            /// </summary>
            /// <param name="timer">The timer.</param>
            /// <returns>The document.</returns>
            private IHTMLDocument3 StopTimerAndGetDocument(object timer)
            {
                (timer as DispatcherTimer).Stop();
                IHTMLDocument3 document = this.browser.Document as IHTMLDocument3;

                return(document);
            }
        /// <summary>
        /// Inserts the extended entry break into the editor.
        /// </summary>
        internal void InsertExtendedEntryBreak()
        {
            IHTMLDocument3 doc3       = (IHTMLDocument3)HTMLElement.document;
            IHTMLElement2  entryBreak = (IHTMLElement2)doc3.getElementById(EXTENDED_ENTRY_ID);

            if (entryBreak == null)
            {
                using (IUndoUnit undo = EditorContext.CreateUndoUnit())
                {
                    using (EditorContext.DamageServices.CreateDamageTracker(ElementRange.Clone(), true))
                    {
                        MarkupPointer insertionPoint =
                            EditorContext.MarkupServices.CreateMarkupPointer(EditorContext.Selection.SelectedMarkupRange.Start);

                        //delete the parent block element of the insertion point if it is empty (bug 421500)
                        DeleteInsertionTargetBlockIfEmpty(insertionPoint);

                        IHTMLElement extendedEntryBreak = InsertExtendedEntryBreak(insertionPoint);

                        //reselect the insertion point
                        MarkupRange selection = EditorContext.MarkupServices.CreateMarkupRange();
                        insertionPoint.MoveAdjacentToElement(extendedEntryBreak, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
                        MarkupPointerMoveHelper.MoveUnitBounded(
                            insertionPoint, MarkupPointerMoveHelper.MoveDirection.RIGHT,
                            MarkupPointerAdjacency.AfterEnterBlock | MarkupPointerAdjacency.BeforeText
                            , HTMLElement);
                        selection.Start.MoveToPointer(insertionPoint);
                        selection.End.MoveToPointer(insertionPoint);
                        selection.ToTextRange().select();
                    }
                    undo.Commit();
                }
            }
        }
Exemple #14
0
        public static IHTMLDocument3 GetFrame(this IHTMLDocument3 document, string frameId)
        {
            dynamic d         = document;
            var     txnWindow = ((IHTMLWindow2)d.frames[frameId]);

            return((IHTMLDocument3)txnWindow.document);
        }
Exemple #15
0
        private void HookIntroPage()
        {
            try
            {
                IWebBrowser2   nativeBrowser = (SHDocVw.IWebBrowser2)webBrowser.ActiveXInstance;
                IHTMLDocument3 introDoc      = nativeBrowser.Document as IHTMLDocument3;

                if (introDoc != null)
                {
                    introDoc.attachEvent("onclick", new HtmlHandler(this.OnIntroClick, ((IHTMLDocument2)introDoc).parentWindow));

                    // Initialize checkbox with value in registry.
                    IHTMLInputElement checkBox          = (IHTMLInputElement)introDoc.getElementById(CatStudioConstants.INTRO_DONT_ASK_AGAIN_ATTR);
                    RegistryKey       twbstStudioRegKey = Registry.CurrentUser.OpenSubKey("Software\\Codecentrix\\OpenTwebst\\Studio", false);

                    if (twbstStudioRegKey != null)
                    {
                        int dontShowIntro = (int)twbstStudioRegKey.GetValue("dontshowintro", 0);

                        checkBox.@checked = (dontShowIntro != 0);
                        twbstStudioRegKey.Close();
                    }
                }
            }
            catch
            {
                // Do nothing. Maybe not this critical.
            }
        }
Exemple #16
0
 public DocHTML(HTMLDocument doc)
 {
     mDoc = doc;
     mDoc2 = (IHTMLDocument2)mDoc;
     mDoc3 = (IHTMLDocument3)mDoc;
     mDoc4 = (IHTMLDocument4)mDoc;
     mDoc5 = (IHTMLDocument5)mDoc;
 }
Exemple #17
0
 public DocHTML(HTMLDocument doc)
 {
     mDoc  = doc;
     mDoc2 = (IHTMLDocument2)mDoc;
     mDoc3 = (IHTMLDocument3)mDoc;
     mDoc4 = (IHTMLDocument4)mDoc;
     mDoc5 = (IHTMLDocument5)mDoc;
 }
Exemple #18
0
 public DocHTML(HTMLDocument doc)
 {
     this.mDoc  = doc;
     this.mDoc2 = (IHTMLDocument2)this.mDoc;
     this.mDoc3 = (IHTMLDocument3)this.mDoc;
     this.mDoc4 = (IHTMLDocument4)this.mDoc;
     this.mDoc5 = (IHTMLDocument5)this.mDoc;
 }
 private static void screenCapture_HtmlDocumentAvailable(object sender, OpenLiveWriter.Api.HtmlDocumentAvailableEventArgs e)
 {
     IHTMLDocument3 document = (IHTMLDocument3)e.Document;
     IHTMLElement mapElement = document.getElementById("map");
     if (mapElement == null || mapElement.getAttribute("loaded", 2) == System.DBNull.Value)
         e.DocumentReady = false;
     else
         e.DocumentReady = true;
 }
        public void DoCapture()
        {
            IHTMLDocument2 doc2  = (IHTMLDocument2)mWb.Document;
            IHTMLDocument3 doc3  = (IHTMLDocument3)mWb.Document;
            IHTMLElement2  body2 = (IHTMLElement2)doc2.body;
            IHTMLElement2  root2 = (IHTMLElement2)doc3.documentElement;

            // Determine dimensions for the image; we could add minWidth here
            // to ensure that we get closer to the minimal width (the width
            // computed might be a few pixels less than what we want).
            int width  = Math.Max(body2.scrollWidth, root2.scrollWidth);
            int height = Math.Max(root2.scrollHeight, body2.scrollHeight);

            // Resize the web browser control
            mWb.SetBounds(0, 0, width, height);

            // Do it a second time; in some cases the initial values are
            // off by quite a lot, for as yet unknown reasons. We could
            // also do this in a loop until the values stop changing with
            // some additional terminating condition like n attempts.
            width  = Math.Max(body2.scrollWidth, root2.scrollWidth);
            height = Math.Max(root2.scrollHeight, body2.scrollHeight);

            //@todo override with fixed values
            Rectangle resolution = System.Windows.Forms.Screen.PrimaryScreen.Bounds;

            width  = resolution.Width;
            height = resolution.Height;
            mWb.SetBounds(0, 0, width, height);

            Bitmap   image = new Bitmap(width, height);
            Graphics g     = Graphics.FromImage(image);

            _RECTL bounds;

            bounds.left   = 0;
            bounds.top    = 0;
            bounds.right  = width;
            bounds.bottom = height;

            IntPtr      hdc = g.GetHdc();
            IViewObject iv  = doc2 as IViewObject;

            // TODO: Write to Metafile instead if requested.

            iv.Draw(1, -1, (IntPtr)0, (IntPtr)0, (IntPtr)0,
                    (IntPtr)hdc, ref bounds, (IntPtr)0, (IntPtr)0, 0);

            g.ReleaseHdc(hdc);
            image.Save(mFile);
            image.Dispose();

            if (mImageDiff != null)
            {
                mImageDiff.run();
            }
        }
Exemple #21
0
        protected virtual void RegisterEvents()
        {
            IHTMLDocument3 doc3 = this._document as IHTMLDocument3;

            if (doc3 != null)
            {
                doc3.attachEvent("onpropertychange", this);
            }
        }
Exemple #22
0
        private void runjs()
        {
            var            docx  = webBrowser2.Document;
            var            frame = docx.Window.Frames;
            IHTMLDocument3 doci  = CorssDomainHelper.GetDocumentFromWindow(frame["course_frm"].DomWindow as IHTMLWindow2);
            HTMLIFrame     if2   = doci.getElementById("course_frame") as HTMLIFrameClass;

            if2.contentWindow.execScript(tb4.Text);
        }
Exemple #23
0
        private IHTMLDocument3 parseFrameDocument(int index)
        {
            object         refIndex = (object)index;
            IHTMLDocument2 htmlDoc  = (IHTMLDocument2)webBrowser.Document.DomDocument;
            IHTMLWindow2   target_mshtmlIHTMLWindow = (IHTMLWindow2)htmlDoc.frames.item(ref refIndex);
            IHTMLDocument2 target_mshtmlIHTMLDoc    = CrossFrameIE.GetDocumentFromWindow(target_mshtmlIHTMLWindow);
            IHTMLDocument3 doc3 = (IHTMLDocument3)target_mshtmlIHTMLDoc;

            return(doc3);
        }
		// Token: 0x0600030C RID: 780 RVA: 0x00020760 File Offset: 0x0001E960
		private bool ComposeEncrypt_onclick()
		{
			IHTMLDocument3 documentFromWindow = webrowserHelper.GetDocumentFromWindow(this.webBrowser1.Document.Window.Frames["alibaba-login-box"].DomWindow as IHTMLWindow2);
			string value = documentFromWindow.getElementById("fm-login-id").getAttribute("value", 0).ToString();
			string value2 = documentFromWindow.getElementById("fm-login-password").getAttribute("value", 0).ToString();
			inihelp.SetValue("特殊", "ali_account", value);
			inihelp.SetValue("特殊", "ali_password", value2);
			this.timer1.Stop();
			return true;
		}
Exemple #25
0
        public void GetServersFromWeb(InternetExplorer ie, bool visible)
        {
            if (!groupName.Equals("PPE"))
            {
                try
                {
                    object Empty = 0;
                    object URL   = Index.CreateInstance().temcurl + "?query=ON&group=" + groupName;

                    ie.Visible = visible;
                    ie.Navigate2(ref URL, ref Empty, ref Empty, ref Empty, ref Empty);

                    System.Threading.Thread.Sleep(5000);

                    while (ie.Busy)
                    {
                        System.Threading.Thread.Sleep(1000);
                    }

                    IHTMLDocument3 document = (IHTMLDocument3)ie.Document;
                    if (document != null)
                    {
                        HTMLTable queryTable = (HTMLTable)document.getElementById("query_table");
                        if (queryTable != null && queryTable.rows != null && queryTable.rows.length > 1)
                        {
                            servers = new List <Server>();
                            for (int i = 1; i < queryTable.rows.length; i++)
                            {
                                HTMLTableRow row = (HTMLTableRow)queryTable.rows.item(i, i);
                                if (row != null && row.cells != null && row.cells.length > 4)
                                {
                                    HTMLTableCell serverCell       = (HTMLTableCell)row.cells.item(0, 0);
                                    HTMLTableCell travelServerCell = (HTMLTableCell)row.cells.item(4, 4);
                                    if (serverCell != null && serverCell.innerText != null && !serverCell.innerText.Equals("") &&
                                        travelServerCell != null && travelServerCell.innerText != null && !travelServerCell.innerText.Equals(""))
                                    {
                                        foreach (string singleTravelServer in travelServerCell.innerText.Split(new char[] { ',' }))
                                        {
                                            servers.Add(new Server(serverCell.innerText, singleTravelServer));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                { Console.WriteLine(exception.Message); }
                finally
                {
                    updateDate = DateTime.Now;
                    OnUpdated(EventArgs.Empty);
                }
            }
        }
Exemple #26
0
        public List <IHTMLElement> GetElementByTagName(String tagname)
        {
            List <IHTMLElement> ret  = new List <IHTMLElement>();
            IHTMLDocument3      doc3 = (IHTMLDocument3)mainDom;

            foreach (IHTMLElement item in doc3.getElementsByTagName(tagname))
            {
                ret.Add(item);
            }
            return(ret);
        }
Exemple #27
0
        /// <summary>
        /// Removes duplicate extended entries that may exist in the document.
        /// </summary>
        private void RemoveDuplicateExtendedEntries()
        {
            IHTMLDocument3         doc3 = (IHTMLDocument3)HTMLElement.document;
            IHTMLElementCollection extendedEntryElements = doc3.getElementsByName(PostBodyEditingElementBehavior.EXTENDED_ENTRY_ID);

            if (extendedEntryElements.length > 1)
            {
                //delete any extended entry markers that are not this element (use a timer to avoid bug 407544)
                ExtendedEntrySweeper extendedEntrySweeper = new ExtendedEntrySweeper(EditorContext, (IHTMLDocument3)HTMLElement.document, HTMLElement);
                TimerHelper.CallbackOnDelay(new InvokeInUIThreadDelegate(extendedEntrySweeper.DoDelete), 10);
            }
        }
        public HTMLDocumentEventHelper(IHTMLDocument3 document, InternetExplorer ieInstance)
        {
            this.document   = document as IHTMLDocument2;
            this.ieInstance = ieInstance;

            this.ondragstart += e => e.returnValue = false;
            var rootElementEvents = document.documentElement as HTMLElementEvents_Event;

            //rootElementEvents.ondragstart += ()=>false;
            rootElementEvents.ondragover += () => false;
            rootElementEvents.ondrop     += () => { SuperDragDrop(); return(false); };
        }
Exemple #29
0
        private void _btnGetFromAgresso_Click(object sender, EventArgs e)
        {
            IHTMLDocument3 doc3 = null;

            try
            {
                doc3 = InternetExplorerUtilities.GetTimesheetDocument();
                if (doc3 == null)
                {
                    MessageBox.Show("Can't find Agresso timesheet page. Please check and try again", "Can't find page", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    IEnumerable <string> currentProjectCodes = Projects.Projects.Select(p => p.Code.ToUpper());
                    IEnumerable <Tuple <string, string> > allCodesAndDescriptions = InternetExplorerUtilities.GetProjectCodesAndDescriptions(doc3);
                    List <Tuple <string, string> >        toAdd = new List <Tuple <string, string> >();

                    if (currentProjectCodes.Count() == 0)
                    {
                        toAdd.AddRange(allCodesAndDescriptions);
                    }
                    else
                    {
                        foreach (var project in allCodesAndDescriptions)
                        {
                            if (!currentProjectCodes.Contains(project.Item1))
                            {
                                toAdd.Add(project);
                            }
                        }
                    }

                    foreach (var newProject in toAdd)
                    {
                        Project p = new Project();
                        p.Code  = newProject.Item1;
                        p.Title = newProject.Item2;
                        Projects.Projects.Add(p);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error when getting workorders", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (doc3 != null)
                {
                    Marshal.ReleaseComObject(doc3);
                }
            }
        }
Exemple #30
0
        /// <summary>
        /// 获取文档也包含iframe列表,支持跨域查找
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        static public IHTMLElementCollection GetFrames(IHTMLDocument2 doc)
        {
            IHTMLDocument3 doc3 = doc as IHTMLDocument3;

            return(doc3.getElementsByTagName("iframe"));
            //mshtml.IHTMLWindow2 window2 = null;
            //window2 = doc.parentWindow as mshtml.IHTMLWindow2;
            //SHDocVw.IWebBrowser2 browser = CrossFrameIE.GetIWebBrowser2(window2);
            //mshtml.IHTMLDocument3 parentDoc = browser.Parent as mshtml.IHTMLDocument3;
            //if (parentDoc == null) return null;
            //return parentDoc.getElementsByTagName("iframe");
        }
Exemple #31
0
        public DocumentAdapter(object document)
        {
            //_documentUri = documentUri;

            _raw = document;

            _document  = document as IHTMLDocument;
            _document2 = document as IHTMLDocument2;
            _document3 = document as IHTMLDocument3;
            _document4 = document as IHTMLDocument4;
            _document5 = document as IHTMLDocument5;
        }
Exemple #32
0
    public DocumentAdapter( object document )
    {
      //_documentUri = documentUri;

      _raw = document;

      _document = document as IHTMLDocument;
      _document2 = document as IHTMLDocument2;
      _document3 = document as IHTMLDocument3;
      _document4 = document as IHTMLDocument4;
      _document5 = document as IHTMLDocument5;
    }
        private static Bitmap GetElementPreviewImage(IHTMLDocument3 doc3, IHTMLElement element, int snapshotWidth, int snapshotHeight)
        {
            try
            {
                // @RIBBON TODO: Need to make this work for RTL as well.
                IDisplayServices displayServices = ((IDisplayServices)doc3);

                element.scrollIntoView(true);

                tagPOINT offset = new tagPOINT();
                offset.x = 0;
                offset.y = 0;
                displayServices.TransformPoint(ref offset, _COORD_SYSTEM.COORD_SYSTEM_CONTENT, _COORD_SYSTEM.COORD_SYSTEM_GLOBAL, element);

                using (Bitmap snapshotAfter = HtmlScreenCaptureCore.TakeSnapshot((IViewObject)doc3, snapshotWidth, snapshotHeight))
                {
                    //snapshotAfter.Save(@"c:\temp\snapshot" + element.id + ".bmp");

                    Rectangle elementRect;
                    elementRect = new Rectangle(Math.Max(2, offset.x), 2, Math.Min(element.offsetWidth, element.offsetParent.offsetWidth), element.offsetHeight);

                    if (element.offsetWidth <= 0 || element.offsetHeight <= 0)
                        return null;

                    Bitmap cropped = ImageHelper2.CropBitmap(snapshotAfter, elementRect);
                    //cropped.Save(@"c:\temp\snapshot" + element.id + ".cropped.bmp");
                    return cropped;
                }
            }
            catch (Exception ex)
            {
                Trace.Fail("Failed to get element preview image for id " + element.id + ": " + ex);
                return null;
            }
        }
 protected internal override BlogEditingTemplate GenerateBlogTemplate(IHTMLDocument3 doc, IHTMLElement titleElement, IHTMLElement[] allTitleElements, IHTMLElement bodyElement)
 {
     return new BlogEditingTemplate(true);
 }
Exemple #35
0
		public DocumentElement(IHTMLDocument3 d, Browser b)
		{
			_Element = d;
			_Browser = b;
		}
Exemple #36
0
        /// <summary>
        /// Handle the HTMLElementEvents event.
        /// </summary>
        /// <param name="e"></param>
        /// 
        void SetDragHandler()
        {
            //To avoid set handler repeatedly, remove previous handler.
            //DateTime tm1 = DateTime.Now;
            try
            {
                document = ieInstance.Document as IHTMLDocument3;
                rootElementEvents = document.documentElement as HTMLElementEvents2_Event;

                rootElementEvents.ondragstart -=
                    new HTMLElementEvents2_ondragstartEventHandler(
                        Events_Ondragstart);
                rootElementEvents.ondragstart +=
                    new HTMLElementEvents2_ondragstartEventHandler(
                        Events_Ondragstart);
                rootElementEvents.ondragover -=
                    new HTMLElementEvents2_ondragoverEventHandler(
                        Events_Ondragover);
                rootElementEvents.ondragover +=
                    new HTMLElementEvents2_ondragoverEventHandler(
                        Events_Ondragover);
                rootElementEvents.ondragend -=
                    new HTMLElementEvents2_ondragendEventHandler(
                        Events_Ondragend);
                rootElementEvents.ondragend +=
                    new HTMLElementEvents2_ondragendEventHandler(
                         Events_Ondragend);
            }
            catch
            {
                //MessageBox.Show("set failed");
            }
            //TimeSpan s = DateTime.Now - tm1;
            //MessageBox.Show(s.TotalMilliseconds.ToString());
        }
        protected internal override BlogEditingTemplate GenerateBlogTemplate(IHTMLDocument3 doc, IHTMLElement titleElement, IHTMLElement[] allTitleElements, IHTMLElement bodyElement)
        {
            // if title is containing with a link then strip the link
            CleanupContainingAnchorTag(titleElement);
            string templateHtml = "";
            StyleBuilder styleBuilder = new StyleBuilder();
            IMarkupServicesRaw rawMarkupServices = doc as IMarkupServicesRaw;
            MshtmlMarkupServices markupServices = new MshtmlMarkupServices(rawMarkupServices);
            MarkupPointer startPointer = markupServices.CreateMarkupPointer(titleElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
            MarkupPointer endPointer = markupServices.CreateMarkupPointer(bodyElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
            MarkupRange range = markupServices.CreateMarkupRange(startPointer, endPointer);

            IHTMLElement stopElement = range.ParentElement();
            IHTMLElement currElement;

            string titleTemplateText = WrapInHiddenHtml(postTitleClass, BlogEditingTemplate.POST_TITLE_MARKER);
            AddTitleStyles(titleElement, styleBuilder);

            currElement = titleElement;
            while (currElement != null && currElement.sourceIndex != stopElement.sourceIndex)
            {
                string className = currElement.tagName + currElement.sourceIndex;
                titleTemplateText = WriteStartTag(currElement, className) + titleTemplateText + WriteEndTag(currElement);
                AddFrameStyles(currElement, "." + className, styleBuilder);
                currElement = currElement.parentElement;
            }

            string bodyTemplateText = WrapInHiddenHtml(postBodyClass, BlogEditingTemplate.POST_BODY_MARKER);
            AddBodyStyles(bodyElement, styleBuilder);

            currElement = bodyElement;
            while (currElement != null && currElement.sourceIndex != stopElement.sourceIndex)
            {
                string className = currElement.tagName + currElement.sourceIndex;
                bodyTemplateText = WriteStartTag(currElement, className) + bodyTemplateText + WriteEndTag(currElement);
                AddFrameStyles(currElement, "." + className, styleBuilder);
                currElement = currElement.parentElement;
            }

            templateHtml = titleTemplateText + bodyTemplateText;
            currElement = range.ParentElement();
            while (currElement != null)
            {
                string className = null;
                if (currElement.tagName == "HTML")
                {
                    MarkupPointer bodyPointer = markupServices.CreateMarkupPointer(((IHTMLDocument2)doc).body, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
                    MarkupPointer docPointer = markupServices.CreateMarkupPointer(currElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
                    MarkupRange headRange = markupServices.CreateMarkupRange(docPointer, bodyPointer);
                    IHTMLElement[] elements = headRange.GetTopLevelElements(new IHTMLElementFilter(IsHeadElement));
                    if (elements.Length > 0)
                    {
                        //string head = elements[0].innerHTML;
                        string head = "";
                        //string defaultStyles = "<style>p, h1, h2, h3, h4, h5, h6, blockquote, pre{ padding-top: 1px; }</style>";
                        styleBuilder.Dispose();
                        head = String.Format(CultureInfo.InvariantCulture, "<head>{0}<style>{1}</style></head>", head, styleBuilder.ToString());
                        templateHtml = head + templateHtml;
                    }
                }
                else
                {
                    className = currElement.tagName + currElement.sourceIndex;
                    AddFrameStyles(currElement, "." + className, styleBuilder);
                }
                templateHtml = WriteStartTag(currElement, className) + templateHtml + WriteEndTag(currElement);
                currElement = currElement.parentElement;
            }

            //prepend the doctype of the document - this prevents styles in the document from rendering improperly
            string docType = HTMLDocumentHelper.GetSpecialHeaders((IHTMLDocument2)doc).DocType;
            //string docType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"[]>";
            if (docType != null)
                templateHtml = docType + "\r\n" + templateHtml;

            return new BlogEditingTemplate(templateHtml);
        }
 private BlogEditingTemplate GenerateBlogTemplate(IHTMLDocument3 doc, IHTMLElement titleElement, IHTMLElement[] allTitleElements, IHTMLElement bodyElement)
 {
     return templateStrategy.GenerateBlogTemplate(doc, titleElement, allTitleElements, bodyElement);
 }
 protected internal abstract BlogEditingTemplate GenerateBlogTemplate(IHTMLDocument3 doc, IHTMLElement titleElement, IHTMLElement[] allTitleElements, IHTMLElement bodyElement);
        /// <summary>
        /// Generates an editing template the almost perfectly matches the existing website (include sidebars, titles, etc).
        /// </summary>
        protected internal override BlogEditingTemplate GenerateBlogTemplate(IHTMLDocument3 doc, IHTMLElement titleElement, IHTMLElement[] allTitleElements, IHTMLElement bodyElement)
        {
            // if title is containing with a link then strip the link
            CleanupContainingAnchorTag(titleElement);

            ClearDocumentContent(doc);

            //update primary titleElement to contain the editable title marker.
            string titleTemplateText = BlogEditingTemplate.POST_TITLE_MARKER;
            titleElement.innerText = titleTemplateText;

            //update the bodyElement to contain the editable body marker.
            string bodyTemplateText = BlogEditingTemplate.POST_BODY_MARKER;
            bodyElement.innerText = bodyTemplateText;

            string templateHtml = HTMLDocumentHelper.HTMLDocToString((IHTMLDocument2)doc);

            //prepend the doctype of the document - this prevents styles in the document from rendering improperly
            string docType = HTMLDocumentHelper.GetSpecialHeaders((IHTMLDocument2)doc).DocType;
            if (docType != null)
                templateHtml = docType + "\r\n" + templateHtml;

            return new BlogEditingTemplate(templateHtml);
        }
        public HTMLDocumentEventHelper(IHTMLDocument3 document, InternetExplorer ieInstance)
        {
            this.document = document as IHTMLDocument2;
            this.ieInstance = ieInstance;

            this.ondragstart += e => e.returnValue = false;
            var rootElementEvents = document.documentElement as HTMLElementEvents_Event;
            //rootElementEvents.ondragstart += ()=>false;
            rootElementEvents.ondragover += () => false;
            rootElementEvents.ondrop += () => { SuperDragDrop(); return false; };
        }
 private void ClearDocumentContent(IHTMLDocument3 doc)
 {
     IHTMLElement body = (doc as IHTMLDocument2).body;
     IHTMLDOMNode bodyNode = body as IHTMLDOMNode;
     ClearNodeContent(bodyNode);
 }
        /// <summary>
        /// Generates a blog editing template based on the HTML in a document.
        /// </summary>
        /// <param name="doc">The full HTML document</param>
        /// <param name="titleElement">the element in the document that surrounds the post title text</param>
        /// <param name="bodyElement">the element in the document that surrounds the post body text</param>
        /// <returns></returns>
        protected internal override BlogEditingTemplate GenerateBlogTemplate(IHTMLDocument3 doc, IHTMLElement titleElement, IHTMLElement[] allTitleElements, IHTMLElement bodyElement)
        {
            // if title is containing with a link then strip the link
            CleanupContainingAnchorTag(titleElement);

            IMarkupServicesRaw rawMarkupServices = doc as IMarkupServicesRaw;
            MshtmlMarkupServices markupServices = new MshtmlMarkupServices(rawMarkupServices);
            MarkupPointer startPointer = markupServices.CreateMarkupPointer(titleElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
            MarkupPointer endPointer = markupServices.CreateMarkupPointer(bodyElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
            MarkupRange range = markupServices.CreateMarkupRange(startPointer, endPointer);

            IHTMLElement stopElement = range.ParentElement();
            IHTMLElement currElement;

            string titleTemplateText = BlogEditingTemplate.POST_TITLE_MARKER;
            MarkupPointer siblingPointer = markupServices.CreateMarkupPointer();

            bool preserveClear = false;
            currElement = titleElement;
            IHTMLElement2 currElement2 = (IHTMLElement2)currElement;
            while (currElement != null && currElement.sourceIndex != stopElement.sourceIndex)
            {
                titleTemplateText = WriteStartTag(currElement, null) + titleTemplateText + WriteEndTag(currElement);

                currElement2 = (IHTMLElement2)currElement;
                string styleFloat = currElement2.currentStyle.styleFloat;
                if (!String.IsNullOrEmpty(styleFloat) && !String.IsNullOrEmpty((string)currElement2.currentStyle.width))
                {
                    if (String.Compare(styleFloat, "LEFT", StringComparison.OrdinalIgnoreCase) == 0 ||
                        String.Compare(styleFloat, "RIGHT", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        preserveClear = true;
                    }
                }

                currElement = currElement.parentElement;
            }

            string bodyTemplateText = BlogEditingTemplate.POST_BODY_MARKER;

            currElement = bodyElement;

            MarkupRange currElementRange = markupServices.CreateMarkupRange();
            while (currElement != null && currElement.sourceIndex != stopElement.sourceIndex)
            {
                // Then we need to look for and preserve siblings with "clear" attribute...
                IHTMLElement parentElement = currElement.parentElement;
                if (preserveClear && parentElement != null)
                {
                    IHTMLElementCollection siblings = (IHTMLElementCollection)parentElement.children;
                    foreach (IHTMLElement sibling in siblings)
                    {
                        if (sibling.sourceIndex == currElement.sourceIndex)
                            continue;

                        siblingPointer.MoveAdjacentToElement(sibling, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);

                        // Does this sibling end before the current element starts?
                        currElementRange.MoveToElement(currElement, true);
                        if (siblingPointer.IsLeftOfOrEqualTo(currElementRange.Start))
                        {
                            IHTMLElement2 sibling2 = (IHTMLElement2)sibling;
                            string styleClear = sibling2.currentStyle.clear;
                            if (!String.IsNullOrEmpty(styleClear) && String.Compare(styleClear, "NONE", StringComparison.OrdinalIgnoreCase) != 0)
                            {
                                // Then preserve the clear...
                                titleTemplateText = titleTemplateText +
                                                    WriteStartTag(sibling, String.Format(@"clear: {0}", styleClear)) +
                                                    WriteEndTag(sibling);
                            }
                        }
                    }
                }

                bodyTemplateText = WriteStartTag(currElement, null) + bodyTemplateText + WriteEndTag(currElement);
                currElement = currElement.parentElement;
            }

            string templateHtml = titleTemplateText + bodyTemplateText;
            currElement = range.ParentElement();
            while (currElement != null)
            {
                if (currElement.tagName == "HTML")
                {
                    MarkupPointer bodyPointer = markupServices.CreateMarkupPointer(((IHTMLDocument2)doc).body, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
                    MarkupPointer docPointer = markupServices.CreateMarkupPointer(currElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
                    MarkupRange headRange = markupServices.CreateMarkupRange(docPointer, bodyPointer);
                    IHTMLElement[] elements = headRange.GetTopLevelElements(new IHTMLElementFilter(IsHeadElement));
                    if (elements.Length > 0)
                    {
                        string head = elements[0].innerHTML;
                        //string defaultStyles = "<style>p, h1, h2, h3, h4, h5, h6, blockquote, pre{ padding-top: 1px; }</style>";
                        head = String.Format(CultureInfo.InvariantCulture, "<head>{0}</head>", head);
                        templateHtml = head + templateHtml;
                    }
                }
                templateHtml = WriteStartTag(currElement, null) + templateHtml + WriteEndTag(currElement);
                currElement = currElement.parentElement;
            }

            //prepend the doctype of the document - this prevents styles in the document from rendering improperly
            string docType = HTMLDocumentHelper.GetSpecialHeaders((IHTMLDocument2)doc).DocType;
            //string docType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"[]>";
            if (docType != null)
                templateHtml = docType + "\r\n" + templateHtml;

            return new BlogEditingTemplate(templateHtml);
        }
Exemple #44
0
		/// <summary>
		/// This constructor will mainly be used by the constructor of FrameCollection
		/// to create an instance of a Frame.
		/// </summary>
		/// <param name="domContainer">The domContainer.</param>
		/// <param name="htmlDocument">The HTML document.</param>
		/// <param name="frameSetParent">The frame set parent.</param>
		/// <param name="frameElementUniqueId">The frame element unique id.</param>
		public Frame(DomContainer domContainer, IHTMLDocument2 htmlDocument, IHTMLDocument3 frameSetParent, string frameElementUniqueId) : base(domContainer, htmlDocument)
		{
			_frameSetParent = frameSetParent;
			_frameElementUniqueId = frameElementUniqueId;
		}
        /// <summary>
        /// Extracts all the HTML code before and after the "body" tag of the pattern HTML page
        /// and saves if on textBeforeBody and textAfterBody members.
        /// This function MUST to be called before start to make calls to ProcessHeadTag.
        /// </summary>
        /// <param name="originalSourcePage">The HTML pattern page to extract the code</param>
        public void PrepareHtmlPattern(IHTMLDocument3 originalSourcePage)
        {
            // Get the encoding of the pattern page:
            try
            {
                inputEncoding = Encoding.GetEncoding(((IHTMLDocument2)originalSourcePage).charset);
            }
            catch
            {
                inputEncoding = null;
            }

            bool beforeBody = true; // Are we currently before or after the "body" node?

            // Traverse the root nodes of the HTML page:
            IHTMLDOMChildrenCollection col = (IHTMLDOMChildrenCollection)originalSourcePage.childNodes;
            foreach (IHTMLElement e in col)
            {
                if (e is IHTMLCommentElement)
                {
                    // head tag and other stuff.
                    IHTMLCommentElement com = (IHTMLCommentElement)e;
                    if (beforeBody)
                        textBeforeBody += com.text + "\n";
                    else
                        textAfterBody += com.text + "\n";
                }
                else if (e is IHTMLHtmlElement)
                {
                    // Copy the <html> tag (TODO: check if clone() can be used here to make the copy)
                    textBeforeBody += "<html ";
                    IHTMLAttributeCollection atrCol = (IHTMLAttributeCollection)((IHTMLDOMNode)e).attributes;
                    // Get the attributes of the html tag:
                    foreach (IHTMLDOMAttribute atr in atrCol)
                    {
                        if (atr.specified)
                            textBeforeBody += atr.nodeName + "=\"" + atr.nodeValue + "\"";
                    }
                    textBeforeBody += " >\n";

                    // Traverse the <html> children:
                    IHTMLElementCollection htmlChidren = (IHTMLElementCollection)e.children;
                    foreach (IHTMLElement child in htmlChidren)
                    {
                        if (child is IHTMLBodyElement)
                            beforeBody = false;
                        else if (child is IHTMLHeadElement)
                            textBeforeBody += ProcessHeadTag(child);
                        else if (beforeBody)
                            textBeforeBody += child.outerHTML + "\n";
                        else
                            textAfterBody += child.outerHTML + "\n";
                    }

                    // Close the HTML tag:
                    textBeforeBody += "</html>\n";
                }

                // TODO: Other tags should not be added too?
            }
        }
 public void create(TreeNode rt,IHTMLDocument3 doc)
 {
     IHTMLDOMNode rootDomNode = (IHTMLDOMNode)doc.documentElement;
     rt.Tag = rootDomNode;
     inttotlevel = 1;
     InsertDOMNodes(rootDomNode, rt, inttotlevel, 1);
 }
 /// <summary>
 /// The HTML element that bounds the fragment being edited
 /// </summary>
 public static IHTMLElement GetFragmentElement(IHTMLDocument3 document, string fragmentId)
 {
     return document.getElementById(fragmentId);
 }
        /// <summary>
        /// Private helper method for the constructors
        /// </summary>
        /// <param name="document2">IHTMLDocument2</param>
        /// <param name="contentWindow">WindowDetails</param>
        private void Init(IHTMLDocument2 document2, WindowDetails contentWindow)
        {
            this.document2 = document2;
            this.contentWindow = contentWindow;
            this.document3 = document2 as IHTMLDocument3;
            // Check what access method is needed for the document
            IHTMLDocument5 document5 = (IHTMLDocument5)document2;
            //compatibility mode affects how height is computed
            if ((document3.documentElement != null) && (!document5.compatMode.Equals("BackCompat"))) {
                isDTD = true;
            } else {
                isDTD = false;
            }
            Rectangle clientRectangle = contentWindow.WindowRectangle;
            try {
                IHTMLWindow3 window3 = (IHTMLWindow3)document2.parentWindow;
                IHTMLWindow2 window2 = (IHTMLWindow2)document2.parentWindow;
                IHTMLScreen2 screen2 = (IHTMLScreen2)window2.screen;
                IHTMLScreen screen = window2.screen;
                if (parent != null) {
                    // Copy parent values
                    zoomLevelX = parent.zoomLevelX;
                    zoomLevelY = parent.zoomLevelY;
                    viewportRectangle = parent.viewportRectangle;
                } else {
                    //DisableScrollbars(document2);

                    // Calculate zoom level
                    zoomLevelX = (double)screen2.deviceXDPI/(double)screen2.logicalXDPI;
                    zoomLevelY = (double)screen2.deviceYDPI/(double)screen2.logicalYDPI;

                    // Calculate the viewport rectangle, needed if there is a frame around the html window
                    LOG.DebugFormat("Screen {0}x{1}", ScaleX(screen.width), ScaleY(screen.height));
                    LOG.DebugFormat("Screen location {0},{1}", window3.screenLeft, window3.screenTop);
                    LOG.DebugFormat("Window rectangle {0}", clientRectangle);
                    LOG.DebugFormat("Client size {0}x{1}", ClientWidth, ClientHeight);
                    int diffX = clientRectangle.Width - ClientWidth;
                    int diffY = clientRectangle.Height - ClientHeight;
                    // If there is a border around the inner window, the diff == 4
                    // If there is a border AND a scrollbar the diff == 20
                    if ((diffX == 4 || diffX >= 20) && (diffY == 4 || diffY >= 20)) {
                        Point viewportOffset = new Point(2, 2);
                        Size viewportSize = new Size(ClientWidth, ClientHeight);
                        viewportRectangle = new Rectangle(viewportOffset, viewportSize);
                        LOG.DebugFormat("viewportRect {0}", viewportRectangle);
                    }
                }
                LOG.DebugFormat("Zoomlevel {0}, {1}", zoomLevelX, zoomLevelY);

            } catch (Exception e) {
                LOG.Warn("Can't get certain properties for documents, using default.  due to: ", e);

            }

            LOG.DebugFormat("Calculated location {0} for {1}", startLocation, document2.title);
            sourceLocation = new Point(ScaleX((int)startLocation.X), ScaleY((int)startLocation.Y));
            destinationLocation = new Point(ScaleX((int)startLocation.X), ScaleY((int)startLocation.Y));

            try {
                if (name == null) {
                    name = document2.title;
                }
            } catch {
            }
            try {
                url = document2.url;
            } catch {
            }

            if (parent != null) {
                return;
            }
            IHTMLFramesCollection2 frameCollection = (IHTMLFramesCollection2)document2.frames;
            for(int frame = 0; frame < frameCollection.length; frame++) {
                IHTMLWindow2 frameWindow = frameCollection.item(frame);
                try {
                    DocumentContainer frameData = new DocumentContainer(frameWindow, contentWindow, this);
                    // check if frame is hidden
                    if (!frameData.isHidden) {
                        LOG.DebugFormat("Creating DocumentContainer for Frame {0} found in window with rectangle {1}", frameData.name, frameData.SourceRectangle);
                        frames.Add(frameData);
                    } else {
                        LOG.DebugFormat("Skipping frame {0}", frameData.Name);
                    }
                } catch (Exception e) {
                    LOG.Warn("Problem while trying to get information from a frame, skipping the frame!", e);
                }
            }
            // Correct iframe locations
            foreach (IHTMLElement frameElement in document3.getElementsByTagName("IFRAME")){
                try {
                    CorrectFrameLocations(frameElement);
                } catch (Exception e) {
                    LOG.Warn("Problem while trying to get information from an iframe, skipping the frame!", e);
                }
            }
        }
Exemple #49
0
        private string GetJavascriptResult(IHTMLDocument3 document)
        {
            try
            {
                var resultElement = document.getElementById("testrResult");
                var result = resultElement.getAttribute("value");

                //LogManager.Write("Response: " + result, LogLevel.Verbose);
                return result ?? string.Empty;
            }
            catch
            {
                // The document may have been redirected which means the member will not be there.
                return string.Empty;
            }
        }
        /// <summary>
        /// Generates an editing template the almost perfectly matches the existing website (include sidebars, titles, etc).
        /// </summary>
        protected internal override BlogEditingTemplate GenerateBlogTemplate(IHTMLDocument3 doc, IHTMLElement titleElement, IHTMLElement[] allTitleElements, IHTMLElement bodyElement)
        {
            // if title is containing with a link then strip the link
            CleanupContainingAnchorTag(titleElement);

            // Remove <noscript> and <noembed> tags from the preview.
            RemoveNoShowElements((IHTMLDocument2)doc);

            //create read-only placeholder for document elements that contain the post title text
            //(including archive and recently posted links). Fixes bug 297877.
            SetDefaultTitleText(BlogEditingTemplate.POST_TITLE_READONLY_MARKER, allTitleElements);

            //update primary titleElement to contain the editable title marker.
            string titleTemplateText = BlogEditingTemplate.POST_TITLE_MARKER;
            titleElement.innerText = titleTemplateText;

            //if the title exists inside the body (which is about to be reset with the body marker),
            //preserve its parent tree so it doesn't get deleted
            IHTMLDOMNode preservedTitleNodes = MaybePreserveTitleTree(titleElement, bodyElement) as IHTMLDOMNode;

            //update the bodyElement to contain the editable body marker.
            string bodyTemplateText = BlogEditingTemplate.POST_BODY_MARKER;
            bodyElement.innerText = bodyTemplateText;

            //if the title parents where preserved, prepend them back into the bodyElement
            if (preservedTitleNodes != null)
            {
                IHTMLDOMNode bodyNode = (IHTMLDOMNode)bodyElement;
                IHTMLDOMNode firstNode = bodyNode.firstChild;
                if (firstNode == null)
                    bodyNode.appendChild(preservedTitleNodes);
                else
                    bodyNode.insertBefore(preservedTitleNodes, firstNode);
            }

            string templateHtml = HTMLDocumentHelper.HTMLDocToString((IHTMLDocument2)doc);
            if (templateHtml == null || templateHtml.IndexOf(BlogEditingTemplate.POST_TITLE_MARKER, StringComparison.OrdinalIgnoreCase) == -1 ||
                templateHtml.IndexOf(BlogEditingTemplate.POST_BODY_MARKER, StringComparison.OrdinalIgnoreCase) == -1)
            {
                Debug.Fail("Failed to insert blog post editing markers");
                throw new Exception("Error inserting template markers");
            }

            //prepend the doctype of the document - this prevents styles in the document from rendering improperly
            string docType = HTMLDocumentHelper.GetSpecialHeaders((IHTMLDocument2)doc).DocType;
            if (docType != null)
                templateHtml = docType + "\r\n" + templateHtml;

            return new BlogEditingTemplate(templateHtml);
        }
        protected internal override BlogEditingTemplate GenerateBlogTemplate(IHTMLDocument3 doc, IHTMLElement titleElement, IHTMLElement[] allTitleElements, IHTMLElement bodyElement)
        {
            CleanupContainingAnchorTag(titleElement);
            StyleBuilder styleBuilder = new StyleBuilder();
            string templateHtml;
            using (styleBuilder)
            {
                string titleTemplateText = WrapInStyledDiv(postTitleClass, BlogEditingTemplate.POST_TITLE_MARKER);
                AddTitleStyles(titleElement, styleBuilder);

                string bodyTemplateText = WrapInStyledDiv(postBodyClass, BlogEditingTemplate.POST_BODY_MARKER);
                AddBodyStyles(bodyElement, styleBuilder);

                templateHtml = titleTemplateText + bodyTemplateText;
            }

            string headHtml = String.Format(CultureInfo.InvariantCulture, "<head><style>{0}</style></head>", styleBuilder.ToString());
            templateHtml = String.Format(CultureInfo.InvariantCulture, "<html>{0}<body>{1}</body></html>", headHtml, templateHtml);

            //prepend the doctype of the document - this prevents styles in the document from rendering improperly
            string docType = HTMLDocumentHelper.GetSpecialHeaders((IHTMLDocument2)doc).DocType;
            if (docType != null)
                templateHtml = docType + "\r\n" + templateHtml;

            return new BlogEditingTemplate(templateHtml);
        }
        public virtual void Visit(IHTMLDocument3 document)
        {
            if (Application.MessageLoop)
                Application.DoEvents();

            //			while (((IHTMLDocument2)document).readyState != "interactive")
            //			{
            //				Application.DoEvents();
            //				Thread.Sleep(50);
            //			}

            //Trace.WriteLine("Begin visit: " + ((IHTMLDocument2)document).readyState + "\r\n" + document.documentElement.innerHTML);

            Stack stack = new Stack();
            stack.Push(new StackItem(document.documentElement));

            while (stack.Count > 0)
            {
                StackItem stackItem = (StackItem)stack.Pop();

                if (stackItem.element == null)
                    continue;
                else if (stackItem.element is IHTMLTextElement)
                    OnText((IHTMLTextElement)stackItem.element);
                else if (stackItem.element is IHTMLCommentElement)
                    OnComment((IHTMLCommentElement)stackItem.element);
                else if (stackItem.element is IHTMLElement)
                {
                    IHTMLElement el = (IHTMLElement)stackItem.element;

                    if (stackItem.begin)
                    {
                        if (!OnElementBegin(el))
                        {
                            //							Trace.WriteLine(Indent + "<" + el + "/> (skipping)");
                            continue;
                        }

                        //						Trace.WriteLine(Indent + "<" + el + "> (children: " + ((IHTMLElementCollection)el.children).length);
                        IncreaseIndent();

                        stackItem.begin = false;
                        // return item to the stack, so we can call OnElementEnd on the way out
                        stack.Push(stackItem);

                        // DO NOT iterate over the DOM this way.  We miss a lot of nodes in Release mode.
                        //						IHTMLElementCollection children = (IHTMLElementCollection)el.children;
                        //						StackItem[] items = new StackItem[children.length];
                        //						int i = 0;
                        //						foreach (IHTMLElement child in children)
                        //							items[i++] = new StackItem(child);
                        //						Array.Reverse(items);

                        ArrayList items = new ArrayList();
                        for (IHTMLDOMNode child = ((IHTMLDOMNode)el).firstChild; child != null; child = child.nextSibling)
                        {
                            IHTMLElement childElement = child as IHTMLElement;
                            if (childElement != null)
                                items.Add(new StackItem(childElement));
                        }
                        items.Reverse();

                        foreach (StackItem si in items)
                            stack.Push(si);
                    }
                    else
                    {
                        DecreaseIndent();
                        //						Trace.WriteLine(Indent + "</" + el.tagName + ">");
                        OnElementEnd(el);
                    }
                }
            }

            //Trace.WriteLine("End visit");
        }
 public ExtendedEntrySweeper(IHtmlEditorComponentContext editorContext, IHTMLDocument3 document, IHTMLElement extendedEntry)
 {
     _editorContext = editorContext;
     _realExtendedEntry = extendedEntry;
     _document = document;
 }
Exemple #54
0
 private IHTMLElement GetElementByName(IHTMLDocument3 doc, string name)
 {
     IHTMLElementCollection elements = doc.getElementsByName(name);
     foreach (IHTMLElement element in elements)
         return element;
     return null;
 }