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>
Related
In the resx properties, I changed the Custom Tool Namespace from DefaultNamespace to MyNamespace.Language and the following code is generated:
namespace MyNamespace.Language
{
public class CommentResources
{
public static global::System.Resources.ResourceManager ResourceManager {
get {
//removed code...
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DefaultNamespace.CommentResources", typeof(CommentResources).Assembly);
}
}
As you can see, only the class namespace is changed, but not the namespace passed in the ResourceManager constructor and because of that, when I instanciate ResourceManager(typeof(CommentResources)) and try to access a key, it throws MissingManifestResourceException, for example:
var manager = new ResourceManager(typeof(CommentResources));
var resource = manager.GetString("myKey");
How can I truly changed the namespace?
EDIT:
Take a look at my solution below. Whenever I create a resx file within Enviroment folder, it creates a unwanted namespace. That's what's I'm trying to avoid
I recently stumbled to the same issue.
It seems that Visual Studio 2017 generates code that creates ResourceManager from RootNamespace.SubFolder.ResourcesFileName instead of CustomToolNamespace.ResourcesFileName.
Since the code is created from the Visual Studio's Single-File Generator tool called either ResXFileCodeGenerator (for internal class) or PublicResXFileCodeGenerator (for public class) that internally uses StronglyTypedResourceBuilder class, there is no way to customize its behavior, other than implementing your own Single-File Generator as a Visual Studio extension and using it as a Generator for the EmbeddedResource.
Fortunately, there is a simpler workaround. In .csproj file, under EmbeddedResource tag, specify LogicalName tag with text value of RootNamespace.SubFolder.ResourcesFileName.resources.
In your specific case, it would look like this:
<LogicalName>DefaultNamespace.CommentResources.resources</LogicalName>
I have created a Xamarin Forms application. I created another PCL library for keeping UI constants like Color codes.
Portable project name is App.
PCL library project is Utilities.
Defined this in my PCL lib
namespace App.Utilities
{
public class Colors
{
public static Color ColorCode1 = Color.Aqua;
}
}
Tried to define xmlns in xcml file like this.
xmlns:colors="clr-namespace:App.Utilities.Colors;assembly=App.Utilities"
But it is throwing xaml parse exception saying the above namespace cannot be found.
Any help?
XMLNS declaration syntax is correct. Namespace need not include the class name. So In this case Namespace has to be just App.Utilities and not App.Utilities.Colors. Changing it to
xmlns:colors="clr-namespace:App.Utilities;assembly=App.Utilities"
will work provided your assembly name is correct.
You can verify if your assembly name is correct by Right-Clicking on PCL Forms prject > Options > Output (Under Build). There we can see the correct assembly name.
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.
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!