CoreWebView2.AddHostObjectToScript throws System.Exception - c#

CoreWebView2.AddHostObjectToScript throws System.Exception: 'The group or resource is not in the correct state to perform the requested operation.'
Version
SDK: 1.0.1245.22 latest stable - (and Microsoft.UI.Xaml 2.8.0-prerelease.210927001)
Runtime:
Framework: UWP
OS: Windows 11, build 22000
Reproduce Steps
Create an UWP project
Add necessary nuget packages (Microsoft.Web.Webview2 latest stable release and Microsoft.UI.Xaml 2.8.0-prerelease)
Add WebView2 component to MainPage.xaml
Create HostObject class with necessary tags
Add code for navigation starting or navigation completed method in WebView2 (MainPage.xaml.cs)
Ensure CoreWebView2 is not null by calling myWebView.EnsureCoreWebView2Async(); inside method
Try use myWebView.CoreWebView2.AddHostObjectToScript("HostObject", hostObject); inside method
(Also tried to make a new project uwp (as Windows Runtime Component) and create the HostObject class there but still same exception. In addition tried to change tags on HostObject class but still same issue)
Example of HostObject class:
[AllowForWeb]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class JsCallbacksUwp
{
public JsCallbacksUwp()
{
}
}
Example code for Navigation Completed that throws the exception:
private async void WebView2_NavigationCompleted(WebView2 sender, CoreWebView2NavigationCompletedEventArgs args)
{
await sender.EnsureCoreWebView2Async();
var browserHostObject = new JSCallbacksUwp();
sender.CoreWebView2.AddHostObjectToScript("HostObject", browserHostObject);
}

I got my answer from github's community at WebView2 Feedback.
Firstly i followed the guide that Syul968 showed me there which was:
The WinRT CoreWebView2 class (the one used by WinUI) tries to automatically create a "wrapper" when this is the case, but it needs a DispatchAdapter instance to be set through CoreWebView2Settings.HostObjectDispatchAdapter.
We have also been working on this feature lately. Our latest pre-release package (1.0.1248-prerelease) includes a tool, wv2winrt, to help project new and existing WinRT components: Call native-side WinRT code from web-side code
Secondly i followed the steps from david-risney answer:
Our current documentation only shows you how to do it for OS provided WinRT APIs and not for your own WinRT APIs. We need to fix this. Until then I would recommend following the existing directions from Call native-side WinRT code from web-side code, and then additionally doing the following:
Add a third project to your VS solution that implements your winrt class.
Have the WinRTAdapter project 'Add a reference' to your new third project containing your winrt class.
Update the WinRTAdapter project's Include filter to also include your new class.
Add an additional line to InitializeWebView2Async to add your winrt class's namespace
WebView2.CoreWebView2.AddHostObjectToScript("MyCustomNamespace",
dispatchAdapter.WrapNamedObject("MyCustomNamespace",
dispatchAdapter));
And optionally add your namespace sync proxy as a global object in script window.MyCustomNamespace =
chrome.webview.hostObjects.sync.MyCustomNamespace; You should then be able to use your type via script.
Lastly you can check my changes to my example.

Related

How to use class from other project in visual studio C#

I have a Xamarin.Forms project and a C# console app project. I want to use one class from the console app in my Xamarin.Forms project.
I added the console app project to the solutions explorer of the Xamarin.Forms project.
Unfortunately, I can't figure out how to use the class from the console app in one of the Xamarin files.
I always get the error message:
The name 'MyClass' does not exist in the current context.
I tried to press alt+enter to show potential fixes but it does not offer me the option of importing/using the class.
I also wrote manual using directives in various forms but it still does not seem to make the class accessible.
The only way I was able to use the class was by adding the class directly to the Xamarin project by adding it with add->existing item. The problem with this is that it imports a copy of the class. Since I'm still working on the class within the other project the added class is fast outdated and I have to manually copy its contents over.
How can I use a class from an external project without making a copy of the file?
Instead of access class from console app(its exe) try creating new reusable library add that class and use in both projects also you can write wrapper class in both projects
Try to add a reference to the second project in your first project. To do this, right-click on your project, select Add Reference then select the project in your solution. Once your main project references the second project, then you can access its public types.

dynamic in android xamarin

