Filescoped namespaces in visual studio 2019 - c#

I am trying to use filescoped namespaces in visual studio 2019. So instead of:-
namespace my.namespace
{
public class MyClass
{
}
}
I want:-
namespace my.namespace;
public class MyClass
{
}
Following online tutorials and going through other answers I have tried adding editorConfig file but the editorConfig visual studio is generating for me is different than what I am seeing online. My file is starting with this text:-
# Rules in this file were initially inferred by Visual Studio IntelliCode from the C:\myproject codebase based on best match to current usage at 3/25/2022
# You can modify the rules from these initially generated values to suit your own policies
# You can learn more about editorconfig here: https://learn.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference
[*.cs]
#Core editorconfig formatting - indentation
#use soft tabs (spaces) for indentation
indent_style = space
#Formatting - indentation options
#indent switch case contents.
csharp_indent_case_contents = true
#indent switch labels
csharp_indent_switch_labels = true
And this file has no information on filescoped namespaces.

Related

Visual Studio Community C# code formatting

I am trying to format C# code of a WinForms .NET Core 7.0 project in Visual Studio Community:
private void Form1_Load(object sender, EventArgs e)
{
Dictionary<String, String> Dictionary = new Dictionary<String, String>
{
{ "operation", "login" },
{ "phone", "123"},
{ "country","456"} ,
{ "otp", "789"},
{"language","111" }
};
}
I have tried Ctrl+K, Ctrl+D, removing the last brace in the code and putting it back.
The extra spaced are not getting removed. Can these be removed in whole code automatically using a command? If not, is there a plugin / extension that can help in code formatting?
Use the shortcut key Ctrl+f.
Enter [^\S\r\n]{2,} in FIND
The value in the "replace" is empty
Select use regular expression(Alt+E)
Click the Replace All button(Alt+A)
Use the Auto Align shortcut (CTRL+K+D)
ReSharper works with VS Community and will reformat that case by either
removing the ; and re-entering it (format on typing)
or reformatting the whole file via Cleanup Code... on the context menu for the C# file.
You'd have to pay for ReSharper, though, unless you're a student, working on an open-source project, or otherwise qualify for the free license.
Visual Studio Community (and probably Pro and Enterprise) doesn't seem to reformat dictionaries regardless of what you seem to do with a .editorconfig file or what you have set in Tools | Options | Text Editor | C# | Code Style | Formatting | General.
There may be other extensions that do this. Perhaps you could find one on the Visual Studio Marketplace.

How can I use a file-scoped namespace declaration in a class template?

C# 10 introduced file-scoped namespaces, which I would like to use in Visual Studio's class templates. I've updated the 'Class' template file to the following:
namespace $rootnamespace$;
class $safeitemrootname$
{
//I put this comment here to make sure it's using the right file
}
But when I create a new empty class I get this autogenerated code:
namespace ProjectName
{
internal class Class1
{
//I put this comment here to make sure it's using the right file
}
}
What do I need to do to make the auto-generated code for an empty class look like this?
namespace ProjectName;
internal class Class1
{
}
For reference, I am using Visual Studio 2022 Professional and my project is using C#10 with .NET 6.
The location of the class template file that I am modifying is: C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\Class.cs
You have to set up your project's editorconfig to prefer File-scoped namespaces.
Right click your project. Select "Add" → "New Item"
Select "editorConfig File (.NET)"
Double click the new editorconfig file. In the "Code Style" tab set "Namespace declarations" to "File scoped"
The code template will now work as expected.
Check this thread: https://stackoverflow.com/a/69889803
They use a .editorconfig file where you can specify the namespace declaration style. When creating a new file in VS 2022 it will use that new style

Change VS option by using the Settings Store: finding the right CollectionPath?

