Change the naming pattern of views that are generated by scaffold

Asked

Viewed 591 times

8

I would like to change the nomenclature where scaffold generates views:

Standard:

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

I want scaffolding to create that way:

Criar.cshtml
Excluir.cshtml
Exibir.cshtml
Editar.cshtml
Index.cshtml
  • Sorry it took so long. I could only sit down and write this down now.

1 answer

9


For this answer, I suppose you’re using the package Mvcscaffolding.VS2015 in the latest version. If you have any problems with the latest version, use version 1.0.10, which works only for VS2015. Don’t forget to fix the 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 own Customscaffold

I created mine with the following command:

PM> scaffold CustomScaffolder Portugues

Visual Studio will create in the directory CodeTemplates of your project another directory called Scaffolders, and within it a directory called Portugues with two files: one file .ps1 (Powershell script extension) and a file .cs.t4, which we will not use. Feel free to delete it if you like.

Step 2: Changing the Customscaffold

Go on the diretório do seu projeto\packages\MvcScaffolding.VS2015.<versão>\tools\Views. Open the file MvcScaffolding.Views.ps1. He must be 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 all the contents of the file MvcScaffolding.Views.ps1 for 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

To the Scaffold not get lost, you will need to copy the templates to your directory Customscaffold.

Installed the package, copy all the extension files cs.t4 of the directory diretório do seu projeto\MvcScaffolding.VS2015.<versão>\tools\RazorView to the directory of your Customscaffold. Once done, rename the name of the archives to the established convention in the previous step. Mine were 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 the 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 Scaffolding are not compatible with those of Mvcscaffolding, and that the templates of Mvcscaffolding are somewhat old, in addition to not being made for Bootstrap. Some work may be necessary to leave the templates with a younger face.

Additionally, there is the aggravating of these templates not having the support of async, but nothing prevents it from implementing all methods such as async if you so wish.


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

Well, then you’ll have to practically copy one Scaffolder of Mvcscaffolding and change it to generate everything in Portuguese.

I’ll have to generate it?

No. I’m in a good mood and I made this 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 that all these files are in the same file directory Portugues.ps1:

Arquivos do Scaffolding em Português


I can use the Mvcscaffolding together with the Scaffolding native?

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.