i have seen in the link below:
Can execute Code Dynamically in monotouch?
that it is impossible to use dynamic in ios xamarin. how about in Andoid xamarin?
I tried to do the following:
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
However, when I want to access MyDinamic.A, it says that Unknown Member: A.
Can someone please help? Thanks.
Edit:I also have added the Microsoft.Csharp dll in the solution reference as per the screenshot:
I'm not sure which IDE did you use for developing your xamarin android app, by my side I used VS2015, and the error is
Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
This is because when use the dynamic keyword in your project. The assembly contains the C# runtime binder. To solve this issue, we need to add reference to Microsoft.CSharp library(Microsoft.CSharp.dll) in our project:
After adding this reference, your code runs well by my side.
But I'm not sure if the Xamarin.Android will limit the use of dynamic object, through I didn't find any limitation in xamarin's official document. For more information about dynamic object, you can refer to:
System.Dynamic.DynamicObject Class
System.Dynamic.ExpandoObject Class
Go to NuGet Package Manager > Manage NuGet packages menu. Then change Source to Microsoft Visual Studio Offline Packages. After adding, it should compile successfully.

Roslyn throws The language 'C#' is not supported

I have created a class library project and did some processing and also used Roslyn to generate code.
I use the library in a WPF GUI application as a reference.
These are the NuGet packages:
Build shows no error, however when I use the following code:
private static void GetGenerator()
{
workspace = new AdhocWorkspace();
generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);
}
I get an exception:
"The language 'C#' is not supported."
at: Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetLanguageServices(String languageName)
at: Microsoft.CodeAnalysis.Host.Mef.MefWorkspaceServices.GetLanguageServices(String languageName)
at: Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetGenerator(Workspace workspace, String language)
According to this and this, I have to copy the CodeAnalysis files locally and add the necessary references. They are there, yet the error occurs.
Is this still a bug that wasn't fixed in the last year?
What else should I do?
Most likely it's because you don't reference Microsoft.CodeAnalysis.CSharp.Workspaces in your code, i.e. you never use a type or method in this dll, so MSBuild thinks it's not needed (see e.g. this question).
So what you could do is e.g. add the following line somewhere in your class library project:
var _ = typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions);
Then MSBuild should copy Microsoft.CodeAnalysis.CSharp.Workspaces.dll over and everything should be fine. No need to reference the NuGet packages from all the other projects.
You have to add the Microsoft.CodeAnalysis package to both the class library project AND the referencing project as well.

Xamarin iOS Dependency services always return null object in iOS application

I use Xamarin Studio and work on iOS Dependency Services
Here I have tried to resolve the runtime issue in case of getting the object through dependency services.
We have tried the same in sample projects as below:
1) Created a PCL project and kept the interfaces there. Using Xamarin.Forms ver 1.2.2.6243.
2) Created an iOS class library (using classic API's) which has the implementation of above
interface.(references added for above)
3) Created an iOS project which is starting point and it has invoked the Dependency Service method
to get the object of implemented class. (references added for both of above)
4) Tried to get the object of above class and call some interface methods implemented in iOS library
project.
Results : I am getting runtime issue as Object returned every time by dependency services was null and not able to call any API’s implemented in iOS library.
Please suggest if we are missing any thing or done some thing wrong here.
put the attribute above namespace.
[assembly: Xamarin.Forms.Dependency(typeof (SQLite_iOS))]
namespace DataBinding.iOS
...
use the full name for 'Dependency', i.e. 'Xamarin.Forms.Dependency(...)'

DLL References into Application but not Class Library

I am trying to integrate the WeifenLuo.WinformsUI.Docking assembly into my application. To rule out external factors I created a new .Net 4 Winforms app and reference the DLL. Works fine.
I then created a .Net 4 Class Library and referenced the DLL. This this doesn't work and as soon as I try to use anything in that Docking namespace it won't compile.
To recap
C# Exe ---reference--> WeifenLuo.WinFormsUI.Docking.DockPanel.dll // OK
C# Class library ---reference--> WeifenLuo.WinFormsUI.Docking.DockPanel.dll // Not OK
I also have the WeifenLuo source and confirmed it's a class library referencing the same version of .Net. I tried adding a class library in their sample solution and referencing the WinForms project directly (not the result in assembly) and it still isn't linking properly.
Updating with Screenshot
You can't declare a private variable Inside a namespace.
Try the following code
namespace Test
{
public class Class1
{
private WeifenLuo.WinFormsUI.Docking.DockPanel dockPannel;
}
}
And if it still doesn't work, provide the error message.

Categories

Resources