Country tag helper–part 1

 

What I want to do is to create a Country Tag Helper for asp.net core.

Something like

<select asp-country=”true”

and then list all countries in this select. More,it should be localized ( Germany vs Allemagne). That means 1 or more resource files 

 

First I need initial data: The WorldBank API gives us the names http://api.worldbank.org/countries and I have made a project https://github.com/ignatandrei/WorldBankAPi that inspects that API.

To retrieve data in resource format,it is simple:

 var r = new CountriesRepository();
            var arr = r.GetCountries().Result.
                Select(it =&gt;
                $&quot;&lt;data name = \&quot;{it.iso2Code}\&quot; xml:space=\&quot;preserve\&quot; &gt;&quot; +

                $&quot;&lt;value&gt;{it.name}&lt;/value&gt;&quot; +
                &quot;&lt;/data&gt;&quot;).ToArray();
            var s = string.Join(Environment.NewLine,arr);
            File.WriteAllText(@&quot;D:\c.txt&quot;,s);

 

Then we could copy paste into resources:

 &lt;data name = &quot;AW&quot; xml:space=&quot;preserve&quot; &gt;&lt;value&gt;Aruba&lt;/value&gt;&lt;/data&gt;
  &lt;data name = &quot;AF&quot; xml:space=&quot;preserve&quot; &gt;&lt;value&gt;Afghanistan&lt;/value&gt;&lt;/data&gt;
  &lt;data name = &quot;AO&quot; xml:space=&quot;preserve&quot; &gt;&lt;value&gt;Angola&lt;/value&gt;&lt;/data&gt;
 ...

 

Now I want to make a list of those names – so I need this code to translate between C# generated code from resource

public static string AD {
            get {
                return ResourceManager.GetString(&quot;AD&quot;,resourceCulture);
            }
        }
public static string AE {
            get {
                return ResourceManager.GetString(&quot;AE&quot;,resourceCulture);
            }
        }
...

 

and a list of names to be put into select.

Reflection to the rescue:

  var t =typeof( ResCTH);
            properties= t.GetProperties(
                BindingFlags.Public |
                BindingFlags.Static |
                BindingFlags.GetProperty);
            CountryISO = properties
                .Where(it=&gt;it.Name.Length==2)
                .Select(it =&gt; it.Name)
                .ToArray();

 

The code is on github https://github.com/ignatandrei/CountryTagHelper and I will improve next time.


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *