public BindingMetadata(string widgetName, string bindingProperty, BindingOptions options, string bindingPath)
 {
     _widgetName = widgetName;
     _widgetBindingProperty = bindingProperty;
     _bindingOptions = options;
     _bindingPath = bindingPath;
 }
예제 #2
0
 /// <summary>
 /// <para>Asynchronously registers a Javascript object in this specific browser instance.</para>
 /// <para>Only methods of the object will be availabe.</para>
 /// </summary>
 /// <param name="name">The name of the object. (e.g. "foo", if you want the object to be accessible as window.foo).</param>
 /// <param name="objectToBind">The object to be made accessible to Javascript.</param>
 /// <param name="options">binding options - camelCaseJavascriptNames default to true </param>
 /// <exception cref="System.Exception">Browser is already initialized. RegisterJsObject must be +
 ///                                     called before the underlying CEF browser is created.</exception>
 /// <remarks>The registered methods can only be called in an async way, they will all return immeditaly and the resulting
 /// object will be a standard javascript Promise object which is usable to wait for completion or failure.</remarks>
 public void RegisterAsyncJsObject(string name, object objectToBind, BindingOptions options = null)
 {
     if (IsBrowserInitialized)
     {
         throw new Exception("Browser is already initialized. RegisterJsObject must be" +
                             "called before the underlying CEF browser is created.");
     }
     managedCefBrowserAdapter.RegisterAsyncJsObject(name, objectToBind, options);
 }
예제 #3
0
 public void Register(string name, object value, BindingOptions options)
예제 #4
0
 public void AddBinding(MockSite site, BindingOptions bindingOptions) => site.Bindings.Add(new MockBinding(bindingOptions));
예제 #5
0
        private MessageConverterConfigurer CreateConverterConfigurer(string channelName, BindingOptions bindingProperties)
        {
            var bindingServiceProperties = new BindingServiceOptions();

            bindingServiceProperties.Bindings.Add(channelName, bindingProperties);
            var applicationContext = GetBinder().ApplicationContext;

            var extractors = applicationContext.GetServices <IPartitionKeyExtractorStrategy>();
            var selectors  = applicationContext.GetServices <IPartitionSelectorStrategy>();
            var bindingServiceOptionsMonitor = new BindingServiceOptionsMonitor(bindingServiceProperties);

            MessageConverterConfigurer messageConverterConfigurer = new MessageConverterConfigurer(applicationContext, bindingServiceOptionsMonitor, new CompositeMessageConverterFactory(), extractors, selectors);

            return(messageConverterConfigurer);
        }
 public void Register(string name, object value, BindingOptions options)
 {
     RootObject.MemberObjects.Add(CreateInternal(name, value, analyseProperties: true, options: options));
 }
예제 #7
0
        public bool RegisterJavascriptObject(string name, object objectToBind, Func <Func <object>, object> interceptCall = null, Func <object, Type, object> bind = null, bool executeCallsInUI = false)
        {
            if (this.chromium.JavascriptObjectRepository.IsBound(name))
            {
                return(false);
            }
            if (executeCallsInUI)
            {
                Func <Func <object>, object> interceptCall2 = (target) => this.Invoke(target);
                return(this.RegisterJavascriptObject(name, objectToBind, interceptCall2, bind, false));
            }
            BindingOptions bindingOptions = new BindingOptions();

            if (bind != null)
            {
                bindingOptions.Binder = new LambdaMethodBinder(bind);
            }
            else
            {
                bindingOptions.Binder = this.binder;
            }
            Func <Func <object>, object> interceptCall3;

            if (interceptCall != null)
            {
                interceptCall3 = delegate(Func <object> target)
                {
                    if (this.isDisposing)
                    {
                        return(null);
                    }
                    object result;
                    try
                    {
                        this.javascriptPendingCalls++;
                        result = interceptCall(target);
                    }
                    finally
                    {
                        this.javascriptPendingCalls--;
                    }
                    return(result);
                };
            }
            else
            {
                interceptCall3 = delegate(Func <object> target)
                {
                    if (this.isDisposing)
                    {
                        return(null);
                    }
                    object result;
                    try
                    {
                        this.javascriptPendingCalls++;
                        result = target();
                    }
                    finally
                    {
                        this.javascriptPendingCalls--;
                    }
                    return(result);
                };
            }
            bindingOptions.MethodInterceptor = new LambdaMethodInterceptor(interceptCall3);
            this.chromium.JavascriptObjectRepository.Register(name, objectToBind, true, bindingOptions);
            return(true);
        }
예제 #8
0
 public DataBinding(string propertyPath, BindingOptions bindingOptions,
                    List <IValidatorProvider> validationRules, bool oneWay)
     : this(propertyPath, bindingOptions, validationRules, null, oneWay)
 {
 }
예제 #9
0
 public void RegisterJsObject(string name, object objectToBind, BindingOptions options = null)
 {
     chromeBrowser.RegisterJsObject(name, objectToBind);
 }
 public void RegisterAsync(string name, object value, BindingOptions options)
 {
     AsyncRootObject.MemberObjects.Add(CreateInternal(name, value, analyseProperties: false, options: options));
 }
        private JavascriptObject CreateInternal(string name, object value, bool analyseProperties, BindingOptions options)
        {
            var camelCaseJavascriptNames = options == null ? true : options.CamelCaseJavascriptNames;
            var jsObject = CreateJavascriptObject(camelCaseJavascriptNames);
            jsObject.Value = value;
            jsObject.Name = name;
            jsObject.JavascriptName = name;
            jsObject.Binder = options == null ? null : options.Binder;

            AnalyseObjectForBinding(jsObject, analyseMethods: true, analyseProperties: analyseProperties, readPropertyValue: false, camelCaseJavascriptNames: camelCaseJavascriptNames);

            return jsObject;
        }
        public void BindObject(IBindableWrapper bObject, string path, string widgetProperty, BindingOptions options)
        {
            _widgetBindingProperty = widgetProperty;
            _bindableObject = bObject;
            _bindingOptions = options;
            _bindableObject.PropertyChanged += OnPropertyChanged;

            string[] pathArray = path.Split('.');
            _boPropertyName = pathArray[pathArray.Length -1]; // the last element of the path is the property
            // now get the object whose property we've got
            if (pathArray.Length == 1)
            {
                _propertyOwner = bObject;
            }
            else
            {
                // the first element of the path have to be a property of the bObject
                int i = 0;
                PropertyInfo prop = bObject.GetType().GetProperty(pathArray[0]);
                _propertyOwner = prop.GetValue(bObject, null);
                while (pathArray.Length -2 > i)
                {
                    i++;
                    prop = _propertyOwner.GetType().GetProperty(pathArray[i]);
                    _propertyOwner = prop.GetValue(_propertyOwner, null); // try this with indexed properties!
                    _boBindingProperty = _propertyOwner.GetType().GetProperty(_boPropertyName);
                }
            }
            Logger.GetInstance().WriteLine("Property owner= " + _propertyOwner);
            Logger.GetInstance().WriteLine("bo binding property = " + _boBindingProperty.Name);
            // read the value of the property for the first time
            OnPropertyChanged(this, new PropertyChangedEventArgs(_boPropertyName));
        }
        public void BindObject(IBindableWrapper bObject, object propertyOwner, 
		                       string bindingProperty, string widgetProperty, BindingOptions options)
        {
            _widgetBindingProperty = widgetProperty;
            _bindableObject = bObject;
            _propertyOwner = propertyOwner;
            _boBindingProperty = propertyOwner.GetType().GetProperty(bindingProperty);
            _boPropertyName = bindingProperty;
            if (_boBindingProperty == null)
            {
                throw new NullReferenceException("Error binding object. Property " + bindingProperty + " doesn't exist");
            }
            Logger.GetInstance().WriteLine("Binding Object property:" + _boBindingProperty.Name);
            _bindableObject.PropertyChanged += OnPropertyChanged;
            _bindingOptions = options;
        }
 public override int GetHashCode()
 {
     return(BindingOptions.GetHashCode());
 }
 public DirectBinding(BindingOptions bindingOptions, List <IValidatorProvider> validationRules)
     : this(bindingOptions, validationRules, null)
 {
 }
 public DirectBinding(BindingOptions bindingOptions)
     : this(bindingOptions, null, null)
 {
 }
예제 #17
0
 public DataBinding(string propertyPath, BindingOptions bindingOptions)
     : this(propertyPath, bindingOptions, null, null, false)
 {
 }
예제 #18
0
파일: IIS.cs 프로젝트: skyhoshi/win-acme
        Task <bool> IInstallationPlugin.Install(
            Target source,
            IEnumerable <IStorePlugin> stores,
            CertificateInfo newCertificate,
            CertificateInfo?oldCertificate)
        {
            // Store validation
            var centralSslForHttp = false;
            var centralSsl        = stores.FirstOrDefault(x => x is CentralSsl);
            var certificateStore  = stores.FirstOrDefault(x => x is CertificateStore);

            if (centralSsl == null && certificateStore == null)
            {
                // No supported store
                var errorMessage = "The IIS installation plugin requires the CertificateStore and/or CentralSsl store plugin";
                _log.Error(errorMessage);
                throw new InvalidOperationException(errorMessage);
            }

            // Determine site types
            foreach (var part in source.Parts)
            {
                part.SiteId ??= _options.SiteId;
                part.SiteType ??= _iisClient.GetSite(part.SiteId !.Value).Type;
            }

            if (centralSsl != null)
            {
                centralSslForHttp = true;
                var supported = true;
                var reason    = "";
                if (_iisClient.Version.Major < 8)
                {
                    reason            = "CentralSsl store requires IIS version 8.0 or higher";
                    supported         = false;
                    centralSslForHttp = false;
                }
                if (source.Parts.Any(p => p.SiteType == IISSiteType.Ftp))
                {
                    reason    = "CentralSsl store is not supported for FTP sites";
                    supported = false;
                }
                if (!supported && certificateStore == null)
                {
                    // Only throw error if there is no fallback
                    // available to the CertificateStore plugin.
                    _log.Error(reason);
                    throw new InvalidOperationException(reason);
                }
            }

            foreach (var part in source.Parts)
            {
                var httpIdentifiers = part.Identifiers.OfType <DnsIdentifier>();
                var bindingOptions  = new BindingOptions();

                // Pick between CentralSsl and CertificateStore
                bindingOptions = centralSslForHttp
                    ? bindingOptions.
                                 WithFlags(SSLFlags.CentralSsl)
                    : bindingOptions.
                                 WithThumbprint(newCertificate.Certificate.GetCertHash()).
                                 WithStore(newCertificate.StoreInfo[typeof(CertificateStore)].Path);

                switch (part.SiteType)
                {
                case IISSiteType.Web:
                    // Optionaly overrule the standard IP for new bindings
                    if (!string.IsNullOrEmpty(_options.NewBindingIp))
                    {
                        bindingOptions = bindingOptions.
                                         WithIP(_options.NewBindingIp);
                    }
                    // Optionaly overrule the standard port for new bindings
                    if (_options.NewBindingPort > 0)
                    {
                        bindingOptions = bindingOptions.
                                         WithPort(_options.NewBindingPort.Value);
                    }
                    bindingOptions = bindingOptions.WithSiteId(part.SiteId !.Value);
                    _iisClient.UpdateHttpSite(httpIdentifiers, bindingOptions, oldCertificate?.Certificate.GetCertHash(), newCertificate.SanNames);
                    if (certificateStore != null)
                    {
                        _iisClient.UpdateFtpSite(0, newCertificate, oldCertificate);
                    }
                    break;

                case IISSiteType.Ftp:
                    // Update FTP site
                    _iisClient.UpdateFtpSite(part.SiteId !.Value, newCertificate, oldCertificate);
                    _iisClient.UpdateHttpSite(httpIdentifiers, bindingOptions, oldCertificate?.Certificate.GetCertHash(), newCertificate.SanNames);
                    break;

                default:
                    _log.Error("Unknown site type");
                    break;
                }
            }

            return(Task.FromResult(true));
        }
