bard83 / csharpextensions

C# Extensions for Visual Studio Code
MIT License
2 stars 1 forks source link

Improve Custom Template with Attribute definition with placeholders #16

Closed heggi closed 12 months ago

heggi commented 1 year ago

Some templates require add some attributes to class definition with placeholders

For example database migration template:

using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

namespace TestProject.Migrations;

[DbContext(typeof(AppDbContext))]
[Migration("m231108_204500_CreateTestTable")]
public class m231108_204500_CreateTestTable: Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
        name: "Test",
        columns: t => new
        {
            Id = t.Column<int>(type: "serial"),
        }
        ).PrimaryKey("PK-Test", c => c.Id);
    }
}

I need option to add attributes DbContext and Migration to class definition. Also attribute Migration must contain class name as his parameter.

Implementation example:

Add new parameter attribute (or other name) to template definition with placeholder replacer. Example:

"csharpextensions.templates": {
    "items": [
        {
           ...
            "construct": "class",
            "attribute": "[DbContext(typeof(AppDbContext))]\n[Migration(\"{{ ClassName }}\")]"                
        }
    ]
},
bard83 commented 1 year ago

Thanks for the feedback. It makes totally sense.

Since there could be several attributes, I'd prefer to define it as a string array instead of a simple string. Just to simplify the life of who is going to write the attributes. Then it won't be necessary to handle the EOL, square brackets and some other tedious little problems. For the placeholder it shouldn't be a problem, since it's already defined. I'd keep the existing syntax ${classname}. Based on your example it will look like so:

"csharpextensions.templates": {
    "items": [
        {
           ...
            "construct": "class",
            "attributes": [
                 "DbContext(typeof(AppDbContext))",
                 "Migration(\"${classname}\""
              ]                
        }
    ]
},