private void waitForBrowserRec(HTMLDocument nextDoc, DialogWatcher dialogWatcher)
 {
     try
     {
         int timeOut = DefaultTimeouts.WaitForBrowserTimeout;
         DateTime start = DateTime.Now;
         while (((!_attachedToModalDialog && currentIEBrowser.Busy) || (currentIEBrowser.ReadyState != tagREADYSTATE.READYSTATE_COMPLETE || !getDocumentReadyState(nextDoc).Equals("complete", StringComparison.OrdinalIgnoreCase)) && (currentIEBrowser.ReadyState != tagREADYSTATE.READYSTATE_INTERACTIVE)) && DateTime.Now < start.AddSeconds(timeOut))
         {
             if (dialogWatcher.FoundDialog) return;
         }
         for (int i = 0; i < nextDoc.frames.length; i++)
         {
             object index = i;
             IHTMLDocument2 _docBypassSecurity = CrossFrameIE.GetDocumentFromWindow((IHTMLWindow2)nextDoc.frames.item(ref index));
             HTMLDocument _docFullAccess = (HTMLDocument)_docBypassSecurity;
             waitForBrowserRec(_docFullAccess, dialogWatcher);
         }
     }
     catch (Exception e)
     {
         HandleWaitForBrowserException(e);
     }
 }
 private void waitForBrowserReadyOnly()
 {
     using (DialogWatcher dialogWatcher = new DialogWatcher(this))
     {
         try
         {
             int timeOut = SWAT.DefaultTimeouts.WaitForBrowserTimeout;
             DateTime startTime = DateTime.Now;
             while ((currentIEBrowser.ReadyState != tagREADYSTATE.READYSTATE_COMPLETE || !getDocumentReadyState(_doc).Equals("complete", StringComparison.OrdinalIgnoreCase)) && DateTime.Now < startTime.AddSeconds(timeOut))
             {
                 if (dialogWatcher.FoundDialog)
                 {
                     break;
                 }
             }
         }
         catch (Exception e) // COMException || InvalidCastException
         {
             HandleWaitForBrowserException(e);
         }
     }
 }
 private void waitForBrowser()
 {
     using (DialogWatcher dialogWatcher = new DialogWatcher(this))
     {
         waitForBrowserRec(_doc, dialogWatcher);
     }
 }
        private void WaitForProcessesToEnd()
        {
            lastBrowserWindowAction = LastBrowserWindowAction.Killed;
            using (DialogWatcher dialogWatcher = new DialogWatcher(this))
            {
                int count = 30;
                while ((Process.GetProcessesByName(BrowserProcess.iexplore.ToString()).Length > 0) && (count > 0))
                {
                    if (dialogWatcher.FoundDialog)
                    {
                        return;
                    }
                    System.Threading.Thread.Sleep(250);
                    count--;
                }
            }
            lastBrowserWindowAction = LastBrowserWindowAction.InUse;

            if (!isBrowserValid())
            {
                curWindowHandle = IntPtr.Zero;
            }
        }
        public void NavigateBrowser(string url)
        {
            navigateTo(url);

            using (DialogWatcher dialogWatcher = new DialogWatcher(this))
            {
                while (currentIEBrowser.ReadyState != tagREADYSTATE.READYSTATE_COMPLETE)
                {
                    if (dialogWatcher.FoundDialog)
                    {
                        break;
                    }
                }

                updateDoc();
                curWindowHandle = new IntPtr(currentIEBrowser.HWND);
            }
        }
 private void WaitForWindowToRefresh()
 {
     WriteToConsole("Waiting for browser window to finish refreshing...");
     lastBrowserWindowAction = LastBrowserWindowAction.Refreshed;
     using (DialogWatcher dialogWatcher = new DialogWatcher(this))
     {
         WaitForBrowserReadyState();
         if (dialogWatcher.FoundDialog)
         {
             return;
         }
     }
     lastBrowserWindowAction = LastBrowserWindowAction.InUse;
 }
        private void WaitForWindowToClose(IntPtr closingWindowHandle)
        {
            lastBrowserWindowAction = LastBrowserWindowAction.Closed;
            using (DialogWatcher dialogWatcher = new DialogWatcher(this))
            {
                bool windowStillOpen = true;
                while (windowStillOpen)
                {
                    if (dialogWatcher.FoundDialog)
                    {
                        return;
                    }

                    windowStillOpen = NativeMethods.IsWindow(closingWindowHandle);

                    if (!windowStillOpen)
                        break;
                }
            }

            lastBrowserWindowAction = LastBrowserWindowAction.InUse;

            if (!isBrowserValid())
            {
                curWindowHandle = IntPtr.Zero;
                _doc = null;
            }
        }
        private void WaitForProcessesToEnd(bool killingProcess)
        {
            lastBrowserWindowAction = LastBrowserWindowAction.Killed;
            using (DialogWatcher dialogWatcher = new DialogWatcher(this))
            {
                WriteToConsole("Waiting for the Firefox process to completely close...");

                DateTime timeout = DateTime.Now.AddSeconds(7.5);
                while ((Process.GetProcessesByName("firefox").Length > 0) && DateTime.Now < timeout)
                {
                    if (dialogWatcher.FoundDialog && !killingProcess)
                        return;
                    Thread.Sleep(1);
                }
            }
            lastBrowserWindowAction = LastBrowserWindowAction.InUse;

            if (Process.GetProcessesByName("firefox").Length == 0)
            {
                ClearAttachedWindowVariables();
            }
            Thread.Sleep(500); // needed to prevent firefox from showing popup when reopening
        }
        private void WaitForWindowToClose()
        {
            lastBrowserWindowAction = LastBrowserWindowAction.Closed;
            using (DialogWatcher dialogWatcher = new DialogWatcher(this))
            {
                WriteToConsole("Waiting for browser window to finish closing...");
                DateTime timeout = DateTime.Now.AddSeconds(30);
                try
                {
                    //if the browser closes check and make sure that the processId does not exist anymore or has Exited need this in a try catch because it throws an exception once the process has terminated
                    while (NativeMethods.IsWindow(curWindowHandle) && DateTime.Now < timeout)
                    {
                        if (dialogWatcher.FoundDialog)
                        {
                            return;
                        }
                        Thread.Sleep(0); //! 250               
                    }
                }
                catch
                {
                }

                if (NativeMethods.GetNumberOfWindowsWithSubString("- Mozilla Firefox") == 0)
                {
                    while (Process.GetProcessesByName("firefox").Length > 0)
                    {
                        Thread.Sleep(0); //! 1000
                    }
                }
            }
            lastBrowserWindowAction = LastBrowserWindowAction.InUse;

            if (Process.GetProcessesByName("firefox").Length == 0)
            {
                ClearAttachedWindowVariables();
            }

            Thread.Sleep(500); // needed to prevent firefox from showing popup when reopening
        }
        public void WaitForBrowserReadyState()
        {
            using (DialogWatcher dialogWatcher = new DialogWatcher(this))
            {
                StringBuilder msg = new StringBuilder();
                msg.Append("var done = true;");
                msg.Append("for (var i = 0; i < firefoxWindow.frames.length && done; i++)");
                msg.Append("{ if (firefoxWindow.frames[i].document.readyState != 'complete') {");
                msg.Append("done = false; } }");
                msg.Append("done = done && browser.webProgress.busyFlags == 0;");
                msg.Append("print(done);");

                DateTime end = DateTime.Now.AddSeconds(DefaultTimeouts.WaitForBrowserTimeout);
                while (DateTime.Now < end)
                {
                    if (dialogWatcher.FoundDialog)
                        return;
                    using (JSSHConnection jssh = GetExtensionConnection(false))
                    {
                        string dialogOpenResult = jssh.SendMessage("print(document.activeElement.label);", true, false);
                        bool dialogIsOpen = dialogOpenResult.Contains("OK") || dialogOpenResult.Contains("Cancel");
                        if (dialogIsOpen)
                            return;
                    }
                    using (JSSHConnection jssh = GetExtensionConnection(true))
                    {
                        string result = jssh.SendMessage(msg.ToString());
                        string title = jssh.SendMessage("print(firefoxWindow.document.title);");
                        if (result == "true" || title.Contains("Problem loading page") ||
                            title.Contains("(application/pdf Object)") || !IsSuccessfulResult(result))
                            break;
                    }
                    Thread.Sleep(0);
                }
            }
        }
        private void WaitForRemainingWindowsToClose()
        {
            lastBrowserWindowAction = LastBrowserWindowAction.KilledExceptTitle;

            string waitForWindowsToCloseCommandString =
                GetWaitForWindowsToCloseCommandString(previousLowerCaseWindowTitleToKeepOpen);
            using (DialogWatcher dialogWatcher = new DialogWatcher(this))
            {
                DateTime timeout = DateTime.Now.AddSeconds(5);
                while (DateTime.Now < timeout)
                {
                    string result;
                    using (JSSHConnection jssh = GetExtensionConnection(true))
                        result = jssh.SendMessage(waitForWindowsToCloseCommandString);

                    if (!result.Contains("windowExists"))
                    {
                        break;
                    }

                    if (dialogWatcher.FoundDialog)
                    {
                        return;
                    }
                    Thread.Sleep(0);
                }
            }

            lastBrowserWindowAction = LastBrowserWindowAction.InUse;

            if (!IsBrowserAttached())
            {
                ClearAttachedWindowVariables();
            }
        }
        public ChromeResponse HandleResponse(ChromeCommand command, bool printConsoleMessages)
        {
            // Wait for a POST request to be pending from the Chrome extension.
            // Note that we need to leave the packet in the queue for the next
            // send message.

            DateTime timeout = DateTime.Now.AddSeconds(PacketTimeoutSeconds);
            browser.DialogInterrupted = false;

            using (DialogWatcher watcher = new DialogWatcher(browser))
            {
                while (DateTime.Now < timeout)
                {
                    lock (responseLock)
                    {
                        if (watcher.FoundDialog)
                        {
                            browser.DialogInterrupted = true;
                            break;
                        }

                        if (receivedResponse)
                            break;
                    }
                }
            }

            ChromeResponse response = new ChromeResponse();

            if (browser.DialogInterrupted)
            {
                response.StatusCode = StatusCode.SUCCESS;
                response.Value = "A JSDialog caused a timeout.";
                return response;
            }

            if (!receivedResponse)
            {
                throw new ChromeCommandTimedOutException(command.Command, PacketTimeoutSeconds);
            }

            // ExtensionRequestPacket packet = pendingRequestQueue.Peek();
            // If the page cannot be found, this gets index out of bounds
            ExtensionRequestPacket packet = pendingRequestQueue[0];

            // Parse the packet content, and deserialize from a JSON object.
            string responseString = ParseResponse(packet.Content);

            if (!string.IsNullOrEmpty(responseString))
            {
                response = JsonConvert.DeserializeObject<ChromeResponse>(responseString);

                if (response == null)
                    throw new ChromeException("No response was returned by the extension.");

                response.Value = response.Value ?? "";
            }

            string valueAsString = response.Value as string;
            if (valueAsString != null)
            {
                // First, collapse all \r\n pairs to \n, then replace all \n with
                // System.Environment.NewLine. This ensures the consistency of 
                // the values.
                response.Value = valueAsString.Replace("\r\n", "\n").Replace("\n", System.Environment.NewLine);
            }
            //Utilities.WriteToConsole(string.Format("Response was {0}", response.ToString()));

            if (printConsoleMessages)
            {
                Utilities.WriteResponse(response);
            }

            switch (response.StatusCode)
            {
                case StatusCode.BADCOMMAND:
                case StatusCode.BADJAVASCRIPT:
                case StatusCode.CONTENTSCRIPTCONNECTFAIL:
                case StatusCode.CONTENTSCRIPTERROR:
                case StatusCode.ELEMENTNOTVISIBLE:
                case StatusCode.INVALIDELEMENTSTATE:
                case StatusCode.NOSUCHFRAME:
                case StatusCode.STALEELEMENTREFERENCE:
                case StatusCode.UNHANDLEDERROR:
                    throw new ChromeException(response.Value.ToString());
            }

            return response;
        }