Skip to content

Instantly share code, notes, and snippets.

@cmorgado
Created September 26, 2014 22:19
Show Gist options
  • Save cmorgado/e514daa7025aa022c916 to your computer and use it in GitHub Desktop.
Save cmorgado/e514daa7025aa022c916 to your computer and use it in GitHub Desktop.
Create a strongly type class to access your resw
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="Microsoft.CSharp" #>
<#@ output extension=".cs" #>
<#
var inputFilePath = @"Resources.resw";
var provider = new CSharpCodeProvider();
string className = CreateClassName(provider);
SetCurrentDirectory();
if (File.Exists(inputFilePath))
{
#>
//------------------------------------------------------------------------------
//
// This code was generated by a resource generator.
//
//------------------------------------------------------------------------------
using System;
using Windows.ApplicationModel.Resources;
namespace Your.Namespace
{
public static class <#= className #>
{
public static ResourceLoader ResourceLoader
{
get; private set;
}
static <#= className #>()
{
ResourceLoader = new ResourceLoader();
}
public static string Get(string resource)
{
return ResourceLoader.GetString(resource);
}
public static string Format(string resource, params object[] args)
{
return String.Format(ResourceLoader.GetString(resource), args);
}
<#
foreach (string name in GetResourceKeys(inputFilePath)) {
#>
public static string <#= BuildPropertyName(provider, name) #>
{
get
{
return ResourceLoader.GetString("<#= BuildResourceString(name) #>");
}
}
<#
}
#>
}
}
<#
}
else
{
throw new FileNotFoundException(String.Format("Unable to find Resource file: {0}", inputFilePath));
}
#>
<#+
private string BuildPropertyName(CSharpCodeProvider provider, string name)
{
return provider.CreateEscapedIdentifier(Regex.Replace(name, @"\[.+\]|\.", String.Empty));
}
private string BuildResourceString(string name)
{
return name.Replace(".", "/");
}
private void SetCurrentDirectory()
{
Directory.SetCurrentDirectory(Host.ResolvePath(""));
}
private string CreateClassName(CSharpCodeProvider provider)
{
return provider.CreateEscapedIdentifier(Path.GetFileNameWithoutExtension(Host.TemplateFile));
}
private string GetNamespace()
{
return Host.ResolveParameterValue("directiveId", "namespaceDirectiveProcessor", "namespaceHint");
}
private static IEnumerable<string> GetResourceKeys(string filePath)
{
var doc = XDocument.Load(filePath);
return doc.Root.Elements("data").Select(e => e.Attribute("name").Value);
}
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment