Is there a way in visual studio 2022 to add a new line before and after namespace? - visual-studio

I am using Visual Stuido 2022 to code my C# project.
Is there a way to configure VS using (.editorconfig file) where a new line is added before and after the namespace?
So my class will look like this
using System;
namespace ProjectName.Tests;
public class Test
{
}
instead of
using System;
namespace ProjectName.Tests;
public class Test
{
}

I'm not sure there is a Visual Studio native way of doing this.
There is definitely not a way to do this in .editorconfig with Visual Studio alone (meaning no plugins). About halfway down Namespace declaration preferences, it talks about csharp_style_namespace_declarations, and the code formatting sample when that value is file_scoped looks like
// csharp_style_namespace_declarations = file_scoped
using System;
namespace Convention;
class C
{
}
which appears to get you part of the way there (blank line after using). When you look at the supported formatting rules, the list is pretty brief.
If you have ReSharper there is a way. These settings in .editorconfig will do what you want:
resharper_blank_lines_after_file_scoped_namespace_directive = 1
resharper_blank_lines_after_imports = 1
If ReSharper is not an option, here are 3 possible paths to take, none all that great. They certainly aren't simple solutions.
try to find something in the Visual Studio Marketplace
write a .NET Analyzer that is configured via .editorconfig (ref. this page)
raise an issue on Developer Community, and hope they get to it.

Like the other guy said,
No, not with editor config (out of the box).
Resharper can do this; you can build a custom format for your code and tell it, for example, where you want certain sections like imports below the class for some weird reason ;) ...of course, with that spacing around those sections.
But now you have to get ReSharper licenses for all your devs. The Resharper devs are very cool, and Jetbrains has been building quality software for a few decades. Maybe I'm sentimental.
Well, there is another option if you don't want to pay...
In DevOps roles of the past, I've used Roslyn to build extensions for custom formatting.
Build a custom Rosyln analyzer.
https://learn.microsoft.com/en-us/visualstudio/code-quality/roslyn-analyzers-overview?view=vs-2022#severity-levels-of-analyzers
You can build a custom code suggestion with this of configurable severity.
It's pretty easy, too, thanks to Rosyln, but you must think a little backward. Let me know if I can help more.

StyleCop.Analyzers has a bunch of formatting related rules that you can enforce and, in some cases, automatically fix across your codebase.
Unfortunately it looks as though there is not yet support for file-scoped namespace formatting in the way you want. There's a PR to add it here, so if you really wanted to have this you could get that PR across the finish line, or make your own build:
https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3512
This issue might also be worth a look:
https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3578

Related

FxCop Custom Rules for Custom Controls

In my project I am using custom controls instead of normal ASP.NET controls. We have build an architecture on .NET and are using its controls.
Now I need to write a custom rule to check for if some of windows controls are being used. Reason being, my team needs to be limited to only my custom controls that were designed to replace the windows controls.
Example: I need to search and if they are using System.Windows.Controls.Textbox.....I need it to be an error.
Can anyone please help me out with code?
I hope the problem is clear ..... in case of any further clarifications needed please let me know.
The logic for this sort of rule is fairly simple:
Check method bodies, visiting each constructor invocation to see if
the target class inherits from the base Control class.
If it does, verify that the target class is in your namespace or assembly (or however you can best identify it as "yours").
This is relatively simple. A much bigger problem is that the relevant contructors will usually be invoked in designer-generated code, which most folks tend to prefer ignoring when executing FxCop. To get your rule to work, you will need to include designer-generated code in your analyses.
The tool NDepend let's write custom code rules on .NET code much more easily than with FxCop. Disclaimer: I am one of the developer of the tool
With this tool you can write custom code rules over LINQ queries (what is named CQLinq). For example, the query you are asking for can be written this way with CQLinq:
// <Name>Don't use system controls</Name>
warnif count > 0
let systemControls = ThirdParty.Types.Where(
t => t.DeriveFrom("System.Windows.Forms.Control".AllowNoMatch()))
where systemControls.Count() > 0
from t in systemControls
let methodsThatCreateT = t.TypesUsingMe.ChildMethods().Where(m => m.CreateA(t))
select new { t, methodsThatCreateT }
While editing such code rule, instantly a browsable result is shown (in 3 milliseconds here). Double clicking any type or method in this result, jumps to its declaration in source code in Visual Studio:
200 default code rules are proposed. The tool is 100% integrated in Visual Studio 2012, 2010, and 2008. Default or custom code rules can be validated inside Visual Studio, and/or at Build Process time, in a generated HTML+javascript report.

