Creating a VS 2019 Generate Type in new file refactoring extension - refactoring

I heavily use the VS 2019 quick refactorings, particularly the "Generate Type in new file" refactoring.
However, this refactoring generates code with private members like this
private FloorId id;
private BuildingId buildingId;
private SiteMapId siteMapId;
whereas I want public properties like
public FloorId Id{get;}
public BuildingId BuildingId{get;}
Public SiteMapId SiteMapId{get;};
Also the class is generated with an internal access modifier on the class itself, and I want public.
I can't determine how to customise the code generation, so I thought I would create a custom VSIX Refactoring Project and build my own refactoring implementation.
I would like to try and find the source code for the "Generate class in new file" refactoring so that I can use that as a basis to build my own.
Does anyone know where I could find this code, or something similar?
It seems like creating custom refactorings VSIX projects is a rather niche subject, and not a great deal out there to work from.

If you're unaware the "Generate new type..." option that's last in the refactoring list, that pops up a dialog that lets you customize some behavior, including the access modifier of the class. We don't let you choose properties but that's a good suggestion.
The C# engine for Visual Studio (Roslyn) is open source, so you can find at least a tiny bit of the code here: https://github.com/dotnet/roslyn/tree/master/src/Features/Core/Portable/GenerateType. That said, there's a lot of code there and a huge amount of stuff it depends on...this is not trivial to rewrite and easily extract. You're probably best off trying to modify that and then running a custom Roslyn to experiment with. You may also want to consider opening an issue or discussion on the Roslyn repository, because honestly this might just be a feature we'd take via pull request.

Related

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

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

Find all references doesn't locate member references in other .NET projects of differing language

I have a VS 2013 solution with one VB.NET ASP.NET project which references several c# class library projects (not DLLs) within the same solution. I made lots of changes to logic within some of the method overloads in one of the c# projects. Since the VB.NET project uses these overloads extensively, I want to see how many places these methods are referenced. I go to the c# project that contains the changes, right-click the overload I want, and select Find All References, but it only shows me the references in the c# projects. However, when I go to one of those methods in the VB.NET project, it finds all the references within the VB.NET project as well as the method declarations in the c# project.
I could do a solution-wide text search for the method name, but this method name is used multiple times because it's overloaded. Therefore, I want to search for a particular overloaded method signature, not the method name.
Is this a known shortcoming of VS 2013? Something else I've also noticed that I've noticed is that selecting Go To Reference from within a VB.NET project on a method that's declared in a c# project will take you to the object browser rather than directly to the method definition in the source project itself.
This is an old problem, there are many bug feedback reports for it on Microsoft's feedback site. The canonical one is probably this one. Quoting Dustin Campbell's response:
The general problem is that C# and Visual Basic do not share any common infrastructure with regard to the symbol tables that are used for features like Find All References, Go to Definition or Rename. So, such features don't work between multiple languages. That said, we are looking at ways to change this in the future, but the work required is very substantial.
Annotating a bit, the C# and VB.NET IDEs look similar at the surface but they are very different under the hood. Part of that is them being supported by distinct groups within Microsoft, a survival strategy for any software company, big groups don't work. But above all history plays a strong role in this, Visual Basic had strong IDE support for a very long time. They did not throw away that work when they moved to VB.NET, not in the least because they had to support all previous IDE features so not to alienate their existing customer base. The C# team got a fresh start without that baggage, they started from scratch. Inevitably the internals between them, like the IntelliSense symbol tables, are drastically different.
Tackling the "common infrastructure" problem was not forgotten, the Roslyn project was the instrumental step. It took a very long time to get finished but it is ready to go today. Integrated into VS2015. Whether it actually solves this problem is something I don't know yet, I will in a couple of months. Maybe somebody that has the RC version can confirm. They did create two versions of Roslyn, one for C# and another for VB.NET. Uh-oh.

Possibilities of the IWizard interface

I've played around with Visual Studio Project Templates and found them useful so far.
Now I've found some material on Wizards and the IWizard interface.
The first basic steps are fairly easy to comprehend and seem very useful, but now I'd like to explore what else the IWizard interface has to offer, other than mere Text replacement. I can imagine a few use cases for the ShouldAddProjectItem method, but what - for example - if I want the user to be able to pick database tables and have the wizard generate model, mapping and CRUD-dao code (I already have an assembly for that tedious task)?
Can anyone give me links or hints on facilities of the interface?
In order to make CRUD, DAO, etc... I'll suggest you to check T4 Templates and, if you want more power.
Combine T4 with Dev Art's Entity Developer
Put it all inside a IWizard
Let me explain it a little bit more...
You'll need to develop some T4 Template integrated with Entity Developer (to apply either Entity Framework's or NHibernate's metadata) or standalone, in order to create as many CRUD-Dao-Service-DTO like classes you need.
Then, with the T4, you can create a new project, add it as long as a Entity Developer empty model, export it as project template, and make a IWizard with a custom dialog as show in the example you referenced.
In this IWizard, you ask for the Connection String, then you make text replacement with IWizard replacement and... you're done! User makes a "Update Model from Database" and the Entities are done.
I hope this hints are enough to start!

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.

Visual Studio - Edit source code located in a database

I am building something similar to Server Explorer for Apache CouchDB. One of the things necessary is to be able to edit CouchDB view definitions which in CouchDB are JavaScript functions.
How can I trick Visual Studio into using my object to retrieve and save the content of the JavaScript function but still use the rest of it - I am happy with editor itself and have no intention of writing my own Editor/Language Service, etc. The latter would be much bigger effort than what this project warrants
Edit
After more digging I am still stuck. Here is what I know: IVsUIShellOpenDocument interface provides a method OpenStandardEditor which can be used to open the standard Visual Studio editor. As one of the parameters this method takes a Pointer to the IUnknown interface of the document data object. This object is supposed to implement several interfaces described in many places all over the MSDN.
Visual Studio SDK also provides a 'sample' implementation of the document data object VsTextBufferClass. I can create an instance of this class and when I pass the pointer to the instance to the OpenStandardEditor I can see my editor and it seems to work ok.
When I try to implement my own class implementing the same interfaces (IVsTextBuffer, VsTextBuffer, IVsTextLines) OpenStandardEditor method returns success, but VS bombs out on call editor.Show() with an access violation.
My suspicion is that VsTextBufferClass also implements some other interface(s) but not in C# way but rather in the good old COM way. I just do not know which one(s).
Any thoughts?
What if you had a program that would export the javascript to files on disk, then imported them back into the database once you were done editing them with Visual Studio? That might be the simplest way to do this.

Resources