Change the naming pattern of Views that are generated by scaffold

8

I would like to change the nomenclature in which scaffold generates Views:

Default:

Create.cshtml
Delete.cshtml
Details.cshtml
Edit.cshtml
Index.cshtml

I want scaffold to create this:

Criar.cshtml
Excluir.cshtml
Exibir.cshtml
Editar.cshtml
Index.cshtml
    
asked by anonymous 03.10.2015 / 20:59

1 answer

8

For this answer, I assume you are using the MvcScaffolding.VS2015 package in the latest version. If you have a problem with the latest version, use version 1.0.10, which works only for VS2015 . Do not forget to fix version numbers to avoid unwanted updates on your packages.config :

<packages>
    <package id="MvcScaffolding.VS2015" version="1.0.10" targetFramework="net452" allowedVersions="[1.0.10]" />
    <package id="T4Scaffolding.Core.VS2015" version="1.0.1" targetFramework="net452" allowedVersions="[1.0.1]" />
    <package id="T4Scaffolding.VS2015" version="1.0.8" targetFramework="net452" allowedVersions="[1.0.8]" />
</packages>

Step 1: Create your CustomScaffold

I created mine with the following command:

PM> scaffold CustomScaffolder Portugues
Visual Studio will create in the CodeTemplates directory of your project another directory named Scaffolders , and inside it a directory named Portugues with two files: a .ps1 file (PowerShell script extension) and a .cs.t4 file, which we will not use. Feel free to erase it if you want.

Step 2: Changing the CustomScaffold

Go to diretório do seu projeto\packages\MvcScaffolding.VS2015.<versão>\tools\Views . Open the file MvcScaffolding.Views.ps1 . It should look something like this:

[T4Scaffolding.Scaffolder(Description = "Adds ASP.NET MVC views for Create/Read/Update/Delete/Index scenarios")][CmdletBinding()]
param(        
    [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0)][string]$Controller,
    [string]$ModelType,
    [string]$Area,
    [alias("MasterPage")]$Layout = "",  # If not set, we'll use the default layout
    [alias("ContentPlaceholderIDs")][string[]]$SectionNames,
    [alias("PrimaryContentPlaceholderID")][string]$PrimarySectionName,
    [switch]$ReferenceScriptLibraries = $false,
    [string]$Project,
    [string]$CodeLanguage,
    [string[]]$TemplateFolders,
    [string]$ViewScaffolder = "View",
    [switch]$Force = $false
)

@("Create", "Edit", "Delete", "Details", "Index", "_CreateOrEdit") | %{
    Scaffold $ViewScaffolder -Controller $Controller -ViewName $_ -ModelType $ModelType -Template $_ -Area $Area -Layout $Layout -SectionNames $SectionNames -PrimarySectionName $PrimarySectionName -ReferenceScriptLibraries:$ReferenceScriptLibraries -Project $Project -CodeLanguage $CodeLanguage -OverrideTemplateFolders $TemplateFolders -Force:$Force
}

What we're going to change is this:

@("Create", "Edit", "Delete", "Details", "Index", "_CreateOrEdit") | %{
    Scaffold $ViewScaffolder -Controller $Controller -ViewName $_ -ModelType $ModelType -Template $_ -Area $Area -Layout $Layout -SectionNames $SectionNames -PrimarySectionName $PrimarySectionName -ReferenceScriptLibraries:$ReferenceScriptLibraries -Project $Project -CodeLanguage $CodeLanguage -OverrideTemplateFolders $TemplateFolders -Force:$Force
}

Copy the entire contents of the MvcScaffolding.Views.ps1 file to your CustomScaffold . Change the above block to:

@("Criar", "Editar", "Excluir", "Detalhes", "Index", "_CriarOuEditar") | %{
    Scaffold $ViewScaffolder -Controller $Controller -ViewName $_ -ModelType $ModelType -Template $_ -Area $Area -Layout $Layout -SectionNames $SectionNames -PrimarySectionName $PrimarySectionName -ReferenceScriptLibraries:$ReferenceScriptLibraries -Project $Project -CodeLanguage $CodeLanguage -OverrideTemplateFolders $TemplateFolders -Force:$Force
}

Step 3: Creating new CodeTemplates in Portuguese

Scaffold does not get lost, you will need to copy the templates to your CustomScaffold directory.

Once the package has been installed, copy all cs.t4 extension files from the diretório do seu projeto\MvcScaffolding.VS2015.<versão>\tools\RazorView directory to your CustomScaffold directory. Once this is done, rename the files for the convention that was established in the previous step. Mine went like this:

_CriarOuEditar.cs.t4
Criar.cs.t4
Detalhes.cs.t4
Editar.cs.t4
Empty.cs.t4
Excluir.cs.t4
Index.cs.t4

Step 4: Testing

If you did everything right, this command generates Scaffold in Portuguese for you:

PM> scaffold Portugues Teste2 -ModelType:MeuProjeto.Models.Banco
Added Criar view at 'Views\Teste2\Criar.cshtml'
Added Editar view at 'Views\Teste2\Editar.cshtml'
Added Excluir view at 'Views\Teste2\Excluir.cshtml'
Added Detalhes view at 'Views\Teste2\Detalhes.cshtml'
Added Index view at 'Views\Teste2\Index.cshtml'

Considerations

Note that the templates of the Scaffolding are not compatible with MvcScaffolding templates, and that MvcScaffolding templates , and not made for Bootstrap. Some work may be required to leave the templates with a more recent face.

Additionally, there is an aggravation that these templates do not support async , but nothing prevents you from implementing all methods as async if you wish.

But what if I want to customize the entire Controller generation process with Views ?

Well, there you will have to practically copy a Scaffolder from MvcScaffolding and change it to generate everything in Portuguese.

Am I going to have to generate this?

No. I'm in a good mood and I did it for you:

CodeTemplates/Scaffolders/Portugues/Portugues.ps1

[T4Scaffolding.ControllerScaffolder("Controller with read/write action and views, using EF data access code", Description = "Adds an ASP.NET MVC controller with views and data access code", SupportsModelType = $true, SupportsDataContextType = $true, SupportsViewScaffolder = $true)][CmdletBinding()]
param(     
    [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)][string]$ControllerName,   
    [string]$ModelType,
    [string]$Project,
    [string]$CodeLanguage,
    [string]$DbContextType,
    [string]$Area,
    [string]$ViewScaffolder = "View",
    [alias("MasterPage")]$Layout,
    [alias("ContentPlaceholderIDs")][string[]]$SectionNames,
    [alias("PrimaryContentPlaceholderID")][string]$PrimarySectionName,
    [switch]$ReferenceScriptLibraries = $false,
    [switch]$Repository = $false,
    [switch]$NoChildItems = $false,
    [string[]]$TemplateFolders,
    [switch]$Force = $false,
    [string]$ForceMode
)

# Interpret the "Force" and "ForceMode" options
$overwriteController = $Force -and ((!$ForceMode) -or ($ForceMode -eq "ControllerOnly"))
$overwriteFilesExceptController = $Force -and ((!$ForceMode) -or ($ForceMode -eq "PreserveController"))

