Esempio n. 1
0
        static void Main()
        {
            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            // Add the event handler for handling UI thread exceptions to the event.
            Application.ThreadException += Program_UIThreadException;

            // Set the unhandled exception mode to force all Windows Forms errors to go through
            // our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // Add the event handler for handling non-UI thread exceptions to the event.
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            //Application.Run(new MainForm());
            if (SingleInstance.SingleApplication.Run(MainForm.Instance))
            {
                var settings = new CefSettings();

#if DEBUG
                // TODO - this doesnt seem to work
                settings.RemoteDebuggingPort = 8088;
#endif

                settings.CachePath = "cache";
                settings.MultiThreadedMessageLoop   = true;
                settings.WindowlessRenderingEnabled = true;

                settings.CefCommandLineArgs.Add("no-proxy-server", "1");

                var architecture = Environment.Is64BitProcess ? "x64" : "x86";
                settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";

                settings.FocusedNodeChangedEnabled = true;

                //The Request Context has been initialized, you can now set preferences, like proxy server settings
                Cef.OnContextInitialized = delegate
                {
                    var cookieManager = Cef.GetGlobalCookieManager();
                    cookieManager.SetStoragePath("cookies", true);
                    cookieManager.SetSupportedSchemes("custom");

                    //Dispose of context when finished - preferable not to keep a reference if possible.
                    using (var context = Cef.GetGlobalRequestContext())
                    {
                        string errorMessage;
                        //You can set most preferences using a `.` notation rather than having to create a complex set of dictionaries.
                        //The default is true, you can change to false to disable
                        context.SetPreference("webkit.webprefs.plugins_enabled", true, out errorMessage);
                    }
                };

                if (!Cef.Initialize(settings, true, false))
                {
                    throw new Exception("Unable to Initialize Cef");
                }
            }
        }
Esempio n. 2
0
 private static void UpdatePrefsInternal()
 {
     using (IRequestContext ctx = Cef.GetGlobalRequestContext()){
         ctx.SetPreference("browser.enable_spellchecking", Program.UserConfig.EnableSpellCheck, out string _);
         ctx.SetPreference("settings.a11y.animation_policy", Program.UserConfig.EnableAnimatedImages ? "allowed" : "none", out string _);
     }
 }
Esempio n. 3
0
        protected const int MaxTimerDelay = 1000 / 30;  // 30fps

        void IBrowserProcessHandler.OnContextInitialized()
        {
            //The Request Context has been initialized, you can now set preferences, like proxy server settings
            var cookieManager = Cef.GetGlobalCookieManager();
            var appDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WaggonerDx");

            if (!Directory.Exists(appDataFolder))
            {
                try
                {
                    Directory.CreateDirectory(appDataFolder);
                }
                catch
                {
                }
            }
            cookieManager.SetStoragePath(Path.Combine(appDataFolder, "cookies"), true);

            //Dispose of context when finished - preferable not to keep a reference if possible.
            using (var context = Cef.GetGlobalRequestContext())
            {
                string errorMessage;
                //You can set most preferences using a `.` notation rather than having to create a complex set of dictionaries.
                //The default is true, you can change to false to disable
                context.SetPreference("webkit.webprefs.plugins_enabled", true, out errorMessage);
            }
        }
Esempio n. 4
0
        internal void CreateBrowser(IntPtr parent)
        {
            if (((IWebBrowserInternal)this).HasParent == false)
            {
                if (IsBrowserInitialized == false || _browser == null)
                {
                    _requestContext = Cef.GetGlobalRequestContext();

                    var windowInfo = CreateBrowserWindowInfo(parent);

                    //We actually check if WS_EX_NOACTIVATE was set for instances
                    //the user has override CreateBrowserWindowInfo and not called base.CreateBrowserWindowInfo
                    _removeExNoActivateStyle = ((WS_EX)windowInfo.ExStyle & WS_EX.NOACTIVATE) == WS_EX.NOACTIVATE;

                    _initialAddressLoaded = !string.IsNullOrEmpty(_config?.StartUrl);
                    Address = _config?.StartUrl;

                    _browserSettings.DefaultEncoding             = "UTF-8";
                    _browserSettings.FileAccessFromFileUrls      = CefState.Enabled;
                    _browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
                    _browserSettings.WebSecurity = CefState.Disabled;

                    _managedCefBrowserAdapter.CreateBrowser(windowInfo, _browserSettings as BrowserSettings, _requestContext as RequestContext, Address);
                }
                else
                {
                    // If the browser already exists we'll reparent it to the new Handle
                    var browserHandle = _browser.GetHost().GetWindowHandle();
                    NativeMethodWrapper.SetWindowParent(browserHandle, parent);
                }

                Logger.Instance.Log.LogInformation("Cef browser successfully created.");
            }
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var settings = new CefSettings
            {
                CachePath = Path.Combine(Path.GetDirectoryName(typeof(App).Assembly.Location), "cache")
            };

            Cef.Initialize(settings);

            _ = Task.Run(async() =>
            {
                var builder = new WebHostBuilder();

                builder.ConfigureServices(services =>
                {
                    var server = new OwinServer();
                    server.UseOwin(appFunc =>
                    {
                        var requestContext = Cef.GetGlobalRequestContext();
                        requestContext.RegisterOwinSchemeHandlerFactory("https", "cefsharp.test", appFunc);
                    });

                    services.AddSingleton <IServer>(server);
                });

                _host = builder
                        .UseStartup <Startup>()
                        .UseContentRoot(Directory.GetCurrentDirectory())
                        .Build();

                await _host.RunAsync();
            });
        }
 void IBrowserProcessHandler.OnContextInitialized()
 {
     using (IRequestContext ctx = Cef.GetGlobalRequestContext()){
         string err;
         ctx.SetPreference("browser.enable_spellchecking", Program.UserConfig.EnableSpellCheck, out err);
     }
 }
