Example #1
0
        private async void ActualizarPadron()
        {
            try
            {
                Preferences.Set("BUSY", false);

                FireBirdData fireBirdData = new FireBirdData();
                var          db           = new SQLiteConnection(Preferences.Get("DB_PATH", ""));

                string querry = "SELECT PV.documento AS CEDULA, PV.nombres, PV.apellidos,pv.padron_visitante_id " +
                                "FROM padron_visitantes PV " +
                                "WHERE CHAR_LENGTH(PV.documento) = 11 AND pv.padron_visitante_id > " + Preferences.Get("MAX_PERSONA_PADRON_ID", "0") +
                                " ORDER BY pv.padron_visitante_id desc ";


                var listPadronVisita = fireBirdData.DownloadPadron(querry, true);
                if (listPadronVisita.Count > 0)
                {
                    foreach (var padron in listPadronVisita)
                    {
                        var persona = db.Query <PADRON>("SELECT * FROM PADRON WHERE CEDULA = '" + padron.CEDULA + "'");
                        if (persona.Any())
                        {
                            continue;
                        }
                        else
                        {
                            db.Insert(padron);
                        }
                    }
                    //db.InsertAll(listPadronVisita);
                    Preferences.Set("MAX_PERSONA_PADRON_ID", listPadronVisita.First().ID_PADRON.ToString());
                }
                OnAppearing();
            }
            catch (Exception ea)
            {
                await DisplayAlert("Error", ea.Message, "OK");

                Debug.WriteLine("Error en el metodo ActualizarPadron " + ea.Message);
                Analytics.TrackEvent("Exception al hacer ActualizarPadron:  " + ea.Message + "\n Escaner: " + Preferences.Get("LECTOR", "N/A"));
            }
            finally
            {
                Preferences.Set("BUSY", true);
            }
        }
