Giter VIP home page Giter VIP logo

template-sample's Introduction

Info on how to create templates that work in dotnet new and Visual Studio/Visual Studio for Mac

This repo contains a couple samples showing how you can create a .net core template that can be used either by the dotnet command line (dotnet new) or Visual Studio & Visual Studio for Mac. For more info see .NET CLI Templates in Visual Studio .

The samples are in the src/content folder.

Add an issue here, or reach out to @SayedIHashimi on twitter with any questions.

To discover templates that have already been created go to https://dotnetnew.azurewebsites.net/.

The main content here assumes that you are working with Visual Studio 2022 and .net 6. Visual Studio 2022/.net 6 has some updates to the community template experience that Visual Studio 2019 doesn't have. At the bottom there is a section that describes the additional work that is needed to fully support VS2019.

I have some templates that can be used to simplifying creating templates at https://github.com/sayedihashimi/sayedha.templates. These are a good reference for creating your own templates as well.

Finding and installing templates

In .net 6 there has been improvements to dotnet new --search to find templates that are published on nuget.org.

You can use the integrated help to learn more about how to use the search command. You can get the command specific help by executing dotnet new --search -h.

To search for a template by name the syntax you'll use is dotnet new <TEMPLATE_NAME> --search. For example, if you are looking for the .NET Boxed templates, you can execute dotnet new boxed --search. When I executed this command the results I received are below.

> dotnet new boxed --search
Searching for the templates...
Matches from template source: NuGet.org
These templates matched your input: 'boxed'

