Andrew Hawes
Andrew Hawes

Reputation: 396

Trying to get NetSuite Country list with enumeration value linked to code and name

I am implementing a integration with NetSuite in C#. In the external system I need to populate a list of countries that will match NetSuite's country list.

The NetSuite Web Service provides an enumeration call Country

public enum Country {
  _afghanistan,
  _alandIslands,
  _albania,
  _algeria,
  ...

You can also get a list of country Name and Code (in an albeit not so straight forward way) from the web service. (See: http://suiteweekly.com/2015/07/netsuite-get-all-country-list/)

Which gives you access to values like this:

But, as you can see, there is no way to link the two together. (I tried to match by index but that didn't work and sounds scary anyway)

NetSuite's "help" files have a list. But this is static and I really want a dynamic solution that updates as NetSuites updates because we know countries will change--even is not that often.

Screenshot of Country Enumerations from NetSuite help docs

The only solutions I have found online are people who have provided static data that maps the two sets of data. (ex. suiteweekly.com /2015/07/netsuite-complete-country-list-in-netsuite/)

I cannot (don't want to) believe that this is the only solution.

Anyone else have experience with this that has a better solution?

NetSuite, if you are reading, come on guys, give a programmer a break.

Upvotes: 4

Views: 3096

Answers (2)

Andrew Hawes
Andrew Hawes

Reputation: 396

The best solution I have come up with is to leverage the apparent relationship between the country name and the enumeration key to forge a link between the two. I am sure others could improve on this solution but what I would really like to see is a solution that isn't a hack like this that relies on an apparent pattern but rather on that is based on an explicit connection. Or better yet NetSuite should just provide the data in one place all together.

For example you can see the apparent relationship here:

_alandIslands -> Aland Islands

With a little code I can try to forge a match.

I first get the Enumeration Keys into an array. And I create a list of objects of type NetSuiteCountry that will hold my results.

var countryEnumKeys = Enum.GetNames(typeof(Country));
var countries = new List<NetSuiteCountry>();

I then loop through the list of country Name and Code I got using the referenced code above (not shown here).

For each country name I then strip all non-word characters from the country name with Regex.Replace, prepend an underscore (_) and then convert the string to lowercase. Finally I try to find a match between the Enumeration Key (converted to lowercase as well) and the matcher string that was created. If a match is found I save all the data together the countries list.

UPDATE: Based on the comments I have added additional code/hacks to try to deal with the anomalies without hard-coding exceptions. Hopefully these updates will catch any future updates to the country list as well, but no promises. As of this writing it was able to handle all the known anomalies. In my case I needed to ignore Deprecated countries so those aren't included.

foreach (RecordRef baseRef in baseRefList)
{
  var name = baseRef.name;

  //Skip Deprecated countries
  if (name.EndsWith("(Deprecated)")) continue;

  //Use the name to try to find and enumkey match and only add a country if found.
  var enumMatcher = $"_{Regex.Replace(name, @"\W", "").ToLower()}";

  //Compares Ignoring Case and Diacritic characters
  var enumMatch = CountryEnumKeys.FirstOrDefault(e => string.Compare(e, enumMatcher, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase) == 0);

  //Then try by Enum starts with Name but only one.
  if (enumMatch == null)
  {
    var matches = CountryEnumKeys.Where(e => e.ToLower().StartsWith(enumMatcher));
    if (matches.Count() == 1)
    {
      Debug.Write($"- Country Match Hack 1 : ");
      enumMatch = matches.First();
    }
  }

  //Then try by Name starts with Enum but only one.
  if (enumMatch == null)
  {
    var matches = CountryEnumKeys.Where(e => enumMatcher.StartsWith(e.ToLower()));
    if (matches.Count() == 1)
    {
      Debug.Write($"- Country Match Hack 2 : ");
      enumMatch = matches.First();
    }
  }

  //Finally try by first half Enum and Name match but again only one.
  if (enumMatch == null)
  {
    var matches = CountryEnumKeys.Where(e => e.ToLower().StartsWith(enumMatcher.Substring(0, (enumMatcher.Length/2))));
    if (matches.Count() == 1)
    {
      Debug.Write($"- Country Match Hack 3 : ");
      enumMatch = matches.First();
    }
  }

  if (enumMatch != null)
  {
    var enumIndex = Array.IndexOf(CountryEnumKeys, enumMatch);
    if (enumIndex >= 0)
    {
      var country = (Country) enumIndex;
      var nsCountry = new NetSuiteCountry
      {
        Name = baseRef.name,
        Code = baseRef.internalId,
        EnumKey = country.ToString(),
        Country = country
      };

      Debug.WriteLine($"[{nsCountry.Name}] as [{nsCountry.EnumKey}]");
      countries.Add(nsCountry);
    }
  }
  else
  {
    Debug.WriteLine($"Could not find Country match for: [{name}] as [{enumMatcher}]");
  }
}

Here is my NetSuiteCountry class:

public class NetSuiteCountry
{
    public string Name { get; set; }
    public string Code { get; set; }
    public string EnumKey { get; set; }
    public Country Country { get; set; }
}

Upvotes: 3

Rob G
Rob G

Reputation: 140

Let me start off with a disclaimer that I'm not a coder, and this is the first day I've tried to look at a C# program.

I need something similar for a Javascript project where I need the complete list of Netsuite company names, codes and their numeric values and when reading the help it seemed like the only way was through webservices.

I downloaded the sample application for webservices from Netsuite and a version of Visual Studio and I was able to edit the sample program provided to create a list of all of the country names and country codes (ex. Canada, CA).

I started out doing something similar to the previous poster to get the list of country names:

string[] countryList = Enum.GetNames(typeof(Country));
foreach (string s in countryList)
{
    _out.writeLn(s);
}

But I later got rid of this and started a new technique. I created a class similar to the previous answer:

public class NS_Country
{
    public string countryCode { get; set; }
    public string countryName { get; set; }
    public string countryEnum { get; set; }
    public string countryNumericID { get; set; }
}

Here is the new code for getting the list of company names, codes and IDs. I realize that it's not very efficient as I mentioned before I'm not really a coder and this is my first attempt with C#, lots of Google and cutting/pasting ;D.

_out.writeLn("  Attempting to get Country list.");
// Create a list for the NS_Country objects
List<NS_Country> CountryList = new List<NS_Country>();

// Create a new GetSelectValueFieldDescription object to use in a getSelectValue search
GetSelectValueFieldDescription countryDesc = new GetSelectValueFieldDescription();
countryDesc.recordType = RecordType.customer;
countryDesc.recordTypeSpecified = true;
countryDesc.sublist = "addressbooklist";
countryDesc.field = "country";

// Create a GetSelectValueResult object to hold the results of the search
GetSelectValueResult myResult = _service.getSelectValue(countryDesc, 0);
BaseRef[] baseRef = myResult.baseRefList;

foreach (BaseRef nsCountryRef in baseRef)
{
    // Didn't know how to do this more efficiently
    // Get the type for the BaseRef object, get the property for "internalId",
    // then finally get it's value as string and assign it to myCountryCode
    string myCountryCode = nsCountryRef.GetType().GetProperty("internalId").GetValue(nsCountryRef).ToString();

    // Create a new NS_Country object
    NS_Country countryToAdd = new NS_Country
    {
        countryCode = myCountryCode,
        countryName = nsCountryRef.name,
        // Call to a function to get the enum value based on the name
        countryEnum = getCountryEnum(nsCountryRef.name)
    };
    try
    {
        // If the country enum was verified in the Countries enum
        if (!String.IsNullOrEmpty(countryToAdd.countryEnum))
        {
            int countryEnumIndex = (int)Enum.Parse(typeof(Country), countryToAdd.countryEnum);
            Debug.WriteLine("Enum: " + countryToAdd.countryEnum + ", Enum Index: " + countryEnumIndex);
            _out.writeLn("ID: " + countryToAdd.countryCode + ", Name: " + countryToAdd.countryName + ", Enum: " + countryToAdd.countryEnum);
        }
    }
    // There was a problem locating the country enum that was not handled
    catch (Exception ex)
    {
        Debug.WriteLine("Enum: " + countryToAdd.countryEnum + ", Enum Index Not Found");
        _out.writeLn("ID: " + countryToAdd.countryCode + ", Name: " + countryToAdd.countryName + ", Enum: Not Found");
    }
    // Add the countryToAdd object to the CountryList
    CountryList.Add(countryToAdd);
}
// Create a JSON - I need this for my javascript
var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonString = javaScriptSerializer.Serialize(CountryList);
Debug.WriteLine(jsonString);

In order to get the enum values, I created a function called getCountryEnum:

static string getCountryEnum(string countryName)
{
    // Create a dictionary for looking up the exceptions that can't be converted
    // Don't know what Netsuite was thinking with these ones ;D
    Dictionary<string, string> dictExceptions = new Dictionary<string, string>()
    {
        {"Congo, Democratic Republic of", "_congoDemocraticPeoplesRepublic"},
        {"Myanmar (Burma)", "_myanmar"},
        {"Wallis and Futuna", "_wallisAndFutunaIslands"}
    };

    // Replace with "'s" in the Country names with "s"
    string countryName2 = Regex.Replace(countryName, @"\'s", "s");
    // Call a function that replaces accented characters with non-accented equivalent
    countryName2 = RemoveDiacritics(countryName2);
    countryName2 = Regex.Replace(countryName2, @"\W", " ");

    string[] separators = {" ","'"}; // "'" required to deal with country names like "Cote d'Ivoire"
    string[] words = countryName2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
    for (var i = 0; i < words.Length; i++)
    {
        string word = words[i];
        if (i == 0)
        {
            words[i] = char.ToLower(word[0]) + word.Substring(1);
        }
        else
        {
            words[i] = char.ToUpper(word[0]) + word.Substring(1);
        }
    }
    string countryEnum2 = "_" + String.Join("", words);

    // return an empty string if the country name contains Deprecated
    bool b = countryName.Contains("Deprecated");
    if (b)
    {
        return String.Empty;
    }
    else
    {
        // test to see if the country name was one of the exceptions
        string test;
        bool isExceptionCountry = dictExceptions.TryGetValue(countryName, out test);
        if (isExceptionCountry == true)
        {
            return dictExceptions[countryName];
        }
        else
        {
            return countryEnum2;
        }
    }
}

In the above I used a function, RemoveDiacritics I found here. I will repost the referenced function below:

static string RemoveDiacritics(string text)
{
    string formD = text.Normalize(NormalizationForm.FormD);
    StringBuilder sb = new StringBuilder();
    foreach (char ch in formD)
    {
        UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(ch);
        if (uc != UnicodeCategory.NonSpacingMark)
        {
            sb.Append(ch);
        }
    }
    return sb.ToString().Normalize(NormalizationForm.FormC);
}

Here are the tricky cases to test any solution you develop with:

// Test tricky names
Debug.WriteLine(getCountryEnum("Curaçao"));
Debug.WriteLine(getCountryEnum("Saint Barthélemy"));
Debug.WriteLine(getCountryEnum("Croatia/Hrvatska"));
Debug.WriteLine(getCountryEnum("Korea, Democratic People's Republic"));
Debug.WriteLine(getCountryEnum("US Minor Outlying Islands"));
Debug.WriteLine(getCountryEnum("Cote d'Ivoire"));
Debug.WriteLine(getCountryEnum("Heard and McDonald Islands"));
// Enums that fail
Debug.WriteLine(getCountryEnum("Congo, Democratic Republic of")); // _congoDemocraticPeoplesRepublic added to exceptions
Debug.WriteLine(getCountryEnum("Myanmar (Burma)")); // _myanmar added to exceptions
Debug.WriteLine(getCountryEnum("Netherlands Antilles (Deprecated)")); // Skip Deprecated
Debug.WriteLine(getCountryEnum("Serbia and Montenegro (Deprecated)")); // Skip Deprecated
Debug.WriteLine(getCountryEnum("Wallis and Futuna")); // _wallisAndFutunaIslands added to exceptions

For my purposes I wanted a JSON object that had all the values for Coutries (Name, Code, Enum, Value). I'll include it here in case anyone is searching for it. The numeric values are useful when you have a 3rd party HTML form that has to forward the information to a Netsuite online form.

Here is a link to the JSON object on Pastebin.

My appologies for the lack of programming knowledge (only really do a bit of javascript), hopefully this additional information will be useful for someone.

Upvotes: 1

Related Questions