Create Language Service for VisualStudio 2010

I want to build a language service for visual studio 2010. I was first trying to follow the tutorial and documentations from MSDN.
The problem is i don't succeed to make this works (i'll explain later my problem). So i digged into existing implementations, i found Ook! and lua . both of these projects doesn't use the tutorial or documentation i found on MSDN, but something based on MEF. Lua used this only with previous Visual Studio versions.
So i'm wondering if i'm using an obsolete method to create a language service (But the documentation aims Visual Studio 2010), or there is different ways to do this, which depends on needs.
In my case, i've got a language that doesn't need to be compiled into cli, but i want to have an editor that have colorization, syntax warnings and errors, intellisense ...
The problem i mentionned is that when launching exp instance, there is no text editor with my file extension, and visual studio begins to have many lags. The language service is registered using 3 attributes : ProvideServiceAttribute, ProvideLanguageServiceAttribute and ProvideLanguageServiceExtension. Also initialized in Package intialize method, like mentionned in Proffer the Language.... The package is loaded when i try to open the file with my extension, the language service is initialized.
So i don't get it why i does not work, could you please help me to understand how language service works, and what is the best way to implement it
Thanks
Good chance your IScanner implementation has an endless loop, happened to me.

How to highlight dynamic code in visual studio

Is it possible and if so how, to make Visual Studio highlight dynamic expressions in code?
When I just hovered above some code, visual studio told me it was a dynamic expression. This made me realize I made a mistake in my code and used one dynamic too many. But I also realized that if I had not hovered, a 'huge swath' of dynamic code that was supposed to be static would have escaped.
So I wondered if it is possible to make Visual Studio change the background color of dynamic expressions, so those pieces will be clearly recognizable.
[edit]
With dynamic expressions I mean the use of the dynamic keyword in regular code.
You would need an Extension. You can create your own, but I would suggest getting pre-built ones.
Visual Studio has a lot of extensions lately, because of it's popularity.
There are many options I could suggest, but many are rather buggy, so I would suggest using one of the safer, more well known ones like Resharper (my all time favorite and that of many others as well)
I also like JustCode.
There are so many others available though, and if you want to find them, cruise down the Visual Studio Gallery like Morvader said.
Visual Studio Gallery
EDIT:
2 notes I forgot to mention:
Dynamic Intellisense is included in Resharper
Dynamic Highlighting is included as well. If you want to modify the color from the default light blue you can go to Tools->Options...->Environments->Fonts and Colors->Display items->ReSharper Late Bound Identifier
Also make sure that in Resharper->Options...->Code Inspection->Settings "Enable code analysis" and "Color identifiers" are checked.

visual studio: is it possible to color custom tags in code?

Is it possible somehow to color specified code in specified color in any version of visual studio? For example, make background of
if( VERIFY( ... ) )
green and background of
if( ! VERIFY( ... ) )
red? Maybe some addon exists or some version of visual studio has such functionality?
NO PLUGIN NEEDED
According to MSDN and this tutorial, you can set user-defined keywords for syntax highlighting in a
usertype.dat file, which you should save in the same directory as Visual Studio's msdev.exe, or devenv.exe for VS.NET.
Now restart Visual Studio.
Then in VS you can set the font properties for those keywords.
Edit: BTW, see the download here for a predefined usertype.dat with a lot of keywords ready to use.
You can use Resharper's "ToDo Items" to accomplish this.
Resharper -> Options
Create a pattern.
Here you can specify the color, pattern, icon etc. This should already give you colorized code, the rest is optional, but makes it easier to find the patterns.
(look at existing patterns for the syntax, or check the docs)
You can use filters to find the patterns, and combinations of patterns
You could create a filter that contains both your patterns for instance.
use Resharper -> Tools -> ToDo-Items to search for the patterns
I don't know of an existing addin that does anything like that but I do know that Developer Express, the company that makes CodeRush, makes the addin engine freely available as a product called DxCore. This makes is much easier to create an addin that decorates the Visual Studio text editor. In Visual Studio 2010, a lot of the extremely difficult code that DxCore abstracts is no longer necessary as there is an official extensibility model for decorating the editor.
Here's a link to some DxCore plugin samples on Google Code.
No, but you may be interested in FxCop, it's more elaborate, but it should allow you the ability to detect the case you're talking about (via a custom rule, if it doesn't exist). It may be more work to set up, but it's worth it (especially if work in a team, and/or, have an existing CI system).
According to the VS Extensibility form Moderator, Ed Dore, it is not possible:
http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/93fc6d61-cfdb-432d-8541-d7dce498cef5/
Unfortunately, no. The code implementing the document tabbing was developed with native Win32 code, and currently doesn't have any VS SDK or automation hooks into it.
It is too bad as this would be beyond useful. (Keep track of different types of files and such.)

Visual Studio Language Service with C# intellisense

Last year I wrote a Language Service for Visual Studio which added syntax highlighting for NHaml files: http://github.com/snappycode/hamleditor.
To clarify, NHaml is a html template language that can mix in code elements like an aspx file can. This plugin adds support to the IDE for editing NHaml files, but basically only adds syntax highlighting.
I was wondering if anyone knows how to add inline c# intellisense to the service like you get now in an aspx file. I'm hoping that would be possible without doing the whole c# grammar myself specific for the plugin.
Has anyone written a language service that mixes languages?
UPDATE:
It looks like the spark view engine guys have made some inroads here, I am investigating their implementation
I checked the Spark View Engine, and they seem to have made a generic ATL stuff (called SparkLanguagePackageLib), that in fact seems to be not containiag anything Spark specific. It seems to be just a generic C# intellisense library that needs the following:
The original code
The C# source that gets generated from the original code
The position mappings between the two (for example the code on line 2 pos 5 gets mapped in the output to line 4 pos 10, etc.)
Some other things, like Paintings(?)
And after that you can call:
events.OnGenerated(
primaryText, // original source code
entry.SourceCode, // generated sourcecode
cMappings, // mappings between the two
ref mappings[0], // ?
cPaints, // ?
ref paints[0]); // ?
I've tried to find Spark-specific stuff in that C++ library, but I couldn't find anything: everythig spark-related is split to a separate C# code file. I think this is good, because:
You don't need to edit the C++ files
If the spark view engine's intellisense support is installed it can be used by other view engines too
You only need to create a class, that maps between the original nhaml file and it's generated C# counterpart.
Btw. Are you still working on this NHaml Intellisense library? If not I'll try to patch their implementation in hope it can be converted to NHaml easily.
this looks like it might help
http://www.codeproject.com/KB/recipes/VSLanguageService.aspx
I finally managed to modify the code to support NHaml. It wasn't that hard at all. Unfortunately the original NHaml library doesn't support everything that was needed, so I had to create a new parser for NHaml. It doesn't support all of the constructs, but it supports most of them (enough to make NHaml programming easier)
Download: http://github.com/sztupy/nhamlsense
Screencast: http://www.youtube.com/watch?v=8jTZ2zC9eYc
You can easily add keywords by creating or modifying a usertype.dat file. Check here for some directions on attaching to specific file extentions. That might get you at least part of the way, without redoing the complete c# syntax.
(In fact, I'm not sure what you mean exactly by 'syntax highlighting' in this context. I'm sure, for instance, you get brace-match highlighting for free in the editor).

Resources