示例#1
0
        public void WS_GPS_SincronizaGPS()
        {
            WS_CONTEXT db = new WS_CONTEXT();

            db.WS_GPS_SincronizaGPS();

            //WS_CONTEXT dbTEST = new WS_CONTEXT("WS_CONTEXT_TEST");
            //dbTEST.WS_GPS_SincronizaGPS();

            //EnviarCorreo("*****@*****.**", "", "", "Ejecucion Quartz", "se ejecuto la tarea sincronizar gps");
        }
示例#2
0
        private Result ValidaUsuarioyPassword(EventoSimple eventosimple)
        {
            WS_CONTEXT db = new WS_CONTEXT();

            Result result = new Result();

            //Obtener el IdUsuario en base a Usuario y Contraseña y validarlo
            var resultado = db.WS_GPS_ValidaUsuarioyPassword(eventosimple.Usuario, eventosimple.Password, eventosimple.IMEI).ToList();

            result.Indicador          = resultado[0].Indicador;
            result.Mensaje            = resultado[0].Mensaje;
            result.IdRegistroAfectado = (int)resultado[0].IdRegistroAfectado;

            return(result);
        }
示例#3
0
        public RespuestaServicio InsertaSimple(EventoSimple eventosimple, string ServicioOrigen = "")
        {
            RespuestaServicio respuesta  = new RespuestaServicio();
            string            DomainName = "";

            try
            {
                DomainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
            }
            catch (Exception Ex)
            {
                DomainName = "";
            }


            //Validaciones de datos

            respuesta.Indicador = 0;
            if (eventosimple.Usuario == "")
            {
                respuesta.Mensaje = "Error: El Usuario no puede estar vacio";
                var json = JsonConvert.SerializeObject(eventosimple);
                log.Error(respuesta.Mensaje + " - " + json);
                return(respuesta);
            }
            if (eventosimple.Password == "")
            {
                respuesta.Mensaje = "Error: El Password no puede estar vacio";
                var json = JsonConvert.SerializeObject(eventosimple);
                log.Error(respuesta.Mensaje + " - " + json);
                return(respuesta);
            }
            //if ((eventosimple.IdGrupo > 0) == false)
            //{
            //    respuesta.Mensaje = "Error: Debe indicar el IdGrupo que le asignaron";
            //    return respuesta;
            //}
            if (eventosimple.IMEI == "")
            {
                respuesta.Mensaje = "Error: El IMEI no puede estar vacio";
                var json = JsonConvert.SerializeObject(eventosimple);
                log.Error(respuesta.Mensaje + " - " + json);
                return(respuesta);
            }
            //if ((eventosimple.Lat > 0) == false)
            //{
            //    respuesta.Mensaje = "Error: Latitud incorrecta";
            //    var json = JsonConvert.SerializeObject(eventosimple);
            //    log.Error(respuesta.Mensaje + " - " + json);
            //    return respuesta;
            //}
            //if (eventosimple.Lng == 0)
            //{
            //    respuesta.Mensaje = "Error: Longitud incorrecta";
            //    var json = JsonConvert.SerializeObject(eventosimple);
            //    log.Error(respuesta.Mensaje + " - " + json);
            //    return respuesta;
            //}
            if (eventosimple.FechaHoraRecepcion <= DateTime.Today.AddDays(-3))
            {
                respuesta.Mensaje = "Error: La fecha es antigua, solo se permiten eventos recientes.";
                return(respuesta);
            }



            //Excepciones
            if (eventosimple.IMEI == "530ER7" && eventosimple.Usuario != "WS_Marloz")
            {
                eventosimple.Usuario  = "WS_Marloz";
                eventosimple.Password = "******";
            }


            //Si pasaron las validaciones intenta hacer el Insert
            try
            {
                Result result = ServicioOrigen == "RestApi" ? ValidaUsuario(eventosimple) : ValidaUsuarioyPassword(eventosimple);


                if (result.Indicador == 1)
                {
                    List <WS_GPS_InsertaSimple_Result> WS_GPS_InsertaSimple;

                    WS_CONTEXT db = new WS_CONTEXT();

                    WS_GPS_InsertaSimple = db.WS_GPS_InsertaSimple(eventosimple.Usuario, eventosimple.IMEI, eventosimple.CodigoEvento, eventosimple.Lat, eventosimple.Lng, eventosimple.Ubicacion, eventosimple.GPSValido, eventosimple.Velocidad, eventosimple.Direccion, eventosimple.NivelBateria, eventosimple.KMOdometro, eventosimple.FechaHoraGeneracion, eventosimple.FechaHoraRecepcion).ToList();
                    if (WS_GPS_InsertaSimple[0].Indicador == 1)
                    {
                        //Pasa el dato por socket a los clientes conectados solo si es en produccion
                        //if (DomainName.Contains("ws.") || DomainName.TrimEnd() == "http://ws.recsolutions.tech" )
                        //{
                        var context = GlobalHost.ConnectionManager.GetHubContext <GPSHub>();
                        context.Clients.All.broadCastMessage("Server", "GPS", eventosimple);
                        //}
                    }

                    if (WS_GPS_InsertaSimple[0].Indicador == 1)
                    {
                        respuesta.Indicador = 1;
                        respuesta.Mensaje   = "OK";
                        return(respuesta);
                    }
                    else
                    {
                        respuesta.Indicador = 0;
                        respuesta.Mensaje   = "Error: " + WS_GPS_InsertaSimple[0].Mensaje;
                        var json = JsonConvert.SerializeObject(eventosimple);
                        log.Error(respuesta.Mensaje + " - " + json);
                        return(respuesta);
                    }
                }
                else
                {
                    respuesta.Indicador = 0;
                    respuesta.Mensaje   = "Error: " + result.Mensaje;
                    var json = JsonConvert.SerializeObject(eventosimple);
                    log.Error(respuesta.Mensaje + " - " + json);
                    return(respuesta);
                }
            }
            catch (Exception Ex)
            {
                respuesta.Indicador = 0;
                respuesta.Mensaje   = "Error: " + Ex.Message;
                var json = JsonConvert.SerializeObject(eventosimple);
                log.Error(respuesta.Mensaje + " - " + json);
                return(respuesta);
            }
        }
