Exemplo n.º 1
0
        public void cargarComboNotificador(Context context, View mView)
        {
            try
            {
                //Se crea la instancia del spinner para el combo de provincias
                Spinner mSpinner = mView.FindViewById <Spinner>(Resource.Id.spinnerDialogoSeleccionNotificador);
                ManejoBaseDatos.Abrir();
                ICursor       cursor = ManejoBaseDatos.Seleccionar("SELECT NombreCompleto,CodigoNotificador FROM OficialesNotificadores");
                List <string> data   = new List <string>();

                if (cursor.MoveToFirst())
                {
                    //agregando en lista data los nombres de los notificadores
                    do
                    {
                        data.Add(cursor.GetString(0));
                        codNotificadores.Add(cursor.GetString(1));
                    }while (cursor.MoveToNext());
                }

                cursor.Close();
                Android.Widget.ArrayAdapter <String> adapter;
                adapter          = new Android.Widget.ArrayAdapter <String>(context, Android.Resource.Layout.SimpleSpinnerItem, data);
                mSpinner.Adapter = adapter;
                ManejoBaseDatos.Cerrar();
            }
            catch (Exception ex)
            {
                //Se guarda el error en el log de errores
                //Logs.saveLogError("FragmentMap.cargarComboNotificador " + e.Message + " " + e.StackTrace);
                //Se muestra un mensaje informando el error
                Console.WriteLine("Error cargando spinner: " + ex.ToString());
                Toast.MakeText(context, GetString(Resource.String.MensajeErrorCargaBaseDatos), ToastLength.Long).Show();
            }
        }
