Пример #1
0
        private void BindGrid()
        {
            using (ChevacaDB context = new ChevacaDB())
            {
                hdnUsuariosCount.Value = context.usuarios.Count().ToString();
                if (context.usuarios.Count() > 0)
                {
                    gridUsuarios.DataSource = context.usuarios.ToList();
                    gridUsuarios.DataBind();
                }
                else
                {
                    var obj = new List <usuarios>();
                    obj.Add(new usuarios());
                    // Bind the DataTable which contain a blank row to the GridView
                    gridUsuarios.DataSource = obj;
                    gridUsuarios.DataBind();
                    int columnsCount = gridUsuarios.Columns.Count;
                    gridUsuarios.Rows[0].Cells.Clear();                      // clear all the cells in the row
                    gridUsuarios.Rows[0].Cells.Add(new TableCell());         //add a new blank cell
                    gridUsuarios.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell

                    //You can set the styles here
                    gridUsuarios.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
                    gridUsuarios.Rows[0].Cells[0].ForeColor       = System.Drawing.Color.Red;
                    gridUsuarios.Rows[0].Cells[0].Font.Bold       = true;
                    //set No Results found to the new added cell
                    gridUsuarios.Rows[0].Cells[0].Text = "No hay registros";
                }
                ScriptManager.RegisterStartupScript(this, typeof(Page), "updateCounts", "updateCounts();", true);
            }
        }
Пример #2
0
        public static List <_Log_Devices> Get_DB_Devices()
        {
            List <_Log_Devices> _Log_Devices_list = new List <_Log_Devices>();

            // Logger variables
            System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            string className  = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
            string methodName = stackFrame.GetMethod().Name;

            using (ChevacaDB context = new ChevacaDB())
            {
                // Hago este pasaje de logs_API a log_Devices para tener más control sobre los datos a futuro.
                string          empty_dataint     = "0";
                List <logs_API> logs_API_elements = context.logs_API.Where(v => !v.Altitud.Equals(empty_dataint)).GroupBy(v => v.Nodo).Select(v => v.FirstOrDefault()).OrderByDescending(v => v.Fecha).ToList();
                foreach (logs_API _logs_API in logs_API_elements)
                {
                    if (_logs_API != null)
                    {
                        _Log_Devices _Log_Devices1 = new _Log_Devices();
                        _Log_Devices1.Log_API_ID = _logs_API.Log_API_ID;
                        _Log_Devices1.LastUpdate = _logs_API.Fecha;
                        _Log_Devices1.Gateway    = _logs_API.Gateway;
                        _Log_Devices1.Nodo       = _logs_API.Nodo;
                        _Log_Devices1.Altitud    = _logs_API.Altitud;
                        _Log_Devices1.Hdop       = _logs_API.Hdop;
                        _Log_Devices1.Latitud    = _logs_API.Latitud;
                        _Log_Devices1.Longitud   = _logs_API.Longitud;

                        _Log_Devices_list.Add(_Log_Devices1);
                    }
                } // foreach
            }
            return(_Log_Devices_list);
        }
Пример #3
0
        protected void gridUsuarios_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            // Logger variables
            System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            string className  = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
            string methodName = stackFrame.GetMethod().Name;


            int Usuario_ID = Convert.ToInt32(gridUsuarios.DataKeys[e.RowIndex].Value);

            using (ChevacaDB context = new ChevacaDB())
            {
                usuarios obj = context.usuarios.First(x => x.Usuario_ID == Usuario_ID);
                context.usuarios.Remove(obj);
                context.SaveChanges();

                #region Guardar log
                try
                {
                    string userID1  = HttpContext.Current.Session["UserID"].ToString();
                    string username = HttpContext.Current.Session["UserName"].ToString();
                    Global_Objects.Logs.AddUserLog("Borra usuarios", obj.GetType().Name + ": " + obj.Usuario_ID, userID1, username);
                }
                catch (Exception ex)
                {
                    Global_Objects.Logs.AddErrorLog("Excepcion. Guardando log. ERROR:", className, methodName, ex.Message);
                }
                #endregion

                BindGrid();
                lblMessage.Text = "Borrado correctamente.";
            }
        }
Пример #4
0
        public static void AddUserLog(string message, string object_ID, string userID_str, string username, string IP_client = "")
        {
            // Logger variables
            System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            string className  = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
            string methodName = stackFrame.GetMethod().Name;

            using (ChevacaDB context = new ChevacaDB())
            {
                logs _logs = new logs();
                _logs.Fecha_creado  = GlobalVariables.GetCurrentTime();
                _logs.Usuario       = username;
                _logs.Descripcion   = message;
                _logs.Dato_afectado = object_ID;
                _logs.IP_client     = IP_client;

                int userID = 0;
                if (!string.IsNullOrWhiteSpace(userID_str))
                {
                    if (!int.TryParse(userID_str, out userID))
                    {
                        userID = 0;
                        AddErrorLog("Excepcion. Convirtiendo int. ERROR:", className, methodName, userID_str);
                    }
                }

                _logs.Usuario_ID = userID;
                context.logs.Add(_logs);
                context.SaveChanges();
            }
        }