예제 #19
0
 public DataBinding(string propertyPath, BindingOptions bindingOptions,
                    List <IValidatorProvider> validationRules, string valueConverter)
     : this(propertyPath, bindingOptions, validationRules, valueConverter, false)
 {
 }
예제 #20
0
        public BrowserTabView()
        {
            InitializeComponent();

            browser.RequestHandler = new RequestHandler();
            browser.RegisterJsObject("bound", new BoundObject(), BindingOptions.DefaultBinder);
            var bindingOptions = new BindingOptions()
            {
                Binder            = BindingOptions.DefaultBinder.Binder,
                MethodInterceptor = new MethodInterceptorLogger() // intercept .net methods calls from js and log it
            };

            browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject(), bindingOptions);
            // Enable touch scrolling - once properly tested this will likely become the default
            //browser.IsManipulationEnabled = true;

            browser.DisplayHandler     = new DisplayHandler();
            browser.LifeSpanHandler    = new LifespanHandler();
            browser.MenuHandler        = new MenuHandler();
            browser.GeolocationHandler = new GeolocationHandler();
            var downloadHandler = new DownloadHandler();

            downloadHandler.OnBeforeDownloadFired  += OnBeforeDownloadFired;
            downloadHandler.OnDownloadUpdatedFired += OnDownloadUpdatedFired;
            browser.DownloadHandler = downloadHandler;

            //Read an embedded bitmap into a memory stream then register it as a resource you can then load custom://cefsharp/images/beach.jpg
            var beachImageStream = new MemoryStream();

            CefSharp.Example.Properties.Resources.beach.Save(beachImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            browser.RegisterResourceHandler(CefExample.BaseUrl + "/images/beach.jpg", beachImageStream, ResourceHandler.GetMimeType(".jpg"));

            var dragHandler = new DragHandler();

            dragHandler.RegionsChanged += OnDragHandlerRegionsChanged;

            browser.DragHandler = dragHandler;
            //browser.ResourceHandlerFactory = new InMemorySchemeAndResourceHandlerFactory();
            //You can specify a custom RequestContext to share settings amount groups of ChromiumWebBrowsers
            //Also this is now the only way to access OnBeforePluginLoad - need to implement IRequestContextHandler
            //browser.RequestContext = new RequestContext(new RequestContextHandler());
            //NOTE - This is very important for this example as the default page will not load otherwise
            //browser.RequestContext.RegisterSchemeHandlerFactory(CefSharpSchemeHandlerFactory.SchemeName, null, new CefSharpSchemeHandlerFactory());

            //You can start setting preferences on a RequestContext that you created straight away, still needs to be called on the CEF UI thread.
            //Cef.UIThreadTaskFactory.StartNew(delegate
            //{
            //    string errorMessage;
            //    //Use this to check that settings preferences are working in your code

            //    var success = browser.RequestContext.SetPreference("webkit.webprefs.minimum_font_size", 24, out errorMessage);
            //});

            browser.RenderProcessMessageHandler = new RenderProcessMessageHandler();

            browser.LoadError += (sender, args) =>
            {
                // Don't display an error for downloaded files.
                if (args.ErrorCode == CefErrorCode.Aborted)
                {
                    return;
                }

                // Don't display an error for external protocols that we allow the OS to
                // handle. See OnProtocolExecution().
                //if (args.ErrorCode == CefErrorCode.UnknownUrlScheme)
                //{
                //	var url = args.Frame.Url;
                //	if (url.StartsWith("spotify:"))
                //	{
                //		return;
                //	}
                //}

                // Display a load error message.
                var errorBody = string.Format("<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>",
                                              args.FailedUrl, args.ErrorText, args.ErrorCode);

                args.Frame.LoadStringForUrl(errorBody, args.FailedUrl);
            };

            CefExample.RegisterTestResources(browser);
        }
예제 #21
0
파일: WebView.cs 프로젝트: uvbs/WebView
        /// <summary>
        /// Registers an object with the specified name in the window context of the browser
        /// </summary>
        /// <param name="name"></param>
        /// <param name="objectToBind"></param>
        /// <param name="interceptCall"></param>
        /// <param name="bind"></param>
        /// <param name="executeCallsInUI"></param>
        /// <returns>True if the object was registered or false if the object was already registered before</returns>
        public bool RegisterJavascriptObject(string name, object objectToBind, Func <Func <object>, object> interceptCall = null, Func <object, Type, object> bind = null, bool executeCallsInUI = false)
        {
            if (chromium.JavascriptObjectRepository.IsBound(name))
            {
                return(false);
            }

            if (executeCallsInUI)
            {
                Func <Func <object>, object> interceptorWrapper = target => Dispatcher.Invoke(target);
                return(RegisterJavascriptObject(name, objectToBind, interceptorWrapper, bind, false));
            }
            else
            {
                var bindingOptions = new BindingOptions();
                if (bind != null)
                {
                    bindingOptions.Binder = new LambdaMethodBinder(bind);
                }
                else
                {
                    bindingOptions.Binder = binder;
                }

                Func <Func <object>, object> interceptorWrapper;
                if (interceptCall != null)
                {
                    interceptorWrapper = target => {
                        if (isDisposing)
                        {
                            return(null);
                        }
                        try {
                            javascriptPendingCalls++;
                            return(interceptCall(target));
                        } finally {
                            javascriptPendingCalls--;
                        }
                    };
                }
                else
                {
                    interceptorWrapper = target => {
                        if (isDisposing)
                        {
                            return(null);
                        }
                        try {
                            javascriptPendingCalls++;
                            return(target());
                        } finally {
                            javascriptPendingCalls--;
                        }
                    };
                }
                bindingOptions.MethodInterceptor = new LambdaMethodInterceptor(interceptorWrapper);
                chromium.JavascriptObjectRepository.Register(name, objectToBind, true, bindingOptions);
            }

            return(true);
        }
예제 #22
0
        public MainWindow()
        {
            InitializeComponent();
            fileSystem.save = false;
            newProjectcheck = false;


            //giving fs the mainwindow instance so it can use it to load any files
            fs.mw = this;
            //Initializing a CSS Property Box Class
            cpb = new cssPropertyBox(htmlTextBox, csstextBox, MainWindowBrowser);

            //CSS Property Box Combo Box Sub
            BorderType.SelectionChanged += new SelectionChangedEventHandler(cssPropertyBox_ComboBox_SelectionChanged);

            FloatProperty.SelectionChanged   += new SelectionChangedEventHandler(cssPropertyBox_ComboBox_SelectionChanged);
            DisplayProperty.SelectionChanged += new SelectionChangedEventHandler(cssPropertyBox_ComboBox_SelectionChanged);

            FontFamily.SelectionChanged += new SelectionChangedEventHandler(cssPropertyBox_FontFamily_SelectionChanged);

            FontWeights.SelectionChanged += new SelectionChangedEventHandler(cssPropertyBox_ComboBox_SelectionChanged);

            FontStyle.SelectionChanged += new SelectionChangedEventHandler(cssPropertyBox_FontStyle_SelectionChanged);


            FontAlign.SelectionChanged      += new SelectionChangedEventHandler(cssPropertyBox_ComboBox_SelectionChanged);
            FontDecoration.SelectionChanged += new SelectionChangedEventHandler(cssPropertyBox_ComboBox_SelectionChanged);

            BackgroundPosition.SelectionChanged += new SelectionChangedEventHandler(cssPropertyBox_ComboBox_SelectionChanged);
            BackgroundRepeat.SelectionChanged   += new SelectionChangedEventHandler(cssPropertyBox_ComboBox_SelectionChanged);



            //CssPropertyBox
            ColumnXS.TextChanged += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            ColumnSM.TextChanged += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            ColumnMD.TextChanged += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            ColumnLG.TextChanged += new TextChangedEventHandler(cssPropertyBox_TextChanged);

            WidthProperty.TextChanged  += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            HeightProperty.TextChanged += new TextChangedEventHandler(cssPropertyBox_TextChanged);

            TopPadding.TextChanged    += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            BottomPadding.TextChanged += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            LeftPadding.TextChanged   += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            RightPadding.TextChanged  += new TextChangedEventHandler(cssPropertyBox_TextChanged);

            TopMargin.TextChanged    += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            BottomMargin.TextChanged += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            LeftMargin.TextChanged   += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            RightMargin.TextChanged  += new TextChangedEventHandler(cssPropertyBox_TextChanged);


            BorderSize.TextChanged += new TextChangedEventHandler(cssPropertyBox_TextChanged);
            FontSize.TextChanged   += new TextChangedEventHandler(cssPropertyBox_TextChanged);

            BackgroundUrl.TextChanged += new TextChangedEventHandler(cssPropertyBox_TextChanged);


            //Typing Assistant
            assistant                          = new TypeAssistant();
            assistant.Idled                   += assistant_Idled;
            cssPropertyBoxTypeAssistant        = new TypeAssistant();
            cssPropertyBoxTypeAssistant.Idled += cssPropertyBoxTypeAssistant_Idled;

            //Setting up Main Window Here
            //Using local drag and drop files (html css js) on a web browser

            //Getting the local js drag and drop files
            //string dndFiles = System.Windows.Forms.Application.StartupPath + @"\\dnd\album.html";
            Console.WriteLine(MainWindowBrowser.Address.Trim());
            if (MainWindowBrowser.Address.Trim().Equals("www.google.com"))
            {
                browserAddress = System.Windows.Forms.Application.StartupPath + @"\\dnd\dandd.html";
            }

            //MainWindowBrowser.Address = browserAddress;

            CefSharpSettings.ConcurrentTaskExecution = true;

            //For async object registration (equivalent to the old RegisterAsyncJsObject)

            dnd.mw        = this;
            dnd.setChange = true;
            MainWindowBrowser.JavascriptObjectRepository.ResolveObject += (sender, e) =>
            {
                var repo = e.ObjectRepository;
                if (e.ObjectName == "getHTMLfromjs")
                {
                    BindingOptions bindingOptions = null;          //Binding options is an optional param, defaults to null
                    bindingOptions = BindingOptions.DefaultBinder; //Use the default binder to serialize values into complex objects, CamelCaseJavascriptNames = true is the default
                    repo.Register("getHTMLfromjs", dnd, isAsync: true, options: bindingOptions);
                }
                else if (e.ObjectName == "getClassfromjs")
                {
                    BindingOptions bindingOptions = null;          //Binding options is an optional param, defaults to null
                    bindingOptions = BindingOptions.DefaultBinder; //Use the default binder to serialize values into complex objects, CamelCaseJavascriptNames = true is the default
                    repo.Register("getClassfromjs", dnd, isAsync: true, options: bindingOptions);
                }
            };
            MainWindowBrowser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender, e) =>
            {
                var name = e.ObjectName;

                Console.WriteLine($"Object {e.ObjectName} was bound successfully.");
            };



            SaveProject.IsEnabled   = false;
            csstextBoxLine.ReadOnly = true;

            //Wait for the page to finish loading (all resources will have been loaded, rendering is likely still happening)

            /*MainWindowBrowser.LoadingStateChanged += (sender, args) =>
             * {
             *  //Wait for the Page to finish loading
             *  if (args.IsLoading == false)
             *  {
             *      MainWindowBrowser.ShowDevTools();
             *  }
             * };*/

            ////setting csstextbox properties
            //System.Drawing.Color backtempcolor = System.Drawing.Color.FromArgb(0x2c2c2c); //Change hex color to rgb
            //csstextBoxLine.BackColor = System.Drawing.Color.FromArgb(backtempcolor.R, backtempcolor.G, backtempcolor.B);
            //csstextBox.Font = new System.Drawing.Font("Consolas, 'Courier New', monospace", 10);
            //csstextBoxLine.Font = new System.Drawing.Font("Consolas, 'Courier New', monospace", 10);

            ////setting htmltextbox Properties
            //htmlTextBoxLine.BackColor = System.Drawing.Color.FromArgb(backtempcolor.R, backtempcolor.G, backtempcolor.B);
            //htmlTextBox.Font = new System.Drawing.Font("Consolas, 'Courier New', monospace", 10);
            //htmlTextBoxLine.Font = new System.Drawing.Font("Consolas, 'Courier New', monospace", 10);
        }
        private JavascriptObject CreateInternal(string name, object value, bool analyseProperties, BindingOptions options)
        {
            var camelCaseJavascriptNames = options == null ? true : options.CamelCaseJavascriptNames;
            var jsObject = CreateJavascriptObject(camelCaseJavascriptNames);

            jsObject.Value             = value;
            jsObject.Name              = name;
            jsObject.JavascriptName    = name;
            jsObject.Binder            = options == null ? null : options.Binder;
            jsObject.MethodInterceptor = options == null ? null : options.MethodInterceptor;

            AnalyseObjectForBinding(jsObject, analyseMethods: true, analyseProperties: analyseProperties, readPropertyValue: false, camelCaseJavascriptNames: camelCaseJavascriptNames);

            return(jsObject);
        }
예제 #24
0
 public void BindObject(IBindableWrapper wrapper, object owner, string path, string widgetProperty, BindingOptions options)
 {
     _widgetCore.BindObject(wrapper, owner, path, widgetProperty, options);
 }
예제 #25
0
 protected DirectChannel CreateBindableChannel(string channelName, BindingOptions bindingProperties)
 {
     // The 'channelName.contains("input")' is strictly for convenience to avoid
     // modifications in multiple tests
     return(CreateBindableChannel(channelName, bindingProperties, channelName.Contains("input")));
 }
예제 #26
0
파일: Binding.cs 프로젝트: furesoft/FureOS
        public static void Bind <Tfirst, Tsecond>(UIProperty <Tfirst> first, UIProperty <Tsecond> second, BindingOptions opts)
        {
            if (opts.Mode == BindingMode.OneWay)
            {
                second.OnChanged += (e) =>
                {
                    object value = e;
                    if (opts.Converter != null)
                    {
                        value = opts.Converter.ConvertTo(e);
                    }

                    first.SetValue((Tfirst)value);
                };
            }
            else
            {
                //ToDo: fix endless call loop
                second.OnChanged += (e) =>
                {
                    first.SetValue((Tfirst)e);
                };
                first.OnChanged += (e) =>
                {
                    second.SetValue((Tsecond)e);
                };
            }
        }
예제 #27
0
        public BrowserTabView()
        {
            InitializeComponent();
            Debug.WriteLine("Debug BrowserTabView InitializeComponent");
            DataContextChanged += OnDataContextChanged;

            //browser.BrowserSettings.BackgroundColor = Cef.ColorSetARGB(0, 255, 255, 255);

            //Please remove the comments below to use the Experimental WpfImeKeyboardHandler.
            //browser.WpfKeyboardHandler = new WpfImeKeyboardHandler(browser);

            //Please remove the comments below to specify the color of the CompositionUnderline.
            //var transparent = Colors.Transparent;
            //var black = Colors.Black;
            //ImeHandler.ColorBKCOLOR = Cef.ColorSetARGB(transparent.A, transparent.R, transparent.G, transparent.B);
            //ImeHandler.ColorUNDERLINE = Cef.ColorSetARGB(black.A, black.R, black.G, black.B);

            browser.RequestHandler = new ExampleRequestHandler();

            var bindingOptions = new BindingOptions()
            {
                Binder            = BindingOptions.DefaultBinder.Binder,
                MethodInterceptor = new MethodInterceptorLogger() // intercept .net methods calls from js and log it
            };

            //To use the ResolveObject below and bind an object with isAsync:false we must set CefSharpSettings.WcfEnabled = true before
            //the browser is initialized.
#if !NETCOREAPP
            CefSharpSettings.WcfEnabled = true;
#endif

            //If you call CefSharp.BindObjectAsync in javascript and pass in the name of an object which is not yet
            //bound, then ResolveObject will be called, you can then register it
            browser.JavascriptObjectRepository.ResolveObject += (sender, e) =>
            {
                var repo = e.ObjectRepository;

                //When JavascriptObjectRepository.Settings.LegacyBindingEnabled = true
                //This event will be raised with ObjectName == Legacy so you can bind your
                //legacy objects
#if NETCOREAPP
                if (e.ObjectName == "Legacy")
                {
                    repo.Register("boundAsync", new AsyncBoundObject(), options: bindingOptions);
                }
                else
                {
                    if (e.ObjectName == "boundAsync")
                    {
                        repo.Register("boundAsync", new AsyncBoundObject(), options: bindingOptions);
                    }
                    else if (e.ObjectName == "boundAsync2")
                    {
                        repo.Register("boundAsync2", new AsyncBoundObject(), options: bindingOptions);
                    }
                }
#else
                if (e.ObjectName == "Legacy")
                {
                    repo.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder);
                    repo.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
                }
                else
                {
                    if (e.ObjectName == "bound")
                    {
                        repo.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder);
                    }
                    else if (e.ObjectName == "boundAsync")
                    {
                        repo.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
                    }
                    else if (e.ObjectName == "boundAsync2")
                    {
                        repo.Register("boundAsync2", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
                    }
                }
#endif
            };

            browser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender, e) =>
            {
                var name = e.ObjectName;

                Debug.WriteLine($"Object {e.ObjectName} was bound successfully.");
            };

            browser.DisplayHandler = new DisplayHandler();
            //This LifeSpanHandler implementaion demos hosting a popup in a ChromiumWebBrowser
            //instance, it's still considered Experimental
            //browser.LifeSpanHandler = new ExperimentalLifespanHandler();
            browser.MenuHandler = new MenuHandler();

            //Enable experimental Accessibility support
            browser.AccessibilityHandler         = new AccessibilityHandler(browser);
            browser.IsBrowserInitializedChanged += (sender, args) =>
            {
                if ((bool)args.NewValue)
                {
                    //Uncomment to enable support
                    //browser.GetBrowserHost().SetAccessibilityState(CefState.Enabled);
                }
            };

            var downloadHandler = new DownloadHandler();
            downloadHandler.OnBeforeDownloadFired  += OnBeforeDownloadFired;
            downloadHandler.OnDownloadUpdatedFired += OnDownloadUpdatedFired;
            browser.DownloadHandler = downloadHandler;
            browser.AudioHandler    = new AudioHandler();

            //Read an embedded bitmap into a memory stream then register it as a resource you can then load custom://cefsharp/images/beach.jpg
            var beachImageStream = new MemoryStream();
            CefSharp.Example.Properties.Resources.beach.Save(beachImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            browser.RegisterResourceHandler(CefExample.BaseUrl + "/images/beach.jpg", beachImageStream, Cef.GetMimeType("jpg"));

            var dragHandler = new DragHandler();
            dragHandler.RegionsChanged += OnDragHandlerRegionsChanged;

            browser.DragHandler = dragHandler;
            //browser.ResourceHandlerFactory = new InMemorySchemeAndResourceHandlerFactory();
            //You can specify a custom RequestContext to share settings amount groups of ChromiumWebBrowsers
            //Also this is now the only way to access OnBeforePluginLoad - need to implement IRequestContextHandler
            //browser.RequestContext = new RequestContext(new RequestContextHandler());
            //NOTE - This is very important for this example as the default page will not load otherwise
            //browser.RequestContext.RegisterSchemeHandlerFactory(CefSharpSchemeHandlerFactory.SchemeName, null, new CefSharpSchemeHandlerFactory());
            //browser.RequestContext.RegisterSchemeHandlerFactory("https", "cefsharp.example", new CefSharpSchemeHandlerFactory());

            //You can start setting preferences on a RequestContext that you created straight away, still needs to be called on the CEF UI thread.
            //Cef.UIThreadTaskFactory.StartNew(delegate
            //{
            //    string errorMessage;
            //    //Use this to check that settings preferences are working in your code

            //    var success = browser.RequestContext.SetPreference("webkit.webprefs.minimum_font_size", 24, out errorMessage);
            //});

            browser.RenderProcessMessageHandler = new RenderProcessMessageHandler();

            browser.LoadError += (sender, args) =>
            {
                // Don't display an error for downloaded files.
                if (args.ErrorCode == CefErrorCode.Aborted)
                {
                    return;
                }

                //Don't display an error for external protocols that we allow the OS to
                //handle in OnProtocolExecution().
                if (args.ErrorCode == CefErrorCode.UnknownUrlScheme && args.Frame.Url.StartsWith("mailto"))
                {
                    return;
                }

                // Display a load error message.
                var errorBody = string.Format("<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>",
                                              args.FailedUrl, args.ErrorText, args.ErrorCode);

                args.Frame.LoadHtml(errorBody, base64Encode: true);
            };

            CefExample.RegisterTestResources(browser);

            browser.JavascriptMessageReceived += OnBrowserJavascriptMessageReceived;
        }
        public void Register(string name, object value, bool isAsync, BindingOptions options)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            //Enable WCF if not already enabled - can only be done before the browser has been initliazed
            //if done after the subprocess won't be WCF enabled it we'll have to throw an exception
            if (!IsBrowserInitialized && !isAsync)
            {
                CefSharpSettings.WcfEnabled = true;
            }

            if (!CefSharpSettings.WcfEnabled && !isAsync)
            {
                throw new InvalidOperationException(@"To enable synchronous JS bindings set WcfEnabled true in CefSharpSettings before you create
                                                    your ChromiumWebBrowser instances.");
            }

            //Validation name is unique
            if (objects.Values.Count(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)) > 0)
            {
                throw new ArgumentException("Object already bound with name:" + name, name);
            }

            //Binding of System types is problematic, so we don't support it
            var type = value.GetType();

            if (type.IsPrimitive || type.BaseType.Namespace.StartsWith("System."))
            {
                throw new ArgumentException("Registering of .Net framework built in types is not supported, " +
                                            "create your own Object and proxy the calls if you need to access a Window/Form/Control.", "value");
            }

            IJavascriptNameConverter nameConverter = null;

            //If a custom name converter was provided we'll use that
            //as a preference
            if (options != null && options.NameConverter != null)
            {
                nameConverter = options.NameConverter;
            }
            else if (options == null || options.CamelCaseJavascriptNames)
            {
                nameConverter = new CamelCaseJavascriptNameConverter();
            }

            var jsObject = CreateJavascriptObject(rootObject: true, nameConveter: nameConverter);

            jsObject.Value             = value;
            jsObject.Name              = name;
            jsObject.JavascriptName    = name;
            jsObject.IsAsync           = isAsync;
            jsObject.Binder            = options?.Binder;
            jsObject.MethodInterceptor = options?.MethodInterceptor;

            AnalyseObjectForBinding(jsObject, analyseMethods: true, analyseProperties: !isAsync, readPropertyValue: false, nameConverter: nameConverter);
        }