I need to set the value of a Visual Studio option found in Visual Studio -> Tools -> Options -> Text Editor -> JavaScript/TypeScript -> EsLint but I can't seem to find the CollectionPath for this option.
GetSubCollectionNames("Text Editor"); yield a number of results, while GetSubCollectionNames("Text Editor\\JavaScript"); yield 0 results.
TL;DR
How would one go about finding the right CollectionPath for the option pictured in the image below?
This is what I'm using currently.
[ImportingConstructor]
internal VSOptions([Import] SVsServiceProvider serviceProvider)
{
var settingsManager = new ShellSettingsManager(serviceProvider);
_writableSettingsStore = settingsManager.GetWritableSettingsStore(SettingsScope.UserSettings)
?? throw new Exception(nameof(settingsManager));
var textEditorSubCollections = _writableSettingsStore.GetSubCollectionNames("Text Editor");
var javaScriptSubCollections = _writableSettingsStore.GetSubCollectionNames("Text Editor\\JavaScript");
// TODO: set option value when we have the right CollectionPath
}
The WritabelSettingsStore class used to extend Visual Studio common settings in Visual Studio. You could use GetPropertyNames("Text Editor\JavaScript") to list all writabel settings for JavaScript, where you will find not all Properties under JavaScript sub collections are listed.
The EsLint is not common Visual Studio Settings. It is third part tool for identifying and reporting on patterns found in ECMAScript/JavaScript code, with the goal of making code more consistent and avoiding bugs.
So we could not change it directly with WritableSettingsStore class. You need to know how the EsLint added in Visual Studio and then modify its configuration file for Visual Studio.

Adding custom format to a template parameters Visual studio project

I have defined a Visual Studio template called classDB.cs. I would like the default name for the class to appear as [projectname]DB.cs, where [projectname] is the name of the current project (as entered in the Create Project dialog). Is there a way to achieve this? I tried setting the name of the class to $safeprojectname$DB.cs, but that didn't work.
UPDATE
I modified my project template but give's this error when it's generating the project
here's the template class
namespace $safeprojectname$.Models
{
public class $safeprojectname$DB : DbContext
{
}
}
I have been battling with a similar error to this for days, and I finally figured it out. Visual Studio escapes the $ in the .csproj file. So you will have a node that looks like this:
<Compile Include="Models\%24safeprojectname%24DB.cs" />
Open up the .csproj file in a text editor, and change it to:
<Compile Include="Models\$safeprojectname$DB.cs" />
And save the file. Your project will reload, but it won't try to escape the filename again! Export your template, and you should find that the parameter now gets replaced.
Try a template like this:
using System;
//...
namespace $rootnamespace$ {
class $safeitemname$DB {
}
}
Works for me.
Make sure you update the correct template (should be located under C:\Users\[user]\Documents\Visual Studio 2010\Templates\ItemTemplates on Windows 7) and restart Visual Studio.
EDIT
The above code is for an Item Template, but that shouldn't differ from a Project Template. According to MSDN, the $safeitemname$ and $safeprojectname$ parameters behaves the same:
safeitemname
The name provided by the user in the Add New Item dialog box, with all unsafe characters and spaces removed.
safeprojectname
The name provided by the user in the New Project dialog box, with all unsafe characters and spaces removed.

Visual Studio Addin "Exclude From Build" Property

I am currently trying to create an addin for Visual Studio 2008 that will list all files which are not excluded from the current build configuration.
I currently have test C++ console application that has 10 files, 2 of which are "Excluded From Build". This is a property that will allow a specific file to be excluded from a specific configuration (i.e. Debug or Release). This property is located when you right click on a file in the solution explorer and select Properties->Configuration Properties->General->Excluded From Build
At the moment I have the following code that will loop though all project files and get the properties for each file.
foreach (Project theProject in _applicationObject.Solution.Projects)
{
getFiles(theProject.ProjectItems);
}
private void getFiles(ProjectItems theItems)
{
foreach (ProjectItem theItem in theItems)
{
string theItemName = theItem.Name;
foreach (Property theProp in theItem.Properties)
{
string thePropName = theProp.Name;
}
getFiles(theItem.ProjectItems);
}
}
The issue I am having is that I cant seem to find the "Excluded From Build" property. I cannot find very good documentation on what properties are listed where. Where is this Excluded From Build property located within the _applicationObject object?
I'm not familiar with the Visual Studio object model, but in the documentation for VS2005 the following objects have an ExcludedFromBuild property:
VCFileConfiguration
VCFileConfigurationProperties
VCPreBuildEventTool
VCPreLinkEventTool
VCPostBuildEventTool
VCWebDeploymentTool
Hopefully this will lead you down the right path.

Categories