Пример #5
0
        public string SayHello()
        {
            // Logger variables
            System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            string className         = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
            string methodName        = stackFrame.GetMethod().Name;
            string exception_message = string.Empty;

            using (ChevacaDB context = new ChevacaDB())
            {
                try
                {
                    logs_API _log_API = new logs_API();
                    _log_API.Fecha  = DateTime.Now;
                    _log_API.Metodo = "SayHello:GET";

                    context.logs_API.Add(_log_API);
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Logs.AddErrorLog("Excepcion. Usando API HttpPost. ERROR:", className, methodName, ex.Message);
                }
            }
            return("Hello from GMaps Controller");
        }
Пример #6
0
        protected void gridOvejas_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            // Logger variables
            System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            string className  = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
            string methodName = stackFrame.GetMethod().Name;

            GridViewRow row  = gridOvejas.Rows[e.RowIndex];
            TextBox     txb1 = row.FindControl("txb1") as TextBox;
            TextBox     txb2 = row.FindControl("txb2") as TextBox;
            TextBox     txb3 = row.FindControl("txb3") as TextBox;

            if (txb1 != null && txb2 != null && txb3 != null)
            {
                using (ChevacaDB context = new ChevacaDB())
                {
                    #region Update registro

                    //ovejas obj = (ovejas)(e.Row.DataItem);
                    int    id  = Convert.ToInt32(gridOvejas.DataKeys[e.RowIndex].Value);
                    ovejas obj = context.ovejas.FirstOrDefault(x => x.Oveja_ID == id);
                    if (obj != null)
                    {
                        obj.Nombre = txb1.Text;

                        int Estancia_ID = obj.Estancia_ID;
                        if (!int.TryParse(txb2.Text, out Estancia_ID))
                        {
                            Estancia_ID = obj.Estancia_ID;
                            Logs.AddErrorLog("Excepcion. Convirtiendo int. ERROR:", className, methodName, txb2.Text);
                        }
                        obj.Estancia_ID = Estancia_ID;

                        context.SaveChanges();
                    }

                    #endregion

                    context.SaveChanges();

                    #region Save log
                    try
                    {
                        string userID1  = HttpContext.Current.Session["UserID"].ToString();
                        string username = HttpContext.Current.Session["UserName"].ToString();
                        Global_Objects.Logs.AddUserLog("Modifica ovejas", obj.GetType().Name + ": " + obj.Oveja_ID, userID1, username);
                    }
                    catch (Exception ex)
                    {
                        Global_Objects.Logs.AddErrorLog("Excepcion. Guardando log. ERROR:", className, methodName, ex.Message);
                    }
                    #endregion

                    lblMessage.Text      = "Guardado correctamente.";
                    gridOvejas.EditIndex = -1;
                    BindGrid();
                }
            }
        }
Пример #7
0
        public HttpResponseMessage Post([FromBody] JSON_Body _objectJSON)
        {
            try
            {
                // Logger variables
                System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
                System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
                string className         = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
                string methodName        = stackFrame.GetMethod().Name;
                string exception_message = string.Empty;

                using (ChevacaDB context = new ChevacaDB())
                {
                    logs_API _log_API = new logs_API();
                    _log_API.Fecha   = GlobalVariables.GetCurrentTime();
                    _log_API.Gateway = _objectJSON.applicationName;
                    _log_API.Nodo    = _objectJSON.deviceName;
                    _log_API.Metodo  = "Post";
                    _log_API.Body    = _objectJSON.ToString();

                    if (!string.IsNullOrWhiteSpace(_objectJSON.objectJSON))
                    {
                        _log_API.JSON = _objectJSON.objectJSON;
                        JSON_Body_Data _JSON_Body_Data = JsonConvert.DeserializeObject <JSON_Body_Data>(_objectJSON.objectJSON);
                        if (_JSON_Body_Data != null)
                        {
                            _log_API.Altitud  = _JSON_Body_Data.alt;
                            _log_API.Hdop     = _JSON_Body_Data.hdop;
                            _log_API.Latitud  = _JSON_Body_Data.lat;
                            _log_API.Longitud = _JSON_Body_Data.lon;
                        }
                        else
                        {
                            Logs.AddErrorLog("Excepcion. No pudo crear el JSON:", className, methodName, "");
                        }
                    }
                    try
                    {
                        context.logs_API.Add(_log_API);
                        context.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        Logs.AddErrorLog("Excepcion. Usando API HttpPost y guardando en BD. ERROR:", className, methodName, ex.Message);
                    }
                }
                var message = Request.CreateResponse(System.Net.HttpStatusCode.Created, "OK");
                message.Headers.Location = new Uri(Request.RequestUri + "Post");
                return(message);
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, ex));
            }
        }
