Unable to run CefSharp in WPF Application

3,483 views
Skip to first unread message

Clayton Johnson

unread,
Aug 22, 2014, 4:59:26 AM8/22/14
to cefs...@googlegroups.com
Hey everyone, I really like the work that's happening with CefSharp and I am trying to use it within my application. I can build and run both the CefSharp.MinimalExample and the CefSharp.WpfExample and they are working flawlessly with no issues (I did have to run nuget restore but that was expected) (Also had to force x86 building).

I have used nuget "Install-Package CefSharp.Wpf -Pre" to install the packages and then used the code from CefSharp.MinimalExample to add a WebView into my application.
I have tried getting this to work for a while now, by reading this group and everything else I can find but I'm still not having any success. I got to the point where when my application loads it throws a System.AccessViolationException from within CefSharp.Core.dll.
Just so that we are on the same page and can hopefully figure out where it is I've gone wrong, I'll start from the beginning and provide the exact steps I am taking.

Step 1:
PM> Install-Package CefSharp.Wpf -Pre
Attempting to resolve dependency 'CefSharp.Common (= 31.0.0-pre1)'.
Attempting to resolve dependency 'cef.redist (≥ 3.1650.1562-pre3 && < 3.1651)'.
Installing 'cef.redist 3.1650.1562-pre3'.
Successfully installed 'cef.redist 3.1650.1562-pre3'.
Installing 'CefSharp.Common 31.0.0-pre1'.
Successfully installed 'CefSharp.Common 31.0.0-pre1'.
Installing 'CefSharp.Wpf 31.0.0-pre1'.
Successfully installed 'CefSharp.Wpf 31.0.0-pre1'.
Adding 'cef.redist 3.1650.1562-pre3' to AppView.
Successfully added 'cef.redist 3.1650.1562-pre3' to AppView.
Adding 'CefSharp.Common 31.0.0-pre1' to AppView.
Successfully added 'CefSharp.Common 31.0.0-pre1' to AppView.
Adding 'CefSharp.Wpf 31.0.0-pre1' to AppView.
Successfully added 'CefSharp.Wpf 31.0.0-pre1' to AppView.

Then I have made classes based on the CefSharp.MinimalExample PropertyChangedExtensionMethods and MainViewModel
My PropertyChangedExtensionMethods.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;

namespace NetUML
{
    public static class PropertyChangedExtensionMethods
    {
        public static bool ChangeAndNotify<T>(this PropertyChangedEventHandler handler,
             ref T field, T value, Expression<Func<T>> memberExpression)
        {
            if (memberExpression == null)
            {
                throw new ArgumentNullException("memberExpression");
            }

            var body = memberExpression.Body as MemberExpression;
            if (body == null)
            {
                throw new ArgumentException("Lambda must return a property.");
            }

            if (EqualityComparer<T>.Default.Equals(field, value))
            {
                return false;
            }

            field = value;

            var vmExpression = body.Expression as ConstantExpression;
            if (vmExpression != null)
            {
                var lambda = Expression.Lambda(vmExpression);
                var vmFunc = lambda.Compile();
                var sender = vmFunc.DynamicInvoke();

                if (handler != null)
                {
                    handler(sender, new PropertyChangedEventArgs(body.Member.Name));
                }
            }

            return true;
        }
    }
}


and BrowserViewModel.cs
using CefSharp.Wpf;
using System.ComponentModel;
using System.Windows;

namespace NetUML.ViewModels
{
    public class BrowserViewModel
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private IWpfWebBrowser webBrowser;
        public IWpfWebBrowser WebBrowser
        {
            get { return webBrowser; }
            set { PropertyChanged.ChangeAndNotify(ref webBrowser, value, () => WebBrowser); }
        }

        private string title;
        public string Title
        {
            get { return title; }
            set { PropertyChanged.ChangeAndNotify(ref title, value, () => Title); }
        }

        public BrowserViewModel()
        {
            PropertyChanged += OnPropertyChanged;
        }

        private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Title")
            {
                Application.Current.MainWindow.Title = "CefSharp.MinimalExample.Wpf - " + Title;
            }
        }
    }
}



My UserControl XAML
<UserControl x:Class="NetUML.View.UserControls.ModellingPane"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:cefSharp="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <cefSharp:WebView Grid.Row="0"
                          Address="http://www.google.com"
                          WebBrowser="{Binding WebBrowser, Mode=OneWayToSource}"
                          Title="{Binding Title, Mode=TwoWay}" />
        <StatusBar Grid.Row="1">
            <ProgressBar HorizontalAlignment="Right"
                         IsIndeterminate="{Binding WebBrowser.IsLoading}"
                         Width="100"
                         Height="16"
                         Margin="3" />
            <Separator />
            <!-- TODO: Could show hover link URL here -->
            <TextBlock />
        </StatusBar>
    </Grid>
</UserControl>

and it's Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

using CefSharp;

using NetUML.ViewModels;

namespace NetUML.View.UserControls
{
    public partial class ModellingPane : UserControl
    {
        public ModellingPane()
        {
            InitializeComponent();
            DataContext = new BrowserViewModel();
        }
    }
}

Ran it in Debug using x86








And this is the output folder with all of the files. The first time I tried I didn't have CefSharp.Core.dll and that was a problem.




















And the StackTace:
at CefSharp.Internals.ClientAdapter.GetCefBrowser(ClientAdapter* , CefRefPtr<CefBrowser>* )
at CefSharp.Internals.RenderClientAdapter.TryGetCefMainFrame(RenderClientAdapter* , CefRefPtr<CefFrame>* )
at CefSharp.ManagedCefBrowserAdapter.LoadUrl(String address)
at CefSharp.Wpf.WebView.OnAddressChanged(String oldValue, String newValue)
at CefSharp.Wpf.WebView.OnAddressChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
at System.Windows.Baml2006.WpfMemberInvoker.SetValue(Object instance, Object value)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
at System.Xaml.XamlObjectWriter.Logic_ApplyPropertyValue(ObjectWriterContext ctx, XamlMember prop, Object value, Boolean onParent)
at System.Xaml.XamlObjectWriter.Logic_DoAssignmentToParentProperty(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.WriteEndMember()
at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at NetUML.View.UserControls.ModellingPane.InitializeComponent() 
in c:\\Users\\Clayton Johnson\\Documents\\Programming\\netuml\\NetUML\\NetUML\\View\\UserControls\\ModellingPane.xaml:line 1
at NetUML.View.UserControls.ModellingPane..ctor() 
in c:\\Users\\Clayton Johnson\\Documents\\Programming\\netuml\\NetUML\\NetUML\\View\\UserControls\\ModellingPane.xaml.cs:line 21




So that was pretty long and I greatly appreciate anyone who takes the times to read this and provide me with any advice that can help me get this working because I really want to use CefSharp in my application but I just can't get it to work.
On another note, occasionally and I mean very occasionally it will load but nothing will display on the page.

Jørn Hansen

unread,
Aug 23, 2014, 10:16:13 AM8/23/14
to cefs...@googlegroups.com
On Friday, August 22, 2014 6:59:26 AM UTC+2, Clayton Johnson wrote:
> Hey everyone, I really like the work that's happening with CefSharp and I am trying to use it within my application. I can build and run both the CefSharp.MinimalExample and the CefSharp.WpfExample and they are working flawlessly with no issues (I did have to run nuget restore but that was expected) (Also had to force x86 building).
>
> I have used nuget "Install-Package CefSharp.Wpf -Pre" to install the packages and then used the code from CefSharp.MinimalExample to add a WebView into my application.
> I have tried getting this to work for a while now, by reading this group and everything else I can find but I'm still not having any success. I got to the point where when my application loads it throws a System.AccessViolationException from within CefSharp.Core.dll.
> Just so that we are on the same page and can hopefully figure out where it is I've gone wrong, I'll start from the beginning and provide the exact steps I am taking.
>

Hi and welcome to CefSharp. First of all thanks for posting such a thorough but still easy to read description of what you tried. It makes it a lot easier to try to give an answer :-)

Your thorough question actually works like the DIY version of the MinimalExample that I think CefSharp has been missing - so if the below fixes your issue it's one step closer to such a guide, that hopefully is useful to others in getting off the ground!

It looks like you could be missing a call to Cef.Initialize()

Like this:
https://github.com/cefsharp/CefSharp.MinimalExample/blob/58792baa5e710f1a379361056b35afa5928155ce/CefSharp.MinimalExample.Wpf/App.xaml.cs#L14

I don't think you actually need to pass in any settings. But as far as I know the Initialize() call is needed.

Best regards,
JornH
> And this is the output folder with all of the files. The first time I tried I didn't have CefSharp.Core.dll and that was a problem.
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

Clayton Johnson

unread,
Aug 24, 2014, 2:09:32 AM8/24/14
to cefs...@googlegroups.com
Wow I can't believe I missed that, especially because I'm pretty sure the first time I tried getting it working I even had the call to Cef.Initialize().

Thanks for your quick reply. I'm glad that the detail I went to was enough to find the solution without much trouble. Since I will be using CefSharp a little more, if it would help out the community I would be more than happy to write up a explanation on how to get set up with their own application.

Regards,
Clayton

Jørn Hansen

unread,
Aug 24, 2014, 10:42:17 AM8/24/14
to cefs...@googlegroups.com

On Sunday, August 24, 2014 4:09:32 AM UTC+2, Clayton Johnson wrote:
Wow I can't believe I missed that, especially because I'm pretty sure the first time I tried getting it working I even had the call to Cef.Initialize().


No problem. It's always the needle in the haystack you have to look for and that's where it helps with an extra pair of eyes :-)
 
Thanks for your quick reply. I'm glad that the detail I went to was enough to find the solution without much trouble. Since I will be using CefSharp a little more, if it would help out the community I would be more than happy to write up a explanation on how to get set up with their own application.

It would be excellent if you could do that! Feel free to either add it as a wiki page (every GitHub user can edit it) or submit it as a pull request in either Markdown or HTML format (maybe as a section in the HTML embedded in the WPF/WinForms example applications) into the repository. Oh, BTW there *is* already one that is a somewhat outdated README.WPF.md in the root of the CefSharp repo, so maybe that's a good place to add/update. Though format and location is less important than having a good up-to-date Getting Started ...

It would really help to have an official version the community can help itself keep current compared to people trying to get CefSharp working based on different outdated blog posts.

And finally just ask if you are new to GitHub etc.!

Cheers,
JornH
 
Regards,
Clayton

Jørn Hansen

unread,
Aug 24, 2014, 10:55:30 AM8/24/14
to cefs...@googlegroups.com
Dear stupid Google Groups - why are you linkifying .md file names? I hope .pdf will never be a TLD ;-)

I was talking about this: https://github.com/cefsharp/CefSharp/blob/master/README.WPF.md *not* a website under the Moldova TLD.

Oh yes and be warned: That .md as of today *really* still is a mix of outdated info from CefSharp1 and a bit of new info relevant to CefSharp3 aka the current master branch.

/JornH
Reply all
Reply to author
Forward
0 new messages