// // Class: LocodeDB // Current CLR: 4.0.30319.42000 // System: Microsoft Visual Studio 10.0 // Author: dani // Created: 1/9/2016 10:10:20 PM // // Copyright (c) 2016 Informatikbüro Daniel Schick. All rights reserved. using System; using System.Collections.Generic; using System.Data; using System.Data.SQLite; namespace bsmd.ExcelReadService { /// /// Locodes suchen (zu Orten), die DB ist aus einem github Projekt: /// https://github.com/kabisa/un_locode /// public class LocodeDB { private static SQLiteConnection _con; private const string _locode_DB_NAME = "db.sqlite"; static LocodeDB() { _con = new SQLiteConnection(string.Format("data source={0}; Version=3;", _locode_DB_NAME)); _con.Open(); } #region public static methods public static string LocodeGERFromCity(string city) { return LocodeDB.LocodeFromCity(city, "DE"); } /// /// Lookup and create locode from local sqlite database /// public static string LocodeFromCity(string city, string country) { string result = null; string query = string.Format("SELECT city_code FROM locodes JOIN countries ON locodes.country_id = countries.ID WHERE countries.code = '{0}' AND locodes.port='t' AND locodes.name like '{1}'", country, city); SQLiteCommand cmd = new SQLiteCommand(query, _con); IDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { result = reader.GetString(0); break; } reader.Close(); if (result != null) result = string.Format("{0}{1}", country, result); return result; } public static List AllLocodesForCityName(string city) { List results = new List(); if(city.Contains(",")) { string[] elems = city.Split(','); string countryCode = CountryCodeFromName(elems[1].Trim()); string lcLookup = LocodeFromCity(elems[0].Trim(), countryCode); if ((countryCode != null) && (lcLookup != null)) results.Add(lcLookup); } string query = string.Format("SELECT city_code, countries.code FROM locodes JOIN countries ON locodes.country_id = countries.ID WHERE locodes.port='t' AND locodes.name like '{0}'", city); SQLiteCommand cmd = new SQLiteCommand(query, _con); IDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { if (!reader.IsDBNull(0) && !reader.IsDBNull(1)) results.Add(string.Format("{0}{1}", reader.GetString(1), reader.GetString(0))); } reader.Close(); return results; } /// /// Lookup 2CHAR Country Code from country name (like search). Hopefully this will result in many hits /// public static string CountryCodeFromName(string countryName) { string result = null; string query = string.Format("SELECT code FROM countries WHERE countries.name like '{0}'", countryName); SQLiteCommand cmd = new SQLiteCommand(query, _con); IDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { result = reader.GetString(0); break; } reader.Close(); return result; } public static void CloseDB() { _con.Close(); } #endregion } }