Click here to Skip to main content
15,894,646 members
Articles / Desktop Programming / Windows Forms

Getting the Place Name that Goes with a Zip Code

Rate me:
Please Sign up or sign in to vote.
3.07/5 (11 votes)
10 Feb 2009CPOL4 min read 33.1K   324   18  
How to import a database-dump from GeoNames.org into SQL Server
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;

///
/// This is an example that shows how to import the data that GeoNames dumps on their
/// site into one of your SQL Servers. Feel free to modify, and don't forget to add the
/// reference to GeoNames.org :)
/// 
/// 
/// add timings!
namespace GeoNamesImporter
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
            comboBoxDataDriver.DataSource = Enum.GetValues(typeof(DataProvider));
        }

        private DateTime startMoment;

        /// <summary>
        /// Performs the actual import from the downloadable textfile
        /// to SQL Server.
        /// </summary>
        private void buttonPerfomImport_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog(this) != DialogResult.OK)
            {
                MessageBox.Show("Action Aborted by User",
                                Application.ProductName,
                                MessageBoxButtons.OK,
                                MessageBoxIcon.None);
                return;
            }

            Cursor.Current = Cursors.WaitCursor;
            panel1.Enabled = false;
            progressBar1.Value = 0;
            progressBar1.Visible = true;
            startMoment = DateTime.Now;
            timerProgressIndication.Start();
            Application.DoEvents();

            string fileName = openFileDialog1.FileName;
            string tableName = textBoxTableName.Text;
            DataInterface dataInterface = DataInterface.New(
                (DataProvider) comboBoxDataDriver.SelectedValue,
                textBoxConnectionString.Text);

            GeoNamesImportArgs args = new GeoNamesImportArgs(fileName, dataInterface, tableName);
            backgroundWorker1.RunWorkerAsync(args);
            Properties.Settings.Default.Save();
        }

        /// <summary>
        /// Test whether we got a valid connection-string in the textbox,
        /// and if we can connect to the instance.
        /// </summary>
        private void buttonTestConnection_Click(object sender, EventArgs e)
        {
            using (DataInterface db = DataInterface.New(
                (DataProvider)comboBoxDataDriver.SelectedValue,
                textBoxConnectionString.Text))
            {
                try
                {
                    db.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format("{0}\n\nConnection string: '{1}'", ex.Message, textBoxConnectionString.Text),
                        Application.ProductName,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
                finally
                {
                    while (db.State == ConnectionState.Connecting)
                        Application.DoEvents();
                    if (db.State == ConnectionState.Open)
                    {
                        MessageBox.Show("Connection Succeeded!",
                                        Application.ProductName,
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                        Properties.Settings.Default.Save();
                    }
                }
            }
        }

        /// <summary>
        /// Show the browser with the GeoNames page
        /// </summary>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(@"http://www.geonames.org/export/");
        }

        /// <summary>
        /// Start the browser with the CC3 license
        /// </summary>
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(@"http://creativecommons.org/licenses/by/3.0/");
        }

        /// <summary>
        /// Validate that the user has specified a tablename
        /// </summary>
        private void textBoxTableName_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = ((sender as TextBox).Text.Trim().Length == 0);
        }

        /// <summary>
        /// Updates the tooltip of the progressbar, when active
        /// </summary>
        private void timerProgressIndication_Tick(object sender, EventArgs e)
        {
            // nothing to report yet that's truly indicative;
            if (progressBar1.Value < 3)
                return;

            DateTime now = DateTime.Now;
            TimeSpan span = now.Subtract(startMoment);

            // how long does it take to do a single item?
            double timePerItem = (span.TotalSeconds / progressBar1.Value);

            // There are ("max" - "value") items remaining, and they'll take (remainingItemCount * timePerItem) seconds.
            int secondsLeft;
            int minutesLeft = Math.DivRem(
                (int) ((progressBar1.Maximum - progressBar1.Value)*timePerItem), 
                60, 
                out secondsLeft);

            toolTip1.SetToolTip(
                progressBar1, 
                String.Format("Estimed time remaining: {0} minute(s), {1} seconds ", minutesLeft, secondsLeft));
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Currently none.
Netherlands Netherlands
I'm a Delphi-convert, mostly into WinForms and C#. My first article is from 2001, extending the Delphi-debugger, which is still visible on the WayBackMachine[^] and even available in Russian[^] Smile | :)

Comments and Discussions