Esempio n. 1
0
        /// <summary>
        /// Samuel Serrano Guerra
        /// Método que retorna la llave de un proveeddor específico
        /// </summary>
        /// <param name="idProveedor"></param>
        /// <returns>objeto de tipo Llave</returns>
        public Llave llaveActiva(int idProveedor)
        {
            Llave llave = null;

            using (NpgsqlConnection con = conexion.GetConexion())
            {
                con.Open();
                string sql = "SELECT * FROM products.pa_get_llave_proveedor(@idProveedor)";


                using (var command = new NpgsqlCommand(sql, con))
                {
                    command.Parameters.AddWithValue("@idProveedor", idProveedor);


                    using (NpgsqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            llave = new Llave(reader.GetInt32(0),
                                              reader.GetString(1),
                                              proveedorDatos.buscarProveedor(reader.GetInt32(2)),
                                              reader.GetDateTime(3));
                        }
                    }
                }
            }

            return(llave);
        }
        public HttpResponseMessage UpdateConfirmar([FromBody] Llave llave)
        {
            HttpResponseMessage msg = null;

            try
            {
                if (llave == null)
                {
                    msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "NOTFOUND");
                }
                else
                {
                    if (LlaveBRL.ConfirmaRecibido(llave) == true)
                    {
                        msg = Request.CreateResponse(HttpStatusCode.OK, "OK");
                    }
                    else
                    {
                        msg = Request.CreateResponse(HttpStatusCode.OK, "RPT");
                    }
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "ERROR" + e);
                return(msg);
            }
            return(msg);
        }
        public async Task <ActionResult> RecibirLlave()
        {
            ReciboDatoLlave dato      = new ReciboDatoLlave();
            Llave           respuesta = await dato.recibirLlave();

            return(View(respuesta));
        }
Esempio n. 4
0
 public static void UpdateLlave(Llave llave)
 {
     if (llave == null)
     {
         throw new ArgumentException("Valores no validos confirmado Recibido");
     }
     DAL.LlaveDSTableAdapters.LlaveTableAdapter adapter = new DAL.LlaveDSTableAdapters.LlaveTableAdapter();
     adapter.Update(llave.Nick, llave.Estado, llave.Tipo, llave.HoraInicio, llave.HoraFin, llave.FechaInicio, llave.FechaFin, llave.Dias, llave.Nombre, llave.ActHora, llave.ActDias, llave.LlaveId);
 }
Esempio n. 5
0
        private void BtnLllave_Click(object sender, RoutedEventArgs e)
        {
            var ruta = Herramientas.Herramientas.obtenerRutaDialogo("*.json|", false, "Seleccione un archivo JSON");

            if (ruta.Count > 0)
            {
                string directorio = Path.GetDirectoryName(ruta[0]);
                string archivo    = Path.GetFileName(ruta[0]);
                llave = LlaveJson.ObtenerLlave(directorio, archivo);
            }
        }
Esempio n. 6
0
        public bool Under()
        {
            int con = 0;

            for (int i = 0; i < Grado; i++)
            {
                if (Llave.ElementAt(i) == null)
                {
                    con++;
                }
            }
            return(con == 0);
        }
Esempio n. 7
0
    private void OnTriggerEnter2D(Collider2D collision)
    {
        //Cuando el jugador colisiona con la llave ponemos tieneLlave a true
        //Activamos la imagen de la llave en la UI del jugador correspondiente
        //Y destruimos la llave
        Llave llave = collision.gameObject.GetComponent <Llave>();

        if (llave != null)
        {
            GameManager.instance.EjecutarSonido("Llave", 3);
            tieneLlave = llave.CogeLlave();
            GameManager.instance.ActualizarLlave(jugador, true);
            Destroy(llave.gameObject);
        }
    }
Esempio n. 8
0
        private static Llave GetLlaveFromRow(LlaveDS.LlaveRow row)
        {
            Llave llave = new Llave();

            llave.LlaveId  = row.LlaveId;
            llave.Codigo   = row.Codigo;
            llave.Estado   = row.Estado;
            llave.Nick     = row.IsNickNull() ? "" : row.Nick;
            llave.AlarmaId = row.AlarmaId;
            llave.Tipo     = row.Tipo == null ? "T" : row.Tipo;
            llave.ActHora  = row.IsActHoraNull() ? 0 : row.ActHora;
            llave.ActDias  = row.IsActDiasNull() ? 0 : row.ActDias;
            // Estado: 0 = desactivado ; 1 = activado ; 2 = cancelado ;
            // Tipo: T = temporal ; P = permanente ;
            if (llave.Tipo.Equals("P"))
            {
                if (llave.ActHora == 1)
                {
                    llave.HoraInicio = row.IsHoraInicioNull() ? TimeSpan.MinValue : row.HoraInicio;
                    llave.HoraFin    = row.IsHoraFinNull() ? TimeSpan.MaxValue : row.HoraFin;
                }
                if (llave.ActDias == 1)
                {
                    llave.Dias = row.IsDiasNull() ? "" : row.Dias;
                }
            }
            if (llave.Tipo.Equals("T"))
            {
                if (llave.ActHora == 1)
                {
                    llave.HoraInicio = row.IsHoraInicioNull() ? TimeSpan.MinValue : row.HoraInicio;
                    llave.HoraFin    = row.IsHoraFinNull() ? TimeSpan.MaxValue : row.HoraFin;
                }
                if (llave.ActDias == 1)
                {
                    llave.Dias = row.IsDiasNull() ? "" : row.Dias;
                }
                llave.FechaInicio = row.IsFechaInicioNull() ? DateTime.MinValue : row.FechaInicio;
                llave.FechaFin    = row.IsFechaFinNull() ? DateTime.MinValue : row.FechaFin;
            }

            if (llave.Estado == 1 || llave.Estado == 2)
            {
                llave.Nombre    = row.IsNombreNull() ? "" : row.Nombre;
                llave.UsuarioId = row.IsUsuarioIdNull() ? 0 : row.UsuarioId;
            }
            return(llave);
        }
Esempio n. 9
0
        public static Llave GetLlaveByLlaveId(int LlaveId)
        {
            if (LlaveId <= 0)
            {
                throw new ArgumentException("Valores no validos Llave por llaveId");
            }

            DAL.LlaveDSTableAdapters.LlaveTableAdapter adapter = new DAL.LlaveDSTableAdapters.LlaveTableAdapter();
            LlaveDS.LlaveDataTable table = adapter.GetLlaveByLlaveId(LlaveId);
            if (table.Rows.Count == 0)
            {
                return(null);
            }

            Llave llave = GetLlaveFromRow(table[0]);

            return(llave);
        }
Esempio n. 10
0
        public static Llave GetLlaveByCodigo(string Codigo)
        {
            if (string.IsNullOrEmpty(Codigo))
            {
                throw new ArgumentException("Valores no validos Llave por Codigo");
            }

            DAL.LlaveDSTableAdapters.LlaveTableAdapter adapter = new DAL.LlaveDSTableAdapters.LlaveTableAdapter();
            LlaveDS.LlaveDataTable table = adapter.GetLlaveByCodigo(Codigo);
            if (table.Rows.Count == 0)
            {
                return(null);
            }

            Llave llave = GetLlaveFromRow(table[0]);

            return(llave);
        }
Esempio n. 11
0
        public static void InsertarLlave(Llave llave)
        {
            int?llaveId = 0;

            if (llave == null)
            {
                throw new ArgumentException("Llave Vacia");
            }

            DAL.LlaveDSTableAdapters.LlaveTableAdapter adapter = new DAL.LlaveDSTableAdapters.LlaveTableAdapter();
            if (llave.Tipo.Equals("T"))
            {
                adapter.InsertLlaveTemporal(llave.Codigo, llave.Estado, llave.Tipo, llave.Nick, llave.HoraInicio, llave.HoraFin, llave.FechaInicio, llave.FechaFin, llave.AlarmaId, llave.Dias, llave.ActHora, llave.ActDias, ref llaveId);
            }
            else
            {
                adapter.Insert(llave.Codigo, llave.Estado, llave.Tipo, llave.Nick, llave.AlarmaId, llave.HoraInicio, llave.HoraFin, llave.Dias, llave.ActHora, llave.ActDias, ref llaveId);
            }
        }
Esempio n. 12
0
        public static List <Llave> GetLlavesPorAlarma(int AlarmaId)
        {
            if (AlarmaId <= 0)
            {
                throw new ArgumentException("Valores no validos llaves prestadas");
            }

            DAL.LlaveDSTableAdapters.LlaveTableAdapter adapter = new DAL.LlaveDSTableAdapters.LlaveTableAdapter();
            LlaveDS.LlaveDataTable table = adapter.GetLlavesPorAlarma(AlarmaId);

            List <Llave> llaves = new List <Llave>();

            foreach (LlaveDS.LlaveRow row in table)
            {
                Llave llave = GetLlaveFromRow(row);
                llaves.Add(llave);
            }
            return(llaves);
        }
Esempio n. 13
0
        public static List <Llave> GetLlavesPropias(int UsuarioID)
        {
            if (UsuarioID <= 0)
            {
                throw new ArgumentException("Valores no validos llaves propias");
            }

            DAL.LlaveDSTableAdapters.LlaveTableAdapter adapter = new DAL.LlaveDSTableAdapters.LlaveTableAdapter();
            LlaveDS.LlaveDataTable table = adapter.GetLlavesPropietario(UsuarioID);

            List <Llave> llaves = new List <Llave>();

            foreach (LlaveDS.LlaveRow row in table)
            {
                Llave llave = GetLlaveFromRow(row);
                llaves.Add(llave);
            }
            return(llaves);
        }
Esempio n. 14
0
        private static void Init()
        {
            IAuto  entAuto    = new Auto();
            ILlave entLlave   = new Llave();
            IAuto  CocheProxy = new AutoProxy(entAuto, entLlave);
            string cLlave     = string.Empty;

            do
            {
                Console.Write("Capturar el codigo de la llave:\n");
                cLlave          = Console.ReadLine();
                entLlave.cLlave = cLlave;
                if (!CocheProxy.EncenderAuto())
                {
                    Console.WriteLine("Llave Incorrecta.");
                }
            }while (cLlave != "449955");

            Console.ReadLine();
        }
Esempio n. 15
0
        /// <summary>
        /// Samuel Serrano Guerra
        /// Método que crea en la BD una llave para un proveedor
        /// </summary>
        /// <param name="idProveedor"></param>
        public void crearLlave(int idProveedor)
        {
            string cod   = (idProveedor * 7 + 5 * 143 - 3) + "trhdJHYGVhtrfc";
            string hash  = cod.GetHashCode().ToString() + "salllave";
            Llave  llave = new Llave(hash, proveedorDatos.buscarProveedor(idProveedor), DateTime.Now.AddDays(3));

            using (NpgsqlConnection con = conexion.GetConexion())
            {
                con.Open();
                string sql = "CALL products.pa_crear_llave(@idProveedor,@llave,@fechaVencimiento);";

                using (var command = new NpgsqlCommand(sql, con))
                {
                    command.Parameters.AddWithValue("@idProveedor", idProveedor);
                    command.Parameters.AddWithValue("@llave", llave.CodLlave);
                    command.Parameters.AddWithValue("@fechaVencimiento", llave.FechaVencimiento);

                    command.ExecuteNonQuery();
                }
            }
        }
Esempio n. 16
0
        public static bool ConfirmaRecibido(Llave llave)
        {
            if (llave == null)
            {
                throw new ArgumentException("Valores no validos confirmado Recibido");
            }

            bool         existe = false;
            List <Llave> llaves = GetLlavesObtenidas(llave.UsuarioId);
            Alarma       alarma = AlarmaBRL.GetAlarmaByID(llave.AlarmaId);

            if (llave.UsuarioId == alarma.UsuarioID)
            {
                existe = true;
            }
            else
            {
                foreach (var key in llaves)
                {
                    if (llave.AlarmaId == key.AlarmaId)
                    {
                        existe = true;
                    }
                }
            }


            if (!existe)
            {
                DAL.LlaveDSTableAdapters.LlaveTableAdapter adapter = new DAL.LlaveDSTableAdapters.LlaveTableAdapter();
                adapter.UpdateConfirmarRecibido(llave.UsuarioId, llave.Nombre, llave.Codigo);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 17
0
        public HttpResponseMessage GetLlavesPrestadas([FromBody] Llave llave)
        {
            HttpResponseMessage msg = null;

            try
            {
                List <Llave> llaves = LlaveBRL.GetLlavesPrestadas(llave.AlarmaId, llave.UsuarioId);
                if (llaves == null)
                {
                    msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "NOTFOUND");
                }
                else
                {
                    msg = Request.CreateResponse(HttpStatusCode.OK, llaves);
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "ERROR" + e);
                return(msg);
            }
            return(msg);
        }
Esempio n. 18
0
        public HttpResponseMessage GetLlaveByLlaveId(string LlaveId)
        {
            HttpResponseMessage msg = null;

            try
            {
                Llave llave = LlaveBRL.GetLlaveByLlaveId(Int32.Parse(LlaveId));
                if (llave == null)
                {
                    msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "NOTFOUND");
                }
                else
                {
                    msg = Request.CreateResponse(HttpStatusCode.OK, llave);
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "ERROR" + e);
                return(msg);
            }
            return(msg);
        }
Esempio n. 19
0
        public HttpResponseMessage Update([FromBody] Llave llave)
        {
            HttpResponseMessage msg = null;

            try
            {
                if (llave == null)
                {
                    msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "NOTFOUND");
                }
                else
                {
                    LlaveBRL.UpdateLlave(llave);
                    msg = Request.CreateResponse(HttpStatusCode.OK, "OK");
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "ERROR" + e);
                return(msg);
            }
            return(msg);
        }
Esempio n. 20
0
        public HttpResponseMessage InserLlave(Llave llave)
        {
            HttpResponseMessage msg = null;

            try
            {
                if (llave == null /*String.IsNullOrEmpty(Codigo) | String.IsNullOrEmpty(Estado) | String.IsNullOrEmpty(Tipo) | String.IsNullOrEmpty(Nick) | String.IsNullOrEmpty(AlarmaId)*/)
                {
                    msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "NOTFOUND");
                }
                else
                {
                    LlaveBRL.InsertarLlave(llave);
                    msg = Request.CreateResponse(HttpStatusCode.OK, "OK");
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "ERROR" + e);
                return(msg);
            }
            return(msg);
        }
Esempio n. 21
0
        private bool validaLlaveMaestra(string TipoUsuario, string userDesencriptado, string Pass_Desencriptado)
        {
            try
            {
                string respuesta = string.Empty;
                try
                {
                    if (isNumeric(TipoUsuario))
                    {
                        respuesta = Llave.validaEmpleado(userDesencriptado, Pass_Desencriptado);
                    }
                    else
                    {
                        respuesta = Llave.validaEmpleado(UsuarioTVA, Pass_Desencriptado);
                    }
                    xml.LoadXml(respuesta);
                }
                catch (Exception ex)
                {
                    THE_LogErrores oLogErrores = new THE_LogErrores();
                    TDI_EMPL       oEmpl       = new TDI_EMPL();
                    oEmpl.EmpleadoLlavePrimaria = int.Parse(UsuarioTVA.Replace("TVA", "").Replace("PTV", ""));
                    oLogErrores.CveEmpleado     = oEmpl;
                    oLogErrores.DirIP           = IPUsr;
                    oLogErrores.Error           = ex.Message + "\n" + ex.StackTrace.ToString();
                    oLogErrores.Pantalla        = "Default.aspx";
                    oLogErrores.MachineName     = "";
                    oLogErrores.FechaCreacion   = DateTime.Now;
                    oLogErrores.Dominio         = Request.Url.Host.ToLower();
                    MngNegocioLogErrores.GuardarLogErrores(oLogErrores);
                }

                if ((respuesta.IndexOf("Respuesta=\"[OK]\"") != -1))
                {
                    //Aqui se debe de mandar a validar si el usuario esta bloqueado por Intentos fallidos
                    IList <THE_BloqueoUsuario> UserBlockInactivo = MngNegocioBloqueoUsuario.ConsultaUsuarioBloqueadoXIdUsuario(usuario.ToUpper().ToString(), "2");
                    if (UserBlockInactivo.Count > 0)
                    {
                        //El Usuario ya ha sido bloqueado
                        string strMessage = string.Empty;
                        strMessage += strMessage == string.Empty ? "" : "<br>";
                        strMessage += " * El Usuario ha sido bloqueado por : " + UserBlockInactivo[0].TipoBloqueo.DescTipoBloqueo;
                        strMessage += "<br>";
                        strMessage += "Favor de Solicitar su desbloqueo por DATASEC";
                        Random random    = new Random();
                        int    NumMsgBox = random.Next(-999999999, 999999999);
                        ClientScript.RegisterStartupScript(Page.GetType(), "AlertBloqueoInactivo" + NumMsgBox, "<script>alert('El Usuario ha sido bloqueado por " + UserBlock[0].TipoBloqueo.DescTipoBloqueo + ". Para desbloquearlo deberá realizar la solicitud en DATASEC');</script>");
                        tdError.InnerHtml = strMessage;
                        tdError.Visible   = true;
                        txtUsuario.Text   = usuario;
                        GuardaLogAcceso(9);
                        return(false);
                    }

                    tdError.Visible   = false;
                    tdError.InnerHtml = "";

                    string      numeroUsuario = xml.FirstChild.ChildNodes[0].Attributes["NumEmp"].Value;
                    XmlDocument UserData      = MgnTDI_Menus.GetUserDataByNumEmpl(numeroUsuario, "", "1,2,5");

                    ObtieneDatosUsuario(UserData);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex) {
                return(false);
            }
            return(true);
        }
Esempio n. 22
0
    protected void registrarAlarma(object sender, EventArgs e)
    {
        String  codigoAlarma     = fcodigoAlarma.Text.Trim();
        String  nombreAlarma     = fnombreAlarma.Text.Trim();
        String  contrasenaAlarma = fcontrasenaAlarma.Text.Trim();
        Usuario user             = (Usuario)Session["USUARIO"];
        int     usuario          = user.UsuarioID;

        if (string.IsNullOrEmpty(codigoAlarma))
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('El campo del código de Alarma no debe quedar vacío')", true);
            return;
        }

        if (string.IsNullOrEmpty(nombreAlarma))
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('El campo del nombre de la Alarma no puede quedar vacío')", true);
            return;
        }

        if (string.IsNullOrEmpty(contrasenaAlarma))
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('El campo de la contraseña de la Alarma no puede quedar vacío')", true);
            return;
        }


        string AL_latitud  = latitudHidden.Value;
        string AL_longitud = longitudHidden.Value;

        if (string.IsNullOrEmpty(AL_latitud) || string.IsNullOrEmpty(AL_longitud))
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Error de Red, Asegurese de que el equipo tenga Conexión a INTERNET')", true);
            return;
        }



        if (id == 0)
        {
            Alarma alarma = AlarmaBRL.GetAlarmaByCodigo(codigoAlarma);

            if (alarma != null && alarma.UsuarioID == -1)
            {
                alarma.Alerta     = 0;
                alarma.UsuarioID  = usuario;
                alarma.Nombre     = nombreAlarma;
                alarma.Contrasena = contrasenaAlarma;
                alarma.Latitud    = AL_latitud;
                alarma.Longitud   = AL_longitud;
                AlarmaBRL.UpdateAlarma(alarma);
                Llave llave = new Llave();
                llave.Codigo   = contrasenaAlarma;
                llave.Estado   = 1;
                llave.Tipo     = "P";
                llave.Nick     = "Propietario";
                llave.AlarmaId = alarma.AlarmaId;
                LlaveBRL.InsertarLlave(llave);
                Response.Redirect("~/AlarmaConfiguracion.aspx");
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('El código de la alarma no es válido')", true);
                Response.Redirect("~/AlarmaConfiguracion.aspx");
            }
        }
        else
        {
            Alarma alarma2 = AlarmaBRL.GetAlarmaByID(id);
            if (alarma2 != null && alarma2.UsuarioID == usuario)
            {
                alarma2.Alerta     = 0;
                alarma2.UsuarioID  = usuario;
                alarma2.Nombre     = nombreAlarma;
                alarma2.Contrasena = contrasenaAlarma;
                alarma2.Latitud    = AL_latitud;
                alarma2.Longitud   = AL_longitud;
                AlarmaBRL.UpdateAlarma(alarma2);
                Response.Redirect("~/AlarmaConfiguracion.aspx");
            }
        }
    }
    protected void RegistrarLlave_Click(object sender, EventArgs e)
    {
        Usuario usuario = (Usuario)Session["USUARIO"];
        int     user    = 0;

        if (usuario == null)
        {
            Response.Redirect("../LlaveConfiguracion.aspx");
        }
        else
        {
            user = usuario.UsuarioID;
        }


        bool   permanente  = RadioButtonList1.Items[0].Selected;
        bool   temporal    = RadioButtonList1.Items[1].Selected;
        string nick1       = txtNick.Text;
        string fechaInicio = FechaInicioc.Value;
        string fechaFin    = FechaFinc.Value;

        if (permanente == false && temporal == false)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Debe seleccionar alguna opción de tipo de llave')", true);
            return;
        }
        if (string.IsNullOrEmpty(nick1))
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Debe ingresar el Nick')", true);
            return;
        }
        if (string.IsNullOrEmpty(fechaInicio))
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Debe ingresar el Nick')", true);
            return;
        }


        String        cod    = Guid.NewGuid().ToString().Substring(0, 10);
        List <Alarma> alarma = AlarmaBRL.GetAlarmaByIdUsuario(user);


        //Horario Inicio
        TimeSpan ts = TimeSpan.Parse(horaInicio.Value);

        //Horario Fin
        TimeSpan ts2 = TimeSpan.Parse(horaFin.Value);

        Llave llave = new Llave();

        if (permanente)
        {
            llave.Tipo        = "P";
            llave.AlarmaId    = alarma[0].AlarmaId;
            llave.Codigo      = cod;
            llave.Nick        = nick1;
            llave.FechaInicio = DateTime.Parse(fechaInicio);
            llave.FechaFin    = DateTime.Parse(fechaFin);
            llave.HoraInicio  = ts;
            llave.HoraFin     = ts2;
            llave.ActHora     = 1;
            llave.Estado      = 1;
        }

        if (temporal)
        {
            llave.Tipo        = "T";
            llave.Nombre      = "Temporal";
            llave.AlarmaId    = alarma[0].AlarmaId;
            llave.Codigo      = cod;
            llave.Nick        = nick1;
            llave.FechaInicio = DateTime.Parse(fechaInicio);
            llave.FechaFin    = DateTime.Parse(fechaFin);
            llave.HoraInicio  = ts;
            llave.HoraFin     = ts2;
            llave.ActHora     = 1;
            llave.ActDias     = 1;
            llave.Estado      = 1;
        }

        if (id == 0)
        {
            LlaveBRL.InsertarLlave(llave);
            Response.Redirect("~/LlaveConfiguracion.aspx");
        }
        else
        {
            llave.LlaveId = id;
            LlaveBRL.UpdateLlave(llave);
            Response.Redirect("~/LlaveConfiguracion.aspx");
        }
    }
