C# wrong reference to namespace - c#

Okay this is driving me crazy. I got one almost finished project (which works perfectly) and I wanted to make another one in the same way. The thing is there is a solution with two layers DataAccessLayer and BusinessLogicLayer. Both of these layers have a Model library with all models in the project. I need to convert the model from the first layer to a model of a second layer in the manager library. This works in the finished project I received but I can not manage to make it on mine.
The thing is I can't make the necessary references to work like they do on the finished project. The structure is:
BusinessLogicLayer
--Managers
----Users
--Models
----User
DataAccessLayer
--Models
----User
In the Managers project I have a reference added to DataAccessLayer.Models.
And inside the Users class I got:
using Library.BusinessLogicLayer.Models;
Now in my project this line is red underlined:
Error CS0234 The type or namespace name 'Models' does not exist in the
namespace 'Library.BusinessLogicLayer' (are you missing an assembly
reference?)
I am not even sure how and why this works on that original project. But I can't figure it out so it's working right on my project and the structure is the exact same. Anyone have an idea about this?
EDIT:
Dunno why I didn't upload this earlier. Here is the structure.
https://i.imgur.com/srnySFJ.jpg
EDIT2:
Since it is not quite understandable I uploaded the whole project on github so you can take a closer look at it.
https://github.com/Morsusy2k/Library
And here is the problem:
https://i.imgur.com/DvCvnMA.jpg

From what you described above and from my understanding, it seems that Managers and Models are two different projects. If that is the case, make sure that you add a reference to BusinessLogicLayer.Models in your BusinessLogicLayer.Managers.
If, on the other hand, you have only two projects BusinessLogicLayer and DataAccessLayer then it could very well mean that Library.BusinessLogicLayer.Models is not the name of the namespace.
UPDATE
From the picture that you added, you might need to add a reference to Library.BusinessLogicLayer.Models.Models. You have a folder named Models and a project named Models. Visual Studio automatically generates namespaces based on the Solution name, Solution folders, project name, folders within project.
There were three issues with your code. The first one is that you are supposed to add a reference to Library.DataAccessLayer.Models and not to Library.BusinessLogicLayer.Models. This is due to the fact that you have User in DataAccessLayer.Models and User2 in BusinessLogicLayer.Models.
The other two issues were with the Map method where you are sending incorrect number of arguments to the constructor (you are missing UserId) and the other issues is with your DateOfBirth and DateJoined being in the wrong order in the same method.
using System;
using System.Collections.Generic;
using System.Linq;
using global::Library.BusinessLogicLayer.Models;
using Library.BusinessLogicLayer.Managers.Properties;
using Library.DataAccessLayer.Models; // <-- Add reference to this
namespace Library.BusinessLogicLayer.Managers
{
public class Users2
{
public IEnumerable<User> GetAll()
{
using(DataAccessLayer.DBAccess.Library library = new DataAccessLayer.DBAccess.Library(Settings.Default.LibraryDbConnection))
{
return library.Users.GetAll().Select(user => Map(user));
}
}
private User Map(DataAccessLayer.Models.User dbUser)
{
if (dbUser == null)
return null;
// TODO: Constructor is missing a paremeter. I'll add a temporary one
int tempUserId = 0;
User user = new User(tempUserId, dbUser.Name, dbUser.UserName, dbUser.Password, dbUser.Email, dbUser.DateJoined, dbUser.DateOfBirth) // <-- The last two params are in the wrong order
{
Id = dbUser.Id
};
return user;
}
private Library.DataAccessLayer.Models.User Map(User2 user)
{
if (user == null)
throw new ArgumentNullException("user","Valid user is mandatory!");
return new DataAccessLayer.Models.User(user.Id,user.Name, user.UserName, user.Password, user.Email, user.DateJoined, user.DateOfBirth);
}
}
}
Also, regarding the last screenshot that you provided, you do not have Library.BusinessLogicLayer.Models2 namespace. Remove number 2 to get it to work.
As I don't have permission to update your repo with the fixed code, you'll have to fix it manually based on my answer. Otherwise, let me know so that we see how I can push the code back.

There are a few things you could try:
This error could be appearing within BusinessLogicLayer because DataAccessLayer failed to build. Try building DataAccessLayer by itself to see if you get a different error.
The references might be "added", but you might not be referencing the correct DLL or version for some reason. Check your .csproj files manually to ensure all references and versions are correct, have the right hint paths, etc. If you have any config files, you should also review them to ensure there are no version conflicts.
In addition to checking the references, it is possible to add if-then and switch case logic inside of the .csproj files. This is an MSBuild feature that Visual Studio doesn't support through its GUI, so you may need to copy/update this logic manually in your current .csproj files if any existed.
Check your default namespaces in project properties to see if they are the same as your old project. If you added new files since you moved to this project, they may have been inadvertently added with the wrong namespace and that namespace may be causing a conflict. You could also try using global::Library.BusinessLogicLayer.Models; to see if that fixes or changes the error message or at least if Intellisense is picking the namespace up.
If that doesn't work, review all of your namespaces in all .cs files to see if you have any that have gone rogue.
Since your Models namespace has the problem and you have 2 of them with the same name, try temporarily renaming one of them (yes, every .cs file in one of the projects) to Models2 to see if it provides a clue (such as the error going away or changing).

Related

Namespace not recognised in using statement. "The type or namespace '#' does not exist in the namespace '#'. Are you missing an assembly reference?

I have a solution with about 14 projects, and am having a problem with a link I am trying to make between two of the projects:
Argus.Web (a web application project)
Argus.Domain.Office.Command (a project that reads data from an API and stores data in a local SQL Server database)
(there is also a project called Argus.Domain which I mention as it may possibly be part of the problem, although it hasn't caused problems in other similar places in my code.)
Argus.Domain.Office.Command has a context (argusOfficeContext) linking it to a database which I would like to access from Argus.Web. (This context works well in other situations.) When I try to add a using directive to reference the context's namespace in a class within Argus.Web I get the error in the title.
Here is the class I am scaffolding up (in Argus.Web) where the error occurs:
using Argus.Domain.Office.Command.Models;
namespace Argus.Web
{
public partial class Calculator
{
}
}
The red wiggly line appears only under 'Office' in the using, and the error in full is "The type or namespace 'Office' does not exist in the namespace 'Argus.Domain'. Are you missing an assembly reference?".
I have checked that the project Argus.Domain.Office.Command is referenced from Argus.Web and when I check Argus.Web build dependencies I see Argus.Domain.Office.Command (as well as the other project Argus.Domain), and it is set to build before Argus.Web. When I check in Argus.Web References > Projects the project Argus.Domain.Office.Command has a tick next to it and I conclude that it is therefore referenced.
Following Peter D's comment I checked the namespace declaration, and it is declared in the project Argus.Domain.Office.Command.
(Probably irrelevant:) here is the class I am trying to reference
using System.Data.Entity;
using Argus.Domain.Office.Command.Models.Mapping;
namespace Argus.Domain.Office.Command.Models
{
public partial class argusOfficeContext : DbContext
{
static argusOfficeContext()
{
Database.SetInitializer<argusOfficeContext>(null);
}
public argusOfficeContext()
: base("Name=argusOfficeContext")
{
}
public DbSet<Location> Locations { get; set; }
public DbSet<LocationPeriodReport> LocationPeriodReports { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new LocationMap());
modelBuilder.Configurations.Add(new LocationPeriodReportMap());
}
}
}
Both projects target .NET Framework 4.5.1, and I have looked for the answer in various places, but the fixes for the other questions below don't seem to fix my case. I'm running Visual Studio 2015. Other questions for reference:
'Using' not detecting namespace-checked client profiling already
Visual Studio 2010 suddenly can't see namespace?
Visual Studio 2015 C# Not finding references
If anyone can advise what I'm doing wrong I would really appreciate it. I have checked lots of other posts looking for an answer, but if you can provide a link to an answer I have missed that would also be great.
Most of the times I see this, the cause is a class with the same name as part of the namespace. These are in two different assemblies.
namespace Library.Foo // assembly 1
{
using Library.Foo.Bar; // error here
public class Bar
{
public void DoIt()
{
new Bell(); // and here
}
}
}
namespace Library.Foo.Bar // assembly 2
{
public class Bell
{
}
}
This can be a real pita to find. I suggest doing a test search of each word in your namespace. You're looking for a class of the same name.
As a side (and there's controversy over this), you can avoid some of these collisions by moving the using inside the namesapce.
OK, so I came up with a solution.
I thought I would try removing and recreating the references, and in a nutshell, this worked. Detail:
I right clicked on Argus.Web in the solution explorer, and then Build Dependencies > Project Dependencies. I tried deselecting Argus.Domain.Office.Command, but got the error 'This dependency was added by the project system and cannot be removed'. I'm not sure why this error appears, but I therefore tried right clicking on the references in Argus.Web, and selected 'Add Reference'. In the Projects section of the window that came up I was able to deselect Argus.Domain.Office.Command, so I did this, commented out the problematic using directive, cleaned and rebuilt my solution, added the reference back (right clicking on the references in Argus.Web, and selecting 'Add Reference'), and it all works again.
I guess that the original references must have been misconfigured, but at present I can't see how this came about. I will add to this post if I work out how this happened.
Many thanks to all respondees, all comments and answers were useful.

How to use partial view from another project in asp.net mvc

I have two MVC projects one as a parent project and the other as a child project. The child project adds reference to the parent project. I like to use partial views from the parent project from the child project something like -
#Html.Partial("_GenericGreeting") <-- in child project
_GenericGreeting.cshtml <-- is in parent project
The child project is the project that starts up. Parent project i mean is like a base/shared project. RazorGenerator has been installed on both projects and each projects can be compiled into single assembles.
When I ran the project, i'm only getting this following error.
The partial view '_GenericGreeting' was not found or no view engine
supports the searched locations.
If i copy the partial view and paste it into the child project it's fine but i don't want to duplicate the files.
I have tried this post but no luck but maybe i'm not adding it right.
Not really good, but simple solution that can solve your problem. One of overloads #Html.Partial() allows you to write full path to your View.
Something like this:
#Html.Partial("~/View/Shared/_GenericGreeting.cshtml")
I accepted teo's answer. He helped me and gave me clue to the problem. But there are few important things to check.
One thing I wasn't aware is the generated cshtml files have properties called PageVirtualPathAttribute. One problem i couldn't get the right combination is because i was getting the path wrong.
Another thing to look is this class which is auto generated when you installed RazorGenerator and it is in your App_Start folder.
public static class RazorGeneratorMvcStart {
public static void Start() {
var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly) {
UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
};
ViewEngines.Engines.Insert(0, engine);
// StartPage lookups are done by WebPages.
VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
}
}
However this line has an overload method to define path to your compiled view. My shared project was created by someone else and he put this path in it.
var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly, #"~/Areas/Cart/", null)
Once I have those bits checked, I just need to use like the following in my view as teo suggested.
#Html.Partial("~/Areas/Cart/Views/Home/_GenericGreeting.cshtml")

Invalid Resx file. Could not load type error why?

I'm getting designer error on code:
The Component i'm willing to define a List of properties for:
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
namespace TestProjectForProperty.Test
{
public class MyTreeView : TreeView
{
private List<TypeDescriptorBase> _descriptorsAvailable = new List<TypeDescriptorBase>();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public List<TypeDescriptorBase> DescriptorsAvailable
{
get { return _descriptorsAvailable; }
set { _descriptorsAvailable = value; }
}
}
}
The Descriptor itself:
using System;
namespace TestProjectForProperty.Test
{
[Serializable]
public class TypeDescriptorBase
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
}
I am getting the following error if i try to use the component for example on a form and add any items on the property sheet or in the component's constructor to the DescriptorsAvailable property
Error 1 Invalid Resx file. Could not load type
System.Collections.Generic.List`1[[TestProjectForProperty.Test.TypeDescriptorBase,
TestProjectForProperty, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089 which is used in the .RESX file.
Ensure that the necessary references have been added to your project.
Line 134, position 5. ...\visual studio
2010\Projects\TestProjectForProperty\TestProjectForProperty\Form1.resx 134 5 TestProjectForProperty
In the Resx file there is data field with base64 encoded stuff inside when this error is present.
I have been searching for an answer, but the best i got is to restart everything, it didn't help me, do you guys have any suggestions? I'm using .net 4 client and visual studio 2010
In my experience, this is due to a change of version of a referenced library, or a change of the lib itself, which contains the backing type of a property you have defined in your user control. The solution is to "force" the visual studio designer to re-initialize it's designer code for that type, and not expect to retrieve a "canned" version of it from the .resx file of the control.
1) Delete the offending data section in the .resx file of your control. This will be a section in the xml of the .resx file associated with your user control, which has a node: <data></data> - the name attribute will be set to whatever you've named that object in the properties of whatever you added this type to. The <data>/data> section contains a base64 encoded string that is the encoded form of the name and version of the library the type comes from. This is where the problem ism, because it now contains an encoded version of the library and/or version number you are no longer referencing in order to include the type. Delete the entire <data>/data> section, from opening to closing tag, save the change and close the file. Now the "artifact" is gone.
2) Now find the place in the designer file for your control, where the type is instantiated; this is initialization code generated for you by visual studio, and it is the place that is expecting to load a "canned" definition of the type from the base64 encoded string contained within the .resx file. The line will look something like this:
this.myCtrlFoo.MyPropertyFroo = ((MyNamespaceFoo.MyTypeFoo)(resources.GetObject("myCtrlFoo.MyPropertyFroo")));
...now just replace the resources.GetObjec call with the instantiation of a new instance of the appropriate type like so:
this.myCtrlFoo.MyPropertyFroo = ((MyNamespaceFoo.MyTypeFoo)(new MyNamespaceFoo.MyTypeFoo()));
...now save the change to the file, close it, rebuild, and everything should now build & run OK.
Put the MyTreeView and TypeDescriptorBase classes into another project and reference it from your GUI project will resolve the issues.
I'm not sure why exactly the problem occurs - I guess it has something to do with the way the serializing process is generating the base64 string for the DescriptorsAvailable Property. Maybe somebody else can give us some insight.
I've struggled quite a bit with this; I have three user controls that all expose the same non-designer property, but for some reason, any change to two of the three would instantly cause the next build to fail with this same issue. This is in VS 2015.
I wound up having to add the following two attributes to the property that kept expanding in the resx file, and it hasn't occurred since. It works for me because they're not available in the designer anyway.
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
For me, this error occured when I used a custom class as a property for the user control. When I switched from property to traditional get- and set- methods, the error disappeared. I guess this is because properties are already compiled at design-time, so when you build the whole project, a new version of the custom class is compiled which is separate from the one of the control, and the reference is broken.
For me, with the custom class Inventory, all I had to do was to switch from this property-based approach:
public Inventory Resources {get;set;}
to this method-based approach:
private Inventory resources;
public Inventory getResources() { return resources; }
public void setResources(Inventory newResources) { resources = newResources; }
I hope this helps someone, as I've been spending some hours on figuring it out.
In my case I've got the error : "error MSB3103: Invalid Resx file. The specified module could not be found" executed in a light windows container based on mcr.microsoft.com/powershell instead of mcr.microsoft.com/windows:1909 (was working fine on 1909).
The error was on a ressource icon that was compressed with PNG inside.
It can be checked by opening the ressource on visual studio : Project > Properties > Ressources.resx, select icons, double click on the icon, check the end of the title that is either "..,BMP]" or "...,PNG]").
Updating the icon with an uncompressed format solve the "Invalid Resx file" issue.
I stumbled across this question today whilst looking for the solution to a similar issue.
Unfortunately none of the above worked for me, however my issue turned out to be that I had different versions of the .NET Framework for different projects. For example;
Project A - .NET Framework 4.7.2
Project B - .NET Framework 4
Where Project B was referencing Project A. Solution was simply to change the .NET Framework version of Project B to 4.7.2 (in my case) and hey presto the issue was resolved.
A shame Visual Studio doesn't provide a more helpful error message in this case, but something to look out for!

How to execute SQLCLR UDF added directly to SSDT sqlproj and resolve reference error SQL71501

I have been trying to find the answer to this simple question - but so far couldn't figure it out.
Let say I have MyDb.sqlproj, with various sql content (sprocs, views, trigger, etc).
I have added a new UDF through Add-> New item -> SQL CLR C#, User Defined Function.
For example:
namespace MyNameSpace
{
public class MyClass
{
[SqlFunction(DataAccess = DataAccessKind.Read)]
//I use different attributes here, but it doesn't matter
public static int Method1()
{
return 0;
}
}
}
In MyDb.sqlproj Properties, SQLCLR tab MyDb is the name of assembly and default namespace
In my sql code I call the clr method using EXTERNAL NAME:
CREATE PROCEDURE ClrMethod1
RETURNS [int] WITH EXECUTE AS CALLER
AS EXTERNAL NAME [MyDb].[MyNamespace.MyClass].[Method1]
I seem to tried everything to get the last line to compile. It cannot resolve the reference and get:
SQL71501: Function: [name of my sql function] has an unresolved
reference to Assembly [MyDb]
Please point me to the right way to get it working. What could I be missing?
I am using VS2010 SP1 and latest version of SSDT
You must add your compiled DLL containing your CLR code as a Reference. So under your MyDb SSDT project->References(right click)->Add Reference, browse to the DLL.
You could probably get away with referencing the project instead of the DLL if you had the CLR(class library) project in the same solution, but in my case I am referencing a DLL(compiled for a seperate solution).
As far as the format of the AS EXTERNAL NAME line:
AS EXTERNAL NAME [AssemblyName].[ClassName].[FunctionName]
Note: For CLR objects I remove the namespaces from around my classes/code just to simplify things, because this step is usually the most problematic. It is easy to confuse the AssmeblyName/DLL Name/Namespace. The AssemblyName is found in your CLR class library project by accessing the Project Properties->Application->"Assembly Name:". I would remove any non alpha-numeric/spaces from it just to simplify the name and rule out that as a problem.
So I would try that, and once you get that working, if you really want namespaces, then you can add the namespace and figure out the syntax from there, and at least you know the other parts are correct.
Ok reallized that you have a *.cs file actually inside the same SSDT project. so in that case if your code is this:
CS file:
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString SqlFunction1()
{
// Put your code here
return new SqlString (string.Empty);
}
}
SQL file:
CREATE PROCEDURE ClrMethod1
RETURNS [int] WITH EXECUTE AS CALLER
AS EXTERNAL NAME [MyDB].[UserDefinedFunctions].[SqlFunction1]
This compiles for me. Note: Again no namespace was used. When I did Add New Item... the generated code did not come with a namespace.

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?

Categories

Resources