예제 #29
0
        public BrowserTabView()
        {
            InitializeComponent();

            //browser.BrowserSettings.BackgroundColor = Cef.ColorSetARGB(0, 255, 255, 255);

            browser.RequestHandler = new ExampleRequestHandler();

            //See https://github.com/cefsharp/CefSharp/issues/2246 for details on the two different binding options
            if (CefSharpSettings.LegacyJavascriptBindingEnabled)
            {
                browser.RegisterJsObject("bound", new BoundObject(), options: BindingOptions.DefaultBinder);
            }
            else
            {
                //Objects can still be pre registered, they can also be registered when required, see ResolveObject below
                //browser.JavascriptObjectRepository.Register("bound", new BoundObject(), isAsync:false, options: BindingOptions.DefaultBinder);
            }

            var bindingOptions = new BindingOptions()
            {
                Binder            = BindingOptions.DefaultBinder.Binder,
                MethodInterceptor = new MethodInterceptorLogger() // intercept .net methods calls from js and log it
            };

            //See https://github.com/cefsharp/CefSharp/issues/2246 for details on the two different binding options
            if (CefSharpSettings.LegacyJavascriptBindingEnabled)
            {
                browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject(), options: bindingOptions);
            }
            else
            {
                //Objects can still be pre registered, they can also be registered when required, see ResolveObject below
                //browser.JavascriptObjectRepository.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
            }

            //To use the ResolveObject below and bind an object with isAsync:false we must set CefSharpSettings.WcfEnabled = true before
            //the browser is initialized.
            CefSharpSettings.WcfEnabled = true;

            //If you call CefSharp.BindObjectAsync in javascript and pass in the name of an object which is not yet
            //bound, then ResolveObject will be called, you can then register it
            browser.JavascriptObjectRepository.ResolveObject += (sender, e) =>
            {
                var repo = e.ObjectRepository;
                if (e.ObjectName == "boundAsync2")
                {
                    repo.Register("boundAsync2", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
                }
                else if (e.ObjectName == "bound")
                {
                    browser.JavascriptObjectRepository.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder);
                }
                else if (e.ObjectName == "boundAsync")
                {
                    browser.JavascriptObjectRepository.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
                }
            };

            browser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender, e) =>
            {
                var name = e.ObjectName;

                Debug.WriteLine($"Object {e.ObjectName} was bound successfully.");
            };

            browser.DisplayHandler       = new DisplayHandler();
            browser.LifeSpanHandler      = new LifespanHandler();
            browser.MenuHandler          = new MenuHandler();
            browser.AccessibilityHandler = new AccessibilityHandler();
            var downloadHandler = new DownloadHandler();

            downloadHandler.OnBeforeDownloadFired  += OnBeforeDownloadFired;
            downloadHandler.OnDownloadUpdatedFired += OnDownloadUpdatedFired;
            browser.DownloadHandler = downloadHandler;
            browser.AudioHandler    = new AudioHandler();

            //Read an embedded bitmap into a memory stream then register it as a resource you can then load custom://cefsharp/images/beach.jpg
            var beachImageStream = new MemoryStream();

            CefSharp.Example.Properties.Resources.beach.Save(beachImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            browser.RegisterResourceHandler(CefExample.BaseUrl + "/images/beach.jpg", beachImageStream, ResourceHandler.GetMimeType(".jpg"));

            var dragHandler = new DragHandler();

            dragHandler.RegionsChanged += OnDragHandlerRegionsChanged;

            browser.DragHandler = dragHandler;
            //browser.ResourceHandlerFactory = new InMemorySchemeAndResourceHandlerFactory();
            //You can specify a custom RequestContext to share settings amount groups of ChromiumWebBrowsers
            //Also this is now the only way to access OnBeforePluginLoad - need to implement IRequestContextHandler
            //browser.RequestContext = new RequestContext(new RequestContextHandler());
            //NOTE - This is very important for this example as the default page will not load otherwise
            //browser.RequestContext.RegisterSchemeHandlerFactory(CefSharpSchemeHandlerFactory.SchemeName, null, new CefSharpSchemeHandlerFactory());

            //You can start setting preferences on a RequestContext that you created straight away, still needs to be called on the CEF UI thread.
            //Cef.UIThreadTaskFactory.StartNew(delegate
            //{
            //    string errorMessage;
            //    //Use this to check that settings preferences are working in your code

            //    var success = browser.RequestContext.SetPreference("webkit.webprefs.minimum_font_size", 24, out errorMessage);
            //});

            browser.RenderProcessMessageHandler = new RenderProcessMessageHandler();

            browser.LoadError += (sender, args) =>
            {
                // Don't display an error for downloaded files.
                if (args.ErrorCode == CefErrorCode.Aborted)
                {
                    return;
                }

                // Don't display an error for external protocols that we allow the OS to
                // handle. See OnProtocolExecution().
                //if (args.ErrorCode == CefErrorCode.UnknownUrlScheme)
                //{
                //	var url = args.Frame.Url;
                //	if (url.StartsWith("spotify:"))
                //	{
                //		return;
                //	}
                //}

                // Display a load error message.
                var errorBody = string.Format("<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>",
                                              args.FailedUrl, args.ErrorText, args.ErrorCode);

                args.Frame.LoadHtml(errorBody, base64Encode: true);
            };

            CefExample.RegisterTestResources(browser);

            browser.JavascriptMessageReceived += OnBrowserJavascriptMessageReceived;
        }
예제 #30
0
        public void UpdatePiramid(string certificateHost, string[] ignoreBindings, string expectedBinding, SSLFlags flags)
        {
            var iis = new MockIISClient(log)
            {
                MockSites = new[] {
                    new MockSite()
                    {
                        Id       = piramidId,
                        Bindings = new List <MockBinding> {
                            new MockBinding()
                            {
                                IP       = DefaultIP,
                                Port     = 80,
                                Host     = "a.b.c.com",
                                Protocol = "http"
                            },
                            new MockBinding()
                            {
                                IP       = DefaultIP,
                                Port     = 80,
                                Host     = "*.b.c.com",
                                Protocol = "http"
                            },
                            new MockBinding()
                            {
                                IP       = DefaultIP,
                                Port     = 80,
                                Host     = "*.x.y.z.com",
                                Protocol = "http"
                            },
                            new MockBinding()
                            {
                                IP       = DefaultIP,
                                Port     = 80,
                                Host     = "*.c.com",
                                Protocol = "http"
                            },
                            new MockBinding()
                            {
                                IP       = DefaultIP,
                                Port     = 80,
                                Host     = "*.com",
                                Protocol = "http"
                            },
                            new MockBinding()
                            {
                                IP       = DefaultIP,
                                Port     = 80,
                                Host     = "",
                                Protocol = "http"
                            }
                        }
                    }
                }
            };

            var bindingOptions = new BindingOptions().
                                 WithSiteId(piramidId).
                                 WithIP(DefaultIP).
                                 WithPort(DefaultPort).
                                 WithStore(DefaultStore).
                                 WithThumbprint(newCert).
                                 WithFlags(flags);

            var piramidSite = iis.GetWebSite(piramidId);
            var originalSet = piramidSite.Bindings.Where(x => !ignoreBindings.Contains(x.Host)).ToList();

            piramidSite.Bindings = originalSet.ToList().OrderBy(x => Guid.NewGuid()).ToList();
            iis.AddOrUpdateBindings(new[] { certificateHost }, bindingOptions, scopeCert);

            var newBindings = piramidSite.Bindings.Except(originalSet);

            Assert.AreEqual(1, newBindings.Count());

            var newBinding = newBindings.First();

            Assert.AreEqual(expectedBinding, newBinding.Host);
        }
예제 #31
0
        /// <summary>
        /// Registers a Javascript object in this specific browser instance.
        /// </summary>
        /// <param name="name">The name of the object. (e.g. "foo", if you want the object to be accessible as window.foo).</param>
        /// <param name="objectToBind">The object to be made accessible to Javascript.</param>
        /// <param name="options">binding options - camelCaseJavascriptNames default to true </param>
        /// <exception cref="System.Exception">Browser is already initialized. RegisterJsObject must be +
        ///                                     called before the underlying CEF browser is created.</exception>
        public void RegisterJsObject(string name, object objectToBind, BindingOptions options = null)
        {
            if (IsBrowserInitialized)
            {
                throw new Exception("Browser is already initialized. RegisterJsObject must be" +
                                    "called before the underlying CEF browser is created.");
            }

            //Enable WCF if not already enabled
            CefSharpSettings.WcfEnabled = true;

            managedCefBrowserAdapter.RegisterJsObject(name, objectToBind, options);
        }
예제 #32
0
        public void Form2_Load()
        {
            // When Form2 is loaded
            string tmp1 = Path.GetTempFileName();

            File.Delete(tmp1);
            string[] tmp2 = tmp1.Split('\\');
            tmp2[tmp2.Length - 1] = "";
            string tmp = String.Join("\\", tmp2);

            tmp += "jc3mpuipackagesandbox\\";
            string appData = this.GetAppDataPath();

            if (!Directory.Exists(appData))
            {
                Directory.CreateDirectory(appData);
            }
            if (!Directory.Exists(tmp))
            {
                Directory.CreateDirectory(tmp);
            }
            this.pathToHomepage = appData + "homepage.html";
            this.pathToTempIAS  = tmp + "index.html";
            this.pathToTempAS   = tmp + "as.js";
            if (!File.Exists(this.pathToHomepage))
            {
                File.WriteAllText(this.pathToHomepage, Properties.Resources.home);
            }
            if (!File.Exists(this.pathToTempIAS) || File.ReadAllText(this.pathToTempIAS) != Properties.Resources.ias)
            {
                File.WriteAllText(this.pathToTempIAS, Properties.Resources.ias);
            }
            if (!File.Exists(this.pathToTempAS) || File.ReadAllText(this.pathToTempAS) != Properties.Resources._as)
            {
                File.WriteAllText(this.pathToTempAS, Properties.Resources._as);
            }
            this.aScripts = new AuxiliaryScripts(this);
            this.aScripts.Load();
            panel1.Size = new Size(this.ClientSize.Width, this.ClientSize.Height);

            this.SetURI(this.pathToHomepage);
            this.DefaultFormBorderStyle = this.FormBorderStyle;
            this.DefaultWindowState     = this.WindowState;

            CefSettings uiSettings = new CefSettings();

            uiSettings.RemoteDebuggingPort = 13173;
            BrowserSettings browserSettings = new BrowserSettings();

            browserSettings.BackgroundColor = ColorToUint(defaultColor);
            Cef.Initialize(uiSettings);

            ui = new ChromiumWebBrowser(this.uri);
            ui.BrowserSettings = browserSettings;
            panel1.Controls.Add(ui);
            ui.Dock = DockStyle.Fill;

            BindingOptions options = new BindingOptions();

            options.CamelCaseJavascriptNames = false;
            this.jcmp   = new JCMPNamespace(this, this.control);
            this.jcmpsc = new JCMPServerClient(this);
            ui.RegisterJsObject("jcmp", this.jcmp, options);

            this.as_ = new Form4(this);
            this.as_.Show();
        }