Take picture with Windows 10, WinRT - c#

hope its something simple stupid, but I am spinning my wheels.
I have a Surface Pro 4, Windows 10 and using Visual Studio 2013 Professional.
Developing WPF using C# 4.5.
In summary, all I am trying to do a simple camera capture to save an image without resorting to other 3rd party libraries I have no control over. The rest of this post are details of other research findings that I HAVE looked into and tried working out and what has failed and what such message from the compiler.
Again, simple camera, capture picture, save to disk, but all the async-await options appear to throw compiler errors.
EDIT 1 SAMPLE CODE
Here is code from the WPF form. I do not even have any control in the form as I can not even get the 'await' to compile.
using System;
using Windows.Media.Capture;
using System.Windows;
namespace CameraCapture
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
JustDoIt();
}
private MediaCapture _mediaManager;
private async void JustDoIt()
{
//initialize mediacapture with default camera
_mediaManager = new MediaCapture();
await _mediaManager.InitializeAsync();
if (_mediaManager == null)
MessageBox.Show("Failed Initialize");
await _mediaManager.StartPreviewAsync();
}
}
}
And my project also has per other links researched from below, the dlls for
System.Runtime.dll and
System.Runtime.WindowsRuntime.dll
Compile error for each of the 'await'
Error 1 'await' requires that the type 'Windows.Foundation.IAsyncAction' have a suitable GetAwaiter method. Are you missing a using directive for 'System'?
and I have "using System;" as the first line. Is there some other "await" going on when using WinRT vs default System include?
END OF EDIT
I started with https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.capture.cameracaptureui.aspx
CameraCaptureUI class
I then found this link https://www.eternalcoding.com/?p=183
How to use specific WinRT API from Desktop apps
I tried going through all the steps as outlined and getting errors associated with
await ... have a suitable GetAwaiter method.
So, I looked up about asynch and await and came across
How and When to use `async` and `await`
how and when to use async and await.
So, I scrapped the first camera capture project, started a new, and did that version
that has simple thread.sleep delay to show the concept of asynch / await. That part works.
So now, I add back the reference to the project and manually edit to add the
<PropertyGroup>
<TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>
to expose the References expose the Windows / Core per the first link and then getting access to the Windows.Media, Windows.Storage. I add in just the first little bit of code about the CameraCaptureUI and CaptureFileAsync as just a starting point such as...
private async void Camera1()
{
var cameraUi = new Windows.Media.Capture.CameraCaptureUI();
var capturedMedia = await cameraUi.CaptureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.Video);
if (capturedMedia == null)
return;
MessageBox.Show("Valid Camera");
}
and get a compile error about:
'await' requires that the type
'Windows.Foundation.IAsyncOperation'
have a suitable GetAwaiter method.
Are you missing a using directive for 'System'?
Also, back to the original Windows version attempt via
private async void Camera2()
{
CameraCaptureUI dialog = new CameraCaptureUI();
Windows.Foundation.Size aspectRatio = new Windows.Foundation.Size(16, 9);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file == null)
return;
MessageBox.Show("Valid Storage File Captured");
}
I even have System.Runtime and System.RunTime.WindowsRuntime as references to the project but still fail on compile.
What am I missing. I know things change between different versions such as Windows 8.1 and Windows 10, and upgrades to features / libraries, but why await works one way, but not another.

For those scratching their heads as I did, I finally came across another post that had a missing link...
How can i import windows.media.capture in my WPF project?
The difference was the
<TargetPlatformVersion>8.1</TargetPlatformVersion>
instead of 8.0.
8.1 showed many of the individual .dll references of Foundation, Media, etc but not the single "Windows" dll.
Once changed to 8.1 and recognized the WINDOWS dll, all worked with respect to the media manager or CameraCaptureUI options.

Related

Reference to type error when adding the DotNetSeleniumExtras package extension

I'm creating a test automation framework in C# .Net using Appium to automate IOS and Android and wanted to use Page Object Design Pattern. So I wanted to utilize the PageFactory extension.
By adding the DotNetSeleniumExtras.PageObjects.Core as NuGet package results in an error (red squiggly lines). 4 errors
CS7069: Reference to type 'IFindsById" claims it is defined in 'WebDriver', but it could not be found.
I needed this extension DotNetSeleniumExtras.PageObjects.Core in order for me to instantiate the Page objects and be able to implement the Page Object Design pattern.
Please let me know if I'm missing something here or if there are any workarounds. Thanks in advance!
Below is my code for added context:
using NUnit.Framework;
using OpenQA.Selenium.Appium.iOS;
using OpenQA.Selenium.Appium.PageObjects;
using SeleniumExtras.PageObjects;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
namespace NativeApp_TestAutomation.Tests.Specs.IOS
{
[TestFixture]
public class LoginTest
{
private IOSDriver<IOSElement> _driver;
private HomeScreen _pageObject;
[OneTimeSetUp]
public void BeforeAll()
{
var capabilities = Capabilities.GetIOSCapabilities("");
var serverUri = Env.ServerIsRemote() ? AppiumServer.RemoteServerUri : AppiumServer.LocalServiceUri;
_driver = new IOSDriver<IOSElement>(serverUri, capabilities, Env.LaunchTimeoutSeconds);
var timeSpan = new TimeOutDuration(new TimeSpan(0, 0, 0, 5, 0));
_pageObject = new HomeScreen(_driver);
PageFactory.InitElements(_driver, _pageObject, new AppiumPageObjectMemberDecorator(timeSpan));
}
}
}
I'm getting the red squiggly lines here with all having the same errors.
One of the most common reasons for that is a mixture of version and assemblies because of different versions and their compatibility.
If you can try following steps the issues most likely would be solved:
Appium.net latest come out with dependency on DotNetSeleniumExtras.PageObjects v3.11.0 and WebDriver 3.141.0
DotNetSeleniumExtras.Core of v3.12.0 (do not use latest, target v3.12.0) come out with dependency on WebDriver 3.12.0
DotNetSeleniumExtras.PageObjects v3.11.0 rely on WebDriver 3.11.0
So by adding WebDriver 3.12.0 version conflict should be fixed.
This one is a simplest approach - if previous version have enough features then It's done and you can just wait for updates.
The second option that can help you is a binding redirects. The idea is pretty simple, you need to ensure that app know where your WebDriver and it is of correct version.
One good explanation is here (but believe me this is the last thing you want to do, fixed in one place become broken in another) Adding a bindingRedirect to a .Net Standard library

"Failed to initialize the [add-in name] because the assembly [path to an add-in DLL file] does not exist" when launching Revit

I've exhausted every resource possible and can not figure out what the issue is. Button images won't show & keep getting this message when I try to use the command.
Failed to initialize the [add-in name] because the assembly [path to an add-in DLL file] does not exist
when launching Revit. Here's my code that I'm using.
#region Namespaces
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.CSharp;
using System.Media;
using System.Reflection;
using System.IO.Packaging;
using System.Windows.Media.Imaging;
using System.Drawing.Imaging;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Architecture;
#endregion
namespace TpMechanical
{
internal class App : IExternalApplication
{
public Result OnStartup(UIControlledApplication a)
{
String tabname = "TpMechanical";
String panelname = "Tools";
//Option 1
BitmapImage b1Image = (System.Windows.Media.Imaging.BitmapImage)TpMechanical.Properties.Resources.ResourceManager.GetObject("_design3_fhY_icon.ico");
BitmapImage b2Image = (System.Windows.Media.Imaging.BitmapImage)TpMechanical.Properties.Resources.ResourceManager.GetObject("_design3_fhY_icon.ico");
BitmapImage b3Image = (System.Windows.Media.Imaging.BitmapImage)TpMechanical.Properties.Resources.ResourceManager.GetObject("_design3_fhY_icon.ico");
//Option 2
//Bitmap b1Image = (System.Drawing.Bitmap)(TpMechanical.Properties.Resources.ResourceManager.GetObject("Icon1.ico"));
//Bitmap b2Image = (System.Drawing.Bitmap)(TpMechanical.Properties.Resources.ResourceManager.GetObject("Image1.jpg"));
//Bitmap b3Image = (System.Drawing.Bitmap)(TpMechanical.Properties.Resources.ResourceManager.GetObject("Image2.bmp"));
//Option 3
//BitmapImage b1Image = new BitmapImage(new Uri("pack:application:,,,/TpMechanical/Resources/Icon1.ico"));
//BitmapImage b2Image = new BitmapImage(new Uri("pack:application:,,,/TpMechanical/Resources/Image1.jpg"));
//BitmapImage b3Image = new BitmapImage(new Uri("pack:application:,,,/TpMechanical/Resources/Image2.bmp"));
a.CreateRibbonTab(tabname);
var Tools = a.CreateRibbonPanel(tabname, panelname);
var button1 = new PushButtonData("TpButton1", "Button1", Assembly.GetExecutingAssembly().Location, "TpMechanical.command");
button1.ToolTip = " This is a short description";
button1.LongDescription = "This is a long description \n " +
"this is the second line";
var btn1 = Tools.AddItem(button1);
button1.Image = b1Image;
var button2 = new PushButtonData("TpButton2", "Button2", Assembly.GetExecutingAssembly().Location, "TpMechanical.command2");
button2.ToolTip = " This is a short description";
button2.LongDescription = "This is a long description \n " +
"this is the second line";
button2.Image = b2Image;
var button3 = new PushButtonData("TpButton3", "Button3", Assembly.GetExecutingAssembly().Location, "TpMechanical.command3");
button3.ToolTip = " This is a short description";
button3.LongDescription = "This is a long description \n " +
"this is the second line";
button3.Image = b3Image;
Tools.AddStackedItems(button2, button3);
return Result.Succeeded;
}
public Result OnShutdown(UIControlledApplication a)
{
return Result.Succeeded;
}
}
}
I also have my manifest code below.
<?xml version="1.0" encoding="utf-8"?>
<RevitAddIns>
<AddIn Type="Command">
<Text>Command TpMechanical</Text>
<Description>Some description for TpMechanical</Description>
<VisibilityMode>AlwaysVisible</VisibilityMode>
<Assembly>C:\My Revit- Custom Files\01-Revit 2021\Revit 2021 Repos\TpMechanical\bin\Debug\TpMechanical.dll</Assembly>
<FullClassName>TpMechanical.Command</FullClassName>
<ClientId>9EDCBEA6-942A-4D9A-932D-612B5E02DC9C</ClientId>
<VendorId>com.typepad.thebuildingcoder</VendorId>
<VendorDescription>The Building Coder, http://thebuildingcoder.typepad.com</VendorDescription>
</AddIn>
<AddIn Type="Command">
<Text>Command TpMechanical</Text>
<Description>Some description for TpMechanical</Description>
<VisibilityMode>AlwaysVisible</VisibilityMode>
<Assembly>C:\My Revit- Custom Files\01-Revit 2021\Revit 2021 Repos\TpMechanical\bin\Debug\TpMechanical.dll</Assembly>
<FullClassName>TpMechanical.Command2</FullClassName>
<ClientId>1A164A1B-8B02-499A-8ADB-94A75557CD66</ClientId>
<VendorId>com.typepad.thebuildingcoder</VendorId>
<VendorDescription>The Building Coder, http://thebuildingcoder.typepad.com</VendorDescription>
</AddIn>
<AddIn Type="Command">
<Text>Command TpMechanical</Text>
<Description>Some description for TpMechanical</Description>
<VisibilityMode>AlwaysVisible</VisibilityMode>
<Assembly>C:\My Revit- Custom Files\01-Revit 2021\Revit 2021 Repos\TpMechanical\bin\Debug\TpMechanical.dll</Assembly>
<FullClassName>TpMechanical.Command3</FullClassName>
<ClientId>C5CEC594-E407-40A8-B1B0-163DAA179CDD</ClientId>
<VendorId>com.typepad.thebuildingcoder</VendorId>
<VendorDescription>The Building Coder, http://thebuildingcoder.typepad.com</VendorDescription>
</AddIn>
<AddIn Type="Application">
<Name>Application TpMechanical</Name>
<Assembly>C:\My Revit- Custom Files\01-Revit 2021\Revit 2021 Repos\TpMechanical\bin\Debug\TpMechanical.dll</Assembly>
<FullClassName>TpMechanical.App</FullClassName>
<ClientId>C12635D2-96E2-4DF4-B172-7BD9487F7AE9</ClientId>
<VendorId>com.typepad.thebuildingcoder</VendorId>
<VendorDescription>The Building Coder, http://thebuildingcoder.typepad.com</VendorDescription>
</AddIn>
</RevitAddIns>
enter image description here
Rereading your question a third time over, it sounds as if your add-in is trying to reference a .NET assembly DLL that cannot be found when Revit tries to load it. Looking at the list of namespaces that you reference in your source code using statements, I see nothing but standard Autodesk Revit, Microsoft and .NET assemblies listed. So, they should all be present and accessible. Are you using anything else elsewhere in your code that is not obvious from that list? You might be able to use tools like fuslogv to analyse your add-in dependencies during load time, as suggested in the note on Exploring Assembly Reference DLL Hell with Fuslogvw.
I suggest you try again with a minimal one-liner external command and a minimal one-liner add-in manifest.
Follow these steps: Revit developers guide add-in registration.
Ensure that Revit has read access to its AddIns folder.
Look at the Hello world walkthrough.
Do not say you exhausted all resources. That would take too long and probably exceed your life span. New resources are being added faster than you can consume them, so any attempt is doomed to fail.
The error message is telling you that the problem is not in the internal implementation code, but just in the basic registration.
Why do you add internal to the IExternalApplication implementation? Isn't that a contradiction? What does that mean?
Why do you use The Building Coder VendorId? That is incorrect. You are not The Building Coder.
Your Assembly path is complex and littered with spaces. In general, I try to avoid such complex paths and all spaces in folder names. I also prefer forward slashes to backward ones. You can omit the folder name entirely if you place the DLL in the same place as the add-in manifest in the AddIns folder.
I am being inundated with similar questions these days. Here is another similar one, a summary of a recent email thread:
[Q] I have dived into the Getting Started with Revit platform API, following the DevTV tutorial by Augusto Goncalves. None of my commands appear on the Revit UI > Add Ins > external commands.
[A] One thing you ought to read is the introductory section of the Revit API developers guide. It tells you exactly what to do to install and launch your add-in. It is shocking of that information is not clear and does not work in the tutorial, though. Thank you for bringing it up!
Installing a Revit add-in is really simple, but people run into difficulties like you describe anyway.
There are only two relevant components:
Add-in manifest file *.addin
.NET class library assembly DLL
These are the important steps:
The DLL must implement IExternalCommand; that means, it must implement the Execute method.
The add-in manifest must point to the DLL and must be placed in the Revit Add-Ins folder for Revit to find and load it.
If the DLL and add-in manifest both reside in the Revit AddIns folder, the full DLL path can be omitted; otherwise it must be specified.
That is really all.
There are thousands of places explaining it; they all say the same thing.
Good luck and lots of fun with the Revit API :-)
[R] I have not had any luck since yesterday about my add-in not appearing in the Revit external commands.
I have carefully structured my code correctly. The add-in manifest file is pointing to my project .dll file. My project class explicitly implements the IExternalCommand interface and fires up the Execute method just fine.
I don't understand what the issue could be, not sure it could be the revit version am using am trying to figure out all possibilities.
[R2] I managed to debug my code. Kindly, ignore previous message.
The location of my manifest add-in file was locked. I guess that was done when my account was set up. The location needed permission to be accessed. This path:
C:\ProgramData\Autodesk\Revit\Addins\2022\
I utilised the try and catch exception to see the issue.
Once I gave access permission, the add-in file is now visible; it worked!

How do I fix the error I receive in Post Processing when launching Unity?

I'm pretty new to Unity so forgive me If I didn't give you enough information but whenever I open project in Unity I get a few errors.
First two are: Unity Error Image
#1:
***Library\PackageCach\.com.unity.postprocessing#2.0.3-preview\PostProccessing\Runtime\PostProcessManager.cs(424,66):error CS0117:'EditorSceneManager' does not contain a definition for 'IsGameObjectInScene'\***
#2: ***Library\PackageCach\.com.unity.postprocessing#2.0.3-preview\PostProccessing\Runtime\PostProcessManager.cs(425,66):error CS0117:'EditorSceneManager' does not contain a definition for 'IsGameObjectInMainScene'***
If I go into the code and delete these two lines
? UnityEditor.SceneManagement.EditorSceneManager.IsGameObjectInScene(volume.gameObject, customScene)
: UnityEditor.SceneManagement.EditorSceneManager.IsGameObjectInMainScenes(volume.gameObject);
From this
#if UNITY_2018_3_OR_NEWER && UNITY_EDITOR
// If the current camera have a custom scene then the camera is rendering that scene,
// otherwise the camera is rendering the scenes in the SceneManager.
var customScene = camera.scene;
return customScene.IsValid()
? UnityEditor.SceneManagement.EditorSceneManager.IsGameObjectInScene(volume.gameObject, customScene)
: UnityEditor.SceneManagement.EditorSceneManager.IsGameObjectInMainScenes(volume.gameObject);
#else
return true;
It gives me a Syntax error in Unity :
; expected
When I fix that error it gives me this error:
**Library\PackageCache\com.unity.postprocessing#2.0.3-preview\PostProcessing\Editor\Utils\PostProcessShaderIncludePath.cs(10,10): error CS0619: 'ShaderIncludePathAttribute' is obsolete: '[ShaderIncludePath] attribute is no longer supported. Your shader library must be under the Assets folder or in a package. To include shader headers directly from a package, use #include "Packages/<package name>/<path to your header file>"'**
After I delete this line of code:
[ShaderIncludePath]
From this:
#if UNITY_2018_1_OR_NEWER
[ShaderIncludePath]
#endif
public static string[] GetPaths()
{
var srpMarker = Directory.GetFiles(Application.dataPath, "POSTFXMARKER", SearchOption.AllDirectories).FirstOrDefault();
var paths = new string[srpMarker == null ? 1 : 2];
var index = 0;
if (srpMarker != null)
{
paths[index] = Directory.GetParent(srpMarker).ToString();
index++;
}
paths[index] = Path.GetFullPath("Packages/com.unity.postprocessing");
return paths;
After fixing all that I can use Unity normally. If this has no future effect on exporting my project I'm fine with deleting it every time. But I have zero idea what any of that code does, so If anyone can help me or knows how to solve it please let me know.
Judging by the fact that the post processing package is version 2.0.3 (preview), and the latest stable is 2.3.0 as of January 2020, I'm going to suggest that you're using grossly outdated packages.
Firstly, check to see if you Unity Editor is up-to-date by using your Unity Hub app, to "Add" new Unity versions. I would suggest if you're looking for the widely regarded, most stable version, grabbing 2019.4 LTS. Otherwise, if you're looking for that "new" thing, the 2020.2 beta is fairly stable under most conditions, but has the benefit of including the new tools and features.
Next, open up your Package Manager under the Window menu, and then check to see if all of your packages are up-to-date.
Once your Unity Editor and packages are all up-to-date, you'll more than likely find this error is resolved. I also suggest updating now, as you've said you're new to Unity, and I'm assuming you're not halfway through a major project. It's generally considered unwise to update your Unity Editor to new major versions partway through a project without a compelling reason.

The component does not have a resource identified by the uri

I want to create a Generic DataGrid to use on all my Views/UserControls.
This is my structure:
Class Library called "Core":
Class called "ViewBase":
public class ViewBase : UserControl
{
public ViewBase()
{
}
//Rest of Methods and Properties
}
Class Library called "Controls":
UserControl Called "GridView":
XAML:
<vb:ViewBase x:Class="Controls.GridView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vb="clr-namespace:Core;assembly=Core">
<Grid>
<DataGrid></DataGrid>
</Grid>
</vb:ViewBase>
Code Behind:
using Core;
public partial class GridView : ViewBase
{
public GridView ()
{
InitializeComponent();
}
}
Then is the WPF Aplication called "WPFApp":
Class called "View":
using Controls;
public class View : GridView
{
public View()
{
InitializeComponent();
}
}
My whole idea is to use GridView where i need a DataGrid.
When i run the application i get this error:
"The component 'WpfApp.View' does not have a resource identified by the URI '/Controls;component/GridView.xaml'."
What am i doing wrong?
Is this the correct approach or am i way off?
Frustratingly, I had exactly this error and spent forever trying to work out the cause. For me, it was once working but then I made some very minor changes to the XAML of the derived control, and the compiler started giving that error message.
Short solution, cutting out many hours of trying to figure it out: shut down Visual Studio and re-opened it, recompiled, problem magically went away! (This is VS2012 Pro)
Just added this in case anyone reading is going round in circles trying to find a non-existent problem with their code. Might be worth trying the "IT Crowd solution" first.
This gave me headaches for 3 days! I have a XAML UserControl in a class library and a class (only C#) that derives from the UserControl in my .exe project.
In xaml designer of my MainWindow.xaml and when starting the application, I got the error "component does not have a resource identified by the uri".
The answer of "Juan Carlos Girón" finally lead me to the solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Reflection;
using System.IO.Packaging;
using System.Windows.Markup;
namespace ClassLibrary1
{
static class Extension
{
public static void LoadViewFromUri(this UserControl userControl, string baseUri)
{
try
{
var resourceLocater = new Uri(baseUri, UriKind.Relative);
var exprCa = (PackagePart)typeof(Application).GetMethod("GetResourceOrContentPart", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { resourceLocater });
var stream = exprCa.GetStream();
var uri = new Uri((Uri)typeof(BaseUriHelper).GetProperty("PackAppBaseUri", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null, null), resourceLocater);
var parserContext = new ParserContext
{
BaseUri = uri
};
typeof(XamlReader).GetMethod("LoadBaml", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { stream, parserContext, userControl, true });
}
catch (Exception)
{
//log
}
}
}
}
and called that from by UserControl's .cs file:
namespace ClassLibrary1
{
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
//InitializeComponent();
this.LoadViewFromUri("/ClassLibrary1;component/myusercontrol.xaml");
}
}
}
Thanks again to "Juan Carlos Girón"!
The reason you are getting this error is because the way InitializeComponent that is implemented (in VS 2010) will always search in the derived class's assembly.
Here is InitializeComponent:
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/WpfApplication1;component/mainwindow.xaml", System.UriKind.Relative);
#line 1 "..\..\..\MainWindow.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
The line where it looks up your XAML resource is System.Windows.Application.LoadComponent(this, resourceLocator). And this most probably fails because equivalent of 'this.GetType().Assembly' is used to determine which assembly to search for the resource identified by the relative Uri. And 'this.GetType()' does get the derived type of the object, not the type of the class where the code is implemented.
PS. Is this a bug? I do not know...
You can try this approach
I created my own InitializeComponent() and I called this way
this.LoadViewFromUri("/NameOfProject;component/mainwindow.xaml");
public static void LoadViewFromUri(this Window window, string baseUri)
{
try
{
var resourceLocater = new Uri(baseUri, UriKind.Relative);
var exprCa = (PackagePart)typeof(Application).GetMethod("GetResourceOrContentPart", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { resourceLocater });
var stream = exprCa.GetStream();
var uri = new Uri((Uri)typeof(BaseUriHelper).GetProperty("PackAppBaseUri", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null, null), resourceLocater);
var parserContext = new ParserContext
{
BaseUri = uri
};
typeof(XamlReader).GetMethod("LoadBaml", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { stream, parserContext, window, true });
}
catch (Exception)
{
//log
}
}
I was doing something very similar with the same result. I had one C# class library that contained a WPF control called UsageControl (xaml with accompanying xaml.cs file). In a separate C# project(i.e. separate dll) I created a C# class CPUUsageControl which inherited from UsageControl, but put its own spin on it. When I tried to use the CpuUsageControl on one of my views I got the same error you did.
What I did to fix that was in my seperate assembly, instead of creating a class that inherited from the base control, i created a new WPF Control that contained the base control. I then put all of the logic that was contained in the CpuUsage class into the WpfCpuUsageControl's code behind. I was able to use this object is all of my other controls just fine.
For your Control "GridView" i would create a new WPF user control, call it GridView and make it contain a "ViewBase" as the content of the Grid control.Inside of the ViewBase's content put in your DataGrid, like this:
<UserControl....>
<Grid>
<ViewBase name="vBase">
<DataGrid name="dGrid" />
</ViewBase>
</Grid>
</UserControl>
It is also not apparent to me that you need ViewBase to inherit from UserControl directly. If all you want are for your controls to have certain properties and method why not just make a BaseControl class (that does not inherit from anyone but object) and have future controls inherit from it. Perhaps an abstract base class or interface is what you're after.
For MVVM WPF projects, I typically have a BaseViewModel which implements INotifyPropertyChanged for me so I don't have to do that same code everywhere.
Best of luck, I know this problem was a huge pain to figure out. The exception message and google are most unhelpful!
Same problem here.
Short version:
Copy Local has to be set to False!
Long version:
We developed a WPF solution (MVVM, 20 projects) and implemented a plug-in system. Our /bin/Debug directory contains the executable, some dll files and a plugin directory that contains the plugins.
There is one project "DialogLib" (Class library, kind of dialog) that defines a window (the view), the ViewModel, Model and some interfaces. One of the plugins used one of the interfaces of DialogLib. The window itself is opened by the main application.
To use the interface of the 'DialogLib' library in the plugin we had to add a project reference of DialogLib to the plugins project references. When the application was started, the plugins were loaded. If the user then selects a menu item, the window should open. At this point the error "... component does not have a resource identified by the URI ..." occured when the windows code behind tried to execute its InitializeComponent().
Where's the problem?
The problem is, that, when we built the solution VS has created the DialogLib.dll correctly and copied it to /bin/Debug/. This is because the main application file wants to open the window. But DialogLib.dll was also copied to /bin/Debug/plugins because one of the plugins referenced it to use one of the interfaces defined in DialogLib.dll. So what?
When the plugin is loaded at runtime it uses the interface defined in /bin/Debug/plugins/DialogLib.dll. and the main application file tries to open the window defined in /bin/Debug/DialogLib.dll. Although the files are identical, VS runs into trouble. Setting the value of Copy Local of the DialogLib reference properties of the plugins references avoids copying DialogLib.dll to /bin/Debug/plugins and thus solves the problem.
We had a similar same problem (but different error) in another project where we wanted to use a type TypeA, that was defined in a dll file, in a plugin and in the main application. Copy Local was set to true which caused a copy of the dll file to be located in ../bin/Debug/plugins and in ../bin/Debug/. It turned out that, even though it was the same dll file, the TypeA in the main app file and TypeA in the plugin were treated as different types respectively as types which could not be exchanged.
Delete obj folder
Delete bin folder
Rebuild solution
Worked for me!
Also if you are loading assemblies using Assembly.LoadFile, check out AppDomain.CurrentDomain.GetAssemblies() for duplicate assemblies in the current AppDomain. Because in auto-generated code of WPF UserControl, the component will be loaded using its relative URI. And since there are duplicate assemblies in the current AppDomain, application doesn't know which one to use.
I resolved this by placing
myusercontrol = Activator.CreateInstance<myusercontrol>();
in the constructor of the window containing the usercontrol before the InitializeComponent(); line
I received the same error when using Visual Studio 2013.
The component does not have a resource identified by the uri
Tried:
Cleaning and rebuilding the solution - did not work.
Closing and opening Visual Studio - did not work.
Solution:
Went into the projects bin directory and cleared out all files.
Ran the project again and worked fine.
Open the Package Manager Console which will open in the root directory of your Solution and run the following powershell command:
Get-ChildItem -inc bin,obj -recurse | Remove-Item -recurse -force -EA SilentlyContinue
#Willem, this seems perfectly OK to me. In fact I tried this and it worked in my case. I used ListBox instead of DataGrid (but that shouldnt matter).
All my namespaces were in one assembly. So I used a common parent namespace for all e.g.
MyWpfApplication.Controls
MyWpfApplciation.GridView
MyWpfApplciation.ViewBase
Coz all these Controls, GridView, ViewBase are clashing with existing System or System.Windows.Controls based namespace and class declarations. So I made sure I referred correct ones MyWpfApplication.* in my project.
I just ran into this problem as well without any inheritance issues. I was just referencing a DLL that contained a dialog and trying to create and display that dialog.
I have assembly resolver that loads assemblies from a specific folder and it turns out that I had added the reference in VS and had not turned off Copy Local. Long story short: my process had loaded two versions of that same DLL. This seems to confuse WPF (or the runtime). Once I cleared the Copy Local and deleted the extra DLL copies, it worked fine again.
I got this error after renaming a xaml file. Reversing the renaming solved the problem.
Furthermore, I found that a reference to the xaml file name in App.xaml was not updated (the StartupUri), but renaming that to the current name didn't resolve the problem (but maybe it does for you). Basically, I can't rename the xaml file.
Fyi, for me, the component 'complaining' in the error was SplitComboBox.
Happend to me when I had the same project opened in two solutions. Modifying the base-control in one project cause the other project to have this problem. If closing and opening doesn't work, then delete all the folders in "C:\Users...\AppData\Local\Microsoft\VisualStudio\12.0\Designer\ShadowCache"
This can happen also when closing and reopening a window. So it could also have nothing to do with packages and/or dlls.
I solved the problem thanks to the solution posted by PainElemental, which is IMHO underrated:
namespace MyNamespace
{
public partial class MyDialog : Window
{
public MyDialog(ExcelReference sheetReference)
{
this.LoadViewFromUri("/MyApp;component/mynamespace/mydialog.xaml");
}
}
}
LoadViewFromUri is implemented as an extension, as PainElemental wrote.
The craziest is that I also wrote in the same project other windows without encountering any problem.
Thank you PainElemental, you ended my protracted pain!
I started consistently seeing a "the component does not have a resource identified by the uri" error when I clicked a particular menu choice from an installed product that was working on other computers. I tried uninstalling the product, making sure its files really were gone, rebooting, and reinstalling the product. The problem remained. I deleted the contents of my %TEMP% directory, and the problem ceased.
Thanks for all the tips in this thread. I think my own variation of this error was for a slightly different reason again, so I'll post here in case it's of use.
In my situation, the error occurred when invoking window.ShowDialog(). More specifically, my window is defined in a separate class library assembly (let's call it AssemblyA.dll).
I have multiple versions of AssemblyA which are used in various products, some of which are plugins and some aren't. In short, the consequence is that the process might end up loading several different strong-named versions of AssemblyA. So there are duplicate assemblies in the app domain as #VahidN pointed out, but they're strictly differently versioned assemblies which are meant to be there, and merely share the same AssemblyShortName.
WPF's auto-generated code for InitializeComponent() looks like this:
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/AssemblyA;component/forms/mywindow.xaml", System.UriKind.Relative);
#line 1 "..\..\..\Forms\MyWindow.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
It's only referring to the short name of AssemblyA, and not to the specific version or public key token of AssemblyA in which the InitializeComponent() method is running. The consequence is that the code just seems to find the first AssemblyA assembly loaded into the process, searches for the XAML, can't find it (because it's found an older version of the assembly first), and then throws an exception. Or perhaps it finds something but maybe it's pulled a different XAML resource than what it's meant to have, from either an older or newer version of the assembly that happens to also be loaded.
It's not perfect, but I've consulted the Pack URI specification, and worked around this by writing my own extension method that makes sure the assembly is found with the appropriate version and public key token, rather than simply the AssemblyShortName.
In case it's of use for others, here's a simplified version of what I've ended up with.
public static void AssemblySensitive_InitializeComponent(this ContentControl contentControl, string componentString)
{
// Strictly speaking this check from the generated code should also be
// implemented, but it doesn't fit directly into an extension method.
//if (_contentLoaded)
//{
// return;
//}
//_contentLoaded = true;
var asm = System.Reflection.Assembly.GetExecutingAssembly();
var shortName = asm.GetName().Name;
var publicKeyToken = GetPublicKeyTokenFromAssembly(asm);
var version = asm.GetName().Version.ToString();
System.Uri resourceLocater = new System.Uri($"/{shortName};V{version};{publicKeyToken};{componentString}", System.UriKind.Relative);
System.Windows.Application.LoadComponent(contentControl, resourceLocater);
}
/// <summary>
/// Gets a public key token from a provided assembly, and returns it as a string.
/// </summary>
/// <param name="assembly"></param>
/// <returns></returns>
/// <remarks>Adapted from https://stackoverflow.com/questions/3045033/getting-the-publickeytoken-of-net-assemblies</remarks>
private static string GetPublicKeyTokenFromAssembly(System.Reflection.Assembly assembly)
{
var bytes = assembly.GetName().GetPublicKeyToken();
if (bytes == null || bytes.Length == 0)
return "None";
var publicKeyToken = string.Empty;
for (int i = 0; i < bytes.GetLength(0); i++)
publicKeyToken += string.Format("{0:x2}", bytes[i]);
return publicKeyToken;
}
The _contentLoaded bit could probably be done with extension properties, but I need the code for this library to compile in C# 7.3 so I have a much longer workaround which I removed so as not to distract.
Then I call it from the constructor like this:
public MyWindow()
{
// Don't use the auto-generated initialize, because if multiple different versions
// are loaded into the process, it can try to load the resource from the wrong one.
//InitializeComponent();
AssemblySensitive_InitializeComponent("component/forms/mywindow.xaml");
// ... do more constructor stuff ...
}
I spent ages getting frustrated trying to figure out what was going on, so I hope this helps someone else out there.
As others have pointed out in their answers, this will happen if you have a base control class with an associated XAML resource, and then define a class in a separate assembly that inherits from the base control. This happens because of a limitation in WPF.
WPF is open source now, so you can see the source code that we need to work around that is called in IntializeComponent() (though it's a bit difficult to follow). In summary, this method get a stream for the control's XAML resource and then loads it with XamlReader.LoadBaml(). The issue is that the framework code does not load the XAML resource file correctly when the derived class is in a different assembly than the XAML resource file.
To work around this issue we need to load the XAML resource stream correctly and then call XamlReader.LoadBaml() manually. There are a few other answers here already that do exactly this, but here's my take on it. The following extension method is a bit more concise than the other answers, accesses only one private method via reflection, and also guards against multiple calls.
private static MethodInfo? _loadBamlMethod;
public static void InitializeComponent(this ContentControl control, string xamlResourceUri, ref bool contentLoaded)
{
// Ensure the control is only initialized once
if (contentLoaded) return;
contentLoaded = true;
// Use reflection to get the private XamlReader.LoadBaml() method and cache the result
_loadBamlMethod ??= typeof(XamlReader).GetMethod("LoadBaml", BindingFlags.NonPublic | BindingFlags.Static)
?? throw new InvalidOperationException("Could not find XamlReader.LoadBaml() via reflection");
// Load the XAML resource for the control
var stream = Application.GetResourceStream(new Uri(xamlResourceUri, UriKind.Relative)).Stream;
var parserContext = new ParserContext { BaseUri = PackUriHelper.Create(new Uri("application://")) };
_loadBamlMethod.Invoke(null, new object[] { stream, parserContext, control, true });
}
Which can then be used like this. Controls in other assemblies may now inherit from BaseControl and not see this issue.
public partial class BaseControl : UserControl
{
protected BaseControl()
{
// The resource URI here can be coped from the generated partial class
// Note that we are also re-using the _contentLoaded field defined in the generated partial class
this.InitializeComponent("/Senti.Common.PrismModules.Hmi;component/controls/basecontrol.xaml", ref _contentLoaded);
}
}
It should definitely be noted that this workaround (as well as the ones in other answers) work by accessing a private method within the WPF framework, which is obviously not a supported use case. That said, I have developed and tested this approach with the .NET 5 version of WPF and not seen any issues. Microsoft has also said that very little development is planned for the WPF framework other than bugfixes etc, so this workaround should be fairly stable.
Quicker than closing all of Visual Studio is just to kill XDescProc.exe in your task manager.
XDescProc is the designer. The moment the process is closed you'll see a Reload the designer link in visual studio. Click that and XDes will be started again and your 'no resource' error should be gone.
Here's the link visual studio shows after you kill the designer process:
I had accidently deleted a user control via a rename/copy action. When I reinstated the project file and the xaml file and .cs from version control this error started happening in the design studio for that control which had mistakenly been deleted/renamed.
That suggested some type of cache on the file in question....so closing Visual Studio, deleting the bin directory and rebuilding worked.
Followed PainElemental's solution (to clarify, for his code the ClassLibrary1 for me was the .dll name without the .dll extension), here's my scenario in case it helps anyone link their specific error messages to the problem:
I use dll's to load and run usercontrols into a main program as their own popup windows. PainElemental's solution was mostly working , but 1 of the 3 classes in my "popup .dll" wouldn't load properly. I would get an exception with 2 inner exceptions, like:
mscorlib InvokeMethod...;
WpfXamlLoader.Load...Provide value on...StaticResourceExtension...;
ResolveBamlType....method or operation is not implemented.
In my case, I confirmed it would load the new URI and work in testing, but when I tried to run it over in my Live environment it would error in LoadViewFromUri().
As I tested further, I narrowed down the issue to not being able to load a separate "library .dll" file I was using which contained a Converter I was using in the .xaml file of the class which was failing, and on further research the issue there was that the Live environment was using a different "library .dll" version than I was using in my test environment, even though the exception message from my "popup .dll" did not make any mention of that.
For reference, I use Copy Local=True and that didn't give me issues. To best debug these kinds of issues, an understanding of the locations where .dll files are searched for by the .exe is helpful. As I understand it, when you are running projects in VS, when Copy Local=True the .dlls get copied to the same folder as the .exe when it is Built. When the .exe is run the standard location it will search for .dlls is the same folder as the .exe. Additional locations that the .exe can look for .dlls can be set in the .exe.config file, in the probing element. In the below example, it can also search in a 'MyDLLs' and the 'MyDLLs\Core' directory relative to the .exe's location. Note that it will not naturally search any subfolders, you have to specify them explicitly. I believe it also searches the GAC, but I currently have minimal knowledge concerning GAC.
<configuration>
...
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="MyDLLs;MyDLLs\Core;"/>
</assemblyBinding>
</runtime>
</configuration>
Hi the way solve this problem was to rename the xaml usercontrol to all smallcaps on InitializeComponent()...
enter image description here
enter image description here
For me, when trying to launch a window dialog (window.ShowDialog()) in my application during startup, the exception was thrown in the InitializeComponent method in the window's class constructor.
After much head scratching I had discovered that the issue was that an app.publish folder was getting created in the debug directory, which contained the application exe only. Deleting the app.publish folder resolved this exception. See the following article to prevent this folder from getting created:
What creates the directory "app.publish" in visual studio 2013?

What does "Unhandled Exception: GLib.GException: Unhandled tag: 'requires'" mean?

I'm trying to get my linux Gtk# application working on Windows. When I try to run it, I get this error message:
Unhandled Exception: GLib.GException:
Unhandled tag: 'requires'
at Gtk.Builder.AddFromFile(String
filename)
at Interface.MainWindow..ctor()
at [My Project Name].MainClass.Main(String[]
args) in c:\Path\To\Main.cs:line 10
It seems to be happening when trying to build the interface from my Glade file. I've checked and the path to the glade file is correct. What might be going wrong?
Here is some code to reproduce the problem:
using System;
using Gtk;
namespace TestGtk {
class MainClass {
public static void Main (string[] args)
{
Application.Init();
string gladefile = #"C:\path\to\gladefile.glade";
Builder builder = new Builder();
builder.AddFromFile(gladefile);
Application.Run();
}
}
}
Strange... I don't know why on windows GTK# does not support requires. Anyway I'd try to remove the <requires ... /> tag from gladefile.glade.
This most likely means that your Glade file is corrupt or has got some weirdness in it.
You're using GtkBuilder to load GladeXML files. GtkBuilder has different XML format, incompatible with GladeXML (it more generic). If you use glade-3 to design your UI, you have an option to save as GtkBuilder XML or GladeXML. Also, glade has utility called gtk-builder-convert that you can use to convert GladeXML to GtkBuilder XML.
So, there are two options:
Use glade-3 and save your UI in GtkBuilder format
Use gtk-builder-convert utility
Glade is for GTK 3.x and your system is probably on GTK 4.x.
I had a similar issue when the version was not specified in a Python app using a .glade file, and upon running it would show:
Use gi.require_version('Gtk', '4.0') before import to ensure that the right version gets loaded.
It worked prior to an Ubuntu update last I ran if. After adding
import gi
gi.require_version("Gtk", "3.0")
It works.
A similar issue was noted in a Haskell app. I am not sure how one changes the reference to GTK3 on C#.

Categories

Resources