Visual Studio and root namespaces - visual-studio-2010

I am using VS2010, is there a way, to disable full root namespaces, when VS is autogenerating code? From this:
{
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
}
to this:
using System.ComponentModel;
{
CollectionChangeEventHandler schemaChangedHandler = new CollectionChangeEventHandler(this.SchemaChanged);
}

I don't know if there is, however doing so is a VERY BAD idea.
VERY BAD.
VERY BAD.
VERY VERY BAD.
First, it suggests you are editing generated code. If you are, see above. The solution is to use partial classes, if you aren't already. Almost all generated code is done using partial classes. If not, open a Connect.
Second, it is there for a reason--it prevents generated code class names and namespaces from clashing with yours. When generated code isn't globally scoped and it does clash, you only have two choices: Either rename your code or edit the generated code every time you regenerate it. This is the definition of a Pain in the Ass.
I know it doesn't look pretty, but the fact is you should NEVER be looking at it.
NEVER.
etc.
Here's a connect I opened because the EF4 T4 templates didn't globally scope their variables, so the generated code clashed with my Debug namespace.

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

Is it possible to generate from code using T4

I have used T4 to generate partial classes from some input file (XML, etc) and then hand code additional partial bits onto those generated classes.
Is it possible to go the other way? To hand craft partial classes, and use T4 to template boiler plate bits to them?
Obviously I can't use reflection to look for the classes since it's not compiled yet, but I see Visual Studio inspect uncompiled code for different utilities. Perhaps Visual Studio offers some feature to support this I don't know about. Long shot, I guess.
Thanks
Also, you can use T4 with VS's CodeModel to read the code in your project without compiling and then generate from that metadata.
There's some pointers to examples here: http://blogs.msdn.com/b/garethj/archive/2009/09/25/dte-and-t4-better-together.aspx
Actually, T4 is used this way frequently. Yes, it requires reflection, but partial classes compile even if bits of them aren't generated yet. I would look at examples for generating strongly typed views as described here for examples of using reflection to generate new files.

Browsing 'Decorated Names' in Visual Studio

I'm working on a (rather horrible) project that involves importing a C++ class hierarchy through a dll interface. One of the more horrible details requires me know the 'decorated' names for the various class elements that are exposed - mostly member functions and static data.
There are many ways to achieve this - the assembly listing or map file, dumpbin, a dependency walker, the _FUNCDNAME_ macro, etc. Unfortunately, they all require me to actually compile the code or have the compiled dll - and all I have available is the header files. (That may leave you scratching your head for a minute - just take my word that it truly is a horrible project.)
Now, I can easily concoct something compilable from just the headers and use one of the above approaches. But if I can avoid it, that would be much better. So my question is: is there a way to browse decorated symbol names from within Visual Studio, a la Object Browser? I know that the decoration is technically done at compile time, but Intellisense does so many other things while you type that I'm hoping it might do this too.
If all else fail take that .h, rename it to .cpp, replace all semicolons (;) with
{
#pragma message(__FUNCDNAME__)
}
edit it a little, and compile it. You'll get your list.

Building a Visual Studio Package based on another one

