I have a C# WebApp that we are doing for a client. I have two classes in the project, defined (in separate files) as such...
A general utility library:
namespace Client.WebApp {
public static class General {
public static MyDbClass GetDB() {
//<creates and returns MyDbClass here>
}
}
}
A PageBase class:
namespace Client.WebApp {
public class PageBase : System.Web.UI.Page {
protected MyDbClass dbo { get; set; }
public PageBase() {
dbo = General.GetDB();
}
}
}
When I try to compile, I get the error from the dbo = General.GetDB(); line:
The name 'General' does not exist in the current context Client.WebApp.
I have double-checked that the namespace is spelled right in both files.
I have tried adding the top-level namespace Client.WebApp as a using directive in the pagebase file.
I have tried fully qualifying the name as in dbo = Client.WebApp.General.GetDB();
Nothing has helped and it insists that my General class does not exist.
Funny thing is that while the build hits this error and stops, the code-editor does not see this error, and the statement does not get red-under-squiggled.
The project is targeting Framework v.4.5.2, and I am working in VS 2015.
It is a strange error, in my VS2015 if I set a file Build Action to anything other than "Compile", I get an error underline on any type for that file.
Anyway the solution here is to verify that the Build Action is set to "Compile", I'm not sure why adding a new file would have set the build action to anything other than "Compile". I've also tested trying to add new files in multiple ways (select a text file template and just name it something.cs), it still sets it as "Compile". You should verify that your VS2015 instance is updated with the latest updates.
I had the same problem: "type or namespace could not be found". It turned out that class was in a file with the "Build Action" property set to "None", meaning the file was not being compiled. I set it to "C# Compiler", that solved it.
This happens to me sometimes. Closing visual studio and opening it again always fixes it for me.
I think I might have figure it out that if we create a file in a folder which suppose to have content files it set that file's build type content automatically. In my Case I create a file under app_code folder and it is a class file but the build type is set to Content which make it unavailable for any other classes i have.
May be it has any other reasons too.
Try to create a new Class in the Project folder and then move it to the folder, you want it to be.
Related
How can I configure default VS Code namespaces for C#?
E.g. I have the following folders structure:
gameplay/input/controllers/foo.cs
I created the foo.cs by right clicking the controllers folder and selecting New C# Class. And here is how the class looks by default without any changes from my side:
namespace play.input.controllers
{
public class foo
{
}
}
While I would expect the namespace in this case to be gameplay.input.controllers.
I am confused why would VS Code change the gameplay to play? How could I fix it?
UPDATE
I can not find the RootNamespace in my project:
So, the provided answer has no value for me.
You can set the default namespace of a project in Project Preferences->Application. The string that is visible in the "Default Namespace" input box is used for new files in the root directory of the project. If you create items in subfolders, these will be included in the namespace by default.
If you want to remove the application name (play in your case), you can define the default namespace as empty.
You can also edit the project file to include the RootNamespace tag, as follows:
<PropertyGroup>
<TargetFrameworks>net5.0;netcoreapp2.1</TargetFrameworks>
<EnableDefaultItems>false</EnableDefaultItems>
....
<RootNamespace>MyRootNamespace</RootNamespace>
....
</PropertyGroup>
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).
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.
I am a newbie of C# and MS visual studio, and I want to use the C# class which defined in another file, but can't get it work.
Here is the program.cs(and why can't I rename that file ?)
using System;
namespace TestCSharp2
{
class Program
{
static void Main(string[] args)
{
Class2 class2 = new Class2();
// here the IDE will complain that cant find namespace or balabala..
class2.setValue(10);
Console.WriteLine(class2.getValue().ToString());
Console.ReadKey();
}
}
}
And here is the Class2 that I want to use in file Class2.cs:
namespace TestCSharp2
{
class Class2
{
int i;
public void setValue(int i)
{
this.i = i;
}
public int getValue()
{
return this.i;
}
}
}
Should I #include or something? isn't use namespace enough?
As some guys asked if they are in the same assembly/same project, I presume they were, because here is the procedure how they are created:
A new project using the template of Console C# Project, then the program.cs was created by default.
The Class2.cs was created with [File] -> [New] -> [File] -> [C# class] and saved in the same folder where program.cs lives.
To be honest, I don't know if they are in same assembly / same project, but I guess they were.
According to your explanation you haven't included your Class2.cs in your project. You have just created the required Class file but haven't included that in the project.
The Class2.cs was created with [File] -> [New] -> [File] -> [C# class] and saved in the same folder where program.cs lives.
Do the following to overcome this,
Simply Right click on your project then -> [Add] - > [Existing Item...] : Select Class2.cs and press OK
Problem should be solved now.
Furthermore, when adding new classes use this procedure,
Right click on project -> [Add] -> Select Required Item (ex - A class, Form etc.)
Yeah, I just made the same 'noob' error and found this thread.
I had in fact added the class to the solution and not to the project.
So it looked like this:
Just adding this in the hope to be of help to someone.
It would be more beneficial for us if we could see the actual project structure, as the classes alone do not say that much.
Assuming that both .cs files are in the same project (if they are in different projects inside the same solution, you'd have to add a reference to the project containing Class2.cs), you can click on the Class2 occurrence in your code that is underlined in red and press CTRL + . (period) or click on the blue bar that should be there. The first option appearing will then add the appropriate using statement automatically. If there is no such menu, it may indicate that there is something wrong with the project structure or a reference missing.
You could try making Class2 public, but it sounds like this can't be a problem here, since by default what you did is internal class Class2 and thus Class2 should be accessible if both are living in the same project/assembly. If you are referencing a different assembly or project wherein Class2 is contained, you have to make it public in order to access it, as internal classes can't be accessed from outside their assembly.
As for renaming: You can click Program.cs in the Solution Explorer and press F2 to rename it. It will then open up a dialog window asking you if the class Program itself and all references thereof should be renamed as well, which is usually what you want. Or you could just rename the class Program in the declaration and again open up the menu with the small blue bar (or, again, CTRL+.) and do the same, but it won't automatically rename the actual file accordingly.
Edit after your question edit: I have never used this option you used, but from quick checking I think that it's really not inside the same project then. Do the following when adding new classes to a project: In the Solution Explorer, right click the project you created and select [Add] -> [Class] or [Add] -> [New Item...] and then select 'Class'. This will automatically make the new class part of the project and thus the assembly (the assembly is basically the 'end product' after building the project). For me, there is also the shortcut Alt+Shift+C working to create a new class.
namespace TestCSharp2
{
**public** class Class2
{
int i;
public void setValue(int i)
{
this.i = i;
}
public int getValue()
{
return this.i;
}
}
}
Add the 'Public' declaration before 'class Class2'.
According to your example here it seems that they both reside in the same namespace. I conclude that they are both part of the same project (if you haven't created another project with the same namespace)
and all classes by default are defined as internal to the project they are defined in, if haven't declared otherwise, therefore I guess the problem is that your file is not included in your project.
You can include it by right clicking the file in the solution explorer window => Include in project, if you cannot see the file inside the project files in the solution explorer then click the show the upper menu button of the solution explorer called show all files (just hover your mouse cursor over the button there and you'll see the names of the buttons).
Just for basic knowledge:
If the file resides in a different project\ assembly then it has to be defined,
otherwise it has to be defined at least as internal or public.
In case your class is inheriting from that class that it can be protected as well.
I was having the same problem here. Found out that the problem was with an Advanced Property of the file. There is there an option with the name 'Compilation Action' (may be not with the exact words, I am translating - my VS is in Portuguese).
My Class1.cs file was there as "Content" and I just had to change it to "Compile" to make it work, and have the classes recognized by the others files in the same project.
Just make two projects in two different files then rename the "Program.cs" of one of the two files
and copy it then paste it next to the Program.cs of the other file and that's it.
In your project there will be a file with .csproj extension.
Double click on it to open the project in the Visual Studio. Otherwise, if you make a new class, it won't link with other classes.
When u diclare your , var
you , can use private , declarasion
using System;
private Class class;
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!