Esempio n. 24
0
        protected void btnLogin_Click(object sender, ImageClickEventArgs e)
        {
            xml = new XmlDocument();
            DataSet ds = new DataSet();
            string  Pass_Desencriptado = "";

            IPUsr = ObtenerIPCliente();
            ViewState["IPUsr"] = IPUsr;
            Azteca.Utility.Security.Rijndael _ChyperRijndael = new Azteca.Utility.Security.Rijndael();
            try
            {
                try
                {
                    string ruta       = _ChyperRijndael.Transmute(ConfigurationManager.AppSettings["LlavePrivada"], Azteca.Utility.Security.enmTransformType.intDecrypt);
                    string Passphrase = "";
                    try
                    {
                        Passphrase = (string)Registry.LocalMachine.OpenSubKey(_ChyperRijndael.Transmute(ConfigurationSettings.AppSettings["Registro"], Azteca.Utility.Security.enmTransformType.intDecrypt)).GetValue("passphrase");
                    }
                    catch
                    {
                        //Esto es para Win 7 64 bits

                        RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
                        localKey   = localKey.OpenSubKey(_ChyperRijndael.Transmute(ConfigurationSettings.AppSettings["Registro"], Azteca.Utility.Security.enmTransformType.intDecrypt));
                        Passphrase = localKey.GetValue("passphrase").ToString();
                        localKey.Dispose();
                    }
                    StreamReader stream = new StreamReader(PGPUtil.DesencriptarTexto(txtContraseña.Text,
                                                                                     File.OpenRead(ruta),
                                                                                     null, Passphrase.ToCharArray()).Datos);
                    StreamReader streamUser = new StreamReader(PGPUtil.DesencriptarTexto(txtUsuario.Text,
                                                                                         File.OpenRead(ruta),
                                                                                         null, Passphrase.ToCharArray()).Datos);

                    Pass_Desencriptado             = stream.ReadToEnd();
                    userDesencriptado              = streamUser.ReadToEnd();
                    ViewState["userDesencriptado"] = userDesencriptado;
                    TipoUsuario = userDesencriptado.ToUpper().Replace("TVA", "").Replace("PTV", "");
                    ViewState["TipoUsuario"] = TipoUsuario;
                    if (isNumeric(TipoUsuario))
                    {
                        isUserName = false;
                        UsuarioTVA = userDesencriptado.ToUpper();
                        usuario    = userDesencriptado.ToUpper();

                        XmlDocument DatosUsua = MngNegocioEmpleadoRol.GetUserDataByNumEmpleado(TipoUsuario, "");
                        string      NumUsua   = (DatosUsua.GetElementsByTagName("NUMUSUA").Count > 0) ? DatosUsua.GetElementsByTagName("NUMUSUA")[0].InnerText : "";
                        EmId = (DatosUsua.GetElementsByTagName("NUMEMPL").Count > 0) ? DatosUsua.GetElementsByTagName("NUMEMPL")[0].InnerText : "";
                        if (userDesencriptado.ToUpper().Contains("TVA"))
                        {
                            UsuarioTVA = "TVA" + TipoUsuario;
                        }
                        else if (userDesencriptado.ToUpper().Contains("PTV"))
                        {
                            UsuarioTVA = "PTV" + TipoUsuario;
                        }
                        else
                        {
                            UsuarioTVA = "TVA" + TipoUsuario;
                        }
                    }
                    else
                    {
                        isUserName = true;
                        usuario    = userDesencriptado.ToUpper();
                        XmlDocument DatosUsua = MngNegocioEmpleadoRol.GetUserDataByNumEmpleado("", usuario);
                        string      NumUsua   = (DatosUsua.GetElementsByTagName("NUMUSUA").Count > 0) ? DatosUsua.GetElementsByTagName("NUMUSUA")[0].InnerText : "";
                        EmId = (DatosUsua.GetElementsByTagName("NUMEMPL").Count > 0) ? DatosUsua.GetElementsByTagName("NUMEMPL")[0].InnerText : "";
                        if (userDesencriptado.ToUpper().Contains("TVA"))
                        {
                            UsuarioTVA = "TVA" + NumUsua;
                        }
                        else if (userDesencriptado.ToUpper().Contains("PTV"))
                        {
                            UsuarioTVA = "PTV" + NumUsua;
                        }
                        else
                        {
                            UsuarioTVA = "TVA" + NumUsua;
                        }
                    }

                    //Primeras Validacion Tipo de Usuario (Red o TVA)
                    IntentosXIP = MngNegocioBloqueoIP.ConsultaUltimoAccesos();

                    if (ValidaIP(IPUsr, IntentosXIP) >= 10)
                    {
                        string strMessage = string.Empty;
                        strMessage       += strMessage == string.Empty ? "" : "<br>";
                        strMessage       += " * Su IP ha sido bloqueada";
                        strMessage       += "<br>";
                        tdError.InnerHtml = strMessage;
                        tdError.Visible   = true;
                        txtUsuario.Text   = usuario;
                        GuardaLogAcceso(8);
                        return;
                    }


                    //Aqui se debe de mandar a validar si el usuario esta bloqueado por Intentos fallidos
                    UserBlock = MngNegocioBloqueoUsuario.ConsultaUsuarioBloqueadoXIdUsuario(usuario.ToUpper().ToString(), "1");

                    if (UserBlock.Count > 0)
                    {
                        //El Usuario ya ha sido bloqueado
                        string strMessage = string.Empty;
                        strMessage        += " * El Usuario ha sido " + UserBlock[0].TipoBloqueo.DescTipoBloqueo;
                        strMessage        += "; Su cuenta se Desbloqueara Automaticamente en 10 Minutos";
                        txtUsuario.Text    = usuario;
                        txtError.InnerText = strMessage;
                        GuardaLogAcceso(9);
                        return;
                    }

                    string respuesta = string.Empty;

                    #region Login

                    LlaveMaestra.Service objServicio = new LlaveMaestra.Service();
                    //LDAPUser ldapUser = new LDAPUser();
                    string resp = "";
                    try
                    {
                        resp = objServicio.gsc_llave(userDesencriptado.ToUpper(), Pass_Desencriptado);
                    }
                    catch
                    {
                    }



                    if (resp.Contains("[OK]"))
                    {
                        if (AutenticaUsuario.Validar("", userDesencriptado, Pass_Desencriptado))
                        {
                            XmlDocument UserData = new XmlDocument();
                            if (isUserName)
                            {
                                UserData = MngNegocioEmpleadoRol.GetUserDataByNumEmpleado("", userDesencriptado);
                            }
                            else
                            {
                                string temp = resp;
                                temp = temp.Substring(temp.IndexOf("NumEmp=")).Replace("NumEmp=", "").Substring(1);
                                temp = temp.Substring(0, temp.IndexOf("\""));


                                UserData   = MngNegocioEmpleadoRol.GetUserDataByNumEmpleado(temp, "");
                                isUserName = true;
                            }
                            string NumEmpl = (UserData.GetElementsByTagName("NUMEMPL").Count > 0) ? UserData.GetElementsByTagName("NUMEMPL")[0].InnerText : "";

                            List <THE_SesionUsuario> existeSesion = MngNegocioUsuarioSesion.ExisteSesionUsuario(Int32.Parse(NumEmpl));

                            if (existeSesion.Count > 0)
                            {
                                var listusr = (from Atributos in existeSesion
                                               orderby Atributos.IdSesion
                                               select Atributos).Take(1);
                                foreach (var itemList in listusr)
                                {
                                    ViewState["vsIdSesion"] = itemList.IdSesion;
                                    Session["IdSesion"]     = itemList.IdSesion;
                                }
                                ViewState["vsIdUser"] = "";
                                ViewState["Opcion"]   = "ContinuaSesion";

                                var sw = new StringWriter();
                                var xw = new XmlTextWriter(sw);
                                UserData.WriteTo(xw);

                                ViewState["vsUserdata"] = sw.ToString();
                                ViewState["vsIdUser"]   = NumEmpl;
                                ctrlMessageBox.AddMessage("Usted tiene una sesion abierta ¿Desea iniciar otra sesion en este equipo?", MessageBox.enmMessageType.Attention, true, true, "Sesion", "Valida Sesion Existente");
                            }
                            else
                            {
                                THE_SesionUsuario ObjSession = new THE_SesionUsuario();
                                ObjSession.DirIP         = IPUsr;
                                ObjSession.FechaCreacion = DateTime.Now;
                                ObjSession.EmplLlavPr    = new THE_Empleado {
                                    EmpleadoLlavePrimaria = int.Parse(NumEmpl)
                                };
                                MngNegocioUsuarioSesion.GuardaSesionUsuario(ObjSession);

                                List <THE_SesionUsuario> SesionExist = MngNegocioUsuarioSesion.ExisteSesionUsuario(Int32.Parse(NumEmpl));
                                if (SesionExist.Count > 0)
                                {
                                    var listu = (from Atributos in SesionExist
                                                 orderby Atributos.IdSesion
                                                 select Atributos).Take(1);
                                    foreach (var itemList in listu)
                                    {
                                        Session["IdSesion"] = itemList.IdSesion;
                                    }
                                }
                                ObtieneDatosUsuario(UserData);
                            }
                        }
                        else
                        {
                            ValidaBloqueosErrorPass();
                        }
                    }
                    else
                    {
                        try
                        {
                            if (isNumeric(TipoUsuario))
                            {
                                respuesta = Llave.validaEmpleado(userDesencriptado, Pass_Desencriptado);
                            }
                            else
                            {
                                respuesta = Llave.validaEmpleado(UsuarioTVA, Pass_Desencriptado);
                            }
                            xml.LoadXml(respuesta);
                        }
                        catch (Exception ex)
                        {
                            THE_LogError oLogErrores = new THE_LogError();
                            oLogErrores.EmplUsua      = UsuarioTVA.Replace("TVA", "").Replace("PTV", "");
                            oLogErrores.DirIP         = IPUsr;
                            oLogErrores.Error         = ex.Message + "\n" + ex.StackTrace.ToString();
                            oLogErrores.Pantalla      = "Default.aspx";
                            oLogErrores.MachineName   = "";
                            oLogErrores.FechaCreacion = DateTime.Now;
                            oLogErrores.Dominio       = Request.Url.Host.ToLower();
                            MngNegocioLogErrores.GuardarLogErrores(oLogErrores);
                        }

                        if ((respuesta.IndexOf("Respuesta=\"[OK]\"") != -1) || respuesta.IndexOf("0 - [") != -1)
                        {
                            //Aqui se debe de mandar a validar si el usuario esta bloqueado por Intentos fallidos
                            IList <THE_BloqueoUsuario> UserBlockInactivo = MngNegocioBloqueoUsuario.ConsultaUsuarioBloqueadoXIdUsuario(usuario.ToUpper().ToString(), "2");
                            if (UserBlockInactivo.Count > 0)
                            {
                                //El Usuario ya ha sido bloqueado
                                string strMessage = string.Empty;
                                strMessage += strMessage == string.Empty ? "" : "<br>";
                                strMessage += " * El Usuario ha sido bloqueado por : " + UserBlockInactivo[0].TipoBloqueo.DescTipoBloqueo;
                                strMessage += "<br>";
                                strMessage += "El bloqueo se quitará automáticamente después los 10 minutos";
                                ClientScript.RegisterStartupScript(Page.GetType(), "AlertBloqueoInactivo" + 3, "<script>alert('El Usuario ha sido bloqueado por " + UserBlock[0].TipoBloqueo.DescTipoBloqueo + ". Para desbloquearlo deberá realizar la solicitud en DATASEC');</script>");
                                tdError.InnerHtml = strMessage;
                                tdError.Visible   = true;
                                txtUsuario.Text   = usuario;
                                GuardaLogAcceso(9);
                                return;
                            }

                            tdError.Visible   = false;
                            tdError.InnerHtml = "";

                            string      numeroUsuario = xml.FirstChild.ChildNodes[0].Attributes["NumEmp"].Value;
                            XmlDocument UserData      = MngNegocioEmpleadoRol.GetUserDataByNumEmpleado(numeroUsuario, "");

                            ObtieneDatosUsuario(UserData);
                        }
                        else
                        {
                            ValidaBloqueosErrorPass();
                        }
                    }
                }
                catch (Exception ex)
                {
                    THE_LogError oLogErrores = new THE_LogError();
                    oLogErrores.EmplUsua      = UsuarioTVA.Replace("TVA", "").Replace("PTV", "");
                    oLogErrores.DirIP         = IPUsr;
                    oLogErrores.Error         = ex.Message + "\n" + ex.StackTrace.ToString();
                    oLogErrores.Pantalla      = "Default.aspx";
                    oLogErrores.MachineName   = "";
                    oLogErrores.FechaCreacion = DateTime.Now;
                    oLogErrores.Dominio       = Request.Url.Host.ToLower();
                    MngNegocioLogErrores.GuardarLogErrores(oLogErrores);
                    txtUsuario.Text = "";
                    GuardaLogAcceso(2);
                }
            }
            catch (Exception ex)
            {
                THE_LogError oLogErrores = new THE_LogError();
                oLogErrores.EmplUsua      = UsuarioTVA.Replace("TVA", "").Replace("PTV", "");
                oLogErrores.DirIP         = IPUsr;
                oLogErrores.Error         = ex.Message + "\n" + ex.StackTrace.ToString();
                oLogErrores.Pantalla      = "Default.aspx";
                oLogErrores.MachineName   = "";
                oLogErrores.FechaCreacion = DateTime.Now;
                oLogErrores.Dominio       = Request.Url.Host.ToLower();
                MngNegocioLogErrores.GuardarLogErrores(oLogErrores);
            }
            #endregion
        }