Exemplo n.º 2
0
        public void HandlePositiveButtonClick(object sender, DialogClickEventArgs e)
        {
            try
            {
                //signature = Activity.FindViewById<SignaturePadView>(Resource.Id.signatureFrame);
                Bitmap       imagen = signature.GetImage();
                MemoryStream ms     = new MemoryStream();
                //ByteArrayOutputStream bos = new ByteArrayOutputStream();
                imagen.Compress(Bitmap.CompressFormat.Png, 100, ms);
                byte[] bArray = ms.ToArray();

                //string id = Guid.NewGuid().ToString();
                System.Console.WriteLine("GUID: " + guid);
                loadConnection();
                db.BeginTransaction();
                //Se almacena en base de datos el BLOB con su respectivo GUID
                try
                {
                    string          sql        = "INSERT INTO IMAGENES (Nombre,Imagen) VALUES(?,?)";
                    SQLiteStatement insertStmt = db.CompileStatement(sql);
                    insertStmt.ClearBindings();
                    insertStmt.BindString(1, guid);
                    insertStmt.BindBlob(2, bArray);
                    insertStmt.ExecuteInsert();
                    db.SetTransactionSuccessful();
                    db.EndTransaction();
                    db.Close();
                    try
                    {
                        if (actor.Equals("notificando", StringComparison.Ordinal))
                        {
                            ManejoBaseDatos.Abrir();
                            ManejoBaseDatos.Actualizar("Notificaciones", "ValidacionNotificando", "S", "CodigoNotificacion=" + codigo + "");
                            ManejoBaseDatos.Cerrar();
                        }
                        if (actor.Equals("testigo", StringComparison.Ordinal))
                        {
                            ManejoBaseDatos.Abrir();
                            ManejoBaseDatos.Actualizar("Notificaciones", "ValidacionTestigo", "S", "CodigoNotificacion=" + codigo + "");
                            ManejoBaseDatos.Cerrar();
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine("Error almacenando confirmacion de firma: " + ex.ToString());
                        Toast.MakeText(this.Activity, "Error guardando confirmacion", ToastLength.Short).Show();
                    }
                }
                catch (Exception ex) { System.Console.WriteLine("Error guardando imagen en db: " + ex.ToString()); }

                Toast.MakeText(this.Activity, "Firma capturada de forma exitosa", ToastLength.Short).Show();
            }
            catch (Exception ex) { System.Console.WriteLine("ERROR guardando la imagen: " + ex.ToString()); }
        }
Exemplo n.º 3
0
        private void Notificador_ItemSelected1(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            try
            {
                Spinner notificador = (Spinner)sender;
                ManejoBaseDatos.Abrir();
                ICursor cursor = ManejoBaseDatos.Seleccionar("SELECT googleMapsX,googleMapsY,RolNocturno FROM Notificaciones WHERE Estado='AsignarParaNotificar' and CodNotificador = '" + notificador.SelectedItem.ToString().Split('-')[1] + "'");
                listaPosiciones.Clear();
                if (cursor.MoveToFirst())
                {
                    listaPosiciones = new List <KeyValuePair <LatLng, bool> >();
                    KeyValuePair <LatLng, bool> posicion;

                    do
                    {
                        NumberFormatInfo provider = new NumberFormatInfo();
                        provider.NumberDecimalSeparator = ".";

                        double latitudeM  = Convert.ToDouble(cursor.GetString(0), provider);
                        double longitudeM = Convert.ToDouble(cursor.GetString(1), provider);
                        //Se obtiene el valor del rol nocturno
                        string rol = cursor.GetString(2);
                        //Si es verdadero el check se marca y si no, se deja sin marcar
                        bool rolNocturno = rol == "True" || rol == "true" ? true : false;

                        Console.WriteLine("latitudeM: " + latitudeM.ToString());
                        Console.WriteLine("longitudeM: " + longitudeM.ToString());

                        posicion = new KeyValuePair <LatLng, bool>(new LatLng(latitudeM, longitudeM), rolNocturno);
                        listaPosiciones.Add(posicion);

                        posiciones.Add(new LatLng(latitudeM, longitudeM));
                    } while (cursor.MoveToNext());
                }
                cursor.Close();
                ManejoBaseDatos.Cerrar();

                ((Activities.MainActivity)Activity).AgregarUbicacionMapaListaColor(listaPosiciones);
            }
            catch (Exception ex)
            {
                //Se guarda el error
                Logs.saveLogError("FragmentMap.Notificador_ItemSelected1 " + ex.Message + " " + ex.StackTrace);
            }
        }
Exemplo n.º 4
0
        private void HandleButtonClick(object sender, DialogClickEventArgs e)
        {
            try
            {
                //Se procede a cerrar la sesion, primero se procede a determinar la lista de las
                //notificaciones que se encuentran en estado notificandose.
                string          consulta   = @"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/Notificaciones/ListarNotificacionesPorNotificadorEstado?POficina=" + FragmentLogin.codOficina + "&PCodNotificador=" + FragmentLogin.codNotificador + "&PEstado=2&PJornada=3";
                servicioCheckDB coneccion  = new servicioCheckDB();
                var             resultados = coneccion.ObtenerListaStrings(consulta, this);

                if (resultados != null)
                {
                    string   fechaApertura = "";
                    DateTime localDate     = DateTime.Now;
                    //string fechalineal = localDate.ToString("yyyyMMdd");
                    string fechaCompleja = localDate.ToString("o");

                    List <string> notificacionesPendientes = new List <string>();
                    for (int k = 0; k < resultados.Count; k++)
                    {
                        notificacionesPendientes.Add(resultados[k]["CodNotificacion"].ToString());
                    }

                    // se extrae de la base de datos la fecha de apertura
                    ManejoBaseDatos.Abrir();

                    ICursor mCursor = ManejoBaseDatos.Seleccionar("SELECT FechaHoraApertura FROM Autenticacion");
                    if (mCursor.MoveToFirst() && mCursor.Count == 1)
                    {
                        do
                        {
                            fechaApertura = mCursor.GetString(0);
                            Console.WriteLine("fecha de Apertura: " + fechaApertura);
                        }while (mCursor.MoveToNext());
                    }
                    else
                    {
                        //Se genera una fecha de apertura
                        fechaApertura = fechaCompleja;
                    }

                    mCursor.Close();
                    ManejoBaseDatos.Cerrar();
                    //se crea la instancial de la clase cierreJornada

                    CierreJornada cierre = new CierreJornada()
                    {
                        codigo             = Guid.NewGuid().ToString(),
                        Apertura           = fechaApertura,
                        OficialNotificador = new OficialNotificador
                        {
                            CodNotificador = FragmentLogin.codNotificador,
                        },
                        Notificaciones = new List <NotificacionFisica>(),
                        Justificacion  = "",
                        Cierre         = fechaCompleja,
                    };

                    foreach (var codigoNotificacion in notificacionesPendientes)
                    {
                        cierre.Notificaciones.Add(new NotificacionFisica {
                            CodNotificacion = Convert.ToInt32(codigoNotificacion)
                        });
                    }

                    string requestCierre = @"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/OficialNotificador/CierreJornadaOficialNotificador";
                    string json          = Newtonsoft.Json.JsonConvert.SerializeObject(cierre);
                    Console.WriteLine("JSON: " + json);

                    bool respuesta = coneccion.envioDatosWeb(requestCierre, json, this);
                    if (respuesta)
                    {
                        //observaciones.Text = "";
                        Toast.MakeText(this, "Cierre de apertura exitoso.", ToastLength.Short).Show();
                        //Se dirige al usuario a la pagina de buzones donde podra realizar el inicio de apertura.
                    }
                    else
                    {
                        Toast.MakeText(this, "Error al intentar cerar apertura.", ToastLength.Short).Show();
                    }
                }
            }
            catch (Exception ex) { Console.WriteLine("Error en manejo de boton positivo: " + ex.ToString()); }
        }
Exemplo n.º 5
0
        public void InitializeDataBase(bool admin, string oficina, string sector, int estado, int jornada)
        {
            List <string> query       = new List <string>();
            List <string> queryResult = new List <string>();
            List <string> tables      = new List <string>();

            //tablas a borrar si no se encuentra informacion respaldada en base de datos.
            tables.Add("Notificaciones");
            tables.Add("OficialesNotificadores");
            tables.Add("Resultados");
            tables.Add("Sectores");

            Console.WriteLine("--fzeledon: Creating DataBase for app");
            ManejoBaseDatos.Abrir();
            string resultadoBorrar = ManejoBaseDatos.BorrarTablas(tables);

            ManejoBaseDatos.Cerrar();

            if (!string.IsNullOrEmpty(resultadoBorrar))
            {
                throw new System.ArgumentException(resultadoBorrar);
            }

            try
            {
                //Consulta de sectores
                query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/SectorNotificacion/ListarSectores?PCodOficina=" + oficina + "");
                //Consulta de resultados positivos
                query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/ResultadoNotificacion/ListarResultadosNotificaciones?PDiligenciado=1");
                //Consulta de resultados negativos
                query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/ResultadoNotificacion/ListarResultadosNotificaciones?PDiligenciado=0");
                //Consulta de Oficiales Notificadores
                query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/OficialNotificador/ListarOficialesNotificadores?PCodOficina=" + oficina + "");
                //consulta de Notificaciones en estado 0 jornada diurna y nocturna con parametro de admin
                if (admin)
                {
                    query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/Notificaciones/ListarNotificacionesPorSectorEstado?PCodOficina=" + oficina + "&PSector=" + sector + "&PEstado=" + estado.ToString() + "&PJornada=" + jornada.ToString() + "");
                }
                else
                {
                    query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/Notificaciones/ListarNotificacionesPorNotificadorEstado?POficina=" + oficina + "&PCodNotificador=" + codNotificador + "&PEstado=" + estado + "&PJornada=" + jornada.ToString() + "");
                }
                Stopwatch sw = Stopwatch.StartNew();

                //Se crean multiples consultas
                foreach (var item in query)
                {
                    try
                    {
                        Console.WriteLine("--fzeledon: Creating query for item: " + item);
                        WebRequest request = HttpWebRequest.Create(item);
                        request.ContentType = "application/json";
                        request.Method      = "GET";
                        string content = "";
                        //se establece un tiempo de respuesta de 10 segundos por solicitud
                        request.Timeout = 10000; //tiempo en milisegundos

                        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                        {
                            if (response.StatusCode != HttpStatusCode.OK)
                            {
                                Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
                            }
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                content = reader.ReadToEnd();
                                if (string.IsNullOrWhiteSpace(content))
                                {
                                    Console.Out.WriteLine("fzeledon -- Response contained empty body...");
                                }
                                else
                                {
                                    queryResult.Add(content);
                                }
                            }
                        }
                    }
                    catch (WebException ex)
                    {
                        Console.WriteLine("WEB Exception: " + ex.ToString());
                        Android.Support.V7.App.AlertDialog.Builder alerta = new Android.Support.V7.App.AlertDialog.Builder(this);
                        alerta.SetTitle("Mensaje de alerta");
                        alerta.SetIcon(Resource.Drawable.alertaNuevo);
                        alerta.SetMessage("El servicio de Internet no se encuentra disponible, por favor revise su conexión e intente ingresar nuevamente");
                        alerta.SetNegativeButton("Salir", HandleButtonClick);
                        alerta.SetCancelable(false);
                        alerta.Create();
                        alerta.Show();
                    }
                }


                // Guargando notificaciones en estado 0
                var jsonParsed = JArray.Parse(queryResult[4]);

                ManejoBaseDatos.Abrir();

                for (int k = 0; k < jsonParsed.Count; k++)
                {
                    string resultado = "";
                    if (FragmentLogin.supervisor.Equals("True", StringComparison.Ordinal) || FragmentLogin.supervisor.Equals("true", StringComparison.Ordinal))
                    {
                        resultado = ManejoBaseDatos.Insertar("Notificaciones", "CodigoNotificacion,Expediente,DespachoDescripcion,Notificando,Medio,Provincia,Canton,Distrito,Direccion,Sector,Urgente,FechaDocumento,FechaEmision,HorarioEntrega,Estado",
                                                             jsonParsed[k]["CodNotificacion"].ToString() + ", " +
                                                             "'" + jsonParsed[k]["NumExpediente"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Despacho"]["Descripcion"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["NombreCompleto"].ToString().Replace("'", "") + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["TipoMedio"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Provincia"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Canton"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Distrito"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Direccion"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Sector"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Urgente"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["FechaDocumento"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["FechaEmision"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["HorarioEntrega"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Estado"].ToString() + "'");
                    }
                    else
                    {
                        resultado = ManejoBaseDatos.Insertar("Notificaciones", "CodigoNotificacion,Expediente,HorarioEntrega,DespachoDescripcion,Notificando,Medio,Provincia,Canton,Distrito,Direccion,Sector,Urgente,FechaDocumento,FechaEmision,Estado,CodNotificador,RolNocturno,DespachoCodigo,DespachoDescripcion",
                                                             jsonParsed[k]["CodNotificacion"].ToString() + ", " +
                                                             "'" + jsonParsed[k]["NumExpediente"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["HorarioEntrega"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Despacho"]["Descripcion"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["NombreCompleto"].ToString().Replace("'", "") + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["TipoMedio"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Provincia"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Canton"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Distrito"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Direccion"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Sector"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Urgente"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["FechaDocumento"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["FechaEmision"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Estado"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["OficialNotificador"]["CodNotificador"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["OficialNotificador"]["RolNocturno"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Despacho"]["Codigo"].ToString() + "'," +
                                                             "'" + jsonParsed[k]["Despacho"]["Descripcion"].ToString() + "'");
                    }
                    if (!String.IsNullOrEmpty(resultado))
                    {
                        throw new System.ArgumentException(resultado);
                    }
                }

                //Guardando resultado de oficiales notificadores
                jsonParsed = JArray.Parse(queryResult[3]);
                for (int k = 0; k < jsonParsed.Count; k++)
                {
                    string resultado = ManejoBaseDatos.Insertar("OficialesNotificadores", "CodigoNotificador,NombreCompleto,DespachoCodigo,CuotaMinima,RolNocturno,Supervisor", "'" + jsonParsed[k]["CodNotificador"].ToString() + "'," + "'" + jsonParsed[k]["NombreCompleto"].ToString() + "'," + "'" + jsonParsed[k]["Oficinas"][0]["Codigo"].ToString() + "'," + "" + jsonParsed[k]["Oficinas"][0]["CuotaMinima"].ToString() + "," + "'" + jsonParsed[k]["RolNocturno"].ToString() + "'," + "'" + jsonParsed[k]["Supervisor"].ToString() + "'");
                    if (!String.IsNullOrEmpty(resultado))
                    {
                        throw new System.ArgumentException(resultado);
                    }
                }


                jsonParsed = JArray.Parse(queryResult[2]);
                for (int k = 0; k < jsonParsed.Count; k++)
                {
                    string resultado = ManejoBaseDatos.Insertar("Resultados", "Codigo,Descripcion,Diligenciada", jsonParsed[k]["Codigo"].ToString() + "," +
                                                                "'" + jsonParsed[k]["Descripcion"].ToString() + "'," +
                                                                "'" + jsonParsed[k]["Diligenciada"].ToString() + "'");
                    if (!String.IsNullOrEmpty(resultado))
                    {
                        throw new System.ArgumentException(resultado);
                    }
                }

                jsonParsed = JArray.Parse(queryResult[1]);
                for (int k = 0; k < jsonParsed.Count; k++)
                {
                    string resultado = ManejoBaseDatos.Insertar("Resultados", "Codigo,Descripcion,Diligenciada", jsonParsed[k]["Codigo"].ToString() + "," +
                                                                "'" + jsonParsed[k]["Descripcion"].ToString() + "'," +
                                                                "'" + jsonParsed[k]["Diligenciada"].ToString() + "'");
                    if (!String.IsNullOrEmpty(resultado))
                    {
                        throw new System.ArgumentException(resultado);
                    }
                }


                jsonParsed = JArray.Parse(queryResult[0]);
                for (int k = 0; k < jsonParsed.Count; k++)
                {
                    string resultado = ManejoBaseDatos.Insertar("Sectores", "Codigo,Descripcion", jsonParsed[k]["Codigo"].ToString() + "," +
                                                                "'" + jsonParsed[k]["Descripcion"].ToString() + "'");
                    if (!String.IsNullOrEmpty(resultado))
                    {
                        throw new System.ArgumentException(resultado);
                    }
                }

                sw.Stop();
                ManejoBaseDatos.Cerrar();
                Console.WriteLine("--fzeledon: Tiempo en milisegundos que dura bajar los datos desde dB: " + sw.ElapsedMilliseconds);
            }
            catch (Exception ex) { Console.WriteLine("--fzeledon: Error while loading data: " + ex.ToString()); }
        }
Exemplo n.º 6
0
        protected override void OnResume()
        {
            base.OnResume();

            int jornada = 0;
            int estado  = 0;

            bool admin = false;

            if (supervisor.Equals("true", StringComparison.Ordinal) || supervisor.Equals("True", StringComparison.Ordinal))
            {
                sector  = "";   //se va a generar informacion para todos los sectores
                jornada = 3;    // se van a ver las notificaciones duirnas y nocturnas
                admin   = true; //propiedad de admin verdadera
                estado  = 1;    // Se van a consultar las notificaciones que se encuentren nuevas a imprimir
            }
            else
            {
                admin  = false; //propiedad de admin en false
                estado = 2;     // asignado para notificar.

                if (rolNocturno.Equals("true", StringComparison.Ordinal) || rolNocturno.Equals("True", StringComparison.Ordinal))
                {
                    jornada = 3;//permite observar notificaciones de ambas jornadas
                }
                else
                {
                    jornada = 1;//permite observar notificaciones de jornada diurna
                }
            }

            Task startupWork = new Task(() =>
            {
                if (coneccionInternet.verificaConeccion(this.ApplicationContext))
                {
                    Stopwatch sw1        = Stopwatch.StartNew();
                    List <string> tables = new List <string>();

                    tables.Add("Notificaciones");
                    tables.Add("OficialesNotificadores");
                    tables.Add("Resultados");
                    tables.Add("Sectores");
                    tables.Add("Autenticacion");

                    Console.WriteLine("--fzeledon: Creating DataBase for app");

                    ManejoBaseDatos.Abrir();
                    string resultadoBorrar = ManejoBaseDatos.BorrarTablas(tables);
                    ManejoBaseDatos.Cerrar();

                    List <string> results = new List <string>();
                    List <string> query   = new List <string>();
                    //Consulta de sectores
                    query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/SectorNotificacion/ListarSectores?PCodOficina=" + oficina + "");
                    //Consulta de resultados positivos
                    query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/ResultadoNotificacion/ListarResultadosNotificaciones?PDiligenciado=1");
                    //Consulta de resultados negativos
                    query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/ResultadoNotificacion/ListarResultadosNotificaciones?PDiligenciado=0");
                    //Consulta de Oficiales Notificadores
                    query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/OficialNotificador/ListarOficialesNotificadores?PCodOficina=" + oficina + "");
                    //consulta de Notificaciones en estado 0 jornada diurna y nocturna con parametro de admin
                    if (admin)
                    {
                        query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/Notificaciones/ListarNotificacionesPorSectorEstado?PCodOficina=" + oficina + "&PSector=" + sector + "&PEstado=" + estado.ToString() + "&PJornada=" + jornada.ToString() + "");
                    }
                    else
                    {
                        query.Add(@"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/Notificaciones/ListarNotificacionesPorNotificadorEstado?POficina=" + oficina + "&PCodNotificador=" + codNotificador + "&PEstado=" + estado + "&PJornada=" + jornada.ToString() + "");
                    }

                    var urls = query.ToArray();

                    var tasks     = urls.Select(GetAsync).ToArray();
                    var completed = Task.Factory.ContinueWhenAll(tasks,
                                                                 completedTasks => {
                        foreach (var result in completedTasks.Select(t => t.Result))
                        {
                            //Console.WriteLine(result);
                            results.Add(result);
                            //Console.WriteLine(result);
                        }
                    });
                    completed.Wait();
                    Console.WriteLine("Tasks completed");
                    //anything that follows gets executed after all urls have finished downloading

                    var jsonParsed = JArray.Parse(results[4]);
                    Console.WriteLine("total de elementos a parsear: " + jsonParsed.Count.ToString());


                    ManejoBaseDatos.Abrir();
                    for (int k = 0; k < jsonParsed.Count; k++)
                    {
                        string resultado = "";
                        if (FragmentLogin.supervisor.Equals("True", StringComparison.Ordinal) || FragmentLogin.supervisor.Equals("true", StringComparison.Ordinal))
                        {
                            resultado = ManejoBaseDatos.Insertar("Notificaciones", "CodigoNotificacion,Expediente,DespachoDescripcion,Notificando,Medio,Provincia,Canton,Distrito,Direccion,Sector,Urgente,FechaDocumento,FechaEmision,Visitas,HorarioEntrega,Estado",
                                                                 jsonParsed[k]["CodNotificacion"].ToString() + ", " +
                                                                 "'" + jsonParsed[k]["NumExpediente"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Despacho"]["Descripcion"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["NombreCompleto"].ToString().Replace("'", "") + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["TipoMedio"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Provincia"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Canton"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Distrito"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Direccion"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Sector"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Urgente"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["FechaDocumento"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["FechaEmision"].ToString() + "'," +
                                                                 "" + jsonParsed[k]["Visitas"].ToString() + "," +
                                                                 "'" + jsonParsed[k]["HorarioEntrega"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Estado"].ToString() + "'");
                        }
                        else
                        {
                            resultado = ManejoBaseDatos.Insertar("Notificaciones", "CodigoNotificacion,Expediente,DespachoDescripcion,Notificando,Medio,Provincia,Canton,Distrito,Direccion,Sector,Urgente,FechaDocumento,FechaEmision,Visitas,Estado,CodNotificador,RolNocturno,DespachoCodigo,HorarioEntrega,DespachoDescripcion",
                                                                 jsonParsed[k]["CodNotificacion"].ToString() + ", " +
                                                                 "'" + jsonParsed[k]["NumExpediente"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Despacho"]["Descripcion"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["NombreCompleto"].ToString().Replace("'", "") + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["TipoMedio"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Provincia"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Canton"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Distrito"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Direccion"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Notificando"]["MedioNotificacion"]["Sector"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Urgente"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["FechaDocumento"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["FechaEmision"].ToString() + "'," +
                                                                 "" + jsonParsed[k]["Visitas"].ToString() + "," +
                                                                 "'" + jsonParsed[k]["Estado"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["OficialNotificador"]["CodNotificador"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["OficialNotificador"]["RolNocturno"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Despacho"]["Codigo"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["HorarioEntrega"].ToString() + "'," +
                                                                 "'" + jsonParsed[k]["Despacho"]["Descripcion"].ToString() + "'");
                        }
                        if (!String.IsNullOrEmpty(resultado))
                        {
                            throw new System.ArgumentException(resultado);
                        }
                    }
                    jsonParsed = JArray.Parse(results[3]);
                    Console.WriteLine("total de elementos a parsear: " + jsonParsed.Count.ToString());

                    for (int k = 0; k < jsonParsed.Count; k++)
                    {
                        string resultado = ManejoBaseDatos.Insertar("OficialesNotificadores", "CodigoNotificador,NombreCompleto,DespachoCodigo,CuotaMinima,RolNocturno,Supervisor", "'" + jsonParsed[k]["CodNotificador"].ToString() + "'," + "'" + jsonParsed[k]["NombreCompleto"].ToString() + "'," + "'" + jsonParsed[k]["Oficinas"][0]["Codigo"].ToString() + "'," + "" + jsonParsed[k]["Oficinas"][0]["CuotaMinima"].ToString() + "," + "'" + jsonParsed[k]["RolNocturno"].ToString() + "'," + "'" + jsonParsed[k]["Supervisor"].ToString() + "'");
                        if (!String.IsNullOrEmpty(resultado))
                        {
                            throw new System.ArgumentException(resultado);
                        }
                    }


                    jsonParsed = JArray.Parse(results[2]);
                    for (int k = 0; k < jsonParsed.Count; k++)
                    {
                        string resultado = ManejoBaseDatos.Insertar("Resultados", "Codigo,Descripcion,Diligenciada", jsonParsed[k]["Codigo"].ToString() + "," +
                                                                    "'" + jsonParsed[k]["Descripcion"].ToString() + "'," +
                                                                    "'" + jsonParsed[k]["Diligenciada"].ToString() + "'");
                        if (!String.IsNullOrEmpty(resultado))
                        {
                            throw new System.ArgumentException(resultado);
                        }
                    }

                    jsonParsed = JArray.Parse(results[1]);
                    for (int k = 0; k < jsonParsed.Count; k++)
                    {
                        string resultado = ManejoBaseDatos.Insertar("Resultados", "Codigo,Descripcion,Diligenciada", jsonParsed[k]["Codigo"].ToString() + "," +
                                                                    "'" + jsonParsed[k]["Descripcion"].ToString() + "'," +
                                                                    "'" + jsonParsed[k]["Diligenciada"].ToString() + "'");
                        if (!String.IsNullOrEmpty(resultado))
                        {
                            throw new System.ArgumentException(resultado);
                        }
                    }


                    jsonParsed = JArray.Parse(results[0]);
                    for (int k = 0; k < jsonParsed.Count; k++)
                    {
                        string resultado = ManejoBaseDatos.Insertar("Sectores", "Codigo,Descripcion", jsonParsed[k]["Codigo"].ToString() + "," +
                                                                    "'" + jsonParsed[k]["Descripcion"].ToString() + "'");
                        if (!String.IsNullOrEmpty(resultado))
                        {
                            throw new System.ArgumentException(resultado);
                        }
                    }
                    ManejoBaseDatos.Cerrar();
                    sw1.Stop();
                    Console.WriteLine("tiempo transcurido en milisegundos: " + sw1.ElapsedMilliseconds.ToString());
                    Console.WriteLine("Parsing completado");
                }
                //InitializeDataBase(admin, oficina, sector, estado, jornada);
                else
                {
                    Android.App.AlertDialog.Builder alerta = new Android.App.AlertDialog.Builder(this.ApplicationContext);
                    alerta.SetTitle("Mensaje de alerta");
                    alerta.SetIcon(Resource.Drawable.alertaNuevo);
                    alerta.SetMessage("El servicio de Internet no se encuentra disponible, por favor revise su conexión e intente ingresar nuevamente");
                    alerta.SetNegativeButton("Salir", HandleButtonClick);
                    alerta.SetCancelable(false);
                    alerta.Create();
                    alerta.Show();
                }
            });

            startupWork.ContinueWith(t =>
            {
                if (admin)
                {
                    Intent intent = new Intent(this, typeof(MailBoxes));
                    intent.PutExtra(MailBoxes.EXTRA_SUPERVISOR, "supervisor");
                    StartActivity(intent);
                }
                else
                {
                    Intent intent = new Intent(this, typeof(MailBoxes));
                    intent.PutExtra(MailBoxes.EXTRA_SUPERVISOR, "notificador");
                    StartActivity(intent);
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
            startupWork.Start();
        }
Exemplo n.º 7
0
        /// <summary>
        /// Se crea el evento para el boton siguiente
        /// Se valida el formulario de la pantalla de Impresión
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///
        private void BtnGuardar_Click(object sender, EventArgs e)
        {
            //verificando si hay un resultado para la notificacion
            if (!string.IsNullOrEmpty(diligenciada))
            {
                //verificando codigo de resultado
                if (listview.CheckedItemPosition >= 0)
                {
                    if (diligenciada.Equals("true", StringComparison.Ordinal))
                    {
                        ManejoBaseDatos.Abrir();
                        ICursor mCursor = ManejoBaseDatos.Seleccionar("SELECT * FROM Imagenes WHERE Nombre='" + guidNotificando + "'");

                        //verificando si existe firma
                        if (mCursor.Count > 0)
                        {
                            //ManejoBaseDatos.Cerrar();

                            //verificando sin hay observaciones
                            if (!string.IsNullOrEmpty(observaciones))
                            {
                                Console.WriteLine("Guardando datos");

                                try
                                {
                                    Console.WriteLine("Guardando datos para NotificacionCompletada");

                                    Console.WriteLine("Codigo notificacion: " + codNotificacion.ToString());

                                    db1 = SQLiteDatabase.OpenDatabase(dbPath, null, DatabaseOpenFlags.OpenReadwrite);
                                    db1.ExecSQL("UPDATE Notificaciones SET Estado='NotificacionCompletada' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                    db1.ExecSQL("UPDATE Notificaciones SET PendienteSubir='S' WHERE CodigoNotificacion=" + codNotificacion + ";");


                                    db1.ExecSQL("UPDATE Notificaciones SET FirmaNotificando='" + guidNotificando + "' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                    db1.ExecSQL("UPDATE Notificaciones SET ResultadoCodigo=" + listview.CheckedItemPosition.ToString() + " WHERE CodigoNotificacion=" + codNotificacion + ";");
                                    db1.ExecSQL("UPDATE Notificaciones SET ResultadoDescripcion='" + listview.GetItemAtPosition(listview.CheckedItemPosition).ToString() + "' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                    db1.ExecSQL("UPDATE Notificaciones SET ResultadoDiligenciada='" + diligenciada + "' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                    db1.ExecSQL("UPDATE Notificaciones SET Observaciones='" + observaciones + "' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                    db1.ExecSQL("UPDATE Notificaciones SET FechaNotificacion='" + "2015-07-13T19:33:38.034Z" + "' WHERE CodigoNotificacion=" + codNotificacion + ";");


                                    //Console.WriteLine("Guid notificando: " + guidNotificando);
                                    //Console.WriteLine("Resultado Codigo: " + listview.CheckedItemPosition.ToString());
                                    //Console.WriteLine("Resultado Descripcion: " + listview.GetItemAtPosition(listview.CheckedItemPosition).ToString());
                                    //Console.WriteLine("Resultado diligenciada: " + diligenciada);
                                    //Console.WriteLine("observaciones: " + observaciones);
                                    //Console.WriteLine("Fecha de notificacion: " + "2015-07-13T19:33:38.034Z");
                                    //Console.WriteLine("Nombre de testigo: " + nombreTestigo);


                                    if (!string.IsNullOrEmpty(nombreTestigo))
                                    {
                                        db1.ExecSQL("UPDATE Notificaciones SET FirmaTestigo='" + guidTestigo + "' WHERE CodigoNotificacion='" + codNotificacion + "';");
                                    }
                                    db1.Close();
                                    Toast.MakeText(this.Activity, "Datos Guardados de forma exitosa", ToastLength.Short).Show();
                                }
                                catch (Exception ex) { Console.WriteLine("ERROR REGISTRANDO DATOS: " + ex.ToString()); }
                            }
                            else
                            {
                                Toast.MakeText(this.Activity, "Por favor agregue observaciones para poder registrar datos.", ToastLength.Long).Show();
                            }
                        }
                        else
                        {
                            //ManejoBaseDatos.Cerrar();
                            mCursor.Close();
                            Toast.MakeText(this.Activity, "Por favor solicite al notificando firmar el acta.", ToastLength.Long).Show();
                        }
                        mCursor.Close();
                        //
                    }


                    if (diligenciada.Equals("false", StringComparison.Ordinal))
                    {
                        if (listview.CheckedItemPosition >= 0)
                        {
                            if (!string.IsNullOrEmpty(observaciones))
                            {
                                //Guardando datos
                                db1 = SQLiteDatabase.OpenDatabase(dbPath, null, DatabaseOpenFlags.OpenReadwrite);
                                db1.ExecSQL("UPDATE Notificaciones SET Estado='NotificacionCompletada' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                db1.ExecSQL("UPDATE Notificaciones SET PendienteSubir='S' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                db1.ExecSQL("UPDATE Notificaciones SET ResultadoCodigo=" + listview.CheckedItemPosition.ToString() + " WHERE CodigoNotificacion=" + codNotificacion + ";");
                                db1.ExecSQL("UPDATE Notificaciones SET ResultadoDescripcion='" + listview.GetItemAtPosition(listview.CheckedItemPosition).ToString() + "' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                db1.ExecSQL("UPDATE Notificaciones SET ResultadoDiligenciada='" + diligenciada + "' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                db1.ExecSQL("UPDATE Notificaciones SET Observaciones='" + observaciones + "' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                db1.ExecSQL("UPDATE Notificaciones SET FechaNotificacion='" + "2015-07-13T19:33:38.034Z" + "' WHERE CodigoNotificacion=" + codNotificacion + ";");
                                db1.Close();
                            }
                            else
                            {
                                Toast.MakeText(this.Activity, "Por favor agregue observaciones para poder registrar datos.", ToastLength.Long).Show();
                            }
                            //
                        }
                        else
                        {
                            Toast.MakeText(this.Activity, "Por favor seleccione la razón del resultado seleccionado.", ToastLength.Long).Show();
                        }
                    }
                }
                else
                {
                    Toast.MakeText(this.Activity, "Por favor seleccione la razón del resultado seleccionado.", ToastLength.Long).Show();
                }
            }
            else
            {
                Toast.MakeText(this.Activity, "Por favor seleccione un resultado para la notificación.", ToastLength.Long).Show();
            }
        }
Exemplo n.º 8
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View view = inflater.Inflate(Resource.Layout.detalle, container, false);

            Button btnRegistroDatos = view.FindViewById <Button>(Resource.Id.btnRegistrarDatos);

            expandable = view.FindViewById <LinearLayout>(Resource.Id.linearLayoutFillData);

            //Definicion de los diferentes espacios de texto a mostrar
            mExpediente            = view.FindViewById <TextView>(Resource.Id.txtExpediente);
            mSector                = view.FindViewById <TextView>(Resource.Id.txtSector);
            mFormaNotificacion     = view.FindViewById <TextView>(Resource.Id.txtFormaNotificacion);
            mProvincia             = view.FindViewById <TextView>(Resource.Id.txtProvincia);
            mCanton                = view.FindViewById <TextView>(Resource.Id.txtCanton);
            mDistrito              = view.FindViewById <TextView>(Resource.Id.textDistrito);
            mDireccion             = view.FindViewById <TextView>(Resource.Id.txtDireccion);
            mCopias                = view.FindViewById <TextView>(Resource.Id.txtCopias);
            mOficial               = view.FindViewById <TextView>(Resource.Id.txtOficialNombreDatos);
            mFechaNotificacion     = view.FindViewById <TextView>(Resource.Id.txtFechaNotificacion);
            mresultadoNotificacion = view.FindViewById <TextView>(Resource.Id.txtResultadoNotificacion);
            mFechaResolucion       = view.FindViewById <TextView>(Resource.Id.txtFechaResolucion);
            mDespacho              = view.FindViewById <TextView>(Resource.Id.txtDespacho);
            mNotificando           = view.FindViewById <TextView>(Resource.Id.txtNotificandoNombre);
            mUrgente               = view.FindViewById <TextView>(Resource.Id.txtUrgente);
            mHorario               = view.FindViewById <TextView>(Resource.Id.txtHorario);

            Switch mSwitch = view.FindViewById <Switch>(Resource.Id.monitored_switch);

            mSwitch.CheckedChange += delegate(object sender, CompoundButton.CheckedChangeEventArgs e)
            {
                mSwitch.Text = "Resultado " + (e.IsChecked ? "Positivo" : "Negativo");
            };
            expandable.Visibility   = ViewStates.Gone;
            btnRegistroDatos.Click += (s, e) =>
            {
                if (expandable.Visibility.Equals(ViewStates.Gone))
                {
                    expandable.Visibility = ViewStates.Visible;
                    int widthSpec  = View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified);
                    int heightSpec = View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified);
                    expandable.Measure(widthSpec, heightSpec);
                    ValueAnimator mAnimator = slideAnimator(0, expandable.MeasuredHeight);
                    mAnimator.Start();
                }
                else
                {
                    int           finalHeight = expandable.Height;
                    ValueAnimator mAnimator   = slideAnimator(finalHeight, 0);
                    mAnimator.Start();
                    mAnimator.AnimationEnd += (object IntentSender, EventArgs arg) => {
                        expandable.Visibility = ViewStates.Gone;
                    };
                }
            };
            //
            if (!string.IsNullOrEmpty(codNotificacion))
            {
                string query = "SELECT * FROM Notificaciones WHERE CodigoNotificacion=" + codNotificacion + "";
                ManejoBaseDatos.Abrir();
                ICursor mCursor = ManejoBaseDatos.Seleccionar(query);
                if (mCursor.MoveToFirst())
                {
                    do
                    {
                        mExpediente.Text        = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Expediente"))) ? mCursor.GetString(mCursor.GetColumnIndex("Expediente")) : "");
                        mSector.Text            = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Sector"))) ? mCursor.GetString(mCursor.GetColumnIndex("Sector")) : "");
                        mProvincia.Text         = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Provincia"))) ? mCursor.GetString(mCursor.GetColumnIndex("Provincia")) : "");
                        mCanton.Text            = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Canton"))) ? mCursor.GetString(mCursor.GetColumnIndex("Canton")) : "");
                        mDireccion.Text         = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Direccion"))) ? mCursor.GetString(mCursor.GetColumnIndex("Direccion")) : "");
                        mSector.Text            = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Sector"))) ? "S-" + mCursor.GetString(mCursor.GetColumnIndex("Sector")) : "");
                        mDistrito.Text          = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Distrito"))) ? mCursor.GetString(mCursor.GetColumnIndex("Distrito")) : "");
                        mFechaResolucion.Text   = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("FechaDocumento"))) ? mCursor.GetString(mCursor.GetColumnIndex("FechaDocumento")) : "");
                        mDespacho.Text          = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("DespachoDescripcion"))) ? mCursor.GetString(mCursor.GetColumnIndex("DespachoDescripcion")) : "");
                        mNotificando.Text       = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Notificando"))) ? mCursor.GetString(mCursor.GetColumnIndex("Notificando")) : "");
                        mFormaNotificacion.Text = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Medio"))) ? mCursor.GetString(mCursor.GetColumnIndex("Medio")) : "");
                        mUrgente.Text           = (mCursor.GetString(mCursor.GetColumnIndex("Urgente")).Equals("True") || (mCursor.GetString(mCursor.GetColumnIndex("Urgente")).Equals("true")) ? "Sí" : "No");
                        mHorario.Text           = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Medio"))) ? "Sí" : "No");
                    } while (mCursor.MoveToNext());
                }
                mCursor.Close();
                ManejoBaseDatos.Cerrar();
            }
            else
            {
                AlertDialog.Builder alerta = new AlertDialog.Builder(this.Context);
                alerta.SetTitle("Mensaje de alerta");
                alerta.SetIcon(Resource.Drawable.alertaNuevo);
                alerta.SetMessage("El usuario tiene una jornada abierta.");
                alerta.SetPositiveButton("Regresar", HandleButtonClick);
                //alerta.SetNegativeButton("Continuar", HandleButonContinuar);
                alerta.SetCancelable(false);
                alerta.Create();
                alerta.Show();
            }
            return(view);
        }
Exemplo n.º 9
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment

            View ubicacion = inflater.Inflate(Resource.Layout.fragmentMap, container, false);

            ((Activities.MainActivity)Activity).habilitarMenuLateral(true);
            ((Activities.MainActivity)Activity).cambiarTituloAplicacion("Rutas Notificadores");

            TextView txt = ubicacion.FindViewById <TextView>(Resource.Id.textView9);

            Button btnSiguiente = ubicacion.FindViewById <Button>(Resource.Id.btnSiguiente);

            btnSiguiente.Click += BtnSiguiente_Click;//Se crea el evento click

            cargarComboNotificador(this.Activity, ubicacion);

            Spinner notificador = ubicacion.FindViewById <Spinner>(Resource.Id.spnNotificador);

            notificador.ItemSelected += Notificador_ItemSelected;

            if (!(FragmentLogin.supervisor.Equals("true") || FragmentLogin.supervisor.Equals("True")))
            {
                txt.Visibility         = ViewStates.Invisible;
                notificador.Visibility = ViewStates.Invisible;
            }
            else
            {
                notificador.Visibility = ViewStates.Visible;
                txt.Visibility         = ViewStates.Visible;
                dbConeccion.setAdaptadorCombo("SELECT NombreCompleto || '-' || CodigoNotificador FROM OficialesNotificadores", Activity, ref notificador);
                notificador.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(Notificador_ItemSelected1);
            }

            posiciones.Clear();
            listaPosiciones.Clear();
            ManejoBaseDatos.Abrir();
            if (FragmentLogin.supervisor.Equals("true", StringComparison.Ordinal) || FragmentLogin.supervisor.Equals("True", StringComparison.Ordinal))
            {
                ICursor cursor = ManejoBaseDatos.Seleccionar("SELECT googleMapsX,googleMapsY,RolNocturno FROM Notificaciones WHERE Estado='AsignarParaNotificar'");
                if (cursor.MoveToFirst())
                {
                    listaPosiciones = new List <KeyValuePair <LatLng, bool> >();
                    KeyValuePair <LatLng, bool> posicion;

                    do
                    {
                        Console.WriteLine("Pares: " + cursor.GetString(0) + " " + cursor.GetString(1));

                        double latitudeM  = double.Parse(cursor.GetString(0), EnglishCulture);
                        double longitudeM = double.Parse(cursor.GetString(1), EnglishCulture);
                        //Se obtiene el valor del rol nocturno
                        string rol = cursor.GetString(2);
                        //Si es verdadero el check se marca y si no, se deja sin marcar
                        bool rolNocturno = rol == "True" || rol == "true" ? true : false;

                        posicion = new KeyValuePair <LatLng, bool>(new LatLng(latitudeM, longitudeM), rolNocturno);
                        listaPosiciones.Add(posicion);

                        posiciones.Add(new LatLng(latitudeM, longitudeM));
                        // se agregan a la lista los diferentes elementos a los cuales se les va a calcular la posicion
                        //data.Add("Costa Rica," + cursor.GetString(0) + "," + cursor.GetString(1));
                        //codNotificacion.Add(cursor.GetString(2));
                    } while (cursor.MoveToNext());
                }
                cursor.Close();
                ManejoBaseDatos.Cerrar();
            }
            else
            {
                string  codigoNotificador = FragmentLogin.codNotificador;
                ICursor cursor            = ManejoBaseDatos.Seleccionar("SELECT googleMapsX,googleMapsY,RolNocturno FROM Notificaciones WHERE Estado='Notificandose' and CodNotificador = '" + codigoNotificador + "'");
                if (cursor.MoveToFirst())
                {
                    listaPosiciones = new List <KeyValuePair <LatLng, bool> >();
                    KeyValuePair <LatLng, bool> posicion;

                    do
                    {
                        NumberFormatInfo provider = new NumberFormatInfo();
                        provider.NumberDecimalSeparator = ".";

                        double latitudeM  = Convert.ToDouble(cursor.GetString(0), provider);
                        double longitudeM = Convert.ToDouble(cursor.GetString(1), provider);
                        //Se obtiene el valor del rol nocturno
                        string rol = cursor.GetString(2);
                        //Si es verdadero el check se marca y si no, se deja sin marcar
                        bool rolNocturno = rol == "True" || rol == "true" ? true : false;

                        Console.WriteLine("latitudeM: " + latitudeM.ToString());
                        Console.WriteLine("longitudeM: " + longitudeM.ToString());

                        posicion = new KeyValuePair <LatLng, bool>(new LatLng(latitudeM, longitudeM), rolNocturno);
                        listaPosiciones.Add(posicion);

                        posiciones.Add(new LatLng(latitudeM, longitudeM));
                    } while (cursor.MoveToNext());
                }
                cursor.Close();
                ManejoBaseDatos.Cerrar();
            }

            ((Activities.MainActivity)Activity).IniciarFragmentoMapa(Resource.Id.map);//Se inicia el mapa en el fragmento
            return(ubicacion);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Se cargan la lista de notificadores
        /// </summary>
        public void cargarNotificadores()
        {
            try
            {
                ManejoBaseDatos.Abrir();
                //Se consulta en la base de datos la lista de los usuarios notificadores
                ICursor cursor = ManejoBaseDatos.Seleccionar("SELECT NombreCompleto, CodigoNotificador, RolNocturno FROM OficialesNotificadores");
                //Instancia de la tabla de notificadores
                TableLayout tablaNotificadores = Activity.FindViewById <TableLayout>(Resource.Id.tbNotificadores);
                //Se crea el objeto para las fila que se van a ingresar en la tabla
                TableRow nuevaFila;
                TableLayout.LayoutParams layoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MatchParent, TableLayout.LayoutParams.MatchParent);

                List <int> listaIndices = new List <int>();
                //Se guardan los indices que se van a eliminar de la tabla de notificadores
                for (int i = 1; i < tablaNotificadores.ChildCount; tablaNotificadores.RemoveViewAt(1))
                {
                    ;
                }

                if (cursor.MoveToFirst())//Se posiciona el cursor en la primera posición
                {
                    do
                    {
                        nuevaFila = new TableRow(Activity);                                    //Se instancia la nueva fila
                        nuevaFila.LayoutParameters = layoutParams;                             //Se agregan los tamaños del layout
                        nuevaFila.SetPadding(5, 5, 5, 5);                                      //Se agregan los margenes de cada fila
                        nuevaFila.SetBackgroundColor(Android.Graphics.Color.Argb(2, 1, 0, 5)); //Se cambia el color del fondo
                        nuevaFila.Clickable = true;
                        nuevaFila.Click    += (s, args) => { };

                        //Se agrega el nombre del notificador
                        TextView nombreNotificador = new TextView(Activity);
                        nombreNotificador.Text = cursor.GetString(0);
                        //Se agrega el rol
                        CheckBox rolNocturno = new CheckBox(Activity);
                        rolNocturno.Gravity = GravityFlags.CenterHorizontal;
                        rolNocturno.Text    = "";
                        //Se obtiene el valor del rol nocturno
                        string check = cursor.GetString(2);
                        //Si es verdadero el check se marca y si no, se deja sin marcar
                        rolNocturno.Checked = check == "True" || check == "true" ? true : false;
                        //Se guarda el codigo del notificador
                        string codigoNotificador = cursor.GetString(1);

                        rolNocturno.CheckedChange += (s, args) =>
                        {
                            ManejoBaseDatos.Abrir();
                            //Se actualiza el rol nocturno
                            string msj = ManejoBaseDatos.Actualizar("OficialesNotificadores", "RolNocturno", "'" + args.IsChecked + "'", "CodigoNotificador='" + codigoNotificador + "'");
                            ManejoBaseDatos.Cerrar();

                            try
                            {
                                if (args.IsChecked)
                                {
                                    string         consulta = @"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/OficialNotificador/AsignarRolNocturno?PCodNotificador=" + codigoNotificador + "";
                                    HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(consulta);
                                    request.Method      = "GET";
                                    request.ContentType = "application/json";
                                    HttpWebResponse myResp = (HttpWebResponse)request.GetResponse();
                                    string          responseText;

                                    using (var response = request.GetResponse())
                                    {
                                        using (var reader = new StreamReader(response.GetResponseStream()))
                                        {
                                            responseText = reader.ReadToEnd();
                                            Console.WriteLine("Respuesta de web service: " + responseText);
                                            if (responseText.Equals("true") || responseText.Equals("True"))
                                            {
                                                Toast.MakeText(this.Activity, "Cambio a Rol Nocturno Exitoso", ToastLength.Short).Show();
                                            }
                                        }
                                    }
                                }
                            }
                            catch (WebException webEx)
                            {
                                Toast.MakeText(this.Activity, "Error al actualizar datos", ToastLength.Short).Show();
                                Console.WriteLine("Error al asignar rol nocturno: " + webEx.ToString());
                            }

                            Toast.MakeText(Activity, msj, ToastLength.Short).Show();
                        };
                        //Se agregan las dos columnas a la fila
                        nuevaFila.AddView(nombreNotificador);
                        nuevaFila.AddView(rolNocturno);
                        //Se agrega la nueva fila a la tabla
                        tablaNotificadores.AddView(nuevaFila);
                    } while (cursor.MoveToNext());
                }
                cursor.Close();

                ManejoBaseDatos.Cerrar();
            }catch (Exception ex)
            {
                //Se guarda el detalle del error
                Logs.saveLogError("RolNocturno.cargarNotificadores " + ex.Message + " " + ex.StackTrace);
            }
        }
Exemplo n.º 11
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);
            //return base.OnCreateView(inflater, container, savedInstanceState);


            View view = inflater.Inflate(Resource.Layout.fragmentLogin, container, false);

            ((MainActivity)Activity).habilitarMenuLateral(false);
            ((MainActivity)Activity).cambiarTituloAplicacion("Autenticación de usuario");

            Button   btnLogin      = view.FindViewById <Button>(Resource.Id.btnLogin);
            EditText txtUsuario    = view.FindViewById <EditText>(Resource.Id.txtUsuario);
            EditText txtContrasena = view.FindViewById <EditText>(Resource.Id.txtPassword);

            TextInputLayout passwordWrapper = view.FindViewById <TextInputLayout>(Resource.Id.txtInputLayoutPassword);
            string          txtPassword     = passwordWrapper.EditText.Text;
            Context         context;

            context            = view.Context;
            txtUsuario.Text    = "";
            txtContrasena.Text = "";

            txtUsuario.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) =>
            {
                usuario = e.Text.ToString();
            };

            txtContrasena.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) =>
            {
                contrasena = e.Text.ToString();
            };

            if (!coneccionInternet.verificaConeccion(this.Context))
            {
                AlertDialog.Builder alerta = new AlertDialog.Builder(this.Context);
                alerta.SetTitle("Mensaje de alerta");
                alerta.SetIcon(Resource.Drawable.alertaNuevo);
                alerta.SetMessage("El servicio de Internet no se encuentra disponible, por favor revise su conexión e intente ingresar nuevamente");
                alerta.SetNegativeButton("Salir", HandleButtonClick);
                alerta.SetCancelable(false);
                alerta.Create();
                alerta.Show();
            }

            //se limpia la tabla de Oficial Notificador
            ManejoBaseDatos.CrearDB();
            ManejoBaseDatos.Abrir();
            List <string> tablas = new List <string>();

            tablas.Add("OficialNotificador");
            ManejoBaseDatos.BorrarTablas(tablas);
            ManejoBaseDatos.Cerrar();

            btnLogin.Click += (o, e) =>
            {
                try
                {
                    if (!string.IsNullOrEmpty(usuario) && (contrasena.Equals("12345", StringComparison.Ordinal)) && (usuario.Equals("supervisor", StringComparison.Ordinal) || usuario.Equals("demo", StringComparison.Ordinal)))
                    {
                        string query = @"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/OficialNotificador/ConsultarOficialNotificador?PCodNotificador=" + usuario + "";
                        if (coneccionInternet.verificaConeccion(this.Context))
                        {
                            try
                            {
                                WebRequest request = HttpWebRequest.Create(query);
                                request.ContentType = "application/json";
                                request.Method      = "GET";
                                string content = "";

                                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                                {
                                    if (response.StatusCode != HttpStatusCode.OK)
                                    {
                                        Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
                                    }
                                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                                    {
                                        content = reader.ReadToEnd();

                                        if (string.IsNullOrWhiteSpace(content))
                                        {
                                            Console.Out.WriteLine("fzeledon -- Response contained empty body...");
                                        }
                                        else
                                        {
                                            try
                                            {
                                                var jsonParsed = JObject.Parse(content);
                                                codOficina     = jsonParsed["Oficinas"][0]["Codigo"].ToString();
                                                supervisor     = jsonParsed["Supervisor"].ToString();
                                                rolNocturno    = jsonParsed["RolNocturno"].ToString();
                                                codNotificador = jsonParsed["CodNotificador"].ToString();
                                                cuotaMinima    = jsonParsed["Oficinas"][0]["CuotaMinima"].ToString();

                                                ManejoBaseDatos.Abrir();
                                                ManejoBaseDatos.Insertar("OficialNotificador", "Activo,CodigoNotificador,DespachoCodigo,Supervisor,RolNocturno", "'" + jsonParsed["Activo"].ToString() + "','" + jsonParsed["CodNotificador"].ToString() + "','" + jsonParsed["Oficinas"][0]["Codigo"].ToString() + "','" + jsonParsed["Supervisor"].ToString() + "','" + jsonParsed["RolNocturno"].ToString() + "'");
                                                ManejoBaseDatos.Cerrar();

                                                //se realiza la comprobacion si se tiene una sesion abierta

                                                servicioCheckDB coneccion     = new servicioCheckDB();
                                                var             sesionAbierta = coneccion.ObtenerString("https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/OficialNotificador/OficialConCierrePendiente?PCodNotificador=" + codNotificador + "", Activity);
                                                //   "\"\""
                                                if (!sesionAbierta.Equals("\"\"", StringComparison.Ordinal))
                                                {
                                                    Console.WriteLine("Sesion abierta");
                                                    AlertDialog.Builder alerta = new AlertDialog.Builder(this.Context);
                                                    alerta.SetTitle("Mensaje de alerta");
                                                    alerta.SetIcon(Resource.Drawable.alertaNuevo);
                                                    alerta.SetMessage("El usuario tiene una jornada abierta.");
                                                    alerta.SetPositiveButton("Cerrar jornada", HandlePositiveButtonClick);
                                                    alerta.SetNegativeButton("Continuar", HandleButonContinuar);
                                                    alerta.SetCancelable(false);
                                                    alerta.Create();
                                                    alerta.Show();
                                                }
                                                else
                                                {
                                                    // se inicia la carga de datos para la actividad de buzones(mailboxes) a traves de la actividad splash
                                                    Toast.MakeText(this.Activity, "Cargando Datos ", ToastLength.Long).Show();
                                                    Intent intent = new Intent(this.Activity, typeof(SplashActivity));
                                                    StartActivity(intent);
                                                }
                                            }
                                            catch (Exception ex) { Console.WriteLine("Error descargando datos de usuario: " + ex.ToString()); }
                                        }
                                    }
                                }
                            }
                            catch (WebException webEx) { Console.WriteLine("Error en solicitud Web: " + webEx.ToString()); }
                        }
                        else
                        {
                            AlertDialog.Builder alerta = new AlertDialog.Builder(this.Context);
                            alerta.SetTitle("Mensaje de alerta");
                            alerta.SetIcon(Resource.Drawable.alertaNuevo);
                            alerta.SetMessage("El servicio de Internet no se encuentra disponible, por favor revise su conexión e intente ingresar nuevamente");
                            alerta.SetNegativeButton("Salir", HandleButtonClick);
                            alerta.SetCancelable(false);
                            alerta.Create();
                            alerta.Show();
                        }
                    }
                    else
                    {
                        Toast.MakeText(this.Activity, "Usted ha digitado un usuario y contraseña incorrecta.", ToastLength.Short).Show();
                    }
                }
                catch (Exception ex) { Console.WriteLine("Error en autenticación " + ex.ToString()); }
            };

            return(view);
        }