Template Name                                  Short Name  Author        Language  Package                       Downloads
---------------------------------------------  ----------  ------------  --------  ----------------------------  ---------
ASP.NET Core API Boxed                         api         .NET Boxed    [C#]      Boxed.Templates                     39k
ASP.NET Core GraphQL Boxed                     graphql     .NET Boxed    [C#]      Boxed.Templates                     39k
ASP.NET Core Orleans Boxed                     orleans     .NET Boxed    [C#]      Boxed.Templates                     39k
Boxed templates: Sophon.Boxed.BasicConsoleApp  bca         ZhaoBingwang  [C#]      Sophon.Boxed.BasicConsoleApp         2k
Boxed templates: Sophon.Boxed.BasicWebApi      bwa         ZhaoBingwang  [C#]      Sophon.Boxed.BasicWebApi             1k
NuGet Package Boxed                            nuget       .NET Boxed    [C#]      Boxed.Templates                     39k


To use the template, run the following command to install the package:
   dotnet new --install <PACKAGE_ID>
Example:
   dotnet new --install Boxed.Templates

Since we are interested in the .NET Boxed templates, the install command would be dotnet new --install Boxed.Templates. After installing these templates you can use those templates from the CLI using dotnet new or Visual Studio.

How to uninstall templates

The command to use to uninstall templates is dotnet new --uninstall. If you simply execute dotnet new --uninstall it will display a list of template packs that have been installed, as well as a command for every template pack that you can use to uninstall that template pack. On my machine I have the .NET Boxed template pack installed. When I execute dotnet new --uninstall the result is shown below.

> dotnet new --uninstall
Currently installed items:
   Boxed.Templates
      Version: 6.10.0
      Details:
         Author: Muhammad Rehan Saeed (RehanSaeed.com)
         NuGetSource: https://api.nuget.org/v3/index.json
      Templates:
         ASP.NET Core API Boxed (api) C#
         .editorconfig file (editorconfig) C#
         .gitattributes file (gitattributes) C#
         ASP.NET Core GraphQL Boxed (graphql) C#
         NuGet Package Boxed (nuget) C#
         ASP.NET Core Orleans Boxed (orleans) C#
      Uninstall Command:
         dotnet new --uninstall Boxed.Templates

The command to uninstall this template pack is shown on the last line dotnet new --uninstall Boxed.Templates. After uninstalling the template, you will no longer be able to access that via dotnet new or Visual Studio. If you are using Visual Studio 2019, it's recommended that you restart Visual Studio after uninstalling templates.

Getting started creating templates

To get started creating templates, take a look at the following resources.

Template analyzer

Sayed is working in his free time to create a tool that can be used to analyze .NET Core templates. You can install the analyzer with the command.

> dotnet tool install --global sayedha.template.command

For usage info run templates -h.

After installing the tool you can invoke it by running templates in the command line. You can analyze templates that are stored in a local folder with the -f parameter. You can also analyze templates that are contained in a NuGet package (.nupkg) file with the -p switch.

For example to analyze a folder you would run.

> templates analyze -f <path-to-folder>

When you pass in a path, the tool will search the sub-folders to discover templates. If you are building several templates, you can pass in a parent folder that contains all the templates, and each template that is discovered will be analyzed.

What the tool looks for

Error if missing a required property

  • $.author,
  • $.sourceName,
  • $.classifications,
  • $.identity,
  • $.name,
  • $.shortName,
  • $.tags,
  • $.tags.language,
  • $.tags.type

Warnings for missing recommended properties

  • $.defaultName,
  • $.description,
  • $.symbols,
  • $.symbols.Framework,
  • $.symbols.Framework.choices

Error if $.tags.type is not set to either project or item Warning if $.symbols.Framework.type is not set to parameter. Warning if $.symbols.Framework.datatype is not set to choice.

Some important things needed to create good templates

Use the schema for completions and validation

You should add the $schema property to your template.json file. Both Visual Studio and Visual Studio Code will provide completions and validation based on the schema. Other editors have similar support as well.

{
"$schema": "http://json.schemastore.org/template",
}

sourceName

In the template.json file you should have a sourceName property declared. The sourceName property is special, and should always be declared. When a project is created, either through the command line or Visual Studio, the project will be given a name. For example, when creating a project with dotnet new you can pass in the -n|--name parameter. In Visual Studio during New Project the user will be prompted to provide a project name. The value provided by the user for project name will replace the string declared in sourceName. This is typically used to replace the namespace declaration in generated files.

{
  "sourceName": "MyCommand",
}

For a full example of sourceName see src/Content/MyCommand/.template.config/template.json

defaultName

When a project is created in Visual Studio, the screen that the user provides the project name will always be pre-populated. If defaultName is declared in the template.json, that value will be used as the default name for the project. Otherwise Project1 is always used. When users create projects from the command line with dotnet new if the -n|--name parameter is not passed in, the defaultName value will be used.

{
  "defaultName": "MyCommandTool",
}

For a full example of sourceName see src/Content/MyCommand/.template.config/template.json

classifications

In Visual Studio when creating a new project there is an All Project Types dropdown that can be used to filter the list of templates shown. You should declare the relevant values from that dropdown in the classifications property of the template.json. Here are some of the values that you can use.

  • Cloud
  • Console
  • Desktop
  • Games
  • IoT
  • Library
  • Mobile
  • Service
  • Web

Here is an example of the declaration.

{
  "classifications": ["Console"],
}

Note: in the current preview the Visual Studio New Project Dialog will add all classifications from installed templates into the All Project Types dropdown. That behavior is likely to change, custom classifications will not be listed. You should select the values that you see in Visual Studio (without any additional templates installed) so that the user can filter.

Language and type

In the template.json you should define the language and type for the template in the tags property. For example

"tags": {
  "language": "C#",
  "type":"project"
},

If the type property is not declared, the template will not be shown in the Visual Studio New Project Dialog

Framework

In the template.json file you should indicate what target framework, or frameworks, the template supports. To do that you'll update the symbols section to include a Framework property. Below is an example of what should be included for a template that targets .NET Core 3.1.

"symbols": {
  "Framework": {
    "type": "parameter",
    "description": "The target framework for the project.",
    "datatype": "choice",
    "choices": [
    {
        "choice": "netcoreapp3.1",
        "description": "Target netcoreapp3.1"
    }
    ],
    "replaces": "netcoreapp3.1",
    "defaultValue": "netcoreapp3.1"
  }
}

If your template supports multiple frameworks, add additional values to the choices array.

Note: due to a bug, if your template contains parameters that you want to appear in Visual Studio, you'll need to specify the framework symbol.

Generating ports for web projects

If your template consists of a web project, it's likely that you'll want to generate new port numbers to be used when the template is used. This is a bit complex to do correctly, but we will explain the different parts. When defining the support, for each different port number we want the following to create a command line parameter that can be used to explicitly set the port number. If the port number is not passed in by the user, then we want to generate a port number automatically.

To achieve this, we will need to create three new symbols in the template.json file. We will create the following symbols.

  • Parameter that the user can pass in
  • A generated port number
  • Symbol to coalesce the user parameter and the generated port

Here is a sample, where we specify the range that we want the port number to be in.

"HttpsPort": {
  "type": "parameter",
  "datatype": "integer",
  "description": "Port number to use for the HTTPS endpoint in launchSettings.json."
},
"HttpsPortGenerated": {
  "type": "generated",
  "generator": "port",
  "parameters": {
  "low": 44300,
  "high": 44399
  }
},
"HttpsPortReplacer": {
  "type": "generated",
  "generator": "coalesce",
  "parameters": {
  "sourceVariableName": "HttpsPort",
  "fallbackVariableName": "HttpsPortGenerated"
  },
  "replaces": "44345"
}

HttpsPort is the user facing parameter that can be passed in when calling dotnet new.

HttpsPortGenerated is the generated port number. In this example we specified a low and a high value. The generated port number will be between those. These parameters are optional.

HttpsPortReplacer is the symbol that will decide between HttpsPort and HttpsPortGenerated. If a value is provided via the command line (HttpsPort) it will be given preference. Take note of 44345 in this symbol. This is the port number that the source files use. Where ever this string is found in the template content, it will be replaced with the new port number.

For a full example of sourceName see src/Content/MyWebApp/.template.config/template.json

How to test template changes locally

In Visual Studio 2022 you can install templates either via a NuGet package (.nupkg file) or via the folder based path (dotnet new --install [local-file-path]).

In order for a template to appear in Visual Studio 2019 it needs to be installed using a NuGet package (.nupkg file). When developing templates locally, when you are ready to test your template using Visual Studio, follow the steps below.

It's recommended that you delete the cache folders that are used for the templates. The cache folders are in the user home directory (~) under the .templateengine folder. The default path on windows is C:\Users\{username}\.templateengine and for macOS /Users/{username}/.templateengine.

  1. Close all instances of Visual Studio
  2. Create a NuGet package that has the template
  3. Delete Template Engine cache folders (folders under ~/.templateengine)
  4. Install the template using dotnet new --install <path-to-nuget-package>
  5. Start Visual Studio

Here is a PowerShell function that you can add to your profile to make this simpler

function Reset-Templates{
    [cmdletbinding()]
    param(
        [string]$templateEngineUserDir = (join-path -Path $env:USERPROFILE -ChildPath .templateengine)
    )
    process{
        'resetting dotnet new templates. folder: "{0}"' -f $templateEngineUserDir | Write-host
        get-childitem -path $templateEngineUserDir -directory | Select-Object -ExpandProperty FullName | remove-item -recurse -force
        &dotnet new --debug:reinit
    }
}

Some issues that can occur when developing folder based templates

Template updates are not detected

If you are installing/uninstalling folder based templates, you may run into an issue where all template changes are not picked up. For example, you change the description, or add a parameter, in some cases those changes may not be detected by the Template Engine. To force an update run the command below.

dotnet new --debug:rebuildcache

Unable to uninstall a template

If you are having issues uninstalling a template that was installed from a folder, try to change directories (cd) to a different folder and try again.

Common issues

If your template is not appearing in Visual Studio, check the following.

Required properties

Ensure that the following required properties are set in the template.json file.

  • author
  • sourceName
  • classifications
  • identity
  • name
  • shortName
  • tags

For tags ensure you have specified the language and type values. See the example below.

  "tags": {
    "language": "C#",
    "type": "project"
  },

The type value can be either project or item, other values should not be used.

primaryOutputs

If you have a single project template, you typically don't have to specify the primaryOutputs property. If your templates.json file has specified primaryOutputs, Visual Studio will open load the project(s) specified. If the value for primaryOutputs is not correct, the project(s) will not load in Visual Studio.

If the value for the primaryOutputs is not correct, the project(s) will not be loaded in Visual Studio

Verify that the NuGet package has the correct files

After creating the .nupkg file you can examine it by extracting the contents using your favorite zip tool. The .nupkg file is just a .zip file with a different file extension. Double check that the .template.config folder is in the package as well as the template.json file and any host files.

How to prevent showing a template in Visual Studio

If you have a template, and do not want that template to appear in Visual Studio when it's been installed using dotnet new --install add the unsupportedHosts property. For example, see the ide.host.json file below.

{
  "$schema": "http://json.schemastore.org/vs-2017.3.host",
  "icon": "icon.png",
  "symbolInfo": [
    {
      "id": "AuthorName",
      "name": {
        "text": "Author Name"
      },
      "isVisible": "true"
    },
    {
      "id": "Description",
      "name": {
        "text": "Description"
      },
      "isVisible": "true"
    }
  ],
  "unsupportedHosts": [
    { 
      "id": "vs"
    } 
  ]
}

The host identifier of "vs" refers to Visual Studio 2019. To exclude from any other host, use the host identifier associated with that product.

How to create a multi-project (Solution) template

Creating a multi-project (solution) template, is very similar to creating a single project template. You'll need to make the following changes to properly create a solution template.

  1. Make sure that the .template.config folder is in the correct folder. It likely should be in the root of the solution. The .sln file should be either in the same directory as .template.config or under it. Same goes for all the content (i.e. projects) that the template should contain.
  2. In the template.json file change the type tag to be solution instead of project.
  3. Update the file name of the solution to be different from sourceName or defaultName, See below for more info.
  4. Update template.json to create unique GUIDs to replace the Project ID in the .sln file.

Solution name best practices

When creating a solution template, make sure that the file name of the solution doesn't match sourceName or defaultName in template.json. For example, if sourceName is set to ContosoBilling, ensure that the solution file is NOT named ContosoBilling.sln. You can change it to ContosoBilling.app.sln and then apply a rename if you want the generated solution file name to match sourceName.

If the solution's file name is allowed to match the sourceName/defaultName, Visual Studio users may see an unexpected "File Modification Detected" dialog immediately after the solution is created and will be prompted to reload.

To rename the solution file, make the following changes to template.json:

  1. In the symbols section, add the following binding so that the HostIdentifier symbol is defined in your template:

    "HostIdentifier": {
      "type": "bind",
      "binding": "HostIdentifier"
    }
  2. In the sources section, add the following modifier to rename the file when projects are created using dotnet new (in Visual Studio, the name specified in the New Project Dialog will be used):

    "condition": "(HostIdentifier == \"dotnetcli\" ||  HostIdentifier == \"dotnetcli-preview\")",
    "rename": {
      "ContosoBilling.app.sln": "ContosoBilling.sln"
    }

Updating guids

For the last step, we will need to update the template.json file. You can use the guids property to help. Below is a sample

The Project ID values can be found in the .sln file. For example here is a snippet from the SolutionTemplate sample in this repo.

...
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{3C7060D1-D7AF-4B5D-BF1F-BC0E4F39E7ED}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Apps", "Apps", "{526E49A6-E41B-4136-8662-FC7BF000776A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SayedHa.Web.MyWeb", "SayedHa.Web.MyWeb\SayedHa.Web.MyWeb.csproj", "{0E62310C-D76A-4681-9926-B1BFFDC379FC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SayedHa.Web.MyClassLibrary", "SayedHa.Web.MyClassLibrary\SayedHa.Web.MyClassLibrary.csproj", "{032123E7-E4E0-4B17-9564-ECA4B57F30B7}"
EndProject
Global
...

The Project ID is the last Guid listed in the Project node. Below is a sample showing how to get those guids to be updated. Full sample is at template.json

...
  "preferNameDirectory": true,
  "guids": [
    "0E62310C-D76A-4681-9926-B1BFFDC379FC",
    "032123E7-E4E0-4B17-9564-ECA4B57F30B7"
  ],
  "symbols": {
...

Note in the initial preview of Visual Studio where this support appeared, we had a bug that required the .sln file to be listed in primaryOutputs.

Project folder nesting

The structure of the generated .nupkg file depends on the location of the .csproj used to generate it. If the .csproj for the template package is in a directory above the template's \src directory, your template .nupkg will have a nested structure and will fail to generate any output when invoked.

As an example, you might need to have your template .csproj outside of the \src folder because you are using a Directory.Build.props in your \src folder that is incompatible with generating the template package.

The fix to this issue is to add the PackagePath="content" attribute on the <Content> element in your template's .csproj. This will place the contents of the \src directory into the package's \content directory, which is the correct location for template packages.

Before

<!-- Template.csproj -->

<ItemGroup>
    <!-- src\ is the location of the template's source files -->
    <!-- this will generate a .nupkg structure of \content\Content\(src files) -->
    <Content Include="src\**\*.*" />
</ItemGroup>

After

<!-- Template.csproj -->

<ItemGroup>
     <!-- this will generate a .nupkg structure of \content\(src files) -->
    <Content Include="src\**\*.*" PackagePath="content" />
</ItemGroup>

How to ship a template inside of a Visual Studio Extension (vsix)

If you are developing a Visual Studio extension (.vsix file extension), you can deliver your templates inside of the vsix instead of relying on the end-user installing templates via dotnet new --install. This section will walk you through how to create a vsix that contains templates.

In order to create Visual Studio extensions you'll need to install the [Visual Studio SDK](Install the Visual Studio SDK). Let's create a new Visual Studio extension, and add a template into it.

Create the Visual Studio Extension project

First we will need to create a new Visual Studio Extension project. If you have an existing project that you are using, you can open your existing project instead of creating a new project. To create the new project, use the New Project dialog in Visual Studio. When you get to open the New Project dialog, you can search for "vsix" in the search box on the top right. See the image below.

New Project Dialog - Search for vsix

From the list below you can select VSIX Project, with either language that you prefer. The language of the extension doesn't have to be the same language as the template itself. Now that the project is created, we need to make a few modifications to support the project templates.

Before starting to add your template into the Visual Studio extension, you should ensure that your template works without issues from the command line. You'll also want to ensure you've added the additional info to templates that is needed to support Visual Studio. That information was presented previously in this doc.

To add support for templates in a VSIX project, the following additions need to be made.

  1. Add the .nupkg file with your template(s) into the project
  2. Update the VSIX project file to include a new target
  3. Add a pkgdef file to indicate where to look for templates
  4. Update the .vsixmanifest file to have a new asset tag for the template

Adding the .nupkg to your extension

Now you need to add the NuGet package (.nupkg file) to the extension. You'll need to copy the .nupkg file into a folder near the source for the extension. In the in the vsix-with-template folder the file is placed in the assets folder. Now we need to modify the vsix project to pickup, and include, the .nupkg file so that it is included in the final vsix file that is built. Add the following target in the vsix project file (.csproj or .vbproj) file.

<Target Name="PreCreateVsixContainer" BeforeTargets="GetVsixSourceItems">
  <ItemGroup>
    <!-- ensure that the path below is correct -->
    <_TemplatePackage Include="..\assets\*.nupkg" />
  </ItemGroup>
  <Error Text="No template files found." Condition="@(_TemplatePackage-&gt;Count()) == 0" />
  <Message Text="Template nuget packages found: @(_TemplatePackage)" Importance="low" />
  <!-- don't modify the following, the pkgdef file uses the path below -->
  <ItemGroup>
    <VSIXSourceItem Include="@(_TemplatePackage)">
      <VSIXSubPath>ProjectTemplates\</VSIXSubPath>
    </VSIXSourceItem>
  </ItemGroup>
</Target>

The PreCreateVsixContainer target will be called during the build process. It will look for .nupkg files in the assets folder and then include them in the vsix that is produced from the build. You may need to customize the path to where the target looks for these .nupkg files. You can verify that the package was included successfully by opening, or extracting, the .vsix file with your favorite zip utility. The package should be in the ProjectTemplates in the vsix. Now that you've added the NuGet package, and updated the build process to include it, we can move on to the next step.

Adding a pkgdef file

Now that the package is in the vsix, we need to add a pkgdef file so that the extension will register the templates during installation. Add a new file named Templates.pkgdef to your vsix project. If you are using Visual Studio, you can use the text file item template in the New Item dialog. It's important that the name of this .pkgdef file is different from the name of the vsix project. If your vsix project is named Templates, then you'll need to change the name of the new .pkgdef file you just added. The content of this new .pkgdef should be similar to the following.

[$RootKey$\TemplateEngine\Templates\sayedha.template.netcoretool.nuspec\1.0.0]
"InstalledPath"="$PackageFolder$\ProjectTemplates"

Here the only values that you want to modify are sayedha.template.netcoretool.nuspec\1.0.0. You should use a path that is likely to be unique to your organization and project. It doesn't have to match the project or templates that you are including. You can customize the version number in the path as needed as well. The second line in the pkgdef file, indicates where the .nupkg files are located relative to the vsix install folder. You shouldn't modify the second line.

You should also mark the Templates.pkgdef file as Content and IncludeInVsix in the properties grid. See the image below.

tempaltes.pkgdef properties grid

Update the .vsixmanifest

Now we are on the last step. The .vsixmanifest file needs to be updated to pickup the new pkgdef file you just created. Open the source.extension.vsixmanifest file and add the asset tag below into the Assets element.

<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="File" Path="Templates.pkgdef" /> 

Adding the asset tag causes Visual Studio to process the new pkgdef file when the extension is installed.

That's it. Now you can build the VSIX project, install the extension and you should see your new template. The next step is to distribute your new extension. You can do that by sharing the .vsix file directly, or publishing to the Visual Studio Marketplace

Supporting Visual Studio 2019

We made some additional changes in Visual Studio 2022/.net 6, which Visual Studio 2019/.net 5 doesn't have. If you have a template(s) that need to support Visual Studio 2019/.net 5, you may need to make some additional changes to get the templates to work in Visual Studio 2019. Below is a summary of the additional work that is needed.

Limitations of Visual Studio 2019 and/or .net 5 regarding community templates.

  • Search functionality in dotnet new is not as robust as in .net 6.
  • VS2019 will need to have the icon and parameter info listed in the ide.host.json file. Parameters are not automatically shown in Visual Studio.
  • VS2019 requires a VS restart to get newly installed templates to appear in the IDE
  • In VS2019 showing CLI templates is disabled by default, see below on how to enable showing those.
  • In VS2019, displaying templates that have been installed with a folder path isn't supported. All templates need to be installed via a NuGet package (.nupkg file).

Parameters

By default all parameters declared in template.json will appear in Visual Studio 2022 if you do not have a ide.host.json (or any Visual Studio host file) file. To control the behavior you can define the tag below in template.json to explicitly state if all parameters should appear or not.

  "tags": {
    "vs_showParametersByDefault": "false"
  },

Values for this tag can be either 'true' or 'false'.

The default value for vs_showParametersByDefault is true if there is no host file detected, and false if a host file is detected.

If you want all parameters to be shown except a set of specific templates, you can use the vs_parametersToHide in tags to hide those specific parameters. The value for this tag should be a semi-colon delimited list of parameter names. For example.

"tags": {
    "vs_parametersToHide": "authorName;useHttps"
  },

Below is some more info based on if a host file is present or not.

No host file present All templates will be shown by default if vs_showParametersByDefault isn't defined in tags. If vs_showParametersByDefault is defined in tags, that value will be used to determine if parameters are shown by default or not. If all templates are shown but there are parameter names listed in vs_parametersToHide, those will not be shown.

Host file present All templates will not be shown by default. To get all of them to appear, set 'vs_showParametersByDefault` to true.

If vs_showParametersByDefault is set to true, and some parameter names are listed in vs_parametersToHide, those will be not be shown in Visual Studio.

Any parameters listed in the host file with isVisible=true will be shown.

TODO: more content will be added soon

How to enable cli templates in Visual Studio and Visual Studio for Mac

The feature to show templates that are installed using the command-line interface (cli) is a preview feature. This feature is disabled by default.

To enable this feature in Visual Studio:

First open the Options dialog, go to Tools > Options. In the dialog go to Environment > Preview Features and then on the right-hand side and select the preview feature named Show all .NET Core templates in the New project dialog. For more info see .NET CLI Templates in Visual Studio .

Visual Studio - Tool > Options > Environment > Preview features

To enable this feature inn Visual Studio for Mac:

Visual Studio - Tool > Options > Environment > Preview features

First open the Preferences dialog, go to Visual Studio (menu) > Preferences.... In the list on the left hand side, select Other > Preview Features and select the preview feature named Show all .NET Core templates in the New project dialog.

Visual Studio support

Starting in previews of 16.8 of Visual Studio we have a feature that can be enabled to show the templates which have been installed with dotnet new. For more info on that take a look at the blog post .NET CLI Templates in Visual Studio .

There are some things that you'll want to make sure you have defined to ensure a good experience for Visual Studio users.

Add an ide.host.json file

Note: in Visual Studio 2022+ the ide.host.json file is no longer required for the template to appear in Visual Studio. If there is an icon named icon.png in the .template.config folder, it will be used for the project template icon in Visual Studio. By default all template parameters will appear in the New Project Dialog in Visual Studio.

In order to get the best support in Visual Studio, you'll want to add an ide.host.json file. This file should be in the .template.config folder next to the template.json file. You'll need to create this file in order to show an icon for the template, to display parameters, to customize the text, and other features.

The schema that you should use when creating this file is shown below.

{
  "$schema": "http://json.schemastore.org/vs-2017.3.host"
}

How to add an icon to be shown in Visual Studio

Note: In Visual Studio 2022, you don't need to create an ide.host.json file to include an icon for the project template. If there is an icon file named icon.png in the .template.config file, it will be picked up automatically. If you'd like to customize that, then create an ide.host.json file as described below.

To add an icon, you will need to declare that in the ide.host.json file. The icon file should be a .png file. The icon file should be in, or under, the .template.config folder. In the ide.host.json file declare the icon property as shown.

{
  "icon": "icon.png"
}

If the icon file is in a sub-folder, provide a relative path in the icon declaration.

In the image below the icon for the sample console template is shown.

New Project Dialog - Custom template with icon

How to make a parameter visible in Visual Studio

Note: in Visual Studio 2022+, by default all template parameters will appear in the New Project Dialog. You do not need to create and ide.host.json file if you want all the parameters to be shown. You can create an ide.host.json if you need to hide some parameters.

In template.json you can declare any number of parameters. Those parameters will not by default show up in Visual Studio. You need to specify which ones should show up in Visual Studio with an ide.host.json file. The MyCommand sample template in this repo has three parameters defined.

  • Framework
  • AuthorName
  • Description

The Framework parameter defines the set of choices of target framework that the template supports. This parameter should always be defined for .NET Core templates. This parameter is special, and doesn't need to be declared in the ide.host.json file to be shown in Visual Studio. If this parameter is defined, the Target Framework dropdown in the New Project Dialog will automatically be shown.

In order to show the other two parameters, you will need to add a file named ide.host.json to the .template.config folder. Below is a sample file that shows how to make those appear in Visual Studio.

{
  "$schema": "http://json.schemastore.org/vs-2017.3.host",
  "icon": "icon.png",
  "symbolInfo": [
    {
      "id": "AuthorName",
      "name": {
        "text": "Author Name"
      },
      "isVisible": "true"
    },
    {
      "id": "Description",
      "name": {
        "text": "Description"
      },
      "isVisible": "true"
    }
  ]
}

After adding this declaration, when the template is used in Visual Studio the parameters will be presented to the user as

New Project Dialog - Additional Info Page

template-sample's People

Contributors

damienbod avatar jemayn avatar markwaterman avatar sayedihashimi avatar seangwright avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

template-sample's Issues

Solution file naming suggestion for wiki

Update the docs to include guidance on naming the sln file in template something other then sourceName.sln or defaultName.sln to avoid reload prompt in Visual Studio when the Place solution and project in same folder is checked.

To preserve sourceName.sln naming for dotnet new, a rename can be provided:

If renaming the file in the template, the following source modifier can be used to rename it when created via dotnet new

          "condition": "(HostIdentifier == \"dotnetcli\" ||  HostIdentifier == \"dotnetcli-preview\")",
          "rename": {
            "Application1.app.sln": "Application1.sln"
          }

Alternatively, if keeping the sln file as Application1.sln in the template , the following source modifier can be used to rename it when created via Visual Studio to avoid the conflict

          "condition": "(HostIdentifier != \"dotnetcli\" &&  HostIdentifier != \"dotnetcli-preview\")",
          "rename": {
            "Application1.sln": "Application1.app.sln"
          }

Validate `template.json` files against JSON Schema

All template.json files in a template should be validated and pass validation against http://json.schemastore.org/template. Currently, there are some validation issues across templates, ranging from the incorrect casing of properties, comments, and more.

Demo Code - Validate Against JSON Schema

This sample uses the following NuGet packages:

  • Newtonsoft.Json
  • Newtonsoft.Json.Schema
  • Spectre.Console (for output)

Note, you'll need to extract all the nupkg templates into a parent directory.

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Spectre.Console;

var templates = Directory.EnumerateFiles(
    "<folder to extracted template packages>", 
    "template.json", 
    SearchOption.AllDirectories);

using var http = new HttpClient();
var jsonSchema = await http.GetStringAsync("https://json.schemastore.org/template");
var schema = JSchema.Parse(jsonSchema);

List<Problem> problems = new();
foreach (var template in templates)
{
    var data = await File.ReadAllTextAsync(template);
    var json = JToken.Parse(data);
    if (!json.IsValid(schema, out IList<string> errors))
    {
        dynamic j = json;
        // just in case name is missing
        var name = (j.name ?? template).ToString();
        problems.Add(new Problem(name, errors));
    }
}

var table = new Table()
    .AddColumn("Name")
    .AddColumn("๐Ÿšจ Errors");

foreach (var problem in problems)
{
    table.AddRow(
        problem.Name, 
        problem.ErrorMessages.EscapeMarkup()
    );
}

AnsiConsole.Render(table);

public record Problem(string Name, IList<string> Errors)
{
    public string ErrorMessages =>
        Errors.Select(e => $"โƒ {e}\n")
            .Aggregate("", (a, i) => a + i);
}

Thoughts

Currently, I extract the archives (i.e. the nupkg files into a parent directory). Since these are essentially zip files, we could use the ZipFile class in .NET to just pull the template.json files out into memory then parse them, helping avoid an additional step. This would also make the tool more flexible as you could give it a directory or a specific nupkg file and it would work just the same.

License

Note that Newtonsoft.Json.Schema is AGPL or requires a license to be purchased if this tool is commercially available.

Helpful Info (VS IDE) .. Maybe Known

Is this the best place to report discoveries and work arounds?
ide.host.json

  • Does not work with "icon": "icon.ico" not recognized. Used a png extension no problem.

template.json

  • "preferNameDirectory": true - did not add projects to solution, either existing or new
    • changed to "preferNameDirectory": false -> worked perfectly
    • added Solution folder first, projects showed up as expected

VS 16.10 Bug - Creates Empty Solution

When I run the following command, everything works:

dotnet new --install Boxed.Templates
dotnet new api

If I select the same options in VS 16.10's new UI, VS opens a blank solution and no files are output to disk except the solution file. How can I debug what went wrong?

Is this the right place for this bug or is it dotnet/templating?

Is there a way to modify the title of the template as shown in VS?

Currently my title looks like this:

image

Which seems to be something like $name ($author) - however I don't see any other template containing the author field.
(The length of our author-filed makes this a bit more.. "ugly")

So: Is there a way to customize the appearance of that section?

Using VSIX to distribute a solution template with discovery via the "Create a new project" interface

It is our goal to be able to create a solution template that contains multiple projects, install that template using VSIX, and then access the solution template via the "Create a new project" interface.

Do you know when Microsoft will introduce support for accessing solution templates via the "Create a new project" window?

I used your example in this repository to create a solution template that's accessible via the dotnet CLI, but the dotnet CLI alone doesn't offer a way in which we can easily distribute templates across the organization.

Thank you in advance for any insight you can provide, @sayedihashimi.

Simplify development of vsix

Some ideas after talking with Mads today.

  1. Make convention to drop .nupkg in ProjectTemplates folder in source folder
  2. Make nuget pkg that users can add to get the target added
  3. On build generate the .pkgdef and add to pipeline
    For the path use RootNamespace-AssemblyName
  4. When installing the package, tranform vsixmanifest to add the asset tag

Framework vs TestFramework

I have the following new Framework symbol but I also want to match up the target framework in the test project e.g.

  • net5.0 -> net5.0
  • netstandard2.1 -> net5.0
  • netstandard2.0 -> net5.0
  • netcoreapp3.1 -> netcoreapp3.1
  • netcoreapp3.0 -> netcoreapp3.0
  • netcoreapp2.2 -> netcoreapp2.2
  • netcoreapp2.1 -> netcoreapp2.1
  • netcoreapp2.0 -> netcoreapp2.0
  • net48 -> net48
  • net472 -> net472
  • net471 -> net471
  • net47 -> net47

How can you achieve this? In my test project I tried this:

    "Framework": {
      "type": "parameter",
      "description": "The target framework for the project.",
      "datatype": "choice",
      "choices": [
        {
          "choice": "net5.0",
          "description": ".NET 5 (net5.0)"
        },
        {
          "choice": "netstandard2.1",
          "description": ".NET Standard 2.1 (netstandard2.1)"
        },
        {
          "choice": "netstandard2.0",
          "description": ".NET Standard 2.0 (netstandard2.0)"
        },
        {
          "choice": "netcoreapp3.1",
          "description": ".NET Core 3.1 (netcoreapp3.1) - Long Term Support (LTS)"
        },
        {
          "choice": "netcoreapp3.0",
          "description": ".NET Core 3.0 (netcoreapp3.0)"
        },
        {
          "choice": "netcoreapp2.2",
          "description": ".NET Core 2.2 (netcoreapp2.2)"
        },
        {
          "choice": "netcoreapp2.1",
          "description": ".NET Core 2.1 (netcoreapp2.1) - Long Term Support (LTS)"
        },
        {
          "choice": "net48",
          "description": ".NET Framework 4.8 (net48)"
        },
        {
          "choice": "net472",
          "description": ".NET Framework 4.72 (net472)"
        },
        {
          "choice": "net471",
          "description": ".NET Framework 4.71 (net471)"
        },
        {
          "choice": "net47",
          "description": ".NET Framework 4.7 (net47)"
        },
        {
          "choice": "net462",
          "description": ".NET Framework 4.62 (net462)"
        },
        {
          "choice": "net461",
          "description": ".NET Framework 4.61 (net461)"
        },
        {
          "choice": "net46",
          "description": ".NET Framework 4.6 (net46)"
        }
      ],
      "replaces": "net5.0",
      "defaultValue": "net5.0"
    },
    "DotnetFramework": {
      "type": "computed",
      "value": "(Framework == \"net48\") || (Framework == \"net472\") || (Framework == \"net471\") || (Framework == \"net47\") || (Framework == \"net462\") || (Framework == \"net461\") || (Framework == \"net46\")"
    },
<PropertyGroup Label="Build">
    <TargetFramework Condition="'$(DotnetFramework)' == 'false'">net5.0</TargetFramework>
    <TargetFramework Condition="'$(DotnetFramework)' == 'true' AND '$(Framework)' == 'net48'">net48</TargetFramework>
    <TargetFramework Condition="'$(DotnetFramework)' == 'true' AND '$(Framework)' == 'net472'">net472</TargetFramework>
    <TargetFramework Condition="'$(DotnetFramework)' == 'true' AND '$(Framework)' == 'net471'">net471</TargetFramework>
    <TargetFramework Condition="'$(DotnetFramework)' == 'true' AND '$(Framework)' == 'net47'">net47</TargetFramework>
    <TargetFramework Condition="'$(DotnetFramework)' == 'true' AND '$(Framework)' == 'net462'">net462</TargetFramework>
    <TargetFramework Condition="'$(DotnetFramework)' == 'true' AND '$(Framework)' == 'net461'">net461</TargetFramework>
    <TargetFramework Condition="'$(DotnetFramework)' == 'true' AND '$(Framework)' == 'net46'">net46</TargetFramework>
  </PropertyGroup>

However, whenever I set Framework to netstandard2.1 or netstandard2.0, the test project also gets set to that because of the replace in the choice symbol. I don't see an easy and obvious way to do it.

Solution Template Bug

Hi,

I try to create my own solution template. I'm facing an infuriating bug or my mistake. I've watched this mini serie on youtube and i read the documentation . Then i applied same things my project. I've updated my template to NuGet and run dotnet new -i <PackageId> command results is as follow;

Capture

No errors and where is my package?

My source code and nuget link is available. Please check it out and help. Thank you.

Solution Template: Open file in editor

When creating a project template, Visual Studio opens one or more files using the primaryOutputs and postActions properties.

This only works in a solution template when the files are at the same level as the solution file. If a project or multiple projects are nested, specific files are not opened.

Enable template author to select the default framework to be used

In my template.json file I default the Framework to use netstandard2.1 (see below), however the UI always shows netcoreapp3.1 by default and the drop down does not actually contain the list of target frameworks that I've listed below.

    "Framework": {
      "type": "parameter",
      "description": "The target framework for the project.",
      "datatype": "choice",
      "choices": [
        {
          "choice": "net5.0",
          "description": ".NET 5 (net5.0)"
        },
        {
          "choice": "netstandard2.1",
          "description": ".NET Standard 2.1 (netstandard2.1)"
        },
        {
          "choice": "netstandard2.0",
          "description": ".NET Standard 2.0 (netstandard2.0)"
        },
        {
          "choice": "netcoreapp3.1",
          "description": ".NET Core 3.1 (netcoreapp3.1) - Long Term Support (LTS)"
        },
        {
          "choice": "netcoreapp3.0",
          "description": ".NET Core 3.0 (netcoreapp3.0)"
        },
        {
          "choice": "netcoreapp2.2",
          "description": ".NET Core 2.2 (netcoreapp2.2)"
        },
        {
          "choice": "netcoreapp2.1",
          "description": ".NET Core 2.1 (netcoreapp2.1) - Long Term Support (LTS)"
        }
      ],
      "replaces": "netstandard2.1",
      "defaultValue": "netstandard2.1"
    },

image

Ideally, the UI should pick up the list from the choices array and respect the defaultValue in the template.json.

Describe the migration path from old VSIX to .NET CLI

especially, https://devblogs.microsoft.com/dotnet/net-cli-templates-in-visual-studio/ states

Templates with CLI and Visual Studio installer (VSIX) manifests with different IDs will show duplicates. Changing to a single identity for the template is recommended.

My expectation when reading that was, that the .NET CLI templates would "hide" the old VSIX templates if I got the IDs right.

First question: Is that true?

And if so, which IDs should be synced? I tried setting $.identity in template.json to TemplateID from the VSIX .vstemplate but that's not it.

Are Item Templates Supported?

Are Item Templates Supported? I've tried the files below and they don't work for me:

template.json

{
  "$schema": "http://json.schemastore.org/template",
  "author": ".NET Boxed",
  "classifications": [
    "Config"
  ],
  "identity": "Dotnet.Boxed.gitattributes.CSharp",
  "name": ".gitattributes file",
  "shortName": "gitattributes",
  "defaultName": ".gitattributes",
  "description": "Controls Git settings like line endings, which files are treated as binary files and Git Large File System (LFS) settings.",
  "tags": {
    "language": "C#",
    "type": "item"
  }
}

Just realized I have the language set to C#. Not sure what should go there.

ide.host.json

{
  "$schema": "http://json.schemastore.org/vs-2017.3.host",
  "order": 0,
  "learnMoreLink": "https://github.com/Dotnet-Boxed/Templates",
  "icon": "icon.png"
}

Show how to add a Choice Parameter Type

I have the following symbol in my template.json file:

    "SourceControl": {
      "type": "parameter",
      "datatype": "choice",
      "choices": [
        {
          "choice": "GitHub",
          "description": "Adds a .github directory containing a code of conduct, contributing guide, pull request template and issue templates."
        },
        {
          "choice": "None",
          "description": "No source control provider is being used."
        }
      ],
      "defaultValue": "GitHub",
      "description": "Select which source control provider you are using if any, to add provider specific features."
    },
    "GitHub": {
      "type": "computed",
      "value": "(SourceControl == \"GitHub\")"
    },

This shows as follows in the VS UI:

image

How can I show the correct labels for the items in the dropdown? This is my ide.host.json:

{
  "$schema": "http://json.schemastore.org/vs-2017.3.host",
  "learnMoreLink": "https://github.com/Dotnet-Boxed/Templates/blob/master/Docs/API.md",
  "icon": "icon.png",
  "symbolInfo": [
    {
      "id": "SourceControl",
      "name": {
        "text": "Source Control"
      },
      "isVisible": true
    },
  ]
}

When I remove the custom label "text": "Source Control" then I get this:

image

The label is now showing as SourceControl without the space.

Choice parameters are not well binded in Visual Studio Template

Hello,
i recently worked on a custom template for vs studio 2019, where i have set some custom choice parameters.
with Cli mode every thing works perfectly. Now when i tried to integrate the template in VStudio (ide.host.json), i have referenced the choice parameter name from ide.host.json.
I've noticed that the template wizard displays a drop down list correctly but items values and texts are not displayed correctly:
example: parameter name : param1 with choices: item1, item2.
In Vstudio wizard the drop down list contains two itemps with text = param1.
there should be an issue while binding choice parameters.

I would like also to have an example of multiple project templates with a choice parameters that works well in Visual Studio. Is it possible to have such sample ?
Thanks a lot for your great job

Parameters are not showing up in VS2022

Not sure where to log these issues, please point me to correct repo if this is not the correct place.

Parameters are not showing up in VS2022. I install my template from a local NuGet package, I'm clearing the cache (.templateengine) between installs and also exit all VS instances before clearing the cache. I've also created an ide.host.json file with the parameters to see if that made any difference, but with no luck (the schema for ide.host.json seems to be outdated http://json.schemastore.org/vs-2017.3.host).
All other changes I make to the template, such as new or changed files, does work. The template fulfills all other requirements you mention here.

These are my symbols in template.json

...
"symbols": {
  "enablelDocker": {
    "type": "parameter",
    "datatype": "bool",
    "defaultValue": "false",
    "description": "Enable Docker support"
  },
  "saPassword": {
    "type": "parameter",
    "datatype": "string",
    "defaultValue": "Qwerty12345!",
    "description": "Password for the SA database account",
    "replaces": "Qwerty12345!"
  }
}
...

and ide.host.json

...
"symbolInfo": [
  {
    "id": "enablelDocker",
    "name": {
      "text": "Enable Docker support"
    },
    "isVisible": "true"
  },
  {
    "id": "saPassword",
    "name": {
      "text": "Password for the SA database account"
    },
    "isVisible": "true"
  }
]
...

What have I missed?

Are there more prerequisites to the image?

Given prerequisites are:

  • png
  • located in, or under, the .template.config

However, my image looks "inverted", somehow.

What it looks like:
image

What I would expect:
image

Information on the file I used:

Image:
  Filename: ..\..\nuspec\cake-medium.png
  Format: PNG (Portable Network Graphics)
  Mime type: image/png
  Class: DirectClass
  Geometry: 256x256+0+0
  Resolution: 28.33x28.33
  Print size: 9.03636x9.03636
  Units: PixelsPerCentimeter
  Colorspace: sRGB
  Type: TrueColorAlpha
  Base type: Undefined
  Endianness: Undefined
  Depth: 8-bit
  Channel depth:
    Red: 8-bit
    Green: 8-bit
    Blue: 8-bit
    Alpha: 8-bit
  Channel statistics:
    Pixels: 65536
    Red:
      min: 0  (0)
      max: 255 (1)
      mean: 88.1718 (0.345772)
      median: 0 (0)
      standard deviation: 85.5569 (0.335517)
      kurtosis: -0.723407
      skewness: 0.577586
      entropy: 0.358177
    Green:
      min: 0  (0)
      max: 255 (1)
      mean: 64.2388 (0.251917)
      median: 0 (0)
      standard deviation: 75.5915 (0.296437)
      kurtosis: 0.520318
      skewness: 1.20242
      entropy: 0.373593
    Blue:
      min: 0  (0)
      max: 255 (1)
      mean: 33.0931 (0.129777)
      median: 0 (0)
      standard deviation: 59.3856 (0.232885)
      kurtosis: 5.19374
      skewness: 2.21748
      entropy: 0.244348
    Alpha:
      min: 0  (0)
      max: 255 (1)
      mean: 155.58 (0.61012)
      median: 0 (0)
      standard deviation: 123.741 (0.48526)
      kurtosis: -1.78816
      skewness: -0.450789
      entropy: 0.147945
  Image statistics:
    Overall:
      min: 0  (0)
      max: 255 (1)
      mean: 85.271 (0.334396)
      median: 0 (0)
      standard deviation: 86.0688 (0.337525)
      kurtosis: -0.984744
      skewness: 0.767422
      entropy: 0.281016
  Alpha: none   #00000000
  Rendering intent: Perceptual
  Gamma: 0.45455
  Chromaticity:
    red primary: (0.64,0.33)
    green primary: (0.3,0.6)
    blue primary: (0.15,0.06)
    white point: (0.3127,0.329)
  Matte color: grey74
  Background color: white
  Border color: srgb(223,223,223)
  Transparent color: none
  Interlace: None
  Intensity: Undefined
  Compose: Over
  Page geometry: 256x256+0+0
  Dispose: Undefined
  Iterations: 0
  Compression: Zip
  Orientation: Undefined
  Properties:
    date:create: 2021-05-01T20:46:35+00:00
    date:modify: 2021-05-01T20:46:35+00:00
    png:gAMA: gamma=0.45455 (See Gamma, above)
    png:IHDR.bit-depth-orig: 8
    png:IHDR.bit_depth: 8
    png:IHDR.color-type-orig: 6
    png:IHDR.color_type: 6 (RGBA)
    png:IHDR.interlace_method: 0 (Not interlaced)
    png:IHDR.width,height: 256, 256
    png:pHYs: x_res=2833, y_res=2833, units=1
    png:sRGB: intent=0 (Perceptual Intent)
    png:text: 1 tEXt/zTXt/iTXt chunks were found
    signature: c0927c9e6b370ad79347d538a8bb688de0667ab9664d5a49d85e3b4229766635
    Software: paint.net 4.0
  Artifacts:
    verbose: true
  Tainted: False
  Filesize: 17063B
  Number pixels: 65536
  Pixels per second: 8.45233MP
  User time: 0.016u
  Elapsed time: 0:01.007
  Version: ImageMagick 7.0.10-58 Q16 x64 2021-01-16 https://imagemagick.org

Using a Wizard with dotnet new project templates

@sayedihashimi

Can you associate a Microsoft.VisualStudio.TemplateWizard.IWizard with the new dotnet new project templates?
If not, is there an equivalent mechanism?

I am currently using an IWizard with my templates authored using .vstemplate. I would like to switch to the new mechanism.

Additional information dialogue in Visual Studio is empty when Framework is not defined in symbols

Without Framework symbol in template.json, the "Additional information" tab in Visual Studio (Community 2019 Version 16.8.3) is blank, despite the ide.host.json file containing info:
image

Adding

"Framework": {
  "type": "parameter",
  "description": "The target framework for the project.",
  "datatype": "choice",
  "choices": [
    {
      "choice": "netstandard2.0",
      "description": "Target netstandard2.0"
    }
  ],
  "replaces": "netstandard2.0",
  "defaultValue": "netstandard2.0"
},

under symbols in template.json fixes the issue, and the "Additional information" tab has all the fields defined in ide.host.json.
image

Solution template - making sure solution-level items exist in same folder as .sln

I have a multi-project solution template and with the recent change to 16.10, I can now use solution-type templates and they work great in the .NET CLI.
However, in a Visual Studio host, I run into an issue if the user selects not to have the solution and project file be in the same location, in the Visual Studio creation dialog, because VS generates a new solution file at a folder level above whatever the template specifies.

I have a .editorconfig and nuget.config files that needs to be alongside the .sln to be loaded, but if the above option is chosen, then those files will end up being created in the child folder. If I select the above option, then it works just like it does with the CLI.

Is there any way for me to output those files in the correct location, depending on whatever the user selects in that dialog?

My template.json can be found here

Unable to see new project template in Visual Studio

I'm working on creation a solution template with multiple projects but I am not able to see the new template in Visual Studio 2019/2022 Preview and VS for Mac New dialog. I tried using the sayedmulti template in this repo and it's also not displayed in the new dialog. I've followed the Common Issues in the readme but to no luck. The template does show up in dotnet cli and Rider though. Are there any other options I can try? I created the template in vscode if that helps. Below is my folder structure.

Project.nuspec
src
.... Content
....... ApiTemplate
.......... .template.config
.............. icon.png
.............. ide.host.json
.............. template.json
.......... nuget.config
.......... Project.sln
.......... src
.............. Project1
.............. Project2
.............. Project3
.......... test
.............. TestProject3

Templates That Already Contain a Solution

All my project templates contain a solution and multiple project files. When I create a project using VS, it creates a new solution for me and does not open the one in the template. Is there a way to hide and disable the 'Solution name' text box below?

image

I've added VS support to my template in this PR: Dotnet-Boxed/Templates#836 if you want to try it.

[Q] Is there a way of converting .vstemplate files?

I was wondering is there a way to generate template.json from an existing .vstemplate file?
And if there isn't, what would be the preferred approach of upgrading them?

To provide you with more context:
We have a Visual Studio extension which provides custom project templates targeting .NET framework which need to be extended/upgraded to target .NET core as well.

adding a non-existing TFM in the Framework symbol choices breaks template creation

I wanted to do something "special" so I created the following symbol for Framework:

"Framework": {
    "type": "parameter",
    "description": "The target frameworks for the project.",
    "datatype": "choice",
    "choices": [
        {
            "choice": "netstandard2.0",
            "description": "Target netstandard2.0 only"
        },
        {
            "choice": "net5.0",
            "description": "Target netstandard2.0 and net5.0"
        },
        {
            "choice": "net461",
            "description": "Target netstandard2.0 and net461"
        },
        {
            "choice": "all",
            "description": "Target netstandard2.0, net461 and net5.0"
        }
    ],
    "defaultValue": "netstandard2.0"
}

While this works perfectly fine in CLI, VS "chokes" on building the options page and freezes.

Removing the "all" choice fixes the problem.

While I would love to have the above working I can live with a workaround. However, I feel that VS should not freeze on incorrect input.

Issues while using the Choice parameter in the conditions

Hello @sayedihashimi

I am working on creating some custom templates using the choice parameters and been having some issues.

Here is the scenario I am using the choice parameter for -
I want to add a choice parameter called Logging, and the choices it would take is NLog, SeriLog, Log4Net. Based on the dotnet new CLI cmd options (dotnet new mycustomtemplate --Logging "NLog"), I want to add the required nuget packages in the csproj file, and may be some code to configure those loggers in the startup.cs file.

The issue I have is -
When I try to add the condition like #if (Logging=="NLog") in the startup.cs file, it doesn't not consider it a condition, like how it does for bool parameters (for example if Logging was bool, then #if Logging works good, but not when it is choice parameter which takes some string values.)

would you be able to point to a sample if you already have one, or let me know how I could use the choice parameter in a condition.

startup.cs
#if Logging=="Nlog"
#endif

Are solution templates supported

There are many cases where several projects are needed at once. An example of where its already done is blazor web assembly core hosted. In that case, 3 projects are created each time. That would be very important to be able to do.

Enable showing parameter descriptions in the New Project Dialog

I have several custom parameters for which I have provided descriptions in my template.json file. This appear when using the CLI. However, in Visual Studio they do not. Is it possible to get them to show up?

image

E.g. I have the following in template.json for the Title parameter:

    "Title": {
      "type": "parameter",
      "datatype": "string",
      "defaultValue": "Project Title",
      "replaces": "PROJECT-TITLE",
      "description": "The name of the project which determines the NuGet package name and assembly product name."
    },

It would be nice if the description could be used in the UI somehow.

Secondly, I have a lot of parameters. Is there a way that I could group related parameters together somehow?

Need ide.host.json Reference Wiki

Hello,

I have looked everywhere for this. I even opened the schema to see if it would help.

In .vstemplate files there are 3 tags, "LanguageTag, ProjectTypeTag & PlatformTag. Looking in the schema I came across uiFilters array. That is just a guess, but how would I go about setting this in ide.host.json.

thx

**Update
Watching your video again, I heard you say "classifications" shows up where the "ProjectTypeTag" is used.

Add a private extension gallery to Visual Studio for multiple devices in the organization

Hi @sayedihashimi,

I am searching for a solution to update multiple devices in the organization to add a private extension gallery to Visual Studio. We would prefer to be able to update all devices with this setting in the background so that our developers don't need to manually add the gallery to their Visual Studio installation.

In my research, I've seen that registry keys may have been used at some point to solve this particular situation. Is this still the recommended solution? If so, do you know of any documentation available that outlines this process?

If there is another way to accomplish this or if registry keys are no longer an option, I'd love to know!

VSIX not working

The VSIX at https://www.dropbox.com/s/1hvvk6p7buuk3yy/MicroService.zip?dl=0 looks like it has all the right content to work. I couldn't figure out why it's not working.

@phenning can you take a look to see what's going on with this vsix?

This issue is a continuation of the discussion at the bottom of #19 with @vondwater.

@vondwater FYI from the sources that you sent me, I made one change. That was to mark the Templates.pkgdef to be included in the VSIX. I think this is missing from the readme. I will get it updated. See the image below. In addition I noticed that your template name ends with "nuspec", that was an error in my sample. You should remove that after we figure out what is happening with this VSIX.

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.