I want to add my own project type based on IronStudio. So,
I downloaded the source for and compiled the latest version of IronPython, then
I created a new Visual Studio Package.
I added the Templates\Projects\MyProject folders, and added a file to it, and set its property "Include in VSIX" to true.
Then modified the main Package class to be derived from IronStudio's PythonProjectPackage instead, and set the ProvideProjectFactory property:
[ProvideProjectFactory(
typeof(PythonProjectFactory),
"Django Project",
"Django Project Files (*.myproj);*.myproj",
"myproj", "myproj",
#"Templates\Projects\MyProject",
LanguageVsTemplate="MyProject")]
public sealed class MyPackage : PythonProjectPackage
And ran it. But MyProject isn't showing up in the project templates. Why not?
The generated .pkgdef file looks like this:
[$RootKey$\InstalledProducts\VSPackage3Package]
#="#110"
"Package"="{5cd7435c-7461-459f-80bc-c0c79e9d462f}"
"PID"="1.0"
"ProductDetails"="#112"
"LogoID"="#400"
[$RootKey$\Packages\{5cd7435c-7461-459f-80bc-c0c79e9d462f}]
#="Microsoft.VSPackage3.VSPackage3Package, VSPackage3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a4f1577d825253f8"
"InprocServer32"="$WinDir$\SYSTEM32\MSCOREE.DLL"
"Class"="Microsoft.VSPackage3.VSPackage3Package"
"CodeBase"="$PackageFolder$\VSPackage3.dll"
[$RootKey$\Editors\{888888c4-36f9-4453-90aa-29fa4d2e5706}]
"Package"="{5cd7435c-7461-459f-80bc-c0c79e9d462f}"
[$RootKey$\Editors\{888888c4-36f9-4453-90aa-29fa4d2e5706}\Extensions]
"py"=dword:00000020
[$RootKey$\Editors\{888888c4-36f9-4453-90aa-29fa4d2e5706}\LogicalViews]
"{7651a701-06e5-11d1-8ebd-00a0c90f26ea}"=""
[$RootKey$\Editors\{888888c4-36f9-4453-90aa-29fa4d2e5706}\LogicalViews]
"{7651a702-06e5-11d1-8ebd-00a0c90f26ea}"=""
[$RootKey$\Editors\{888888c4-36f9-4453-90aa-29fa4d2e5706}\LogicalViews]
"{7651a703-06e5-11d1-8ebd-00a0c90f26ea}"=""
[$RootKey$\CLSID\{888888fd-3c4a-40da-aefb-5ac10f5e8b30}]
#="Microsoft.IronPythonTools.Project.PythonGeneralPropertyPage"
"InprocServer32"="$WinDir$\SYSTEM32\MSCOREE.DLL"
"Class"="Microsoft.IronPythonTools.Project.PythonGeneralPropertyPage"
"CodeBase"="$PackageFolder$\VSPackage3.dll"
"ThreadingModel"="Both"
[$RootKey$\Projects\{888888a0-9f3d-457c-b088-3a5042f75d52}]
#="PythonProjectFactory"
"DisplayName"="My Project"
"DisplayProjectFileExtensions"="My Project Files (*.myproj);*.myproj"
"Package"="{5cd7435c-7461-459f-80bc-c0c79e9d462f}"
"DefaultProjectExtension"="myproj"
"PossibleProjectExtensions"="myproj"
"ProjectTemplatesDir"="$PackageFolder$\Templates\Projects\MyProject"
"Language(VsTemplate)"="MyProject"
[$RootKey$\NewProjectTemplates\TemplateDirs\{5cd7435c-7461-459f-80bc-c0c79e9d462f}\/1]
#="My Project"
"SortPriority"=dword:00000064
"TemplatesDir"="$PackageFolder$\Templates\Projects\MyProject"
[$RootKey$\Projects\{888888a0-9f3d-457c-b088-3a5042f75d52}]
#="PythonProjectFactory"
"DisplayName"="IronPython"
"DisplayProjectFileExtensions"="IronPython Project Files (*.pyproj);*.pyproj"
"Package"="{5cd7435c-7461-459f-80bc-c0c79e9d462f}"
"DefaultProjectExtension"="pyproj"
"PossibleProjectExtensions"="pyproj"
"ProjectTemplatesDir"="$PackageFolder$\.\NullPath"
"Language(VsTemplate)"="IronPython"
[$RootKey$\NewProjectTemplates\TemplateDirs\{5cd7435c-7461-459f-80bc-c0c79e9d462f}\/1]
#="IronPython"
"SortPriority"=dword:00000064
"TemplatesDir"="$PackageFolder$\.\NullPath"
[$RootKey$\Services\{b98e41c4-581e-3532-beee-06829b683d39}]
#="{5cd7435c-7461-459f-80bc-c0c79e9d462f}"
"Name"="IPythonStarter"
I just want to get the bare bones up and running so I can start overriding some functionality (like the Add New Item dialog).
Update:
Reading my initial analysis once again increases my impression that some of the required components are missing (e.g. a dedicated ProjectFactory) and/or wired up incorrectly - from the MSDN documentation of the ProvideProjectFactoryAttribute Class:
ProvideProjectFactoryAttribute declares that a package provides a project factory.
And further:
If a VSPackage declares that it provides a project factory, it should create the factory and offer it to Visual Studio in the Initialize method of the Package-derived class.
You package is declaring to provide PythonProjectFactory, but (likely) doesn't offer it to VS, rather it is offered by the IronPython package. In turn you are providing arguments within the ProvideProjectFactory attribute list which PythonProjectFactory won't know about when asked for by VS.
Consequently you should at least provide a dedicated ProjectFactory yourself as per the walkthrough, wire up the classes accordingly and see how this turns out regarding the issues outlined below.
Initial analysis:
There appear to be several issues here at first sight - have you followed any tutorial on how to do this? In case, please note that some of those easily discoverable via search engines are outdated still. Either way I'd try working through and/or comparing your result with Walkthrough: Part 1 - Creating a Basic Project System from the MSDN documentation for VS 2010; please note that even this one is claimed to be outdated a bit according to the Community Content section on the bottom of the page.
Here is what I'd look into myself given the code you present, comparing with the walkthrough on the fly for more insights:
You realized already that the duplicate fragment starting with the GUID above PythonProjectFactory doesn't make sense - this is essentially trying to register two packages at once, which, even if allowed at all syntactically (which I doubt), can't possibly work like so due to both being registered with the same GUID [cross checking with the sample file in section Examining the Template Registration confirms this suspicion, as expected there is only one such fragment].
Please note that the GUID in question is the one identifying PythonProjectFactory (as per the respective source code), see below for more on this.
[Guid(PythonConstants.ProjectFactoryGuid)]
public class PythonProjectFactory : ProjectFactory {
Given .pkgdef is a generated file the next question is where this duplication/violation stems from. When two generated artifacts end up with the same GUID the respective definition in the sources is most likely messed up somehow, usually due to copy&paste duplication. Consequently you should verify whether {5cd7435c-7461-459f-80bc-c0c79e9d462f} is defined and referenced as intended, though here might be one or two other causes as well for this, see below.
A Package class needs to be identified by a GUID and the VS wizard generates some already in Guids.cs and references it accordingly on the class definition, however, the following is missing in your fragment [cross checking with the sample fragment in section To register the project template confirms this omission as well]:
[Guid(GuidList.guidMyPackagePkgString)]
public sealed class MyPackage : Package
Likewise it appears incorrect to derive MyPackage from PythonProjectPackage but reference PythonProjectFactory still rather than providing MyFactory as well (including a dedicated GUID), because the latter tells Visual Studio the location of your project template folder [see section Creating a Skeletal Project Factory]:
While it might well be possible to simply reuse all functionality from the base class PythonProjectFactory, inheriting is likely required simply because the factory must have a dedicated GUID too (as outlined in the walkthrough) in order to properly wire up the attribute specified data.
Likely unrelated, but still suspicious is that your two code blocks don't relate, as the Package class definition specifies Django Project Files (*.myproj);*.myproj, yet the result shows My Project Files (*.myproj);*.myproj.
Have you by chance mixed this from different builds or is this really a result of a clean one?
Good luck!
This stackoverflow posting might be helpful: VS2010: VSIX installation doesn't deploy item templates inside it
If this is not what you're looking for, try to see if you're missing something around the creation of custom project templates, I believe that's where the "missing link" is:
For VS 2008:
http://blogs.msdn.com/b/webdevelopertips/archive/2008/12/02/tip-32-did-you-know-how-to-easily-create-your-own-project-templates.aspx
For VS 2010:
http://blog.reybango.com/2010/09/21/how-to-create-html5-website-and-page-templates-for-visual-studio-2010/
and on MSDN:
http://msdn.microsoft.com/en-us/library/s365byhx.aspx
and here is how to create a project
template manually:
http://msdn.microsoft.com/en-us/library/ms185291.aspx
and here is how to create a new item template in VS 2010: http://msdn.microsoft.com/en-us/library/ms247113.aspx
Hope this helps
$PackageFolder$.\NullPath may have something to do with it.

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