Esempio n. 7
0
        protected const int MaxTimerDelay = 1000 / 30;  // 30fps

        void IBrowserProcessHandler.OnContextInitialized()
        {
            //The Request Context has been initialized, you can now set preferences, like proxy server settings
            var cookieManager = Cef.GetGlobalCookieManager();

            cookieManager.SetStoragePath("cookies", true);
            cookieManager.SetSupportedSchemes(new string[] { "custom" });
            if (cookieManager.SetCookie("custom://cefsharp/home.html", new Cookie
            {
                Name = "CefSharpTestCookie",
                Value = "ILikeCookies",
                Expires = DateTime.Now.AddDays(1)
            }))
            {
                cookieManager.VisitUrlCookiesAsync("custom://cefsharp/home.html", false).ContinueWith(previous =>
                {
                    if (previous.Status == TaskStatus.RanToCompletion)
                    {
                        var cookies = previous.Result;

                        foreach (var cookie in cookies)
                        {
                            Debug.WriteLine("CookieName:" + cookie.Name);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("No Cookies found");
                    }
                });

                cookieManager.VisitAllCookiesAsync().ContinueWith(t =>
                {
                    if (t.Status == TaskStatus.RanToCompletion)
                    {
                        var cookies = t.Result;

                        foreach (var cookie in cookies)
                        {
                            Debug.WriteLine("CookieName:" + cookie.Name);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("No Cookies found");
                    }
                });
            }

            //Dispose of context when finished - preferable not to keep a reference if possible.
            using (var context = Cef.GetGlobalRequestContext())
            {
                string errorMessage;
                //You can set most preferences using a `.` notation rather than having to create a complex set of dictionaries.
                //The default is true, you can change to false to disable
                context.SetPreference("webkit.webprefs.plugins_enabled", true, out errorMessage);
            }
        }
Esempio n. 8
0
        private void InitiliazeChromium(string URL)
        {
            chromeBrowser = new ChromiumWebBrowser(URL);
            var contx = Cef.GetGlobalRequestContext();

            Cef.UIThreadTaskFactory.StartNew(delegate
            {
                contx.SetPreference("profile.default_content_setting_values.plugins", 1, out string err);
            });
        private static void UpdatePrefsInternal()
        {
            UserConfig config = Program.Config.User;

            using IRequestContext ctx = Cef.GetGlobalRequestContext();

            ctx.SetPreference("browser.enable_spellchecking", config.EnableSpellCheck, out string _);
            ctx.SetPreference("spellcheck.dictionary", config.SpellCheckLanguage, out string _);
            ctx.SetPreference("settings.a11y.animation_policy", config.EnableAnimatedImages ? "allowed" : "none", out string _);
        }
Esempio n. 10
0
 public static void ShutDown(bool sleep = true)
 {
     Cef.GetGlobalRequestContext()?.Dispose();
     Cef.Shutdown();
     Cef.ExecuteProcess();
     if (!sleep)
     {
         return;
     }
     Thread.Sleep(150);
 }
Esempio n. 11
0
        /// <summary>
        /// Enables requests to certain schemes (http, https and scchrom) to be exchanged and manipulated.
        /// Also adds the scchrom scheme to provide scchrom internal stuff like the editors help content.
        /// </summary>
        private void setupSchemes()
        {
            var    whitelist       = new List <RequestIdentifier>();
            string whitelistString = Arguments.GetArgument("request-whitelist", "").Trim();

            if (!string.IsNullOrWhiteSpace(whitelistString))
            {
                string[] whitelistEntries = whitelistString.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                foreach (string entry in whitelistEntries)
                {
                    whitelist.Add(new RequestIdentifier(entry));
                }
            }

            List <Tuple <RequestIdentifier, string> > response_exchanges_utf8 = null;
            var exchangeResponseHandler = Tools.Arguments.GetStackedArguments("exchange-response-utf8");

            if (exchangeResponseHandler != null)
            {
                response_exchanges_utf8 = new List <Tuple <RequestIdentifier, string> >();
                foreach (var rrh in exchangeResponseHandler)
                {
                    var filter = new RequestIdentifier(rrh.Key);
                    response_exchanges_utf8.Add(new Tuple <RequestIdentifier, string>(filter, rrh.Value));
                }
            }

            List <Tuple <RequestIdentifier, string> > js_Rewrites = null;
            var js_rewriteHandler = Tools.Arguments.GetStackedArguments("exchange-response-utf8_script");

            if (js_rewriteHandler != null)
            {
                js_Rewrites = new List <Tuple <RequestIdentifier, string> >();
                foreach (var rrh in js_rewriteHandler)
                {
                    var filter = new RequestIdentifier(rrh.Key);
                    js_Rewrites.Add(new Tuple <RequestIdentifier, string>(filter, rrh.Value));
                }
            }


            var resourceSchemehandler = new Handler.SchemeHandlerFactory(whitelist, response_exchanges_utf8, js_Rewrites);

            // remove old schemes and ...
            Cef.ClearSchemeHandlerFactories();

            // ... register all new schemes
            var globalRequestContext = Cef.GetGlobalRequestContext();

            globalRequestContext.RegisterSchemeHandlerFactory("http", "", resourceSchemehandler);
            globalRequestContext.RegisterSchemeHandlerFactory("https", "", resourceSchemehandler);
            globalRequestContext.RegisterSchemeHandlerFactory("scchrom", "", resourceSchemehandler);
        }
Esempio n. 12
0
        public void InitializeChromium()
        {
            Debug.Assert(SetProcessDpiAwareness(PROCESS_DPI_AWARENESS.Process_System_DPI_Aware) == false);

            CefSettings settings = new CefSettings();

            // Specifying a CachePath is required for persistence of cookies, saving of passwords, etc.
            settings.CachePath = System.IO.Path.GetFullPath("cache");

            // For Windows 7 and above, best to include relevant app.manifest entries as well
            //Cef.EnableHighDPISupport();

            settings.CefCommandLineArgs.Add("disable-gpu", "1");
            settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");

            // Initialize cef with the provided settings
            Cef.Initialize(settings);

            #region MultiThreadedMessageLoop
            // CEF message loop integrated into the application message loo (Part 1)
            //settings.MultiThreadedMessageLoop = false;

            //// CEF message loop integrated into the application message loo (Part 2)
            //var timer = new Timer();
            //timer.Interval = 16;
            //timer.Tick += Timer_Tick;
            //timer.Start();
            #endregion

            var result = Cef.AddCrossOriginWhitelistEntry("http://local.kiewic.com", "http", "heyhttp.org", allowTargetSubdomains: false);
            Debug.Assert(result == true, "Calling AddCrossOriginWhitelistEntry");

            Cef.GetGlobalRequestContext().RegisterSchemeHandlerFactory(
                "http",
                domainName: "local.kiewic.com",
                factory: new CustomSchemeHandlerFactory());

            // Create a browser component
            chromeBrowser                              = new ChromiumWebBrowser("http://local.kiewic.com/index.html");
            chromeBrowser.Dock                         = DockStyle.Fill;
            chromeBrowser.KeyboardHandler              = new CustomKeyboardHandler();
            chromeBrowser.RequestHandler               = new CustomRequestHandler();
            chromeBrowser.IsBrowserInitializedChanged += ChromeBrowser_IsBrowserInitializedChanged;

            // Add it to the form and fill it to the form window.
            this.Controls.Add(chromeBrowser);

            chromeBrowser.JavascriptObjectRepository.Register("coolGuidGenerator", new GuidGenerator(), isAsync: false);
            chromeBrowser.JavascriptObjectRepository.Register("coolGuidGenerator2", new GuidGenerator(), isAsync: true);
            chromeBrowser.JavascriptObjectRepository.Register("boundAsync", new BoundObject(), isAsync: true);
        }
Esempio n. 13
0
        void IBrowserProcessHandler.OnContextInitialized()
        {
            //The Request Context has been initialized, you can now set preferences, like proxy server settings
            var cookieManager = Cef.GetGlobalCookieManager();

            cookieManager.SetStoragePath("cookies", true);
            cookieManager.SetSupportedSchemes("custom");

            //Dispose of context when finished - preferable not to keep a reference if possible.
            using (var context = Cef.GetGlobalRequestContext())
            {
                string errorMessage;
                //You can set most preferences using a `.` notation rather than having to create a complex set of dictionaries.
                //The default is true, you can change to false to disable
                context.SetPreference("webkit.webprefs.plugins_enabled", true, out errorMessage);
            }
        }
Esempio n. 14
0
        protected override void OnStartup(StartupEventArgs e)
        {
            //System.AppContext.SetSwitch("Switch.System.Windows.Input.Stylus.DisableStylusAndTouchSupport", true);
            System.AppContext.SetSwitch("Switch.System.Windows.Input.Stylus.EnablePointerSupport", true);


#if DEBUG
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                //MessageBox.Show("When running this Example outside of Visual Studio please make sure you compile in `Release` mode.", "Warning");
            }
#endif

            const bool multiThreadedMessageLoop = true;

            IBrowserProcessHandler browserProcessHandler;

            if (multiThreadedMessageLoop)
            {
                browserProcessHandler = new BrowserProcessHandler();
            }
            else
            {
                browserProcessHandler = new WpfBrowserProcessHandler(Dispatcher);
            }

            var settings = new CefSettings();
            settings.MultiThreadedMessageLoop = multiThreadedMessageLoop;
            settings.ExternalMessagePump      = !multiThreadedMessageLoop;
            //Disable GPU Acceleration
            settings.CefCommandLineArgs.Add("disable-gpu");
            //settings.CefCommandLineArgs.Add("disable-gpu-compositing");
            // Enable System Wide Flash Installation
            settings.CefCommandLineArgs.Add("enable-system-flash", "1");
            settings.CefCommandLineArgs.Add("plugin-policy", "allow");
            settings.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
            var cacheFolder = $"{DateTime.Now:yyyyMMdd_HHmmssfff}_{Process.GetCurrentProcess().Id}";
            settings.CachePath = Path.Combine(Path.GetTempPath(), "CefSharp\\Cache", cacheFolder);

            CefExample.Init(settings, browserProcessHandler: browserProcessHandler);

            var contx = Cef.GetGlobalRequestContext();
            Cef.UIThreadTaskFactory.StartNew(delegate
            {
                contx.SetPreference("profile.default_content_setting_values.plugins", 1, out string err);
            });
Esempio n. 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChromiumWebBrowser"/> class.
 /// </summary>
 /// <param name="parent">The parent handle.</param>
 public void CreateBrowser(IntPtr parent)
 {
     if (((IWebBrowserInternal)this).HasParent == false)
     {
         if (IsBrowserInitialized == false || browser == null)
         {
             //TODO: Revert temp workaround for default url not loading
             RequestContext = Cef.GetGlobalRequestContext();
             browserCreated = true;
             managedCefBrowserAdapter.CreateBrowser(BrowserSettings, (RequestContext)RequestContext, parent, null);
         }
         else
         {
             //If the browser already exists we'll reparent it to the new Handle
             var browserHandle = browser.GetHost().GetWindowHandle();
             NativeMethodWrapper.SetWindowParent(browserHandle, parent);
         }
     }
 }
Esempio n. 16
0
        private static void InitBrowser()
        {
            // 获取启动应用程序可执行文件的路径
            string startUpPath = System.Windows.Forms.Application.StartupPath;
            // 初始化设置
            CefSettings cefSettings = new CefSettings();

            cefSettings.Locale = "zh-CN";
            cefSettings.CefCommandLineArgs.Add("enable-npapi", "1");
            cefSettings.CefCommandLineArgs.Add("enable-system-flash", "1");          //启用flash
            cefSettings.CefCommandLineArgs.Add("enable-media-stream", "1");          //启用媒体流
            cefSettings.CefCommandLineArgs.Add("ppapi-flash-version", "99.0.0.999"); //设置flash插件版本
            cefSettings.CefCommandLineArgs.Add("ppapi-flash-path", startUpPath + @"Plugins\pepflashplayer.dll");
            cefSettings.CefCommandLineArgs.Add("plugin-policy", "allow");
            // 要在浏览器对象初始化运行前使用
            // 用用户提供的设置初始化CefSharp
            // initialize 和Shutdown 必须在你的主应用程序线程(通常UI 线程)调用
            Cef.Initialize(cefSettings, true);
            Cef.EnableHighDPISupport();
            var contx = Cef.GetGlobalRequestContext();

            Cef.UIThreadTaskFactory.StartNew(() => contx.SetPreference("profile.default_content_setting_values.plugins", 1, out string err));
        }
Esempio n. 17
0
        protected const int ThirtyTimesPerSecond = 1000 / 30;  //30fps

        void IBrowserProcessHandler.OnContextInitialized()
        {
            //The Global CookieManager has been initialized, you can now set cookies
            var cookieManager = Cef.GetGlobalCookieManager();

            cookieManager.SetSupportedSchemes(new string[] { "custom" }, true);
            if (cookieManager.SetCookie("custom://cefsharp/home.html", new Cookie
            {
                Name = "CefSharpTestCookie",
                Value = "ILikeCookies",
                Expires = DateTime.Now.AddDays(1)
            }))
            {
                cookieManager.VisitUrlCookiesAsync("custom://cefsharp/home.html", false).ContinueWith(previous =>
                {
                    if (previous.Status == TaskStatus.RanToCompletion)
                    {
                        var cookies = previous.Result;

                        foreach (var cookie in cookies)
                        {
                            Debug.WriteLine("CookieName: " + cookie.Name);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("No Cookies found");
                    }
                });

                cookieManager.VisitAllCookiesAsync().ContinueWith(t =>
                {
                    if (t.Status == TaskStatus.RanToCompletion)
                    {
                        var cookies = t.Result;

                        foreach (var cookie in cookies)
                        {
                            Debug.WriteLine("CookieName: " + cookie.Name);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("No Cookies found");
                    }
                });
            }

            //The Request Context has been initialized, you can now set preferences, like proxy server settings
            //Dispose of context when finished - preferable not to keep a reference if possible.
            using (var context = Cef.GetGlobalRequestContext())
            {
                string errorMessage;
                //You can set most preferences using a `.` notation rather than having to create a complex set of dictionaries.
                //The default is true, you can change to false to disable
                context.SetPreference("webkit.webprefs.plugins_enabled", true, out errorMessage);

                //string error;
                //var dicts = new List<string> { "en-GB", "en-US" };
                //var success = context.SetPreference("spellcheck.dictionaries", dicts, out error);

                //The no-proxy-server flag is set in CefExample.cs class, you'll have to remove that before you can test
                //this code out
                //var v = new Dictionary<string, string>
                //{
                //    ["mode"] = "fixed_servers",
                //    ["server"] = "scheme://*****:*****@"..\..\..\..\CefSharp.Example\Resources";
#else
                    @"..\..\..\..\..\..\CefSharp.Example\Resources";
#endif
                var folderSchemeHandlerExample = new FolderSchemeHandlerFactory(rootFolder: cefSharpExampleResourcesFolder,
                                                                                hostName: "cefsharp.example", //Optional param no hostname checking if null
                                                                                defaultPage: "home.html");    //Optional param will default to index.html

                context.RegisterSchemeHandlerFactory("https", "cefsharp.example", folderSchemeHandlerExample);
            }
        }
Esempio n. 18
0
        protected const int MaxTimerDelay = 1000 / 30;  // 30fps

        void IBrowserProcessHandler.OnContextInitialized()
        {
            //The Global CookieManager has been initialized, you can now set cookies
            //var cookieManager = Cef.GetGlobalCookieManager();
            //cookieManager.SetStoragePath("cookies", true);
            //cookieManager.SetSupportedSchemes(new string[] {"custom"});
            //if(cookieManager.SetCookie("custom://cefsharp/home.html", new Cookie
            //{
            //    Name = "CefSharpTestCookie",
            //    Value = "ILikeCookies",
            //    Expires = DateTime.Now.AddDays(1)
            //}))
            //{
            //    cookieManager.VisitUrlCookiesAsync("custom://cefsharp/home.html", false).ContinueWith(previous =>
            //    {
            //        if (previous.Status == TaskStatus.RanToCompletion)
            //        {
            //            var cookies = previous.Result;

            //            foreach (var cookie in cookies)
            //            {
            //                Debug.WriteLine("CookieName:" + cookie.Name);
            //            }
            //        }
            //        else
            //        {
            //            Debug.WriteLine("No Cookies found");
            //        }
            //    });

            //    cookieManager.VisitAllCookiesAsync().ContinueWith(t =>
            //    {
            //        if (t.Status == TaskStatus.RanToCompletion)
            //        {
            //            var cookies = t.Result;

            //            foreach (var cookie in cookies)
            //            {
            //                Debug.WriteLine("CookieName:" + cookie.Name);
            //            }
            //        }
            //        else
            //        {
            //            Debug.WriteLine("No Cookies found");
            //        }
            //    });
            //}

            //The Request Context has been initialized, you can now set preferences, like proxy server settings
            //Dispose of context when finished - preferable not to keep a reference if possible.
            using (var context = Cef.GetGlobalRequestContext())
            {
                string errorMessage;
                //You can set most preferences using a `.` notation rather than having to create a complex set of dictionaries.
                //The default is true, you can change to false to disable
                context.SetPreference("webkit.webprefs.plugins_enabled", true, out errorMessage);

                //It's possible to register a scheme handler for the default http and https schemes
                //In this example we register the FolderSchemeHandlerFactory for https://cefsharp.example
                //Best to include the domain name, so only requests for that domain are forwarded to your scheme handler
                //It is possible to intercept all requests for a scheme, including the built in http/https ones, be very careful doing this!
                //var folderSchemeHandlerExample = new FolderSchemeHandlerFactory(rootFolder: @"..\..\..\..\CefSharp.Example\Resources",
                //                                                        hostName: "cefsharp.example", //Optional param no hostname checking if null
                //                                                        defaultPage: "home.html"); //Optional param will default to index.html

                //context.RegisterSchemeHandlerFactory("https", "cefsharp.example", folderSchemeHandlerExample);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// 网页加载完成操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            if (e.Frame.IsMain)//单次加载页面会调用此事件多次,需加这个判断
            {
                //直接转换成ChromiumWebBrowser browserFor 不能获取Address
                var browserFor = (ChromiumWebBrowser)sender;
                //Console.WriteLine("获取的地址:"+ browserFor.Address);
                var result = await browser.GetSourceAsync();

                if (sourceFromData.FromSource.Contains(browserFor.Address))//说明进到了伪装的一级路由页面
                {
                    if (SourceFromConfig.ROUTING_SINA_BLOG_TYPE == sourceFromData.Type)
                    {
                        //设置ip
                        //进入下载页面之前将ip更改
                        await Cef.UIThreadTaskFactory.StartNew(delegate
                        {
                            var rc    = Cef.GetGlobalRequestContext();
                            var v     = new Dictionary <string, object>();
                            v["mode"] = "fixed_servers";
//测试屏蔽2018-02-23 21:19:00 代理ip
                            v["server"] = WuyouProxy.getProxyIpAndPort();
                            string error;
                            bool success = rc.SetPreference("proxy", v, out error);
                            if (success)
                            {
                            }
                        });


                        //Random rd = new Random();
                        //int randomSleepSecond = rd.Next(1,6);//1-5秒
                        Console.WriteLine("进入的伪装路由连接:" + sourceFromData.FromSource + ",且类型为新浪博客");
                        //Console.WriteLine("从伪装页面进入下载页面的随机睡眠时间:"+randomSleepSecond+"s");
                        //Thread.Sleep(randomSleepSecond*1000);

                        StringBuilder scriptCode = new StringBuilder();
                        scriptCode.Append("var aElements = new Array();");
                        scriptCode.Append("var x = document.getElementById('sina_keyword_ad_area2').getElementsByTagName(\"div\");");
                        scriptCode.Append("for(var i = 0;i<x.length;i++){");
                        scriptCode.Append("    var sonDiv = x[i];");
                        scriptCode.Append("    var aInSonDiv = sonDiv.getElementsByTagName(\"a\");");
                        scriptCode.Append("    if(aInSonDiv&&aInSonDiv.length>0){");
                        scriptCode.Append("        aElements[aElements.length] = aInSonDiv[0];");
                        scriptCode.Append("    }else{");
                        scriptCode.Append("        console.log(\"不包含子标签\");");
                        scriptCode.Append("    }");
                        scriptCode.Append("}");
                        scriptCode.Append("var randomA = aElements[Math.floor(Math.random()*aElements.length)];");
                        scriptCode.Append("sourceFromData.actualAccessDownloadPageUrl=randomA.getAttribute(\"href\");");//js调用c#
                        scriptCode.Append("randomA.click();");
                        browser.GetBrowser().MainFrame.ExecuteJavaScriptAsync(scriptCode.ToString());

                        //Console.WriteLine("实际点击的下载页面的url:"+ sourceFromData.actualAccessDownloadPageUrl); //估计是异步的,这里还没获取这个值呢,但在RequestHandler中已经获取此值
                        //Console.WriteLine("测试。。。。。。");
                        //browser.Load("https://www.baidu.com/s?wd=%E6%88%91%E7%9A%84ip&rsv_spt=1&rsv_iqid=0x914838db0001e715&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=94789287_hao_pg&rsv_enter=1&rsv_sug3=5&rsv_sug1=3&rsv_sug7=100&rsv_t=2fec3e53%2FvqkD9VS1c4ogr84NRknqB%2FGqrZrxz5Cxm5EsGDivYD6hdnRTYE7%2BQZBJN4p7tl%2B");


                        //Console.WriteLine("测试结束-------------");
                        //Console.WriteLine("执行到这"+ scriptCode.ToString());
                    }
                    else
                    {
                        throw new Exception("不能识别的伪装路由类型:" + sourceFromData.Type);
                    }
                }
                else//说明已经到了具体下载页面了
                {
                    //每次请求更换ip 下载之头无需切换ip

                    /*
                     * await Cef.UIThreadTaskFactory.StartNew(delegate
                     * {
                     *  //Console.WriteLine("获取的ip:" + ipAndPort);
                     *  //Console.WriteLine("browser2是否初始化:" + browser);
                     *  var rc = Cef.GetGlobalRequestContext();
                     *  var v = new Dictionary<string,
                     *      object>();
                     *  v["mode"] = "fixed_servers";
                     * //                        v["server"] = WuyouProxy.getProxyIpAndPort();
                     *  v["User-Agent"] = userAgent;
                     * //                        v["Referer"] = sourceFromData.FromSource;//设置来源信息
                     *  string error;
                     *  bool success = rc.SetPreference("proxy", v, out error);
                     *  if (success)
                     *  {
                     *
                     *  }
                     * });
                     */
                    //Console.WriteLine("测试load");
                    //browser.Load("https://www.baidu.com/s?wd=%E6%88%91%E7%9A%84ip&rsv_spt=1&rsv_iqid=0x914838db0001e715&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=94789287_hao_pg&rsv_enter=1&rsv_sug3=5&rsv_sug1=3&rsv_sug7=100&rsv_t=2fec3e53%2FvqkD9VS1c4ogr84NRknqB%2FGqrZrxz5Cxm5EsGDivYD6hdnRTYE7%2BQZBJN4p7tl%2B");
                    Random rd = new Random();
                    int    randomSleepSecond = rd.Next(1000, 6000);//1000-5999毫秒
                    Console.WriteLine("点击下载之头,随机睡眠:" + randomSleepSecond + "s");
                    Thread.Sleep(randomSleepSecond);

                    Console.WriteLine("城通网盘下载页面,开始下载...");
                    browser.GetBrowser().MainFrame.ExecuteJavaScriptAsync("document.getElementById('free_down_link').click();");
                }



                // Console.WriteLine("页面加载完成:" + result);
                Console.WriteLine("sender:" + sender);
                //
            }
            else
            {
                Console.WriteLine("非主窗口加载完毕,不执行任何逻辑!");
            }
        }
Esempio n. 20
0
        public static void Init(bool osr, bool multiThreadedMessageLoop)
        {
            // Set Google API keys, used for Geolocation requests sans GPS.  See http://www.chromium.org/developers/how-tos/api-keys
            // Environment.SetEnvironmentVariable("GOOGLE_API_KEY", "");
            // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_ID", "");
            // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_SECRET", "");

            //Chromium Command Line args
            //http://peter.sh/experiments/chromium-command-line-switches/
            //NOTE: Not all relevant in relation to `CefSharp`, use for reference purposes only.

            var settings = new CefSettings();

            settings.RemoteDebuggingPort = 8088;
            //The location where cache data will be stored on disk. If empty an in-memory cache will be used for some features and a temporary disk cache for others.
            //HTML5 databases such as localStorage will only persist across sessions if a cache path is specified.
            settings.CachePath = "cache";
            //settings.UserAgent = "CefSharp Browser" + Cef.CefSharpVersion; // Example User Agent
            //settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
            //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "1");
            //settings.CefCommandLineArgs.Add("enable-media-stream", "1"); //Enable WebRTC
            //settings.CefCommandLineArgs.Add("no-proxy-server", "1"); //Don't use a proxy server, always make direct connections. Overrides any other proxy server flags that are passed.
            //settings.CefCommandLineArgs.Add("debug-plugin-loading", "1"); //Dumps extra logging about plugin loading to the log file.
            //settings.CefCommandLineArgs.Add("disable-plugins-discovery", "1"); //Disable discovering third-party plugins. Effectively loading only ones shipped with the browser plus third-party ones as specified by --extra-plugin-dir and --load-plugin switches
            //settings.CefCommandLineArgs.Add("enable-system-flash", "1"); //Automatically discovered and load a system-wide installation of Pepper Flash.
            //settings.CefCommandLineArgs.Add("allow-running-insecure-content", "1"); //By default, an https page cannot run JavaScript, CSS or plugins from http URLs. This provides an override to get the old insecure behavior. Only available in 47 and above.

            //settings.CefCommandLineArgs.Add("enable-logging", "1"); //Enable Logging for the Renderer process (will open with a cmd prompt and output debug messages - use in conjunction with setting LogSeverity = LogSeverity.Verbose;)
            //settings.LogSeverity = LogSeverity.Verbose; // Needed for enable-logging to output messages

            //settings.CefCommandLineArgs.Add("disable-extensions", "1"); //Extension support can be disabled
            //settings.CefCommandLineArgs.Add("disable-pdf-extension", "1"); //The PDF extension specifically can be disabled

            //Load the pepper flash player that comes with Google Chrome - may be possible to load these values from the registry and query the dll for it's version info (Step 2 not strictly required it seems)
            //settings.CefCommandLineArgs.Add("ppapi-flash-path", @"C:\Program Files (x86)\Google\Chrome\Application\47.0.2526.106\PepperFlash\pepflashplayer.dll"); //Load a specific pepper flash version (Step 1 of 2)
            //settings.CefCommandLineArgs.Add("ppapi-flash-version", "20.0.0.228"); //Load a specific pepper flash version (Step 2 of 2)

            //NOTE: For OSR best performance you should run with GPU disabled:
            // `--disable-gpu --disable-gpu-compositing --enable-begin-frame-scheduling`
            // (you'll loose WebGL support but gain increased FPS and reduced CPU usage).
            // http://magpcss.org/ceforum/viewtopic.php?f=6&t=13271#p27075
            //https://bitbucket.org/chromiumembedded/cef/commits/e3c1d8632eb43c1c2793d71639f3f5695696a5e8

            //NOTE: The following function will set all three params
            //settings.SetOffScreenRenderingBestPerformanceArgs();
            //settings.CefCommandLineArgs.Add("disable-gpu", "1");
            //settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");
            //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1");

            //settings.CefCommandLineArgs.Add("disable-gpu-vsync", "1"); //Disable Vsync

            //Disables the DirectWrite font rendering system on windows.
            //Possibly useful when experiencing blury fonts.
            //settings.CefCommandLineArgs.Add("disable-direct-write", "1");

            settings.MultiThreadedMessageLoop = multiThreadedMessageLoop;

            // Off Screen rendering (WPF/Offscreen)
            if (osr)
            {
                settings.WindowlessRenderingEnabled = true;
                // Disable Surfaces so internal PDF viewer works for OSR
                // https://bitbucket.org/chromiumembedded/cef/issues/1689
                //settings.CefCommandLineArgs.Add("disable-surfaces", "1");
                settings.EnableInternalPdfViewerOffScreen();

                // DevTools doesn't seem to be working when this is enabled
                // http://magpcss.org/ceforum/viewtopic.php?f=6&t=14095
                //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1");
            }

            var proxy = ProxyConfig.GetProxyInformation();

            switch (proxy.AccessType)
            {
            case InternetOpenType.Direct:
            {
                //Don't use a proxy server, always make direct connections.
                settings.CefCommandLineArgs.Add("no-proxy-server", "1");
                break;
            }

            case InternetOpenType.Proxy:
            {
                settings.CefCommandLineArgs.Add("proxy-server", proxy.ProxyAddress);
                break;
            }

            case InternetOpenType.PreConfig:
            {
                settings.CefCommandLineArgs.Add("proxy-auto-detect", "1");
                break;
            }
            }

            //settings.LogSeverity = LogSeverity.Verbose;

            if (DebuggingSubProcess)
            {
                var architecture = Environment.Is64BitProcess ? "x64" : "x86";
                settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
            }

            settings.RegisterScheme(new CefCustomScheme
            {
                SchemeName           = CefSharpSchemeHandlerFactory.SchemeName,
                SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
                                       //SchemeHandlerFactory = new InMemorySchemeAndResourceHandlerFactory()
            });

            settings.RegisterScheme(new CefCustomScheme
            {
                SchemeName           = CefSharpSchemeHandlerFactory.SchemeNameTest,
                SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
            });

            settings.RegisterExtension(new CefExtension("cefsharp/example", Resources.extension));

            settings.FocusedNodeChangedEnabled = true;

            //The Request Context has been initialized, you can now set preferences, like proxy server settings
            Cef.OnContextInitialized = delegate
            {
                var cookieManager = Cef.GetGlobalCookieManager();
                cookieManager.SetStoragePath("cookies", true);
                cookieManager.SetSupportedSchemes("custom");

                //Dispose of context when finished - preferable not to keep a reference if possible.
                using (var context = Cef.GetGlobalRequestContext())
                {
                    string errorMessage;
                    //You can set most preferences using a `.` notation rather than having to create a complex set of dictionaries.
                    //The default is true, you can change to false to disable
                    context.SetPreference("webkit.webprefs.plugins_enabled", true, out errorMessage);
                }
            };

            if (!Cef.Initialize(settings, shutdownOnProcessExit: true, performDependencyCheck: !DebuggingSubProcess))
            {
                throw new Exception("Unable to Initialize Cef");
            }
        }
Esempio n. 21
0
        /// <summary>
        /// 单线程业务逻辑
        /// </summary>
        private void oneThreadChengTongService()
        {
            //TODO 如果不能动态更改userAgent,那就多启动几个客户端程序,谁抢到了下载线程谁就执行,或者开通城通的多线程下载


            //获取要伪装的上级页面地址
            sourceFromData = SourceFromConfig.randomSourceFromData();
            //随机的userAgent信息
            userAgent = UserAgent.randomUserAgent();
            if (!Cef.IsInitialized)
            {
                CefSettings settings = new CefSettings()
                {
                    CachePath = Directory.GetCurrentDirectory() + @"\Cache",
                };
                settings.UserAgent             = userAgent;
                settings.PersistSessionCookies = true;                                              //支持cookie
                settings.CefCommandLineArgs.Add("ppapi-flash-path", @"Plugins\pepflashplayer.dll"); //cef 支持flash http://blog.csdn.net/xxhongdev/article/details/77195339
                settings.AcceptLanguageList = "zh-CN,zh;q=0.8";

                //settings.CefCommandLineArgs.Add("proxy-server", ipAndPort);
                //settings.CefCommandLineArgs.Add("no-proxy-server", "1")
                //settings.UserAgent = "Hello!";

                Cef.Initialize(settings);
            }

            //browser = new ChromiumWebBrowser("https://www.baidu.com/s?wd=%E6%88%91%E7%9A%84ip&rsv_spt=1&rsv_iqid=0x914838db0001e715&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=94789287_hao_pg&rsv_enter=1&rsv_sug3=5&rsv_sug1=3&rsv_sug7=100&rsv_t=2fec3e53%2FvqkD9VS1c4ogr84NRknqB%2FGqrZrxz5Cxm5EsGDivYD6hdnRTYE7%2BQZBJN4p7tl%2B");
            String testIp = "https://www.baidu.com/s?wd=%E6%88%91%E7%9A%84ip&rsv_spt=1&rsv_iqid=0x914838db0001e715&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=94789287_hao_pg&rsv_enter=1&rsv_sug3=5&rsv_sug1=3&rsv_sug7=100&rsv_t=2fec3e53%2FvqkD9VS1c4ogr84NRknqB%2FGqrZrxz5Cxm5EsGDivYD6hdnRTYE7%2BQZBJN4p7tl%2B";

            browser = new ChromiumWebBrowser(sourceFromData.FromSource)
            {
                //browser = new ChromiumWebBrowser(testIp){
                BrowserSettings = new BrowserSettings()
                {
                    Plugins = CefState.Enabled
                },
                Dock = DockStyle.Fill
            };

            browser.FrameLoadEnd   += browser_FrameLoadEnd;                 //网页加载完成
            browser.DownloadHandler = new MyDownLoadFile();                 //下载器配置
            browser.LifeSpanHandler = new MyLifeSpanHandler();              //在同一窗口打开链接
            browser.RequestHandler  = new MyRequestHandler(sourceFromData); //动态更改 header
            //TODO: 在官方demo里CefSharp.Example中->Handlers->RequestHandler中93行说明了如何让每次请求都更改user-agent,可以参考
            //browser.RequestHandler = new MyRequestHandler();//每次请求都更换User-Agent 注意IRequestHandler在CefSharp.IRequestHandler



            browser.Dock = DockStyle.Fill;

            //js调用c#
            //browser表示你的CefSharp对象使用它的RegisterJsObject来绑定你的.net类
            browser.RegisterJsObject("sourceFromData", sourceFromData);


            //Console.WriteLine("browser是否初始化:" + browser);
            //由于在下载之头启用了代理ip,此处要禁止代理ip
            Cef.UIThreadTaskFactory.StartNew(delegate {
                //Console.WriteLine("获取的ip:" + ipAndPort);
                //Console.WriteLine("browser2是否初始化:" + browser);
                var rc    = Cef.GetGlobalRequestContext();
                var v     = new Dictionary <string, object>();
                v["mode"] = "fixed_servers";
                //v["server"] = WuyouProxy.getProxyIpAndPort();
                v["User-Agent"] = userAgent;
                string error;
                bool success = rc.SetPreference("proxy", v, out error);
                if (success)
                {
                }
            });

            this.panel1.Controls.Clear();
            this.panel1.Controls.Add(browser);
        }
Esempio n. 22
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            log4net.Config.XmlConfigurator.Configure();
            m_Log = LogManager.GetLogger(this.GetType());

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            var tmpFolder = System.IO.Path.GetTempPath() + "CotgBrowser_Cache";

            if (CotGBrowser.Properties.Settings.Default.ClearCache)
            {
                var dirInfo = new System.IO.DirectoryInfo(tmpFolder);

                foreach (System.IO.FileInfo file in dirInfo.GetFiles())
                {
                    file.Delete();
                }

                CotGBrowser.Properties.Settings.Default.ClearCache = false;
                CotGBrowser.Properties.Settings.Default.Save();
            }

            var settings = new CefSettings();

            settings.CachePath = tmpFolder;
            //settings.CefCommandLineArgs.Clear();
            settings.RemoteDebuggingPort = 8088;
            settings.CefCommandLineArgs.Add("enable-crash-reporter", "1");
            settings.CefCommandLineArgs.Add("proxy-auto-detect", "1");

            //single_process
            //settings.CefCommandLineArgs.Add("single_process", "1");
            //settings.CefCommandLineArgs.Add("renderer-process-limit", "1");

            //WPF opt
            settings.WindowlessRenderingEnabled = true;
            settings.EnableInternalPdfViewerOffScreen();
            //settings.CefCommandLineArgs.Add("disable-gpu", "1");
            settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");
            //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1");

            //settings.CefCommandLineArgs.Add("enable-logging", "v=1");

            //settings.CefCommandLineArgs.Add("js-flags", "--max-old-space-size=2000");

            //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "1");
            //settings.CefCommandLineArgs.Add("disable-gpu-vsync", "1");
            //settings.CefCommandLineArgs.Add("disable-canvas-aa", "1");
            //settings.CefCommandLineArgs.Add("disable-gpu-rasterization", "1");

            settings.MultiThreadedMessageLoop  = true;
            settings.FocusedNodeChangedEnabled = true;
            settings.LogSeverity = LogSeverity.Error;

            Cef.OnContextInitialized = delegate
            {
                var cookieManager = Cef.GetGlobalCookieManager();
                cookieManager.SetStoragePath("cookies", true);

                //Dispose of context when finished - preferable not to keep a reference if possible.
                using (var context = Cef.GetGlobalRequestContext())
                {
                    string errorMessage;
                    //You can set most preferences using a `.` notation rather than having to create a complex set of dictionaries.
                    //The default is true, you can change to false to disable
                    context.SetPreference("webkit.webprefs.plugins_enabled", true, out errorMessage);
                }
            };

            if (!Cef.Initialize(settings, shutdownOnProcessExit: true, performDependencyCheck: false))
            {
                throw new Exception("Unable to Initialize Cef");
            }

            /*
             * Task.Run(() =>
             * {
             *  while (true)
             *  {
             *      try
             *      {
             *          //Application.Current.Dispatcher.Invoke(new Action(
             *          //  () => Cef.DoMessageLoopWork()));
             *          Cef.DoMessageLoopWork();
             *          System.Threading.Thread.Sleep(100);
             *      }
             *      catch (Exception eml)
             *      {
             *          m_Log.Error(eml.Message, eml);
             *      }
             *  }
             * });
             */

            //konf. fabryki
            IoCHelper.GetIoC();

            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile <GotGLib.NH.Schema.MapperProfile>();
            });
            Mapper.AssertConfigurationIsValid();

            m_Log.Info("Application started.");

            Application.Current.MainWindow = IoCHelper.GetIoC().Resolve <Views.MainWindow>();
            Application.Current.MainWindow.Show();
            Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;

            CotGNotifyIcon notify = new CotGNotifyIcon();

            IoCHelper.GetIoC().RegisterInstance <CotGNotifyIcon>(notify, new ContainerControlledLifetimeManager());
            notify.AppStarted();
        }
Esempio n. 23
0
 public void StopAllConection()
 {
     this._browser.GetBrowser().GetHost().RequestContext?.CloseAllConnections((ICompletionCallback)null);
     Cef.GetGlobalRequestContext()?.CloseAllConnections((ICompletionCallback)null);
 }
Esempio n. 24
0
        public async Task UpdateProxyInProgram(Settings settings, bool loadTestPage = true)
        {
            ProxyPanelViewModel proxyPanelViewModel  = this;
            ProxyForChrome      proxyFromProxyConfig = proxyPanelViewModel.ExtractMainProxyFromProxyConfig(settings.ProxyConfig);
            CredentialsForHostInIRequestContext credentialsFromProxyConfig      = proxyPanelViewModel.ExtractMainProxyCredentialsFromProxyConfig(settings.ProxyConfig);
            List <ProxyPanelViewModel.ProxyForBookmakerData> proxyForBookmakers = proxyPanelViewModel.ExtractProxyForBookmakers(settings.UserSettings.BookmakersList);

            foreach (Api allApi in Api.AllApis)
            {
                RequestHandler innerHandler = allApi.Request.GetInnerHandler();
                innerHandler?.AddProxyDataCredentials(credentialsFromProxyConfig);
                if (settings.ProxyConfig.CurrentProxy.HeaderAuth != null && innerHandler != null)
                {
                    innerHandler.AddCutomRequestHeader(settings.ProxyConfig.CurrentProxy.HeaderAuth);
                }
            }
            ProxyForChrome proxy;

            if (proxyForBookmakers.Count > 0)
            {
                PacScript pacScript = new PacScript(proxyFromProxyConfig);
                foreach (ProxyPanelViewModel.ProxyForBookmakerData forBookmakerData in proxyForBookmakers)
                {
                    pacScript.AddNewProxyForHost(forBookmakerData.Host, forBookmakerData.Proxy);
                    if (forBookmakerData.IsNeedCredentials)
                    {
                        foreach (Api allApi in Api.AllApis)
                        {
                            allApi.Request.StopLoadingOnce();
                            allApi.Request.GetInnerHandler()?.AddProxyDataCredentials(forBookmakerData.Credentials);
                        }
                    }
                }
                proxy = (ProxyForChrome)pacScript;
            }
            else
            {
                proxy = proxyFromProxyConfig;
            }
            SetPreferenceRezult preferenceRezult = await Cef.GetGlobalRequestContext().SetProxy(proxy);

            if (!preferenceRezult.IsSuccess)
            {
                await proxyPanelViewModel.ShowErrorDialogAsync((BaseViewModel)proxyPanelViewModel._mainVm, "Прокси НЕ УСТАНОВЛЕН! " + preferenceRezult.ErrorMessage);
            }
            else
            {
                bool isClosed;
                try
                {
                    isClosed = await proxyPanelViewModel.CloseAllConnection(Cef.GetGlobalRequestContext());

                    int num = await proxyPanelViewModel.ClearAllConnectionErrors(Cef.GetGlobalRequestContext()) ? 1 : 0;
                }
                catch (Exception ex)
                {
                    isClosed = false;
                }
                if (!isClosed)
                {
                    await proxyPanelViewModel.ShowMessageDialogAsync((BaseViewModel)proxyPanelViewModel._mainVm, "Предупреждение", "Перезапустите программу, что бы корректно закрыть все соединения или попробуйте еще раз сохранить!");
                }
                if (!loadTestPage)
                {
                    return;
                }
                await Task.Delay(TimeSpan.FromMilliseconds(500.0));

                proxyPanelViewModel._workerOne?.LoadPage("https://2ip.ru");
                proxyPanelViewModel._workerTwo?.LoadPage("https://yandex.ru/internet");
            }
        }