/// <summary>
        /// This is for unit tests only.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        internal string ReadGeckoMIMEInputStreamAsUTF8(MimeInputStream stream)
        {
            byte[] buffer = new byte[2048];
            var    count  = stream.Read(buffer, 0, 2048);

            return(System.Text.UTF8Encoding.UTF8.GetString(buffer).Trim());
        }
Beispiel #2
0
        private static void ShowInForm(Size size, string url, string postQuery)
        {
            using (var frm = FormFactory.GetForm(size))
            {
                if (!Xpcom.IsInitialized)
                {
                    Xpcom.Initialize("Firefox");
                }

                using (var wb = new GeckoWebBrowser())
                {
                    frm.ShowIcon        = false;
                    frm.FormBorderStyle = FormBorderStyle.FixedToolWindow;
                    frm.StartPosition   = FormStartPosition.CenterParent;
                    frm.Controls.Add(wb);

                    wb.Dock = DockStyle.Fill;
                    var postData = MimeInputStream.Create();
                    postData.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                    postData.AddContentLength = true;
                    postData.SetData(postQuery);

                    wb.Navigate(url, GeckoLoadFlags.BypassCache, "", postData);

                    frm.FormBorderStyle = FormBorderStyle.Sizable;
                    frm.ShowDialog();
                }
            }
        }
Beispiel #3
0
        public void AddContentLength_ToTrue_HeaderContainsContentLength()
        {
            MimeInputStream stream = MimeInputStream.Create();

            stream.AddContentLength = true;

            Assert.IsTrue(ReadGeckoMIMEInputStreamAsUTF8(stream).Contains("Content-Length"));
        }
        public void SetData_SimpleData_HeaderContainsSimpleData()
        {
            MimeInputStream stream     = MimeInputStream.Create();
            string          simpleData = "id=hello";

            stream.SetData(simpleData);

            Assert.IsTrue(ReadGeckoMIMEInputStreamAsUTF8(stream).Contains(simpleData));
        }
Beispiel #5
0
        public void AddHeader_AddValidHeaderEntry_HeaderContainsHeaderEntry()
        {
            MimeInputStream stream = MimeInputStream.Create();

            stream.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            string header = ReadGeckoMIMEInputStreamAsUTF8(stream);

            Assert.IsTrue(header.Contains("Content-Type"));
            Assert.IsTrue(header.Contains("application/x-www-form-urlencoded"));
        }
Beispiel #6
0
        //
        // Summary:
        //     Loads the document at the specified Uniform Resource Locator (URL) into the
        //     System.Windows.Forms.WebBrowser control, replacing the previous document.
        //
        // Parameters:
        //   urlString:
        //     The URL of the document to load.
        //
        // Exceptions:
        //   System.ObjectDisposedException:
        //     This System.Windows.Forms.WebBrowser instance is no longer valid.
        //
        //   System.InvalidOperationException:
        //     A reference to an implementation of the IWebBrowser2 interface could not
        //     be retrieved from the underlying ActiveX WebBrowser control.
        public void Navigate(string urlString)
        {
            this.SetIsLoading(true);

            urlString = ParseValue(urlString);

            if (!string.IsNullOrEmpty(urlString))
            {
                this.urlTextBox.Text = urlString;
            }

            if (string.IsNullOrEmpty(this.homeUrl))
            {
                this.homeUrl = this.urlTextBox.Text;
            }

            string url = this.urlTextBox.Text;

            if (this.browserType == BrowserType.InternetExplorer)
            {
                if (this.BrowserCredential.Authentication == BrowserAuthentication.Basic)
                {
                    Uri uri = new Uri(url);

                    string authHdr = "Authorization: Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(this.browserCredential.UserName + ":" + this.browserCredential.Password)) + "\r\n";

                    this.internetExplorer.Navigate(uri, null, null, authHdr);
                }
                else
                {
                    this.internetExplorer.Navigate(url);
                }
            }
#if GECKO
            else if (this.browserType == BrowserType.Firefox)
            {
                MimeInputStream headers = null;

                if (this.BrowserCredential.Authentication == BrowserAuthentication.Basic)
                {
                    UriBuilder uriSite = new UriBuilder(url);
                    uriSite.UserName = BrowserCredential.UserName;
                    uriSite.Password = BrowserCredential.Password;
                    this.firefox.Navigate(uriSite.Uri.ToString(), GeckoLoadFlags.BypassCache, null, null, null);
                    return;
                }

                this.firefox.Navigate(url, GeckoLoadFlags.BypassCache, null, null, headers);
            }
#endif
        }
Beispiel #7
0
        /// <summary>
        ///  Navigates to the specified URL using the given load flags, referrer and post data
        ///  In order to find out when Navigate has finished attach a handler to NavigateFinishedNotifier.NavigateFinished.
        /// </summary>
        /// <param name="url">The url to navigate to.  If the url is empty or null, the browser does not navigate and the method returns false.</param>
        /// <param name="loadFlags">Flags which specify how the page is loaded.</param>
        /// <param name="referrer">The referring URL, or null.</param>
        /// <param name="postData">post data and headers, or null</param>
        /// <param name="headers">headers, or null</param>
        /// <returns>true if Navigate started. false otherwise.</returns>
        public bool Navigate(string url, GeckoLoadFlags loadFlags, string referrer, MimeInputStream postData, MimeInputStream headers)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(false);
            }

            // added these from http://code.google.com/p/geckofx/issues/detail?id=5 so that it will work even if browser isn't currently shown
            //if (!IsHandleCreated) CreateHandle();
            //if (IsBusy) this.Stop();


            //	if (!IsHandleCreated)
            //		throw new InvalidOperationException("Cannot call Navigate() before the window handle is created.");

            // WebNav.LoadURI throws an exception if we try to open a file that doesn't exist...
            Uri created;

            if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out created) && created.IsAbsoluteUri && created.IsFile)
            {
                if (!File.Exists(created.LocalPath) && !Directory.Exists(created.LocalPath))
                {
                    return(false);
                }
            }

            nsIURI referrerUri = null;

            if (!string.IsNullOrEmpty(referrer))
            {
                //referrerUri = Xpcom.GetService<nsIIOService>("@mozilla.org/network/io-service;1").NewURI(new nsAUTF8String(referrer), null, null);
                referrerUri = IOService.CreateNsIUri(referrer);
            }


            _webNav.LoadURI(url, (uint)loadFlags, referrerUri, postData != null ? postData._inputStream : null, headers != null ? headers._inputStream : null);

            return(true);
        }
Beispiel #8
0
 /// <summary>
 ///  Navigates to the specified URL using the given load flags, referrer and post data
 ///  In order to find out when Navigate has finished attach a handler to NavigateFinishedNotifier.NavigateFinished.
 /// </summary>
 /// <param name="url">The url to navigate to.  If the url is empty or null, the browser does not navigate and the method returns false.</param>
 /// <param name="loadFlags">Flags which specify how the page is loaded.</param>
 /// <param name="referrer">The referring URL, or null.</param>
 /// <param name="postData">post data and headers, or null</param>
 /// <returns>true if Navigate started. false otherwise.</returns>
 public bool Navigate(string url, GeckoLoadFlags loadFlags, string referrer, MimeInputStream postData)
 {
     return(Navigate(url, loadFlags, referrer, postData, null));
 }
Beispiel #9
0
        private byte[] ConvertToPdf(string url, string html, string tempFilePath, NameValueCollection headers = null, IEnumerable <GeckoCookie> cookies = null)
        {
            // Initialize gecko engine
            if (!HeadlessGecko.IsInitialized)
            {
                var initSignal = new SemaphoreSlim(0, 1);
                HeadlessGecko.OnInitialized += () =>
                {
                    initSignal.Release();
                };

                HeadlessGecko.Initialize(GeckoBinDirectory);
                initSignal.Wait();
            }

            var printReadySignal = new SemaphoreSlim(0, 1);

            var browser = HeadlessGecko.CreateBrowser();

            browser.DocumentCompleted += (s, e) =>
            {
                // After loading document, waits some time, and send print ready signal
                Task.Run(() =>
                {
                    Thread.Sleep(1000); // Some delay need, otherwise throws COMException
                    printReadySignal.Release();
                });
            };


            // Invoke navigate method in STA browser thread
            browser.Invoke((MethodInvoker) delegate
            {
                Uri uri          = null;
                var isUriSuccess = Uri.TryCreate(url, UriKind.Absolute, out uri);

                if (isUriSuccess && cookies != null)
                {
                    foreach (var cookie in cookies)
                    {
                        CookieManager.Add(uri.Host, cookie.Path, cookie.Name, cookie.Value, cookie.Secure, cookie.HttpOnly, false, cookie.ExpiresUnix);
                    }
                }
                var geckoHeaders = MimeInputStream.Create();
                if (headers != null)
                {
                    var headersItems = headers.AllKeys.SelectMany(headers.GetValues, (k, v) => new { Key = k, Value = v });
                    foreach (var header in headersItems)
                    {
                        geckoHeaders.AddHeader(header.Key, header.Value);
                    }
                    return;
                }
                else
                {
                    geckoHeaders.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0");
                    geckoHeaders.AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    geckoHeaders.AddHeader("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3");
                    geckoHeaders.AddHeader("Accept-Encoding", "gzip, deflate, br");
                    geckoHeaders.AddHeader("X-Compress", "1");
                    geckoHeaders.AddHeader("Connection", "keep-alive");
                }

                if (string.IsNullOrEmpty(html))
                {
                    browser.Navigate(url, GeckoLoadFlags.None, url, null, geckoHeaders);
                }
                else
                {
                    browser.LoadHtml(html, url);
                }
            });

            printReadySignal.Wait(); // Waiting before print will completed
            //browser.NavigateFinishedNotifier.BlockUntilNavigationFinished();

            // Create temporary file and print page to him
            if (string.IsNullOrEmpty(tempFilePath))
            {
                tempFilePath = Path.GetTempFileName();
            }

            var fi = new FileInfo(tempFilePath);

            if (!fi.Exists)
            {
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
                File.Create(tempFilePath).Close();
            }

            browser.Invoke((MethodInvoker) delegate
            {
                browser.PrintToFile(_config, tempFilePath);
            });

            var attempts = 0;

            while (Tools.IsFileLocked(tempFilePath) || attempts >= _config.MaxLockingCheckAttempts)
            {
                attempts++;
                Thread.Sleep(_config.PdfLockingCheckDelay);
            }

            if (attempts >= _config.MaxLockingCheckAttempts)
            {
                throw new IOException("Generated pdf file locked too long");
            }

            // Read temporary file to MemoryStream and delete
            var bytes = File.ReadAllBytes(tempFilePath);

            File.Delete(tempFilePath);

            browser.Invoke((MethodInvoker) delegate
            {
                browser.Dispose();
            });

            return(bytes);
        }