示例#4
0
文件: APIS.cs 项目: recws/ReCServices
        public static async void KOSMOS_ObtenerPosicion(string UsuarioReC, string Usuario, string Password)
        {
            var responseJson = "";

            try
            {
                using (var client = new HttpClient())
                {
                    //setup client
                    client.BaseAddress = new Uri("http://www.utrax2.com/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    //setup login data
                    var formContent = new FormUrlEncodedContent(new[]
                    {
                        //new KeyValuePair<string, string>("grant_type", "password"),
                        new KeyValuePair <string, string>("User", Usuario),
                        new KeyValuePair <string, string>("Password", Password),
                        new KeyValuePair <string, string>("Page", ""),
                    });

                    //send request
                    HttpResponseMessage responseMessage = await client.PostAsync("/web%20services/ws_last_position/ws_last_position.asmx/GetLastPosition_02", formContent);

                    //HttpResponseMessage responseMessage = await client.PostAsync("/web%20services/ws_last_position/ws_last_position.asmx/GetLastPosition_02?User="******"&Password="******"&Page=", formContent);

                    //get access token from response body
                    responseJson = await responseMessage.Content.ReadAsStringAsync();

                    //load into XElement
                    XElement doc = XElement.Parse(responseJson);
                    var      res = doc.ToDynamicList();

                    for (int i = 0; i < res.Count; i++)
                    {
                        //Consulta si ya existe la posicion, por si es repetida y no ha actualizado el equipo
                        string imei         = ((dynamic)res[i]).Device_Id;
                        string codigoevento = ((dynamic)res[i]).eCode;

                        string lat       = ((dynamic)res[i]).Latitude;
                        string lng       = ((dynamic)res[i]).Longitude;
                        string evento    = ((dynamic)res[i]).Evento;
                        string odometro  = ((dynamic)res[i]).Odometer;
                        string placas    = ((dynamic)res[i]).Plates;
                        string velocidad = ((dynamic)res[i]).Speed;
                        string direccion = ((dynamic)res[i]).Course;
                        string fechahora = ((dynamic)res[i]).DateTime_GPS;

                        //Validaciones
                        if (imei == "~" || imei.Length <= 1)
                        {
                            continue;
                        }
                        if (lng == "~" || lng.Length <= 1)
                        {
                            continue;
                        }
                        if (lat == "~" || lat.Length <= 1)
                        {
                            continue;
                        }
                        if (fechahora == "~" || fechahora.Length <= 1)
                        {
                            continue;
                        }

                        imei         = imei == "~" ? "" : imei;
                        codigoevento = codigoevento == "~" ? "" : codigoevento;
                        evento       = evento == "~" ? "" : evento;
                        lat          = lat == "~" ? "0" : lat;
                        lng          = lng == "~" ? "0" : lng;
                        odometro     = odometro == "~" ? "0" : odometro;
                        placas       = placas == "~" ? "" : placas;

                        velocidad = velocidad == "~" ? "0" : velocidad;
                        if (velocidad.IndexOf(".") >= 0)
                        {
                            velocidad = velocidad.Remove(velocidad.IndexOf("."));
                        }
                        direccion = direccion == "~" ? "0" : direccion;
                        if (direccion.IndexOf(".") >= 0)
                        {
                            direccion = direccion.Remove(direccion.IndexOf("."));
                        }
                        fechahora = fechahora == "~" ? "1900-01-01" : fechahora;

                        ////Conversiones de datos
                        //codigoevento = codigoevento;
                        //evento = evento;
                        var LAT      = decimal.Parse(lat);
                        var LNG      = decimal.Parse(lng);
                        var ODOMETRO = int.Parse(odometro);
                        var PLACAS   = System.Text.RegularExpressions.Regex.Replace(placas, "-", "");
                        PLACAS = System.Text.RegularExpressions.Regex.Replace(PLACAS, " ", "");
                        var VELOCIDAD = int.Parse(velocidad);
                        var DIRECCION = int.Parse(direccion);
                        //string[] formats = { "M/dd/yyyy hh:mm:ss tt" };
                        //var dateTime = DateTime.ParseExact(fechahora, formats, new System.Globalization.CultureInfo("en-US"), System.Globalization.DateTimeStyles.None);
                        var dateTime = DateTime.ParseExact(fechahora, "M/d/yyyy h:m:ss tt", CultureInfo.InvariantCulture);
                        dateTime = dateTime.ToUniversalTime();

                        //Si no es repetida la inserta
                        List <WS_GPS_InsertaSimple_Result> WS_GPS_InsertaSimple;

                        WS_CONTEXT db = new WS_CONTEXT();

                        WS_GPS_InsertaSimple = db.WS_GPS_InsertaSimple(UsuarioReC, imei, codigoevento, decimal.Parse(lat), decimal.Parse(lng), "", true, int.Parse(velocidad), int.Parse(direccion), 100, int.Parse(odometro), dateTime, dateTime).ToList();
                        if (WS_GPS_InsertaSimple[0].Indicador == 1)
                        {
                        }
                        else
                        {
                            var json = JsonConvert.SerializeObject(res[i]);
                            log.Error("Error al Insertar evento de " + UsuarioReC + ". " + WS_GPS_InsertaSimple[0].Mensaje + ". " + json);
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                if (Ex.Message == "'System.Dynamic.ExpandoObject' no contiene una definición para 'Latitude'.")
                {
                    //No guarda nada en el log por que aveces no viene completa la trama
                }
                else
                {
                    log.Error("Error KOSMOS_ObtenerPosicion: " + UsuarioReC + ". " + responseJson + ". " + Ex.Message);
                }
            }
        }
示例#5
0
文件: APIS.cs 项目: recws/ReCServices
        public static async void REESER_ObtenerPosicion(string UsuarioReC, string Usuario, string Password)
        {
            var responseJson = "";

            try
            {
                using (var client = new HttpClient())
                {
                    //setup client
                    client.BaseAddress = new Uri("http://rastreo.resser.com/api/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var byteArray = Encoding.ASCII.GetBytes(Usuario + ":" + Password);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));


                    //var credentials = new System.Net.NetworkCredential(Usuario, Password);
                    //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);
                    //setup login data
                    var offset      = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
                    var formContent = new FormUrlEncodedContent(new[]
                    {
                        //new KeyValuePair<string, string>("grant_type", "password"),
                        new KeyValuePair <string, string>("Id", "11601"),
                        new KeyValuePair <string, string>("TimeZone", offset.ToString()),
                        //new KeyValuePair<string, string>("Page", ""),
                    });

                    //send request
                    HttpResponseMessage responseMessage = await client.GetAsync("lastpositionreport?id=11601&timezone=" + offset.Hours.ToString());

                    responseJson = await responseMessage.Content.ReadAsStringAsync();

                    var result = JsonConvert.DeserializeObject <RootObject>(responseJson);

                    for (int i = 0; i < result.items.Count; i++)
                    {
                        //Consulta si ya existe la posicion, por si es repetida y no ha actualizado el equipo
                        string imei         = result.items[i].id.ToString();
                        string codigoevento = result.items[i].status.ToString();

                        string lat      = result.items[i].position.latitude.ToString();
                        string lng      = result.items[i].position.longitude.ToString();
                        string evento   = result.items[i].status.ToString();
                        string odometro = result.items[i].odometer.ToString();
                        //string placas = ((dynamic)res[i]).Plates;
                        string velocidad = result.items[i].position.speed.ToString();
                        string bateria   = "";
                        try
                        {
                            bateria = result.items[i].batteryPercentage == null ? "0" : result.items[i].batteryPercentage.ToString();
                        }
                        catch (Exception Ex)
                        {
                            bateria = "";
                        }

                        int    index             = result.items[i].position.orientation.ToString().IndexOf("°");
                        string direccion         = (index > 0 ? result.items[i].position.orientation.ToString().Substring(0, index) : "0");
                        string fechahoragps      = result.items[i].position.gps_date + " " + result.items[i].position.gps_time;
                        string fechahoraservidor = result.items[i].date + " " + result.items[i].time;

                        //Validaciones

                        ////Conversiones de datos
                        //codigoevento = codigoevento;
                        //evento = evento;
                        var LAT      = decimal.Parse(lat);
                        var LNG      = decimal.Parse(lng);
                        var ODOMETRO = int.Parse(odometro);
                        //var PLACAS = System.Text.RegularExpressions.Regex.Replace(placas, "-", "");
                        //PLACAS = System.Text.RegularExpressions.Regex.Replace(PLACAS, " ", "");
                        var VELOCIDAD = int.Parse(velocidad);
                        var DIRECCION = int.Parse(direccion);
                        var BATERIA   = int.Parse(bateria);
                        //string[] formats = { "M/dd/yyyy hh:mm:ss tt" };
                        //var dateTime = DateTime.ParseExact(fechahora, formats, new System.Globalization.CultureInfo("en-US"), System.Globalization.DateTimeStyles.None);
                        var dateTimegps = DateTime.ParseExact(fechahoragps, "M/d/yyyy h:m tt", CultureInfo.InvariantCulture);
                        dateTimegps = dateTimegps.ToUniversalTime();
                        var dateTimeservidor = DateTime.ParseExact(fechahoraservidor, "M/d/yyyy h:m:ss tt", CultureInfo.InvariantCulture);
                        dateTimeservidor = dateTimeservidor.ToUniversalTime();

                        //Si no es repetida la inserta
                        List <WS_GPS_InsertaSimple_Result> WS_GPS_InsertaSimple;

                        WS_CONTEXT db = new WS_CONTEXT();

                        WS_GPS_InsertaSimple = db.WS_GPS_InsertaSimple(UsuarioReC, imei, codigoevento, LAT, LNG, "", true, VELOCIDAD, DIRECCION, BATERIA, ODOMETRO, dateTimegps, dateTimeservidor).ToList();
                        if (WS_GPS_InsertaSimple[0].Indicador == 1)
                        {
                        }
                        else
                        {
                            log.Error("Error al Insertar evento de " + UsuarioReC + ". " + WS_GPS_InsertaSimple[0].Mensaje + ". " + responseJson);
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                if (Ex.Message == "'System.Dynamic.ExpandoObject' no contiene una definición para 'Latitude'.")
                {
                    //No guarda nada en el log por que aveces no viene completa la trama
                }
                else
                {
                    log.Error("Error REESER_ObtenerPosicion: " + UsuarioReC + ". " + responseJson + ". " + Ex.Message);
                }
            }
        }