# If you haven't specified a model type, we'll guess from the controller name
if (!$ModelType) {
    if ($ControllerName.EndsWith("Controller", [StringComparison]::OrdinalIgnoreCase)) {
        # If you've given "PeopleController" as the full controller name, we're looking for a model called People or Person
        $ModelType = [System.Text.RegularExpressions.Regex]::Replace($ControllerName, "Controller$", "", [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
        $foundModelType = Get-ProjectType $ModelType -Project $Project -ErrorAction SilentlyContinue
        if (!$foundModelType) {
            $ModelType = [string](Get-SingularizedWord $ModelType)
            $foundModelType = Get-ProjectType $ModelType -Project $Project -ErrorAction SilentlyContinue
        }
    } else {
        # If you've given "people" as the controller name, we're looking for a model called People or Person, and the controller will be PeopleController
        $ModelType = $ControllerName
        $foundModelType = Get-ProjectType $ModelType -Project $Project -ErrorAction SilentlyContinue
        if (!$foundModelType) {
            $ModelType = [string](Get-SingularizedWord $ModelType)
            $foundModelType = Get-ProjectType $ModelType -Project $Project -ErrorAction SilentlyContinue
        }
        if ($foundModelType) {
            $ControllerName = [string](Get-PluralizedWord $foundModelType.Name) + "Controller"
        }
    }
    if (!$foundModelType) { throw "Cannot find a model type corresponding to a controller called '$ControllerName'. Try supplying a -ModelType parameter value." }
} else {
    # If you have specified a model type
    $foundModelType = Get-ProjectType $ModelType -Project $Project
    if (!$foundModelType) { return }
    if (!$ControllerName.EndsWith("Controller", [StringComparison]::OrdinalIgnoreCase)) {
        $ControllerName = $ControllerName + "Controller"
    }
}
Write-Host "Scaffolding $ControllerName..."

if(!$DbContextType) { $DbContextType = [System.Text.RegularExpressions.Regex]::Replace((Get-Project $Project).Name, "[^a-zA-Z0-9]", "") + "Context" }
if (!$NoChildItems) {
    if ($Repository) {
        Scaffold Repository -ModelType $foundModelType.FullName -DbContextType $DbContextType -Area $Area -Project $Project -CodeLanguage $CodeLanguage -Force:$overwriteFilesExceptController
    } else {
        $dbContextScaffolderResult = Scaffold DbContext -ModelType $foundModelType.FullName -DbContextType $DbContextType -Area $Area -Project $Project -CodeLanguage $CodeLanguage
        $foundDbContextType = $dbContextScaffolderResult.DbContextType
        if (!$foundDbContextType) { return }
    }
}
if (!$foundDbContextType) { $foundDbContextType = Get-ProjectType $DbContextType -Project $Project }
if (!$foundDbContextType) { return }

$primaryKey = Get-PrimaryKey $foundModelType.FullName -Project $Project -ErrorIfNotFound
if (!$primaryKey) { return }

$outputPath = Join-Path Controllers $ControllerName
# We don't create areas here, so just ensure that if you specify one, it already exists
if ($Area) {
    $areaPath = Join-Path Areas $Area
    if (-not (Get-ProjectItem $areaPath -Project $Project)) {
        Write-Error "Cannot find area '$Area'. Make sure it exists already."
        return
    }
    $outputPath = Join-Path $areaPath $outputPath
}

# Prepare all the parameter values to pass to the template, then invoke the template with those values
$repositoryName = $foundModelType.Name + "Repository"
$defaultNamespace = (Get-Project $Project).Properties.Item("DefaultNamespace").Value
$modelTypeNamespace = [T4Scaffolding.Namespaces]::GetNamespace($foundModelType.FullName)
$controllerNamespace = [T4Scaffolding.Namespaces]::Normalize($defaultNamespace + "." + [System.IO.Path]::GetDirectoryName($outputPath).Replace([System.IO.Path]::DirectorySeparatorChar, "."))
$areaNamespace = if ($Area) { [T4Scaffolding.Namespaces]::Normalize($defaultNamespace + ".Areas.$Area") } else { $defaultNamespace }
$dbContextNamespace = $foundDbContextType.Namespace.FullName
$repositoriesNamespace = [T4Scaffolding.Namespaces]::Normalize($areaNamespace + ".Models")
$modelTypePluralized = Get-PluralizedWord $foundModelType.Name
$relatedEntities = [Array](Get-RelatedEntities $foundModelType.FullName -Project $project)
if (!$relatedEntities) { $relatedEntities = @() }

$templateName = if($Repository) { "ControllerWithRepository" } else { "ControllerWithContext" }
Add-ProjectItemViaTemplate $outputPath -Template $templateName -Model @{
    ControllerName = $ControllerName;
    ModelType = [MarshalByRefObject]$foundModelType; 
    PrimaryKey = [string]$primaryKey; 
    DefaultNamespace = $defaultNamespace; 
    AreaNamespace = $areaNamespace; 
    DbContextNamespace = $dbContextNamespace;
    RepositoriesNamespace = $repositoriesNamespace;
    ModelTypeNamespace = $modelTypeNamespace; 
    ControllerNamespace = $controllerNamespace; 
    DbContextType = [MarshalByRefObject]$foundDbContextType;
    Repository = $repositoryName; 
    ModelTypePluralized = [string]$modelTypePluralized; 
    RelatedEntities = $relatedEntities;
} -SuccessMessage "Added controller {0}" -TemplateFolders $TemplateFolders -Project $Project -CodeLanguage $CodeLanguage -Force:$overwriteController

if (!$NoChildItems) {
    $controllerNameWithoutSuffix = [System.Text.RegularExpressions.Regex]::Replace($ControllerName, "Controller$", "", [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
    if ($ViewScaffolder) {
        @("Criar", "Editar", "Excluir", "Detalhes", "Indice", "_CriarOuEditar") | %{
            Scaffold $ViewScaffolder -Controller $controllerNameWithoutSuffix -ViewName $_ -ModelType $foundModelType.FullName -Template $_ -Area $Area -Layout $Layout -SectionNames $SectionNames -PrimarySectionName $PrimarySectionName -ReferenceScriptLibraries:$ReferenceScriptLibraries -Project $Project -CodeLanguage $CodeLanguage -OverrideTemplateFolders $TemplateFolders -Force:$overwriteFilesExceptController
        }
    }
}

Make sure all these files are in the same directory as the Portugues.ps1 file:

Can I use MvcScaffolding along with Scaffolding native?

You can, but note that two contexts will be generated: A ApplicationDbContext and SeuProjetoContext . To avoid duplicate contexts, delete SeuProjetoContext and rename ApplicationDbContext to SeuProjetoContext .

    
14.10.2015 / 16:45