Example #2
0
        private async void BtSync_Clicked(object sender, EventArgs e)
        {
            string Password    = "******";
            string TryPassword = await DisplayPromptAsync("verificacion", "Ingrese la contraseña maestra para continuar", "Aceptar", "Cancelar", "Contraseña", 11, null);

            if (Password == TryPassword)
            {
                Preferences.Set("BUSY", false);
                Debug.WriteLine("Timer Stopped");
                App.syncTimer.Stop();
                App.syncTimer.Enabled = false;
                var db = new SQLiteConnection(Preferences.Get("DB_PATH", ""));
                Preferences.Set("IS_SYNC", "true");
                if (Connectivity.NetworkAccess == NetworkAccess.Internet)
                {
                    try
                    {
                        fireBird = new FireBirdData();
                        //Mostramos el popup
                        popupLoadingView.IsVisible = true;

                        pbLoading.IsVisible = true;
                        aiLoading.IsVisible = false;
                        aiLoading.IsRunning = false;
                        lblLoadingText.Text = "Loading...";

                        var querry1 = "";

                        //Vamos a buscar el directorio de la base de datos

                        //Buscamos el Chunk Size
                        var iChunkSize = int.Parse(Preferences.Get("CHUNK_SIZE", "10000"));

                        //Vamos a poner el timeout del http en 20 min seg
                        _client.Timeout = new TimeSpan(0, 40, 0);

                        Debug.WriteLine("Setting timeout to 20 min");

                        string querry           = "";
                        string connectionString = fireBird.connectionString(false);


                        FbCommand cmd;
                        //var Url = "http://" + Preferences.Get("SERVER_IP", "localhost") + ":" + Preferences.Get("SERVER_PORT", "4444")
                        //+ "/?sql=";

                        //TODO: Buscar cuantas cedulas se van a descargar.

                        querry = "select count(p.cedula) as anyCount from padron p";
                        int tries = 0;
                        //string contenido;
                        int maxRegistro = 0;
                        while (true)
                        {
                            try
                            {
                                FbConnection fb = new FbConnection(connectionString);

                                fb.Open();
                                FbCommand command = new FbCommand(
                                    querry,
                                    fb);


                                FbDataReader reader = command.ExecuteReader();

                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        maxRegistro = Convert.ToInt32(reader[0]);
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine("No rows found.");
                                }
                                reader.Close();

                                fb.Close();
                                fb.Dispose();

                                break;
                            }
                            catch (Exception ex)
                            {
                                Analytics.TrackEvent("Error al conectarse a base de datos " + ex.Message + "\n Escaner: " + Preferences.Get("LECTOR", "N/A"));
                                Debug.WriteLine("Error en Sync");
                                if (tries >= 5)
                                {
                                    throw new Exception("No se pudo conectar con la base de datos.");
                                }
                                var x = ex.Message;
                                tries += 1;
                            }
                        }

                        //var maxRegistroList = JsonConvert.DeserializeObject<List<counterObj>>(contenido);
                        //var maxRegistro = maxRegistroList.First();

                        //Descargar CEDULAS

                        querry = "select p.cedula, p.nombres, p.apellido1, p.apellido2 from padron p";

                        if (maxRegistro > 0)
                        {
                            int    loadedRegistros   = 1;
                            int    commitedRegistros = 0;
                            double progress          = 0.0;
                            var    listPadron        = new List <PADRON>();
                            while (loadedRegistros < maxRegistro)
                            {
                                progress = (double)loadedRegistros / maxRegistro;
                                if (maxRegistro - loadedRegistros < iChunkSize - 1)
                                {
                                    querry1 = querry1 = querry + " ROWS "
                                                        + loadedRegistros.ToString() + " TO " + maxRegistro.ToString();
                                    progress = 1.0;
                                }
                                else
                                {
                                    querry1 = querry + " ROWS "
                                              + loadedRegistros.ToString() + " TO " + (loadedRegistros + iChunkSize - 1).ToString();
                                }

                                await Task.Factory.StartNew(() =>
                                {
                                    listPadron.AddRange(fireBird.DownloadPadron(querry1, false));

                                    //var listPadronTemp = JsonConvert.DeserializeObject<List<PADRON>>(contenidoTBL);
                                    //listPadron = listPadron.Concat(listPadronTemp).ToList();
                                    if (listPadron.Count >= int.Parse(Preferences.Get("COMMIT_SIZE", "1000000")) || maxRegistro - loadedRegistros < iChunkSize - 1)
                                    {
                                        try
                                        {
                                            Device.BeginInvokeOnMainThread(() =>
                                            {
                                                lblLoadingText.Text = "Commited " + commitedRegistros.ToString() + "/" + maxRegistro.ToString() + " CEDULAS";
                                            });
                                            Debug.WriteLine("Se van a insertar: " + listPadron.Count.ToString() + " En la BBDD Local");
                                            //await Task.Factory.StartNew(() =>
                                            //{
                                            db.InsertAll(listPadron);
                                            //});
                                            commitedRegistros = commitedRegistros + listPadron.Count;
                                            //Preferences.Set("TOTAL_CEDULAS_DESCARGADAS", commitedRegistros.ToString());
                                            Device.BeginInvokeOnMainThread(() =>
                                            {
                                                //lblCantidadPadron.Text = $"Cantidad de cedulas descargadas: {Preferences.Get("TOTAL_CEDULAS_DESCARGADAS", commitedRegistros.ToString())}";
                                                Debug.WriteLine($"Cantidad de cedulas descargadas: {Preferences.Get("TOTAL_CEDULAS_DESCARGADAS", commitedRegistros.ToString())}");
                                            });
                                            listPadron.Clear();
                                        }
                                        catch (Exception ea)
                                        {
                                            Debug.WriteLine("Se ha encontrado una excepcion, Error: " + ea.Message);
                                        }
                                    }

                                    Device.BeginInvokeOnMainThread(() =>
                                    {
                                        lblLoadingText.Text = "Downloading CEDULAS: " + loadedRegistros.ToString() + "/" + maxRegistro.ToString();
                                    });
                                    Debug.WriteLine("Downloading CEDULAS: " + loadedRegistros.ToString() + "/" + maxRegistro.ToString());
                                    loadedRegistros = loadedRegistros + iChunkSize;
                                });

                                await pbLoading.ProgressTo(progress, 200, Easing.Linear);
                            }

                            pbLoading.Progress  = 0.0;
                            lblLoadingText.Text = "Guardando Padron";
                            pbLoading.IsVisible = false;
                            aiLoading.IsVisible = true;
                            aiLoading.IsRunning = true;
                            Debug.WriteLine("Se van a insertar: " + listPadron.Count.ToString() + " En la BBDD Local");
                            await Task.Factory.StartNew(() =>
                            {
                                db.InsertAll(listPadron);
                            });

                            pbLoading.IsVisible = true;
                            aiLoading.IsVisible = false;
                            aiLoading.IsRunning = false;
                            lblLoadingText.Text = "Loading...";

                            //Si hay Cedulas para cargar entramos
                        }
                    }
                    catch (Exception ey)
                    {
                        Debug.WriteLine("Error syncronisando: " + ey.Message);
                        popupLoadingView.IsVisible = false;
                        try
                        {
                            var options = new NotificationOptions()
                            {
                                Title       = "Error syncronisando",
                                Description = "Hubo un error en la syncronización, intente nuevamente",
                                IsClickable = false // Set to true if you want the result Clicked to come back (if the user clicks it)
                            };
                            var notification = DependencyService.Get <IToastNotificator>();
                            var result       = notification.Notify(options);
                        }
                        catch (Exception eo)
                        {
                            Debug.WriteLine("Error en notificacion: " + eo.Message);
                        }
                    }
                    finally
                    {
                        db.Dispose();

                        popupLoadingView.IsVisible = false;
                        try
                        {
                            _client.Timeout = new TimeSpan(0, 0, 100);
                        }
                        catch (Exception eu)
                        {
                            Debug.WriteLine("Error devolviendo el time out: " + eu.Message);
                        }
                        Debug.WriteLine("Setting timeout to 100 seconds");
                        Debug.WriteLine("Timer Start");
                        //Preferences.Set("IS_SYNC", "false");
                        App.syncTimer.Enabled = true;
                        App.syncTimer.Start();
                        Preferences.Set("BUSY", true);
                    }
                    //"select b.boleta_id, b.boleta, b.fecha_lectura, null as SUBIDA from boletas b where b.fecha_lectura is NULL"
                }
                else
                {
                    //Si no hay connecion a internet avisar al usuario
                    Debug.WriteLine("NO NETWORK");
                    popupLoadingView.IsVisible = false;
                    var options = new NotificationOptions()
                    {
                        Title       = "No hay conexión",
                        Description = "No se puede sincronizar sin una conexión a la red",
                        IsClickable = false // Set to true if you want the result Clicked to come back (if the user clicks it)
                    };
                    var notification = DependencyService.Get <IToastNotificator>();
                    var result       = notification.Notify(options);
                    Debug.WriteLine("Timer Start");
                    Preferences.Set("IS_SYNC", "false");
                    App.syncTimer.Enabled = true;
                    App.syncTimer.Start();
                }
            }
            else
            {
                await DisplayAlert("Credencial incorrecta", "La credencial ingresada no es valida", "OK");
            }
        }