C sharp - Cómo mejorar código de normalización de direcciones?

 
Vista:

Cómo mejorar código de normalización de direcciones?

Publicado por patricio (1 intervención) el 06/04/2015 16:35:48
Hola! Estoy trabajando en una aplicación c# escritorio que normaliza y segmenta direcciones geograficas. Tengo una base de datos con los nombres de las vías. El funcionamiento es el siguiente: Selecciono un archivo access, le indico un id único, la dirección a normalizar y la comuna. Según la comuna consulta a la base de datos el error y trae el nombre de vía correcto. Todo funciona ok, el normalizado y segmentado pero funciona muy lento, demora aprox una hora por cada 10.000 registros.
Cómo podré mejorar este código?
Muchas gracias!
Esta es la parte del código que demora mucho tiempo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
private void Normalizacion()
        {
            CheckForIllegalCrossThreadCalls = false;
 
            CambiarEnabled(false);
            pBloading.Enabled = true;
            label4.Enabled = true;
            lblRegistrosNormalizados.Enabled = true;
 
            this.Invoke(new MethodInvoker(this.ShowProgressGifDelegate));
 
            try
                {
                    ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtProjectPath.Text;
					string queryAgregarColumnas = "ALTER TABLE " + listBox1.SelectedItem.ToString() + " ADD COLUMN tipoVia TEXT(50), nombreVia TEXT(100), numeracion TEXT(25), resto TEXT(255), lat TEXT(25), lon TEXT(25), url TEXT(255)" ;
                    string querySeleccionaRegistros=  "SELECT " + cbxId.SelectedItem + ", " + cbxDireccion.SelectedItem + ", " + cbxCut.SelectedItem + " FROM " + listBox1.SelectedItem.ToString() + " where " + cbxDireccion.SelectedItem + " Is Not Null and " + cbxCut.SelectedItem + " Is Not Null";
 
                    DataTable results = new DataTable();
 
                    using (OleDbConnection _conexion = new OleDbConnection(ConnectionString))
                    {
 
                        OleDbCommand commandAgregarColumnas = new OleDbCommand(queryAgregarColumnas, _conexion);
 
                        OleDbCommand commandSeleccionaRegistros = new OleDbCommand(querySeleccionaRegistros, _conexion);
                        commandSeleccionaRegistros.CommandTimeout = 5000;
 
                        _conexion.Open();
 
                        commandAgregarColumnas.ExecuteNonQuery();
 
                        OleDbDataAdapter adapter = new OleDbDataAdapter(commandSeleccionaRegistros);
                        adapter.Fill(results);
 
                        /////////////////////////////////////////////////////////////
                        // limpio todo menos - . / numeros y letras
                        Regex reg = new Regex("[^a-zA-ZáÁéÉíÍóÓúÚñÑ0-9-./ ]");
                        // limpio todo menos numeros y letras
				        Regex reg2 = new Regex("[^a-zA-ZáÁéÉíÍóÓúÚñÑ0-9 ]");
                        /////////////////////////////////////////////////////////////
 
                        ViaCorrecto_SelectByNVcutTableAdapter _adapter = new ViaCorrecto_SelectByNVcutTableAdapter();
 
                        ViaCorrecto_SelectGlosaCutTableAdapter _adapterGlosa = new ViaCorrecto_SelectGlosaCutTableAdapter();
 
                        long count = 0;
 
                        for (int i = 0; i < results.Rows.Count; i++)
                        {
 
                            #region procesoNormalizacion
 
                            string id = results.Rows[i][cbxId.SelectedItem.ToString()].ToString();
                            string direccion = results.Rows[i][cbxDireccion.SelectedItem.ToString()].ToString();
                            string cut = results.Rows[i][cbxCut.SelectedItem.ToString()].ToString();
 
                            var seg = Segmentar(direccion);
 
						    string NombreViaOriginal = seg.NombreVia == null ? "" : reg2.Replace(seg.NombreVia, "");
						    string Numeracion = seg.Numeracion == null ? "" : seg.Numeracion;
						    string Resto = seg.Resto == null ? "" : reg.Replace(seg.Resto, "");
 
 
                            string TipoViaNormalizado = _adapter.GetData(NombreViaOriginal,cut).Rows.Count > 0 ? _adapter.GetData(NombreViaOriginal,cut).Rows[0][1].ToString() : "";
                            string NVnormalizado = _adapter.GetData(NombreViaOriginal,cut).Rows.Count > 0 ? _adapter.GetData(NombreViaOriginal,cut).Rows[0][0].ToString() : "";
 
                            string glosaCut = _adapterGlosa.GetData(cut).Rows.Count > 0 ? _adapterGlosa.GetData(cut).Rows[0][0].ToString() : "";
 
                            string lat = "";
                            string lng = "";
                            string url = "";
 
                            if( rbConGoogle.Checked)
                            {
                                var request = new GeocodingRequest();
                                request.Address = NVnormalizado + ",  " + Numeracion + ",  " + glosaCut + ", Chile";
                                request.Sensor = false;
                                var response = new GeocodingService().GetResponse(request);
                                var result = response.Results.FirstOrDefault();
 
                                lat = Convert.ToString(result.Geometry.Location.Latitude).Replace(",", ".") == "" ? "" : Convert.ToString(result.Geometry.Location.Latitude).Replace(",", ".");
                                lng = Convert.ToString(result.Geometry.Location.Longitude).Replace(",", ".") == "" ? "" : Convert.ToString(result.Geometry.Location.Longitude).Replace(",", ".");
                                url = lat == "" || lng == "" ? "" : "http://maps.google.com/?q=" + lat + "," + lng;
                            }
 
                            if (NVnormalizado != "")
                            {
                                try
                                {
                                    string queryActualizarRegistros= "update " + listBox1.SelectedItem.ToString() + " set tipoVia='" + TipoViaNormalizado + "', nombreVia='" + NVnormalizado + "', numeracion = '" + Numeracion + "', resto = '" + Resto + "', lat = '" + lat + "', lon = '" + lng + "', url = '" + url + "' where " + cbxId.SelectedItem + " = " + id + ";";
                                    OleDbCommand commandActualizarRegistros = new OleDbCommand(queryActualizarRegistros, _conexion);
							        commandActualizarRegistros.ExecuteNonQuery();
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message);
                                }
                            }
 
                            #endregion
 
                            lblRegistrosNormalizados.Text = Convert.ToString(count++);
                        }
                        _conexion.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
 
            ////////////////////////////
            System.Threading.Thread.Sleep(5000);
            this.Invoke(new MethodInvoker(this.HideProgressGifDelegate));
            ResetCampos();
            CambiarEnabled(true);
            MessageBox.Show("Proceso terminado satisfactoriamente");
        }
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder