private async void button1_Click(object sender, EventArgs e)
        {
            this.button1.Enabled = false;
            try
            {
                WebBrowserExt.SetFeatureBrowserEmulation();     // enable HTML5

                var cts = new CancellationTokenSource((int)TimeSpan.FromMinutes(3).TotalMilliseconds);

                await ScrapSitesAsync(
                    new[] { "http://example.com", "http://example.org", "http://example.net" },
                    cts.Token);

                MessageBox.Show("Completed.");
            }
            catch (Exception ex)
            {
                while (ex is AggregateException && ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                MessageBox.Show(ex.Message);
            }
            this.button1.Enabled = true;
        }
Пример #2
0
        /// <summary>
        /// Wrap the SVG markup in HTML with a meta tag to ensure the
        /// WebBrowser control is in Edge mode to enable SVG rendering.
        /// We also set the padding and margin for the body to zero as
        /// there is a default margin of 8.
        /// </summary>
        /// <param name="content">The content to render.</param>
        /// <param name="cx">The maximum thumbnail size, in pixels.</param>
        /// <returns>A thumbnail of the rendered content.</returns>
        public static Bitmap GetThumbnail(string content, uint cx)
        {
            if (cx > MaxThumbnailSize)
            {
                return(null);
            }

            Bitmap thumbnail = null;

            // Wrap the SVG content in HTML in IE Edge mode so we can ensure
            // we render properly.
            string        wrappedContent = WrapSVGInHTML(content);
            WebBrowserExt browser        = new WebBrowserExt();

            browser.Dock = DockStyle.Fill;
            browser.IsWebBrowserContextMenuEnabled = false;
            browser.ScriptErrorsSuppressed         = true;
            browser.ScrollBarsEnabled = false;
            browser.AllowNavigation   = false;
            browser.Width             = (int)cx;
            browser.Height            = (int)cx;
            browser.DocumentText      = wrappedContent;

            // Wait for the browser to render the content.
            while (browser.IsBusy || browser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }

            // Check size of the rendered SVG.
            var svg = browser.Document.GetElementsByTagName("svg").Cast <HtmlElement>().FirstOrDefault();

            if (svg != null)
            {
                // Update the size of the browser control to fit the SVG
                // in the visible viewport.
                browser.Width  = svg.OffsetRectangle.Width;
                browser.Height = svg.OffsetRectangle.Height;

                // Wait for the browser to render the content.
                while (browser.IsBusy || browser.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }

                // Capture the image of the SVG from the browser.
                thumbnail = GetBrowserContentImage(browser, svg.OffsetRectangle, Color.White);
                if (thumbnail.Width != cx && thumbnail.Height != cx)
                {
                    // We are not the appropriate size for caller.  Resize now while
                    // respecting the aspect ratio.
                    float scale       = Math.Min((float)cx / thumbnail.Width, (float)cx / thumbnail.Height);
                    int   scaleWidth  = (int)(thumbnail.Width * scale);
                    int   scaleHeight = (int)(thumbnail.Height * scale);
                    thumbnail = ResizeImage(thumbnail, scaleWidth, scaleHeight);
                }
            }

            return(thumbnail);
        }
Пример #3
0
        /// <summary>
        /// Start the preview on the Control.
        /// </summary>
        /// <param name="dataSource">Path to the file.</param>
        public override void DoPreview <T>(T dataSource)
        {
            this.InvokeOnControlThread(() =>
            {
                try
                {
                    this.infoBarDisplayed = false;

                    StringBuilder sb       = new StringBuilder();
                    string filePath        = dataSource as string;
                    string fileText        = File.ReadAllText(filePath);
                    this.extension.BaseUrl = Path.GetDirectoryName(filePath);

                    Regex rgx = new Regex(@"<[ ]*img.*>");
                    if (rgx.IsMatch(fileText))
                    {
                        this.infoBarDisplayed = true;
                    }

                    MarkdownPipeline pipeline = this.pipelineBuilder.Build();
                    string parsedMarkdown     = Markdown.ToHtml(fileText, pipeline);
                    sb.AppendFormat("{0}{1}{2}", this.htmlHeader, parsedMarkdown, this.htmlFooter);
                    string markdownHTML = sb.ToString();

                    this.browser = new WebBrowserExt
                    {
                        DocumentText = markdownHTML,
                        Dock         = DockStyle.Fill,
                        IsWebBrowserContextMenuEnabled = false,
                        ScriptErrorsSuppressed         = true,
                        ScrollBarsEnabled = true,
                        AllowNavigation   = false,
                    };
                    this.Controls.Add(this.browser);

                    if (this.infoBarDisplayed)
                    {
                        this.infoBar = this.GetTextBoxControl(Resources.BlockedImageInfoText);
                        this.Controls.Add(this.infoBar);
                    }

                    this.Resize += this.FormResized;
                    base.DoPreview(dataSource);
                    MarkdownTelemetry.Log.MarkdownFilePreviewed();
                }
                catch (Exception e)
                {
                    MarkdownTelemetry.Log.MarkdownFilePreviewError(e.Message);
                    this.infoBarDisplayed = true;
                    this.infoBar          = this.GetTextBoxControl(Resources.MarkdownNotPreviewedError);
                    this.Resize          += this.FormResized;
                    this.Controls.Clear();
                    this.Controls.Add(this.infoBar);
                    base.DoPreview(dataSource);
                }
            });
        }
Пример #4
0
 /// <summary>
 /// Adds a Web Browser Control to Control Collection.
 /// </summary>
 /// <param name="svgData">Svg to display on Browser Control.</param>
 private void AddBrowserControl(string svgData)
 {
     this.browser = new WebBrowserExt();
     this.browser.DocumentText = svgData;
     this.browser.Dock         = DockStyle.Fill;
     this.browser.IsWebBrowserContextMenuEnabled = false;
     this.browser.ScriptErrorsSuppressed         = true;
     this.browser.ScrollBarsEnabled = true;
     this.browser.AllowNavigation   = false;
     this.Controls.Add(this.browser);
 }
Пример #5
0
        /// <summary>
        /// Start the preview on the Control.
        /// </summary>
        /// <param name="dataSource">Path to the file.</param>
        public override void DoPreview <T>(T dataSource)
        {
            this.InvokeOnControlThread(() =>
            {
                try
                {
                    LoadConfig();


                    string filePath = dataSource as string;


                    FileInfo fileInfo = new FileInfo(filePath);


                    string html = "";
                    if (fileInfo.Length > maxFileSize)
                    {
                        html = GenerateBigFileHTML(filePath, fileInfo.Length);
                    }
                    else
                    {
                        html = GenerateHighlightHTML(filePath);
                    }


                    //string html = String.Format("<html><body>{0}, {1}, {2}</body></html>", highLighter, highLighterArgs, filePath);
                    //CodeTelemetry.Info(String.Format("html: %s", html));

                    this.browser = new WebBrowserExt
                    {
                        DocumentText = html,
                        Dock         = DockStyle.Fill,
                        IsWebBrowserContextMenuEnabled = true,
                        ScriptErrorsSuppressed         = true,
                        ScrollBarsEnabled = true,
                        AllowNavigation   = false,
                    };
                    this.Controls.Add(this.browser);
                    base.DoPreview(dataSource);
                }
                catch (Exception e)
                {
                    CodeTelemetry.Info(e.Message);
                    base.DoPreview(dataSource);
                }
            });
        }
Пример #6
0
        public SerferService()
        {
            // CancellationToken cancelToken

            WebBrowserExt.SetFeatureBrowserEmulation();
            _cancelToken = new CancellationToken();

            // create an independent STA thread
            _apartment = new MessageLoopApartment();

            // create a WebBrowser on that STA thread
            _browser = _apartment.Run(() => new WebBrowser(), _cancelToken).Result;

            //// Add a handler for the web browser to auto comlete registration
            //_browser.DocumentCompleted += WebBrowser_DocumentCompleted;
            //// Add a handler for the web browser to capture content change
            //_browser.DocumentTitleChanged += WebBrowser_DocumentTitleChanged;
        }
Пример #7
0
        /// <summary>
        /// Start the preview on the Control.
        /// </summary>
        /// <param name="dataSource">Path to the file.</param>
        public override void DoPreview <T>(T dataSource)
        {
            this.infoBarDisplayed = false;

            try
            {
                if (!(dataSource is string filePath))
                {
                    throw new ArgumentException($"{nameof(dataSource)} for {nameof(MarkdownPreviewHandler)} must be a string but was a '{typeof(T)}'");
                }

                string fileText      = File.ReadAllText(filePath);
                Regex  imageTagRegex = new Regex(@"<[ ]*img.*>");
                if (imageTagRegex.IsMatch(fileText))
                {
                    this.infoBarDisplayed = true;
                }

                this.extension.BaseUrl = Path.GetDirectoryName(filePath);
                MarkdownPipeline pipeline       = this.pipelineBuilder.Build();
                string           parsedMarkdown = Markdown.ToHtml(fileText, pipeline);
                string           markdownHTML   = $"{this.htmlHeader}{parsedMarkdown}{this.htmlFooter}";

                this.InvokeOnControlThread(() =>
                {
                    this.browser = new WebBrowserExt
                    {
                        DocumentText = markdownHTML,
                        Dock         = DockStyle.Fill,
                        IsWebBrowserContextMenuEnabled = false,
                        ScriptErrorsSuppressed         = true,
                        ScrollBarsEnabled = true,
                        AllowNavigation   = false,
                    };
                    this.Controls.Add(this.browser);

                    if (this.infoBarDisplayed)
                    {
                        this.infoBar = this.GetTextBoxControl(Resources.BlockedImageInfoText);
                        this.Resize += this.FormResized;
                        this.Controls.Add(this.infoBar);
                    }
                });

                PowerToysTelemetry.Log.WriteEvent(new MarkdownFilePreviewed());
            }
            catch (Exception e)
            {
                PowerToysTelemetry.Log.WriteEvent(new MarkdownFilePreviewError {
                    Message = e.Message
                });

                this.InvokeOnControlThread(() =>
                {
                    this.Controls.Clear();
                    this.infoBarDisplayed = true;
                    this.infoBar          = this.GetTextBoxControl(Resources.MarkdownNotPreviewedError);
                    this.Resize          += this.FormResized;
                    this.Controls.Add(this.infoBar);
                });
            }
            finally
            {
                base.DoPreview(dataSource);
            }
        }
Пример #8
0
        /// <summary>
        /// Start the preview on the Control.
        /// </summary>
        /// <param name="dataSource">Path to the file.</param>
        public override void DoPreview<T>(T dataSource)
        {
            _infoBarDisplayed = false;

            try
            {
                if (!(dataSource is string filePath))
                {
                    throw new ArgumentException($"{nameof(dataSource)} for {nameof(CodeFilePreviewHandler)} must be a string but was a '{typeof(T)}'");
                }

                string ext = Path.GetExtension(filePath);
                string fileText = File.ReadAllText(filePath);

                string codeFileHTML = string.Empty;
                if (ext.Equals(".xml", StringComparison.OrdinalIgnoreCase))
                {
                    codeFileHTML = fileText;
                }
                else
                {
                    StyleDic theme = StyleDic.DefaultLight;
                    string background = "{background:#FFFFFF;}";
                    string baseColor = ControlzEx.Theming.WindowsThemeHelper.GetWindowsBaseColor();
                    if (baseColor == "Dark")
                    {
                        theme = StyleDic.DefaultDark;
                        background = "{background:#202020;}";
                    }

                    string header = string.Format(System.Globalization.CultureInfo.CurrentCulture, htmlHeader, background);
                    HtmlFormatter formatter = new HtmlFormatter(theme);
                    codeFileHTML = formatter.GetHtmlString(fileText, GetLanguageByExtension(ext));
                    codeFileHTML = $"{header}{codeFileHTML}{htmlFooter}";
                }

                /* not work, why? the result of "codeFileHTML" is right. render fail.
                string lang = GetLangByExtension(ext);
                string js = File.ReadAllText(@"C:\res\shjs\sh_main.min.js");
                string jsLang = File.ReadAllText($"C:\\res\\shjs\\lang\\sh_{lang}.min.js");
                string css = File.ReadAllText(@"C:\res\shjs\css\default.css");
                string header = $"<!doctype html><html><head><style>{css}</style><script>{js}{jsLang}</script></head><body onload=\"sh_highlightDocument();\">";
                string footer = "</body></html>";
                string codeFileHTML = $"{header}<pre class=\"sh_{lang}\">{HttpUtility.HtmlEncode(fileText)}</pre>{footer}";
                */

                InvokeOnControlThread(() =>
                {
                    _browser = new WebBrowserExt
                    {
                        DocumentText = codeFileHTML,
                        Dock = DockStyle.Fill,
                        IsWebBrowserContextMenuEnabled = false,
                        ScriptErrorsSuppressed = true,
                        ScrollBarsEnabled = true,
                        AllowNavigation = false,
                    };
                    Controls.Add(_browser);

                    if (_infoBarDisplayed)
                    {
                        _infoBar = GetTextBoxControl(codeFileHTML);
                        Resize += FormResized;
                        Controls.Add(_infoBar);
                    }
                });

                PowerToysTelemetry.Log.WriteEvent(new CodeFilePreviewed());
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                PowerToysTelemetry.Log.WriteEvent(new CodeFilePreviewError { Message = ex.Message });

                InvokeOnControlThread(() =>
                {
                    Controls.Clear();
                    _infoBarDisplayed = true;
                    _infoBar = GetTextBoxControl(Resources.CodeFileNotPreviewedError);
                    Resize += FormResized;
                    Controls.Add(_infoBar);
                });
            }
            finally
            {
                base.DoPreview(dataSource);
            }
        }