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.
Related
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
I have created a Visual Studio template using this link: http://msdn.microsoft.com/en-us/library/ms185301.aspx.
I am able to create a dialog where the user enters a custom message and it gets displayed:
namespace TemplateProject
{
class WriteMessage
{
static void Main(string[] args)
{
Console.WriteLine("$custommessage$");
}
}
}
What I want to do it allow the user to rename the class names so I want to do something like:
But you see I'm getting errors of "Unexpected character $"
How can I do this?
EDIT
I see from this link: http://msdn.microsoft.com/en-us/library/eehb4faa(v=vs.110).aspx that
To enable parameter substitution in templates:
In the .vstemplate file of the template, locate the ProjectItem element that corresponds to the item for which you want to enable parameter replacement.
Set the ReplaceParameters attribute of the ProjectItem element to true.
BUT above I have not yet generated the template yet as I am still defining the classes. I understnad that the above step needs to be done in order to get the parameter substitution enabled for a File-->New Project scenario.
It looks like you have your template file as a cs file, which is causing Visual Studio to attempt to build it directly.
From what I can tell you should create a functioning Project, export it, and then modify the resulting template to add any replacements you need.
I've searched everywhere and I don't think I'm getting my search terms correctly.
Here's the link for VS shortcuts:
http://visualstudioshortcuts.com/2013/
The official shortcut link from Microsoft:
http://msdn.microsoft.com/en-us/library/da5kh0wa.aspx
I remember in Visual Studio there was a shortcut to creating a field.
You started typing something like this
string
Then you pressed something like CTRL+L,1 and it would generate the following:
string test = new string();
One option you could try is to type propfull, fill out the fields using the quick tabbing, press enter, and then delete the property.
Propfull creates the property and its backing field.
As others suggested though, it will probably be cleaner to create your own snippet.
If you'd like your own snippet, the easiest way to do that is to find the prop snippet, located on my installation at:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC#\Snippets\1033\Visual C#\prop.snippet
You can find where it is located by using the snippet manager.
Within that snippet file, edit the line that reads
<Code Language="csharp"><![CDATA[public $type$ $property$ { get; set; }$end$]]>
to make it say
<Code Language="csharp"><![CDATA[public $type$ $property$; $end$]]>
And then save it to a new file called field.snippet. At the very least, you also need to change the shortcut tag from "prop" to "field" so it doesn't collide with the existing prop snippet, but I would also recommend changing all references to "property" in the file to "field".
You can then load the snippet using the snippet manager by clicking Add... and pointing it to the directory your new snippet is saved in. You should now be able to type field TAB TAB to get the new field snippet, hopefully without even a Visual Studio restart. Cheers!
I created a new VSIX extension project in Visual Studio 2012, and wrote a MEF classifier (as a test) that should simply highlight all text in a .mylang file. Here are the relevant parts of my .NET 4.5 code:
internal static class MyLangLanguage
{
public const string ContentType = "mylang";
public const string FileExtension = ".mylang";
[Export(typeof(ClassificationTypeDefinition))]
[Name(ContentType)]
[BaseDefinition("code")]
internal static ContentTypeDefinition MyLangSyntaxContentTypeDefinition = null;
[Export]
[FileExtension(FileExtension)]
[ContentType(ContentType)]
internal static FileExtensionToContentTypeDefinition MyLangSyntaxFileExtensionDefinition = null;
}
[Export(typeof(IClassifierProvider))]
[ContentType(MyLangLanguage.ContentType)]
[Name("MyLangSyntaxProvider")]
internal sealed class MyLangSyntaxProvider : IClassifierProvider
{
[Import]
internal IClassificationTypeRegistryService ClassificationRegistry = null;
public IClassifier GetClassifier(ITextBuffer buffer)
{
return buffer.Properties.GetOrCreateSingletonProperty(() => new MyLangSyntax(ClassificationRegistry, buffer));
}
}
internal sealed class MyLangSyntax : IClassifier { }
Here is the full code.
These are the relevant parts from my source.extension.vsixmanifest file. Based on suggestions and similar files I found across the web, I added the dependency on MPF and the two assets.
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<!-- ... -->
<Dependencies>
<Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="4.5" />
<Dependency d:Source="Installed" Id="Microsoft.VisualStudio.MPF.11.0" DisplayName="Visual Studio MPF 11.0" Version="[11.0,12.0)" />
</Dependencies>
<Assets>
<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" />
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" />
</Assets>
</PackageManifest>
I also tried a version 1.0 manifest:
<?xml version="1.0" encoding="utf-8"?>
<Vsix Version="1.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2010">
<!-- ... -->
<References />
<Content>
<MefComponent>|%CurrentProject%|</MefComponent>
</Content>
</Vsix>
When I run it, it starts an experimental instance of Visual Studio 2012, and the Extensions and Updates window shows that my extension is active. However, it does not do anything when I load or create a .mylang file. Any exceptions I throw (as a test) from my extension are never thrown. Breakpoints are never hit, and get an exclamation mark with the following warning:
The breakpoint will not currently be hit. No symbols have been loaded for this document.
It feels as if my extension is never really loaded at all. My problem is similar to this problem and this problem, but I'm using Visual Studio 2012 which uses a new VSIX manifest format.
What I know:
I can find my DLL and VSIX file in the %localappdata%\Microsoft\VisualStudio\11.0Exp\Extensions\MyLang\VSIXProject1\1.0 folder, so I know they are copied.
Their timestamp corresponds to when I last built the project, so I know they are up-to-date.
Project Properties > Debug > Start external program: is already automatically set to C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe, and the Command line arguments were automatically set to /rootsuffix Exp.
The Visual Studio log (created with the /log option) has two entries related to my extension: Successfully loaded extension... and Extension is enabled....
My DLL does not appear on the Modules tab (list of all loaded DLLs) of the debugging Visual Studio, while some (not all) other extensions do appear.
It doesn't get loaded in Visual Studio 2012 or 2010 both on my laptop and my desktop PC.
What I've tried:
Set <IncludeAssemblyInVSIXContainer> to true in the .csproj file, per this suggestion, but it did not make any difference.
I can't add the line <MefComponent>|%CurrentProject%|</MefComponent> to the source.extension.vsixmanifest file as it uses a different format (2.0) than VSIX projects for previous versions of Visual Studio (1.0).
This suggestion (setting IncludeAssemblyInVSIXContainer and friends in my .csproj to true) but it does not make a difference. And my breakpoints are still showing the warning and not being hit.
Reset the VS Experimental instance using the Reset the Visual Studio 2012 Experimental Instance shortcut in the Start Menu, as per this suggestion. It didn't make a difference.
How can I at the very least be sure my VSIX MEF extension is loaded and works? And if possible, how can I make by breakpoint work and debug it?
Edit: The problem is you've improperly exported your ContentTypeDefinition as a ClassificationTypeDefinition. You should use the following instead:
[Export] // <-- don't specify the type here
[Name(ContentType)]
[BaseDefinition("code")]
internal static ContentTypeDefinition MyLangSyntaxContentTypeDefinition = null;
Here's my two guesses right now:
Try removing the following line from your vsixmanifest. I assume you do not have a class in your project that extends Package, in which case Visual Studio might be refusing to load your package due to the following Asset line (your extension does not actually provide this asset).
<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" />
If that fails, try replacing your current source.extension.vsixmanifest with one written to the old schema (version 1.0). I know this form still works in Visual Studio 2012 because all ~20 extensions I work on (with >10 public releases) use the old schema.
280Z28 solved the problem! For completeness, this is the full tried and tested code that will create a super simple VSIX Visual Studio MEF extension that colors all text in a .mylang file blue (or whatever the current keyword color is).
How to create a simple coloring MEF VSIX extension
Make sure you have the Visual Studio SDK installed. (VS2010 SP1 SDK, VS2012 SDK)
Create a new VSIX Project(From the template under Installed → Templates → Visual C# → Extensibility.)
Enter something in the Author field of the VSIX manifest editor, then save and close it.
Add references to the following libraries,version 10.0.0.0 for VS2010, or 11.0.0.0 for VS2012:
Microsoft.VisualStudio.CoreUtility.dll
Microsoft.VisualStudio.Language.StandardClassification.dll
Microsoft.VisualStudio.Text.Data.dll
Microsoft.VisualStudio.Text.Logic.dll
Microsoft.VisualStudio.Text.UI.dll
Microsoft.VisualStudio.Text.UI.Wpf.dll
Add a reference to the following library:
System.ComponentModel.Composition.dll version 4.0.0.0
Create and add a new code file MyLang.cs, and copy-and-paste the code below in it.
Edit source.extension.vsixmanifest as XML.
For Visual Studio 2010, add the following XML just before the closing tag </Vsix>, and save:
<Content>
<MefComponent>|%CurrentProject%|</MefComponent>
</Content>
(If there is already an empty <Content/>, remove it.)
For Visual Stuio 2012, add the following XML just before the closing tag </PackageManifest>, and save:
<Assets>
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" />
</Assets>
(If there is already an empty <Assets/>, remove it.)
Only for Visual Studio 2010:
Unload the VSIX project (right-click the project → Unload project).
Edit the .csproj project file (right-click the project → Edit MyProject.csproj).
Change the value at <IncludeAssemblyInVSIXContainer> to true.
Save and close the file.
Reload the VSIX project (right-click the project → Reload project).
Now build and run it. When you load a .mylang file, all text should be colored blue (or whatever the default keyword color is).
MyLang.cs
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
namespace VSIXProject1
{
internal static class MyLangLanguage
{
public const string ContentType = "mylang";
public const string FileExtension = ".mylang";
[Export]
[Name(ContentType)]
[BaseDefinition("code")]
internal static ContentTypeDefinition MyLangSyntaxContentTypeDefinition = null;
[Export]
[FileExtension(FileExtension)]
[ContentType(ContentType)]
internal static FileExtensionToContentTypeDefinition MyLangSyntaxFileExtensionDefinition = null;
}
[Export(typeof(IClassifierProvider))]
[ContentType(MyLangLanguage.ContentType)]
[Name("MyLangSyntaxProvider")]
internal sealed class MyLangSyntaxProvider : IClassifierProvider
{
[Import]
internal IClassificationTypeRegistryService ClassificationRegistry = null;
public IClassifier GetClassifier(ITextBuffer buffer)
{
return buffer.Properties.GetOrCreateSingletonProperty(() => new MyLangSyntax(ClassificationRegistry, buffer));
}
}
internal sealed class MyLangSyntax : IClassifier
{
private ITextBuffer buffer;
private IClassificationType identifierType;
private IClassificationType keywordType;
public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;
internal MyLangSyntax(IClassificationTypeRegistryService registry, ITextBuffer buffer)
{
this.identifierType = registry.GetClassificationType(PredefinedClassificationTypeNames.Identifier);
this.keywordType = registry.GetClassificationType(PredefinedClassificationTypeNames.Keyword);
this.buffer = buffer;
this.buffer.Changed += OnBufferChanged;
}
public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan snapshotSpan)
{
var classifications = new List<ClassificationSpan>();
string text = snapshotSpan.GetText();
var span = new SnapshotSpan(snapshotSpan.Snapshot, snapshotSpan.Start.Position, text.Length);
classifications.Add(new ClassificationSpan(span, keywordType));
return classifications;
}
private void OnBufferChanged(object sender, TextContentChangedEventArgs e)
{
foreach (var change in e.Changes)
ClassificationChanged(this, new ClassificationChangedEventArgs(new SnapshotSpan(e.After, change.NewSpan)));
}
}
}
Set <IncludeAssemblyInVSIXContainer> to true in the .csproj file, per
this suggestion.
I had exactly the same problem and this solved it. Do a full rebuild.
I've created a class that extends DbConnection in a brand new project.
public class FakeDbConnection : DbConnection { ... }
In the Solution Explorer the class looks like this:
And when double-clicking it wants to open it in design mode which won't work. Opening up the .csproj-file reveals the problem
<ItemGroup>
<Compile Include="FakeADO\FakeDbConnection.cs">
<SubType>Component</SubType>
</Compile>
</ItemGroup>
Even if I remove the SubType tag VS2010 immediately re-adds it. Very annoying.
How can I stop VS2010 from opening up my .cs file in designer mode and just open it up as a regular code file?
As described in an answer to this question you can do this:
[System.ComponentModel.DesignerCategory("Code")]
class FakeDbConnection: DbConnection { ... }
Important: The attribute needs to be fully qualified otherwise VS2010 will ignore this.
Important (thanks to jmbpiano): The attribute only applies to the first class in the file.
The inheritance hierarchy indicates that this class (DbConnection) inherits from System.ComponentModel.Component. Try right click the file and View Source instead.
As always you can check MSDN! Here is the documentation for DbConnection.
Thats because DBConnection inherits "Component".
About disabling VS to add "Subtype" in csproj-file - I don't think thats possible.
You can still aceess the code, by right-clicking in designer -> show code (I think "F7" is the shortcut key for that)