Пример #8
0
        public static void AddErrorLog(string message, string className, string methodName, string obj, [CallerLineNumber] int numberNumber = 0)
        {
            try
            {
                string Path_Data = @"Logs\";
                if (ConfigurationManager.AppSettings != null)
                {
                    Path_Data = ConfigurationManager.AppSettings["Path_Log"].ToString();
                }

                string File_ErrorLog = "error_log.txt";
                if (ConfigurationManager.AppSettings != null)
                {
                    File_ErrorLog = ConfigurationManager.AppSettings["File_ErrorLog"].ToString();
                }

                string path_complete = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path_Data);
                if (!Directory.Exists(Path.GetDirectoryName(path_complete)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path_complete));
                }

                using (StreamWriter writer = new StreamWriter(path_complete + "/" + File_ErrorLog, true))
                {
                    string text = DateTime.Now.ToString() + ": [ln:" + numberNumber + "] " + className + ": " + methodName + "() - " + message + " " + obj + ".";
                    writer.WriteLine(text);
                }

                using (ChevacaDB context = new ChevacaDB())
                {
                    logs _logs = new logs();
                    _logs.Usuario_ID    = 0;
                    _logs.Fecha_creado  = GlobalVariables.GetCurrentTime();
                    _logs.Usuario       = "Externo";
                    _logs.IP_client     = "N/D";
                    _logs.Descripcion   = message + "|" + obj;
                    _logs.Dato_afectado = "N/D";

                    context.logs.Add(_logs);
                    context.SaveChanges();
                }
            }
            catch (Exception) { }
        }
Пример #9
0
        protected void gridUsuarios_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            // Logger variables
            System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            string className  = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
            string methodName = stackFrame.GetMethod().Name;

            if (e.CommandName == "InsertNew")
            {
                GridViewRow row  = gridUsuarios.FooterRow;
                TextBox     txb1 = row.FindControl("txbNew1") as TextBox;
                TextBox     txb2 = row.FindControl("txbNew2") as TextBox;
                TextBox     txb3 = row.FindControl("txbNew3") as TextBox;

                if (txb1 != null && txb2 != null && txb3 != null)
                {
                    if (!string.IsNullOrWhiteSpace(txb1.Text) && !string.IsNullOrWhiteSpace(txb2.Text))
                    {
                        using (ChevacaDB context = new ChevacaDB())
                        {
                            usuarios obj = new usuarios();
                            obj.Usuario = txb1.Text;
                            obj.Clave   = txb2.Text;

                            int Rol_usuario_ID = 0;
                            if (!int.TryParse(txb3.Text, out Rol_usuario_ID))
                            {
                                Rol_usuario_ID = 0;
                                Logs.AddErrorLog("Excepcion. Convirtiendo int. ERROR:", className, methodName, txb3.Text);
                            }
                            obj.Rol_usuario_ID = Rol_usuario_ID;

                            context.usuarios.Add(obj);
                            context.SaveChanges();

                            #region Guardar log
                            try
                            {
                                int      id       = 1;
                                usuarios usuarios = (usuarios)context.usuarios.OrderByDescending(p => p.Usuario_ID).FirstOrDefault();
                                if (usuarios != null)
                                {
                                    id = usuarios.Usuario_ID;
                                }

                                string userID1  = HttpContext.Current.Session["UserID"].ToString();
                                string username = HttpContext.Current.Session["UserName"].ToString();
                                Global_Objects.Logs.AddUserLog("Agrega usuarios", usuarios.GetType().Name + ": " + id, userID1, username);
                            }
                            catch (Exception ex)
                            {
                                Global_Objects.Logs.AddErrorLog("Excepcion. Guardando log. ERROR:", className, methodName, ex.Message);
                            }
                            #endregion

                            lblMessage.Text = "Agregado correctamente.";
                            BindGrid();
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('Por favor ingrese el Nombre');", true);
                    }
                }
            }
            else if (e.CommandName == "View")
            {
                string[] values = e.CommandArgument.ToString().Split(new char[] { ',' });
                if (values.Length > 1)
                {
                    string tabla = values[0];
                    string dato  = values[1];
                    if (!string.IsNullOrWhiteSpace(tabla) && !string.IsNullOrWhiteSpace(dato))
                    {
                        Response.Redirect("Listados.aspx?tabla=" + tabla + "&dato=" + dato);
                    }
                }
            }
            else
            {
                //BindGrid();
            }
        }
Пример #10
0
        private void BindGridLogs(string date_start = "", string date_end = "")
        {
            using (ChevacaDB context = new ChevacaDB())
            {
                // Logger variables
                System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
                System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
                string className  = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
                string methodName = stackFrame.GetMethod().Name;

                bool isResult = false;

                if (!string.IsNullOrWhiteSpace(date_start) && !string.IsNullOrWhiteSpace(date_end))
                {
                    DateTime date1 = DateTime.Now;
                    if (!DateTime.TryParseExact(date_start, GlobalVariables.ShortDateTime_format1, CultureInfo.InvariantCulture, DateTimeStyles.None, out date1))
                    {
                        date1 = DateTime.Now;
                        Logs.AddErrorLog("Excepcion. Convirtiendo datetime. ERROR:", className, methodName, date_start);
                    }

                    DateTime date2 = DateTime.Now;
                    if (!DateTime.TryParseExact(date_end, GlobalVariables.ShortDateTime_format1, CultureInfo.InvariantCulture, DateTimeStyles.None, out date2))
                    {
                        date2 = DateTime.Now;
                        Logs.AddErrorLog("Excepcion. Convirtiendo datetime. ERROR:", className, methodName, date_end);
                    }

                    var elements = context.logs.Where(e => e.Fecha_creado >= date1 && e.Fecha_creado <= date2).OrderByDescending(e => e.Fecha_creado).ToList();
                    if (elements.Count() > 0)
                    {
                        gridLogs.DataSource = elements;
                        gridLogs.DataBind();

                        isResult = true;
                    }
                }
                else
                {
                    var elements = context.logs.OrderByDescending(e => e.Fecha_creado).ToList();
                    if (elements.Count() > 0)
                    {
                        gridLogs.DataSource = elements;
                        gridLogs.DataBind();

                        isResult = true;
                    }
                }

                if (!isResult)
                {
                    var obj = new List <logs>();
                    obj.Add(new logs());

                    /* Grid Viajes */

                    // Bind the DataTable which contain a blank row to the GridView
                    gridLogs.DataSource = obj;
                    gridLogs.DataBind();
                    int columnsCount = gridLogs.Columns.Count;
                    gridLogs.Rows[0].Cells.Clear();                      // clear all the cells in the row
                    gridLogs.Rows[0].Cells.Add(new TableCell());         //add a new blank cell
                    gridLogs.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell

                    //You can set the styles here
                    gridLogs.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
                    gridLogs.Rows[0].Cells[0].ForeColor       = System.Drawing.Color.Red;
                    gridLogs.Rows[0].Cells[0].Font.Bold       = true;

                    //set No Results found to the new added cell
                    gridLogs.Rows[0].Cells[0].Text = "No hay registros";
                }

                gridLogs.UseAccessibleHeader    = true;
                gridLogs.HeaderRow.TableSection = TableRowSection.TableHeader;
            }
        }
Пример #11
0
        private void Perform_login(string username, string password, bool isPasswordInput_hashed = false)
        {
            // Logger variables
            System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            string className         = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
            string methodName        = stackFrame.GetMethod().Name;
            string exception_message = string.Empty;

            int resultado = 0;

            if (!string.IsNullOrWhiteSpace(username) || !string.IsNullOrWhiteSpace(password))
            {
                using (ChevacaDB context = new ChevacaDB())
                {
                    try
                    {
                        string IP_client = Logs.GetIPAddress();

                        context.Database.Connection.Open();
                        usuarios _usuario = (usuarios)context.usuarios.FirstOrDefault(v => v.Usuario == username && v.Clave == password);
                        if (_usuario != null)
                        {
                            Session["UserID"]   = _usuario.Usuario_ID;
                            Session["UserName"] = username;

                            #region Guardar log
                            try
                            {
                                string userID1 = _usuario.Usuario_ID.ToString();
                                Logs.AddUserLog("OK: Acceso al sistema correcto con contraseña: '" + password + "'.", "", userID1, username, IP_client);
                            }
                            catch (Exception ex)
                            {
                                Logs.AddErrorLog("Excepcion. Guardando log. ERROR:", className, methodName, ex.Message);
                            }
                            #endregion

                            Response.Redirect("/Pages/Datos", false);
                        }
                        else
                        {
                            // No se pudo autenticar
                            resultado = 2;
                            Logs.AddUserLog("ERROR: Intento de acceso al sistema con contraseña: '" + password + "'.", "", "-", username, IP_client);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logs.AddErrorLog("Excepcion. Haciendo login. ERROR:", className, methodName, ex.Message);
                        exception_message = ex.Message;
                        resultado         = 3;
                    }
                }
            }
            else
            {
                resultado = 1;
            }

            ScriptManager.RegisterStartupScript(this, typeof(Page), "ShowErrorMessage", "ShowErrorMessage('" + resultado + "', '" + exception_message + "');", true);
        }