Skip to content

Instantly share code, notes, and snippets.

@bezysoftware
Last active September 9, 2018 08:00
Show Gist options
  • Select an option

  • Save bezysoftware/9cdc1a58521bee3404ad00361ae4fb01 to your computer and use it in GitHub Desktop.

Select an option

Save bezysoftware/9cdc1a58521bee3404ad00361ae4fb01 to your computer and use it in GitHub Desktop.
Designer generator
function Convert-Everything([string] $rootDir, [string[]]$languages)
{
$resources = "$rootDir"
$neutralStrings = "$resources/strings.xml"
# generate appresources.designer.cs file
Write-DesignerFile $neutralStrings $neutralResx | Out-File -FilePath 'AppResources.Designer.cs'
# generate neutral appresources.resx
Convert-StringsToResX $neutralStrings $neutralResx | Out-File -FilePath 'AppResources.resx' -encoding utf8
# generate appresources.{language}.resx for each language
$languages | foreach {
$lng = $_
Convert-StringsToResX "$rootDir/strings.$lng.xml" "$rootDir/windows.$lng.resx" $false | Out-File -FilePath "AppResources.$lng.resx" -encoding utf8
}
}
function Write-DesignerFile([string] $neutralResource)
{
[xml]$neutralXml = Get-Content -Path $neutralResource
Write-DesignerHeader
# iterate over regular strings
$nodes = $neutralXml.SelectNodes("/resources/string")
foreach ($node in $nodes)
{
Write-DesignerProperty $node.name $node.InnerText
}
# iterate over plural forms
$nodes = $neutralXml.SelectNodes("/resources/plurals")
foreach ($node in $nodes)
{
foreach ($item in $node.SelectNodes("item"))
{
# each plural form has a name and quantity, merge those to create a new Resx key - e.g. 'oranges_few', 'orangers_one' etc.
Write-DesignerProperty "$($node.name)_$($item.quantity)" $item.InnerXml
}
Write-PluralMethod $node.name
}
Write-DesignerFooter
}
function Write-PluralMethod([string] $name)
{
# convert snake_case to TitleCase and append "WithCount(int count)"
$camel = ($name -csplit '_' | foreach { (Get-Culture).TextInfo.ToTitleCase($_) }) -join ''
Write-Output " public string $($camel)WithCount(int count) {
var key = `"`";
switch (count)
{
case 1: # one is one
key = `"$($name)_one`";
break;
case var c when (c < 5): # less than 5 is few
key = `"$($name)_few`";
break;
default: # 5 and more is other
key = `"$($name)_other`";
break;
};
return string.Format(ResourceManager.GetString(key, this.resourceCulture), count);
}
"
}
function Write-DesignerProperty([string] $name, [string] $value)
{
# putting the default (english) value into the documentation comment helps you while writing code and looking for a specific phrase
$val = $value -replace '\\"', '""' -replace "`n"," " -replace "`r"," "
# convert snake_case into TitleCase
$title = ($name -csplit '_' | foreach { (Get-Culture).TextInfo.ToTitleCase($_) }) -join ''
Write-Output " /// <summary>
/// $val
/// </summary>
public string $title => ResourceManager.GetString(`"$name`", this.resourceCulture);
"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment