public usuario Get(int id)
 {
     usuario oUsuario = new usuario();
     using (cooperativaEntities bd = new cooperativaEntities())
     {
         var regis = (from p in bd.usuario
                      where p.id_usuario == id
                      select p).Single();
         oUsuario.id_usuario = regis.id_usuario;
         oUsuario.nombre = regis.nombre;
         oUsuario.login = regis.login;
         oUsuario.password = regis.password;
         oUsuario.modificarDatos = regis.modificarDatos;
         oUsuario.facturacion_anulacion = regis.facturacion_anulacion;
         oUsuario.impresion_reimpresion = regis.impresion_reimpresion;
         oUsuario.cobranza_cierreCaja = regis.cobranza_cierreCaja;
         oUsuario.listados_reportes = regis.listados_reportes;
         oUsuario.avisosDeuda_listadosCortes = regis.avisosDeuda_listadosCortes;
         oUsuario.reparar_optimizar_respaldo = regis.reparar_optimizar_respaldo;
         oUsuario.configurar = regis.configurar;
         oUsuario.administracion = regis.administracion;
         oUsuario.autorizarCobroSI = regis.autorizarCobroSI;
         oUsuario.autorizarConvenios = regis.autorizarConvenios;
         oUsuario.listados_padrones = regis.listados_padrones;
         oUsuario.judicial_codene = regis.judicial_codene;
         oUsuario.mantenimiento = regis.mantenimiento;
         oUsuario.activo = oUsuario.activo;
         return oUsuario;
     }
 }
Esempio n. 2
0
        public ActionResult RegistrarUsuario(String userESPOL, String newPassword, String newNombre, String newApellido, String placa)
        {
            DawEntities dawDB = new DawEntities();
            List<usuario> list_users = dawDB.usuario.ToList();

            foreach(usuario usuario in list_users)
            {
                if (usuario.nombUsuario == userESPOL)
                    return Content("<script>alert('Usuario ya existe!');location='/2014_1T/Grupo11/index/';</script>");
            }

            EspolWS.wsandroidSoapClient ws = new EspolWS.wsandroidSoapClient();
            DataSet res = ws.wsConsultaCodigoEstudiante(userESPOL);
            DataRow dr = res.Tables[0].Rows[0];//MATRICULA
            String matricula = dr["COD_ESTUDIANTE"].ToString();

            usuario usr = new usuario();

            int carro = 0;
            if(placa!=null)
                carro = 1;

            usr.nombres = newNombre;
            usr.apellidos = newApellido;
            usr.nombUsuario = userESPOL;
            usr.contrasenia = newPassword;
            usr.matricula = matricula;
            usr.tieneCarro = carro;
            usr.nSeguidores = 0;
            usr.nSiguiendo = 0;

            dawDB.usuario.Add(usr);
            int cambios = dawDB.SaveChanges();
            return Content("<script>alert('Usuario registrado exitosamente!');location='/2014_1T/Grupo11/index/';</script>");
        }
 public List<usuario> Filtrar(usuario usuario)
 {
     return repositoryusuario.ObterPorFiltros(b => (
         (usuario.ID == Guid.Empty || b.ID == usuario.ID) &&
         (usuario.nome == null || b.nome.ToUpper().Contains(usuario.nome)) &&
         (usuario.email == null || b.email.ToUpper().Contains(usuario.email)) &&
         (usuario.senha == null || b.senha.ToUpper().Contains(usuario.senha)) &&
         (usuario.empresaID == Guid.Empty || b.empresaID == usuario.empresaID)
         )).ToList();
 }
    protected void Button_Cambiar_Click(object sender, EventArgs e)
    {
        String USU_LOG = Session["USU_LOG"].ToString();
        String USU_CEDULA = null;

        Boolean correcto = true;

        usuario _usuario = new usuario(Session["idEmpresa"].ToString());

        DataTable tablaInfoUsuario = _usuario.ObtenerUsuarioPorUsuLog(USU_LOG);

        if (tablaInfoUsuario.Rows.Count <= 0)
        {
            if (_usuario.MensajeError != null)
            {
                Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, _usuario.MensajeError, Proceso.Error);
            }
            else
            {
                Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, "Nombre de usuario no registrado, No se pudo cambiar el password.", Proceso.Advertencia);
            }

            correcto = false;
        }
        else
        {
            DataRow filaInfoUsuario = tablaInfoUsuario.Rows[0];

            if (filaInfoUsuario["USU_TIPO"].ToString().ToUpper() == "PLANTA")
            {
                USU_CEDULA = filaInfoUsuario["NUM_DOC_IDENTIDAD"].ToString().Trim();
            }
            else
            {
                USU_CEDULA = filaInfoUsuario["NUM_DOC_IDENTIDAD_EXTERNO"].ToString().Trim();
            }

            correcto = _usuario.ActualizarClaveUsuarioDesdeInicioSesion(filaInfoUsuario, USU_CEDULA, TextBox_USU_PSW_ANT.Text.Trim(), TextBox_USU_PSW_NEW.Text);

            if (correcto == false)
            {
                Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, _usuario.MensajeError, Proceso.Error);
            }
            else
            {
                Ocultar(Acciones.Inicio);
                Desactivar(Acciones.Inicio);
                Mostrar(Acciones.Inicio);
                Limpiar(Acciones.Inicio);
                Cargar(Acciones.Inicio);

                Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, "El password fue correctamente actualizado. A partir deeste momento debe ingresar al sistema utilizando el nuevo password.", Proceso.Correcto);
            }
        }
    }
Esempio n. 5
0
        public ActionResult Create(usuario usuario)
        {
            if (ModelState.IsValid)
            {
                db.usuario.Add(usuario);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.EMPLEADO_id = new SelectList(db.empleado, "id", "nombre1", usuario.EMPLEADO_id);
            ViewBag.ROL_id = new SelectList(db.rol, "id", "nombre", usuario.ROL_id);
            return View(usuario);
        }
Esempio n. 6
0
        private void PublicarPregunta_Click(object sender, EventArgs e)
        {
            usuario u = new usuario();

            Label nombrePublicacion = new Label();
            nombrePublicacion.Text = u.nombreUsuario;

            Label contenidoPublicacion = new Label();
            contenidoPublicacion.Text = ContenidoAPublicar.Text;
            contenidoPublicacion.AutoSize = true;
            contenidoPublicacion.Location = new Point(10, 100);

            //this.GBMuro.Controls.Add(nombrePublicacion);
            this.GBMuro.Controls.Add(contenidoPublicacion);
        }
Esempio n. 7
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     usuario miuser = new usuario();
     miuser._Nombre = TextBox1.Text;
     miuser._Clave = TextBox2.Text;
     if (miuser.verUsuario())
     {
         Session["usuario"] = miuser._Nombre;
         Response.Redirect("principal.aspx");
     }
     else
     {
         Session["usuario"] = "No Existe Usuario";
         Response.Redirect("index.aspx");
     }
 }
Esempio n. 8
0
        public string PasswordSignIn(string email, string senha)
        {
            usuario usuario = new usuario();
            Facade.administracaoFacade facadeAdmin = new Facade.administracaoFacade();
            List<usuario> lstUsuario = new List<Model.usuario>();
            string retorno = "Failure";
            usuario.email = email;
            usuario.senha = senha;
            lstUsuario = facadeAdmin.FiltrarUsuario(usuario);

            if (lstUsuario.Count > 0)
            {
                retorno = "Success";
            }

            return retorno;
        }
        private void btnGuardar_Click(object sender, RoutedEventArgs e)
        {
            if (comprobarCampos())
            {
                int nivel = cmbNivel.Items.Count - 1 - cmbNivel.SelectedIndex; //en el combo están ordenados alrevés que en los niveles numéricos, cuanto más alto está en el combo, más bajo es su nivel de autorización
                usuario miUsuario = new usuario(txtNombre.Text.Trim(), txtPass.Text.Trim(), nivel, txtMail.Text.Trim());
                if (!miUsuario.guardar())
                    MessageBox.Show("Hubo un problema al guardar el usuario. O usted no tiene el nivel de autorización suficiente, o algo pasó. Contacte con la gente de sistemas", "Error");

                txtMail.Text = "";
                txtNombre.Text = "";
                txtPass.Text = "";
                cmbNivel.SelectedIndex = 0;

                cargarUsuarios();
            }
        }
Esempio n. 10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user"] != null)              // se verifica la sesion de usuario
            {
                us        = (usuario)Session["User"]; //trae los datos del usuario y los deja en la varible us.
                rut       = us.rut;
                nombre    = us.nombre;
                apellido  = us.apellido;
                correo    = us.correo;
                direccion = us.direccion;
                password  = us.password;
                fecha_na  = us.fecha_nacimiento;
                rol       = us.id_rol;

                //vistas bloqueadas
                linksesion.Visible = false;
            }
            else
            {
                //vistas bloqueadas
                linklogout.Visible = false;
                linkperfil.Visible = false;
            }
        }
Esempio n. 11
0
        public ActionResult Create(usuario usuario)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            //para capturar errores
            try
            {
                using (var db = new inventarioEntities())
                {
                    usuario.password = UsuarioController.HashSHA1(usuario.password);
                    db.usuario.Add(usuario);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "error" + ex);
                return(View());
            }
        }
        public List <ocorrencia> ListarPorUsuario(usuario u)
        {
            try
            {
                SqlConnection c     = conectar();
                string        query = "SELECT id, situacao, numero_ocorrencia, descricao, id_usuario, tipoPublico FROM ocorrencia WHERE id_usuario = @id_usuario";

                SqlCommand comand = new SqlCommand(query, c);
                comand.Parameters.AddWithValue("@id_usuario", u.Id);

                SqlDataReader reader = comand.ExecuteReader();


                List <ocorrencia> oc = new List <ocorrencia>();

                while (reader.Read())
                {
                    ocorrencia oco = new ocorrencia();

                    oco.Id                = reader.GetInt32(reader.GetOrdinal("id"));
                    oco.Situacao          = reader.GetString(reader.GetOrdinal("situacao"));
                    oco.Numero_ocorrencia = reader.GetString(reader.GetOrdinal("numero_ocorrencia"));
                    oco.Descricao         = reader.GetString(reader.GetOrdinal("descricao"));
                    oco.Id_usuario.Id     = reader.GetInt32(reader.GetOrdinal("id_usuario"));
                    oco.TipoPublico       = reader.GetInt32(reader.GetOrdinal("tipoPublico"));

                    oc.Add(oco);
                }
                desconectar(c);
                return(oc);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Esempio n. 13
0
        public static void Venta(int idAuto, int usuario, int comprador, venta Venta)
        {
            try
            {
                var  ctx = new DataModel();
                auto aut = ctx.autos.Where(r => r.idauto == idAuto).FirstOrDefault();
                ctx.autos.Attach(aut);
                Venta.autos = aut;

                usuario usu = ctx.usuarios.Where(r => r.idusuario == usuario).FirstOrDefault();
                ctx.usuarios.Attach(usu);
                Venta.usuarios = usu;

                comprador com = ctx.compradores.Where(r => r.idcomprador == idAuto).FirstOrDefault();
                ctx.compradores.Attach(com);
                Venta.compradores = com;

                ctx.Entry(Venta).State = EntityState.Added;
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 14
0
        public bool CambiarClave(usuario unUsuario)
        {
            CambioClave asistente = new CambioClave();
            bool        respuesta = false;

            try
            {
                asistente.UsuarioVerificado = unUsuario;
                asistente.ShowDialog();
                //VERIFICAMOS CLAVE ANTERIOR
                if (asistente.Registrar)
                {
                    UsuarioPr usuario = new UsuarioPr();
                    unUsuario.clave      = asistente.NuevaClave;
                    unUsuario.Modificado = true;
                    int i = usuario.Grabar(unUsuario);
                    if (i == 0)
                    {
                        throw new Exception("No se pudo completar el cambio de clave. \nPor favor consulte con el Administrador del sistema.");
                    }

                    General.Mensaje("Nueva clave registrada.", MessageBoxIcon.Information);
                    respuesta = true;
                    usuario   = null;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                asistente.Dispose();
            }
            return(respuesta);
        }
Esempio n. 15
0
        public ActionResult getGraba()
        {
            usuario        usu   = (usuario)Session["cliente"];
            List <Compras> lista = (List <Compras>)Session["canasta"];
            double         sm    = 0;

            foreach (var cp in lista)
            {
                sm = sm + cp.total;
            }
            string fac = "";

            //string fac = db.grabafac(usu.idusuario, (decimal)sm).FirstOrDefault();

            foreach (var dt in lista)
            {
                //db.grabadeta(fac, dt.idusuario, dt.cantidad);
            }
            string clinom = usu.nombreusuario + "," + usu.sedes;

            Session["canasta"] = null;
            Session["cliente"] = null;
            return(RedirectToAction("getResumen", new { nro = fac, total = sm, nombre = clinom }));
        }
Esempio n. 16
0
 public ActionResult VistaProducto(int idProducto = 0)
 {
     try
     {
         usuario oUsuario = (usuario)Session["Usuario"];
         if (oUsuario == null)
         {
             Session.Clear();
             return(RedirectToAction("Index", "Home"));
         }
         srvProducto sProducto = new srvProducto();
         producto    oProducto = sProducto.ObtenerProducto(idProducto);
         ViewBag.ValorUSD = GetValorUsd();
         if (oProducto == null || oProducto.idProducto == 0)
         {
             throw new Exception();
         }
         return(View(oProducto));
     }
     catch (Exception)
     {
         return(RedirectToAction("Error", "Error", new { stError = "El producto solicitado no se ha encontrado." }));
     }
 }
Esempio n. 17
0
        public ActionResult Create(usuario usuario)
        {
            LoadFormPerfil();
            LoadFormFaculdade();

            try
            {
                usuario.fk_id_faculdade = 1; //Faculdade CNEC Unaí

                if (validateusuario(usuario))
                {
                    return(View(usuario));
                }

                usuario.senha_usuario = SecurityHelper.EncryptData(usuario.senha_usuario);
                UsuarioRepository.Create(usuario);

                return(RedirectToAction("List", new { message = "Dados cadastrados com sucesso!" }));
            }
            catch
            {
                return(View(usuario));
            }
        }
Esempio n. 18
0
        public ActionResult CreateAluno(usuario usuario)
        {
            LoadFormCurso();

            try
            {
                usuario.fk_id_perfil    = 4; //Aluno
                usuario.fk_id_faculdade = 1; //Faculdade CNEC Unaí

                if (validatealuno(usuario))
                {
                    return(PartialView(usuario));
                }

                usuario.senha_usuario = SecurityHelper.EncryptData(usuario.senha_usuario);
                UsuarioRepository.Create(usuario);

                return(RedirectToAction("Login", "Account", new { message = "Usuário criado com sucesso!" }));
            }
            catch
            {
                return(PartialView(usuario));
            }
        }
Esempio n. 19
0
        public ActionResult Edit(usuario editUser)
        {
            try
            {
                using (var db = new inventarioEntities1())
                {
                    usuario user = db.usuario.Find(editUser.id);

                    user.nombre           = editUser.nombre;
                    user.apellido         = editUser.apellido;
                    user.email            = editUser.email;
                    user.fecha_nacimiento = editUser.fecha_nacimiento;
                    user.password         = editUser.password;

                    db.SaveChanges();
                    return(RedirectToAction("index"));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "error " + ex);
                return(View());
            }
        }
Esempio n. 20
0
 public ActionResult NuevaVenta(int nroPagina = 1, int tamañoPagina = 6, bool paginacion = false)
 {
     try
     {
         usuario oUsuario = (usuario)Session["Usuario"];
         if (oUsuario == null)
         {
             Session.Clear();
             return(RedirectToAction("Index", "Home"));
         }
         srvEstado       sEstado      = new srvEstado();
         srvProducto     sProducto    = new srvProducto();
         srvCategoria    sCategoria   = new srvCategoria();
         List <producto> lstProductos = (List <producto>)Session["lstProducto"];
         if (lstProductos == null || lstProductos.Count == 0 || paginacion == false)
         {
             Session["lstProducto"] = new List <producto>();
             lstProductos           = new List <producto>();
         }
         if (Session["venta"] == null)
         {
             Session["venta"] = new venta();
         }
         ViewBag.lstCategorias = sCategoria.ObtenerCategorias();
         ViewBag.lstEstados    = sEstado.ObtenerEstados("VENTA");
         ViewBag.filtros       = ";;;";
         ProductoController ProductoController = new ProductoController();
         ViewBag.ValorUSD = ProductoController.GetValorUsd();
         PagedList <producto> model = new PagedList <producto>(lstProductos.ToList(), nroPagina, tamañoPagina);
         return(View(model));
     }
     catch (Exception)
     {
         return(RedirectToAction("Error", "Error", new { stError = "Se produjo un error al intentar obtener los datos del servidor." }));
     }
 }
Esempio n. 21
0
        public async Task <ActionResult <dynamic> > Authenticate([FromBody] usuario model)
        {
            // Recupera o usuário
            var user = _userRepository.Get(model.Email, model.Senha);

            // Verifica se o usuário existe
            if (user == null)
            {
                return(NotFound(new { message = "Usuário ou senha inválidos" }));
            }

            // Gera o Token
            var token = TokenService.GenerateToken(user);

            // Oculta a senha
            user.Senha = "";

            // Retorna os dados
            return(new
            {
                user = user,
                token = token
            });
        }
Esempio n. 22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            UsuarioAtual = (usuario)Session["UsuarioAtual"];

            if (Session["UsuarioPerfil"] != null)
            {
                UsuarioPerfil = UR.GetOne((int)Session["UsuarioPerfil"]);
                if (!Page.IsPostBack)
                {
                    CriaPerfil();
                }
            }
            else if (Session["UsuarioAtual"] != null)
            {
                UsuarioPerfil = (usuario)Session["UsuarioAtual"];
                if (!Page.IsPostBack)
                {
                    CriaPerfil();
                }
            }
            if (!Page.IsPostBack)
            {
                Session["jsPesquisaAtivo"] = false;
                Session["sobreAtivo"]      = false;
            }
            if (string.IsNullOrEmpty(UsuarioPerfil.linkfoto))
            {
                imgPerfil.ImageUrl = "https://i.imgur.com/6BPMqMa.png";
            }
            else
            {
                imgPerfil.ImageUrl = UsuarioPerfil.linkfoto;
            }
            this.Page.Title           = UsuarioPerfil.nicknameusuario + " - unNamed";
            bttEnviarMensagem.Enabled = false;
        }
Esempio n. 23
0
        public ActionResult btnLogin_Click(FormCollection solicitud)
        {
            string nombreUsuario = solicitud["nombre"].ToString();
            string contrasenna   = solicitud["contrasenna"].ToString();

            var users = from m in db.usuario
                        select m;

            users = users.Where(m => m.nombre == nombreUsuario);
            if (users.Count() < 1)
            {
                return(View("Login"));
            }
            usuario usr = users.First();

            if (contrasenna == usr.contrasenna)
            {
                Console.WriteLine("estoy vivo joder");
                Session["IDUsuario"] = usr.idusuario;

                if (usr.tipousuario.Equals("Empleado"))
                {
                    //empleado
                    return(RedirectToAction("MainAdministrador", "Administrador"));
                }
                else
                {
                    //cliente
                    return(RedirectToAction("MainCliente", "Cliente"));
                }
            }
            else
            {
                return(View("Login"));
            }
        }
Esempio n. 24
0
    protected void cmdSalvar_Click(object sender, EventArgs e)
    {
        usuario Usuario = (usuario)HttpContext.Current.Session["Usuario"];

        if (PodeSalvar())
        {
            int iIDCampanha = Convert.ToInt32(dropCampanha.SelectedValue);

            prospectCTL CProspect = new prospectCTL();

            //Exclui todos os DDDs para cadastrar novamente
            CProspect.ExcluirBloqueioDDD(iIDCampanha);
            foreach (ListItem itemChecked in chkDDD.Items)
            {
                if (itemChecked.Selected == true)
                {
                    CProspect.CadastrarBloqueioDDD(Convert.ToInt32(itemChecked.ToString()), Usuario.IDUsuario, iIDCampanha);
                }
            }

            LimparCampos();
            PontoBr.Utilidades.Diversos.ExibirAlertaScriptManager("Registros salvos com sucesso!", this.Page);
        }
    }
Esempio n. 25
0
        public ActionResult SigninAdmin(FormCollection solicitud)
        {
            try
            {
                usuario  usr = new usuario();
                empleado emp = new empleado();

                usr.nombre      = solicitud["usuario"].ToString();
                usr.contrasenna = solicitud["contrasenna"].ToString();
                usr.tipousuario = "Empleado";
                emp.nombre      = solicitud["nombre"].ToString();
                emp.idempleado  = Convert.ToDecimal(solicitud["id"].ToString());
                db.usuario.Add(usr);
                emp.idusuario = Convert.ToDecimal(solicitud["id"].ToString());
                db.empleado.Add(emp);
                db.SaveChanges();

                return(RedirectToAction("MainAdministrador", "Administrador"));
            }
            catch (Exception e)
            {
                return(View("SigninAdmin"));
            }
        }
Esempio n. 26
0
    private void Awake()
    {
        user = FindObjectOfType <usuario>();
        //Recojo todos los componentes
        canvas = FindObjectOfType <Canvas>();

        contador = GameObject.Find("Contador").GetComponent <Text>();
        //elijo un case aleatorio entre el minimo numero de elementos en la lista de imagenes y el maximo(y le sumo 1 por que el ultimo elemtno no es inclusivo)
        caseSwitch = (int)Random.Range(1, imagen.Length + 1);
        //defino contador
        contador.text = " " + tiempo;

        //defino palabras_1
        palabras_1 = new List <string>();

        //apago todos los textos por defecto
        for (int i = 0; i < boton.Length; i++)
        {
            boton[i] = GameObject.Find("Boton" + i).GetComponent <Button>();

            boton[i].gameObject.SetActive(false);
            textos[i] = GameObject.Find("Btext" + i).GetComponent <Text>();
        }
    }
Esempio n. 27
0
        public ActionResult Resumen()
        {
            // Validacion de ingreso
            usuario usuario = (usuario)Session["Usuario"];

            if (usuario == null)
            {
                return(RedirectToAction("Login"));
            }

            using (Entities obj = new Entities())
            {
                var            x = obj.edicion;
                List <edicion> lista_ediciones       = x.ToList();
                List <edicion> nueva_lista_ediciones = new List <edicion>();

                if (usuario.tipoUsuario.Equals("agente"))
                {
                    foreach (edicion edi in lista_ediciones)
                    {
                        if (edi.codUsuario.Equals(usuario.codUsuario))
                        {
                            nueva_lista_ediciones.Add(edi);
                        }
                    }
                }
                else
                {
                    nueva_lista_ediciones = lista_ediciones;
                }

                ViewBag.usuario         = usuario;
                ViewBag.lista_ediciones = nueva_lista_ediciones;
                return(View());
            }
        }
Esempio n. 28
0
        private void btnregistrar_Click(object sender, EventArgs e)
        {
            char genero;

            if (comgenero.Text.Equals("Masculino"))
            {
                genero = 'M';
            }
            else
            {
                if (comgenero.Text.Equals("Femenino"))
                {
                    genero = 'F';
                }
                else
                {
                    genero = 'O';
                }
            }
            ManagerUser mu = new ManagerUser();

            if (mu.Usuariorepetido(txtuser.Text))
            {
                usuario user = new usuario(txtnombre.Text, txtapellido.Text,
                                           genero, txtuser.Text,
                                           txtcorreo.Text, txtcontraseña.Text, txtconfcontraseña.Text);
                MessageBox.Show("Usuario creado exitosamente");
                this.Hide();
                FrmPrincipal f2 = new FrmPrincipal(txtuser.Text, txtcorreo.Text);
                f2.Show();
            }
            else
            {
                MessageBox.Show("Es usuario " + txtuser.Text + " ya esiste!!!");
            }
        }
        public ActionResult Editar(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            usuario us = db.usuario.Find(id);

            if (us == null)
            {
                return(HttpNotFound());
            }
            if (us.pessoa.email != HttpContext.User.Identity.Name)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            // var itemIds = db.usuario.Select(x => x.pessoa_id_pessoa).ToArray();
            var listaPessoasDisponiveis = db.pessoa.Where(x => x.id_pessoa.Equals(us.pessoa_id_pessoa));


            ViewBag.pessoa_id_pessoa = new SelectList(listaPessoasDisponiveis, "id_pessoa", "nome");
            return(View(us));
        }
Esempio n. 30
0
        private void button1_Click(object sender, EventArgs e)
        {
            M_Registrar_Cliente _clF          = new M_Registrar_Cliente();
            usuario             _usuario      = new usuario();
            controlOrden        _controlOrden = new controlOrden();

            _clF.Id     = int.Parse(cbcliebtellevar.SelectedValue.ToString());
            _usuario.Id = int.Parse(cbAtendio.SelectedValue.ToString());


            _clF.Respuesta = _controlOrden.altaOrdenParaLlevar(txtDescricion.Text, _clF, _usuario);
            if (_clF.Respuesta == true)
            {
                lblRespuesta.Text = "La orden Se ha registrado";
            }
            else
            {
                lblRespuesta.Text = "Erroe al registrar la orden";
            }

            panel2.Enabled     = false;
            btnOpcion2.Enabled = false;
            btlOpcion1.Enabled = false;
        }
    protected void Button_InformarDescarte_Click(object sender, EventArgs e)
    {
        Decimal ID_REQUERIMIENTO = Convert.ToDecimal(HiddenField_ID_REQUERIMIENTO.Value);
        Decimal ID_SOLICITUD = Convert.ToDecimal(HiddenField_ID_SOLICITUD.Value);

        ConRegContratoTemporal _contratoTemporal = new ConRegContratoTemporal(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        Boolean correcto = _contratoTemporal.DescartarConRegContratosTemporal(ID_REQUERIMIENTO, ID_SOLICITUD, TextBox_ObservacionesDescarte.Text.Trim());

        if (correcto == false)
        {
            Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, _contratoTemporal.MensajeError, Proceso.Error);
        }
        else
        {
            parametro _parametro = new parametro(Session["idEmpresa"].ToString());

            DataTable tablaRolParaInformar = _parametro.ObtenerParametrosPorTabla(tabla.PARAMETROS_ROL_INFORMAR_DESCARTE_PROCESO_CONTRATACION);

            if (tablaRolParaInformar.Rows.Count <= 0)
            {
                tools _tools = new tools();
                SecureQueryString QueryStringSeguro;
                QueryStringSeguro = new SecureQueryString(_tools.byteParaQueryStringSeguro());

                QueryStringSeguro["img_area"] = "contratacion";
                QueryStringSeguro["nombre_area"] = "CONTRATACIÓN Y RELACIONES LABORALES";
                QueryStringSeguro["nombre_modulo"] = "HOJA DE TRABAJO DE CONTRATACIÓN";
                QueryStringSeguro["accion"] = "descarteContratacionNoRol";

                Response.Redirect("~/contratacion/hojaTrabajoContratacion.aspx?data=" + HttpUtility.UrlEncode(QueryStringSeguro.ToString()));
            }
            else
            {
                DataRow filaParametroRol = tablaRolParaInformar.Rows[0];

                String NOMBRE_ROL = filaParametroRol["CODIGO"].ToString().Trim();

                usuario _usuario = new usuario(Session["idEmpresa"].ToString());
                DataTable tablaUsuariosAInformar = _usuario.ObtenerListaUsuariosSistemaActivosPorNombreRol(NOMBRE_ROL);

                if (tablaUsuariosAInformar.Rows.Count <= 0)
                {
                    tools _tools = new tools();
                    SecureQueryString QueryStringSeguro;
                    QueryStringSeguro = new SecureQueryString(_tools.byteParaQueryStringSeguro());

                    QueryStringSeguro["img_area"] = "contratacion";
                    QueryStringSeguro["nombre_area"] = "CONTRATACIÓN Y RELACIONES LABORALES";
                    QueryStringSeguro["nombre_modulo"] = "HOJA DE TRABAJO DE CONTRATACIÓN";
                    QueryStringSeguro["accion"] = "descarteContratacionNoUsuarios";

                    Response.Redirect("~/contratacion/hojaTrabajoContratacion.aspx?data=" + HttpUtility.UrlEncode(QueryStringSeguro.ToString()));
                }
                else
                {
                    Int32 contadorEnvios = 0;
                    Int32 contadorErrores = 0;

                    StreamReader archivo_original = new StreamReader(Server.MapPath(@"~\plantillas_reportes\email_informativo_descarte_contratacion.htm"));
                    String html_formato_plantilla_email = archivo_original.ReadToEnd();
                    archivo_original.Dispose();
                    archivo_original.Close();

                    String NOMBRE_CANDIDATO = Label_NOMBRE_TRABAJADOR.Text;
                    String NUMERO_IDENTIFICACION = Label_NUM_DOC_IDENTIDAD.Text;
                    String OBSERVACIONES_DESCARTE = TextBox_ObservacionesDescarte.Text.Trim();

                    String NOMBRE_USUARIO;
                    DataTable tablaUsuario = _usuario.ObtenerUsuarioPorUsuLog(Session["USU_LOG"].ToString());
                    DataRow filaUsuario = tablaUsuario.Rows[0];

                    if (filaUsuario["USU_TIPO"].ToString().ToUpper() == "PLANTA")
                    {
                        NOMBRE_USUARIO = filaUsuario["NOMBRES"].ToString().Trim() + " " + filaUsuario["APELLIDOS"].ToString().Trim();
                    }
                    else
                    {
                        NOMBRE_USUARIO = filaUsuario["NOMBRES_EXTERNO"].ToString().Trim() + " " + filaUsuario["APELLIDOS_EXTERNO"].ToString().Trim();
                    }

                    html_formato_plantilla_email = html_formato_plantilla_email.Replace("[NOMBRE_CANDIDATO]", NOMBRE_CANDIDATO);
                    html_formato_plantilla_email = html_formato_plantilla_email.Replace("[NUMERO_IDENTIFICACION]", NUMERO_IDENTIFICACION);
                    html_formato_plantilla_email = html_formato_plantilla_email.Replace("[OBSERVACIONES_DESCARTE]", OBSERVACIONES_DESCARTE);
                    html_formato_plantilla_email = html_formato_plantilla_email.Replace("[NOMBRE_USUARIO]", NOMBRE_USUARIO);

                    tools _tools = new tools();

                    foreach (DataRow filausuario in tablaUsuariosAInformar.Rows)
                    {
                        if (DBNull.Value.Equals(filausuario["USU_MAIL"]) == false)
                        {
                            try
                            {
                                _tools.enviarCorreoConCuerpoHtml(filausuario["USU_MAIL"].ToString().Trim(), "DESCARTE EN CONTRATACIÓN", html_formato_plantilla_email);
                                contadorEnvios += 1;
                            }
                            catch
                            {
                                contadorErrores += 1;
                            }
                        }
                        else
                        {
                            contadorErrores += 1;
                        }
                    }

                    if (contadorEnvios <= 0)
                    {
                        SecureQueryString QueryStringSeguro;
                        QueryStringSeguro = new SecureQueryString(_tools.byteParaQueryStringSeguro());

                        QueryStringSeguro["img_area"] = "contratacion";
                        QueryStringSeguro["nombre_area"] = "CONTRATACIÓN Y RELACIONES LABORALES";
                        QueryStringSeguro["nombre_modulo"] = "HOJA DE TRABAJO DE CONTRATACIÓN";
                        QueryStringSeguro["accion"] = "descarteContratacionNoEmail";

                        Response.Redirect("~/contratacion/hojaTrabajoContratacion.aspx?data=" + HttpUtility.UrlEncode(QueryStringSeguro.ToString()));
                    }
                    else
                    {
                        SecureQueryString QueryStringSeguro;
                        QueryStringSeguro = new SecureQueryString(_tools.byteParaQueryStringSeguro());

                        QueryStringSeguro["img_area"] = "contratacion";
                        QueryStringSeguro["nombre_area"] = "CONTRATACIÓN Y RELACIONES LABORALES";
                        QueryStringSeguro["nombre_modulo"] = "HOJA DE TRABAJO DE CONTRATACIÓN";
                        QueryStringSeguro["accion"] = "descarteContratacionOk";

                        Response.Redirect("~/contratacion/hojaTrabajoContratacion.aspx?data=" + HttpUtility.UrlEncode(QueryStringSeguro.ToString()));
                    }
                }
            }
        }
    }
 private void lblEliminar_MouseDown(object sender, MouseButtonEventArgs e)
 {
     if (listUsuarios.SelectedItem != null)
     {
         controlContacto tarjeta = (controlContacto)listUsuarios.SelectedItem;
         usuario unUsuario = new usuario(tarjeta.lblUsuario.Content.ToString());
         unUsuario.eliminar();
         listUsuarios.Items.Remove(listUsuarios.SelectedItem);
     }
 }
Esempio n. 33
0
        public Result Salvar(usuario usuario)
        {
            Result retorno = new Result();

            try
            {
                if (usuario.ID == Guid.Empty)
                {
                    usuario.ID = Guid.NewGuid();
                    repositoryusuario.Adicionar(usuario);
                }
                else
                {
                    repositoryusuario.Alterar(usuario);
                }

                context.SaveChanges();

                retorno.Ok("Cadastro realizado com sucesso.");
            }
            catch (Exception erro)
            {
                retorno.Erro(erro.Message);
            }

            return retorno;
        }
Esempio n. 34
0
 public UsuarioViewModel(usuario usuario)
 {
     this.Nome = usuario.usu_ds_nome;
 }
Esempio n. 35
0
 public void salvar(usuario usuario)
 {
     insert(usuario);
 }
    public byte[] GenerarPDFEntrevistaRetiro(Decimal ID_EMPLEADO, Decimal ID_SOLICITUD, Decimal ID_EMPRESA)
    {
        String USULOG_ENTREVISTA = Session["USU_LOG"].ToString();

        tools _tools = new tools();

        // OBTENEMOS INFORMACION DE USUARIO
        usuario _usuario = new usuario(Session["idEmpresa"].ToString());
        DataTable tablaUsuario = _usuario.ObtenerUsuarioPorUsuLog(USULOG_ENTREVISTA); //ACA VA ES EL DE LA ENTREVISTA
        DataRow filaUsuario = tablaUsuario.Rows[0];

        String NOMBRE_DILIGENCIA = "";
        if (filaUsuario["USU_TIPO"].ToString().ToUpper() == "PLANTA")
        {
            NOMBRE_DILIGENCIA = filaUsuario["NOMBRES"].ToString().Trim() + " " + filaUsuario["APELLIDOS"].ToString().Trim();
        }
        else
        {
            NOMBRE_DILIGENCIA = filaUsuario["NOMBRES_EXTERNO"].ToString().Trim() + " " + filaUsuario["APELLIDOS_EXTERNO"].ToString().Trim();
        }

        //OBTENEMOS LA INFORMACION DEL CLIENTE
        cliente _cliente = new cliente(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablaCliente = _cliente.ObtenerEmpresaConIdEmpresa(ID_EMPRESA);
        DataRow filaCliente = tablaCliente.Rows[0];

        String RAZ_SOCIAL = filaCliente["RAZ_SOCIAL"].ToString().Trim();
        String NIT_EMPRESA = filaCliente["NIT_EMPRESA"].ToString().Trim() + "-" + filaCliente["DIG_VER"].ToString().Trim();
        String DIR_EMPRESA = filaCliente["DIR_EMP"].ToString().Trim() + " " + filaCliente["ID_CIUDAD_EMPRESA"].ToString().Trim();

        //OBTENEMOS LA INFORMACION DE LA SOLICITUD DE INGRESO
        radicacionHojasDeVida _radicacionHojasDeVida = new radicacionHojasDeVida(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablaSolicitud = _radicacionHojasDeVida.ObtenerRegSolicitudesingresoPorIdSolicitud(Convert.ToInt32(ID_SOLICITUD));
        DataRow filaSolicitud = tablaSolicitud.Rows[0];

        String NOMBRE_ASPIRANTE = filaSolicitud["NOMBRES"].ToString().Trim() + " " + filaSolicitud["APELLIDOS"].ToString().Trim();
        String DOC_IDENTIDAD_ASPIRANTE = filaSolicitud["TIP_DOC_IDENTIDAD"].ToString().Trim() + " " + filaSolicitud["NUM_DOC_IDENTIDAD"].ToString().Trim();
        int EDAD_ASPIRANTE = 0;
        if (DBNull.Value.Equals(filaSolicitud["FCH_NACIMIENTO"]) == false)
        {
            try
            {
                EDAD_ASPIRANTE = _tools.ObtenerEdadDesdeFechaNacimiento(Convert.ToDateTime(filaSolicitud["FCH_NACIMIENTO"]));
            }
            catch
            {
                EDAD_ASPIRANTE = 0;
            }
        }
        String DIRECCION_ASPIRANTE = filaSolicitud["DIR_ASPIRANTE"].ToString().Trim();
        String CIUDAD_ASPIRANTE = filaSolicitud["NOMBRE_CIUDAD"].ToString().Trim();
        String SECTOR_ASPIRANTE = filaSolicitud["SECTOR"].ToString();
        String TELEFONOS_ASPIRANTE = filaSolicitud["TEL_ASPIRANTE"].ToString();
        String EMAIL_ASPIRANTE = filaSolicitud["E_MAIL"].ToString().Trim();

        //DATOS DEL MOTIVO DE RETIRO
        MotivoRotacionRetiro _motivo = new MotivoRotacionRetiro(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablaResultadosEntrevista = _motivo.ObtenerResultadosEntrevistaDeRetiroParaEmpleado(ID_EMPLEADO);

        //CREAMOS LA TABLA DE MOTIVOS DE RETIRO
        Boolean yaSeTieneObservaciones = false;
        String OBSERVACIONES = null;

        String html_tabla_motivos = "<table border=\"1\" cellpadding=\"1\" cellspacing=\"0\" width=\"95%\" align=\"center\" style=\"font-size:8px; line-height:9px;\">";
        html_tabla_motivos += "<tr>";
        html_tabla_motivos += "<td width=\"50%\" style=\"text-align:center;\">";
        html_tabla_motivos += "CATEGORÍA";
        html_tabla_motivos += "</td>";
        html_tabla_motivos += "<td width=\"50%\" style=\"text-align:center;\">";
        html_tabla_motivos += "MOTIVO";
        html_tabla_motivos += "</td>";
        html_tabla_motivos += "</tr>";
        foreach (DataRow filaMotivo in tablaResultadosEntrevista.Rows)
        {
            if (yaSeTieneObservaciones == false)
            {
                //SOLO UNA VEZ
                OBSERVACIONES = filaMotivo["OBSERVACIONES"].ToString().Trim();
                yaSeTieneObservaciones = true;
            }

            Decimal ID_DETALLE_ROTACION_EMPLEADO = Convert.ToDecimal(filaMotivo["ID_DETALLE_ROTACION_EMPLEADO"]);
            Decimal ID_MAESTRA_ROTACION_EMPLEADO = Convert.ToDecimal(filaMotivo["ID_MAESTRA_ROTACION_EMPLEADO"]);
            Decimal ID_ROTACION_EMPRESA = Convert.ToDecimal(filaMotivo["ID_ROTACION_EMPRESA"]);

            //OBTENEMOS DATOS COMPLEMENTARIOS POR MEDIO DE ID_ROTACION_EMPRESA
            DataTable tablaInfoComplementaria = _motivo.ObtenerMotivoEmpresaPorId(ID_ROTACION_EMPRESA);
            DataRow filaInfoComplementaria = tablaInfoComplementaria.Rows[0];

            html_tabla_motivos += "<tr>";
            html_tabla_motivos += "<td width=\"50%\" style=\"text-align:justify;\">";
            html_tabla_motivos += filaInfoComplementaria["TITULO_MAESTRA_ROTACION"];
            html_tabla_motivos += "</td>";
            html_tabla_motivos += "<td width=\"50%\" style=\"text-align:justify;\">";
            html_tabla_motivos += filaInfoComplementaria["TITULO"];
            html_tabla_motivos += "</td>";
            html_tabla_motivos += "</tr>";
        }
        html_tabla_motivos += "</table>";

        /*
         * Generación del archi de informe de entrevista de retiro
         * Stream con el contenido del pdf.
        */
        String html_encabezado = "<html>";
        html_encabezado += "<head>";
        html_encabezado += "</head>";
        html_encabezado += "<body>";

        String html_pie = "</body>";
        html_pie += "</html>";

        //En esta variable cargamos el documento plantilla
        StreamReader archivo_original = new StreamReader(Server.MapPath(@"~\plantillas_reportes\entrevista_retiro.htm"));

        String html_formato_entrevista = html_encabezado + archivo_original.ReadToEnd();

        archivo_original.Dispose();
        archivo_original.Close();

        html_formato_entrevista = html_formato_entrevista.Replace("[RAZ_SOCIAL]", RAZ_SOCIAL);
        html_formato_entrevista = html_formato_entrevista.Replace("[NIT_EMPRESA]", NIT_EMPRESA);
        html_formato_entrevista = html_formato_entrevista.Replace("[DIR_EMPRESA]", DIR_EMPRESA);

        html_formato_entrevista = html_formato_entrevista.Replace("[NOMBRE_ASPIRANTE]", NOMBRE_ASPIRANTE);
        html_formato_entrevista = html_formato_entrevista.Replace("[DOC_IDENTIDAD_ASPIRANTE]", DOC_IDENTIDAD_ASPIRANTE);
        if (EDAD_ASPIRANTE > 0)
        {
            html_formato_entrevista = html_formato_entrevista.Replace("[EDAD_ASPIRANTE]", EDAD_ASPIRANTE.ToString() + " Años.");
        }
        else
        {
            html_formato_entrevista = html_formato_entrevista.Replace("[EDAD_ASPIRANTE]", "Desconocida.");
        }
        html_formato_entrevista = html_formato_entrevista.Replace("[DIRECCION_ASPIRANTE]", DIRECCION_ASPIRANTE);
        html_formato_entrevista = html_formato_entrevista.Replace("[CIUDAD_ASPIRANTE]", CIUDAD_ASPIRANTE);
        html_formato_entrevista = html_formato_entrevista.Replace("[SECTOR_ASPIRANTE]", SECTOR_ASPIRANTE);
        html_formato_entrevista = html_formato_entrevista.Replace("[TELEFONOS_ASPIRANTE]", TELEFONOS_ASPIRANTE);
        html_formato_entrevista = html_formato_entrevista.Replace("[EMAIL_ASPIRANTE]", EMAIL_ASPIRANTE);

        html_formato_entrevista = html_formato_entrevista.Replace("[TABLA_MOTIVOS_RETIRO]", html_tabla_motivos);

        html_formato_entrevista = html_formato_entrevista.Replace("[OBSERVACIONES]", OBSERVACIONES);

        html_formato_entrevista = html_formato_entrevista.Replace("[NOMBRE_DILIGENCIA]", NOMBRE_DILIGENCIA);

        html_formato_entrevista += html_pie;

        //creamos un configuramos el documento de pdf
        //(tamaño de la hoja,margen izq, margen der, margin arriba margen abajo)
        iTextSharp.text.Document document = new iTextSharp.text.Document(new Rectangle(595, 842), 50, 50, 80, 45);

        using (MemoryStream streamArchivo = new MemoryStream())
        {
            iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(document, streamArchivo);

            // Our custom Header and Footer is done using Event Handler
            pdfEvents PageEventHandler = new pdfEvents();
            writer.PageEvent = PageEventHandler;

            // Define the page header
            // Define the page header
            if (Session["idEmpresa"].ToString() == "1")
            {
                PageEventHandler.dirImagenHeader = Server.MapPath("~/imagenes/reportes/logo_sertempo.png");
            }
            else
            {
                PageEventHandler.dirImagenHeader = Server.MapPath("~/imagenes/reportes/logo_eficiencia.png");
            }

            PageEventHandler.fechaImpresion = DateTime.Now;
            PageEventHandler.tipoDocumento = "entrevista_retiro";

            document.Open();

            //capturamos el archivo temporal del response
            String tempFile = Path.GetTempFileName();

            //y lo llenamos con el html de la plantilla
            using (StreamWriter tempwriter = new StreamWriter(tempFile, false))
            {
                tempwriter.Write(html_formato_entrevista);
            }

            //leeemos el archivo temporal y lo colocamos en el documento de pdf
            List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StreamReader(tempFile), new StyleSheet());

            foreach (IElement element in htmlarraylist)
            {
                if (element.Chunks.Count > 0)
                {
                    if (element.Chunks[0].Content == "linea para paginacion de pdf")
                    {
                        document.NewPage();
                    }
                    else
                    {
                        document.Add(element);
                    }
                }
                else
                {
                    document.Add(element);
                }
            }

            //limpiamos todo
            document.Close();

            writer.Close();

            return streamArchivo.ToArray();
        }
    }
    private void Cargar(Acciones accion)
    {
        DataTable dataTable = new DataTable();
        switch(accion)
        {
            case Acciones.Inicio:
                cliente _cliente = new cliente(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
                dataTable = _cliente.ObtenerTodasLasEmpresasActivas();
                Cargar(dataTable, this.DropDownList_empresas, "ID_EMPRESA", "RAZ_SOCIAL");

                dataTable = _cliente.ObtenerEmpresaConIdEmpresa(Convert.ToDecimal(this.HiddenField_ID_EMPRESA.Value));
                Cargar(dataTable);

                usuario _usuario = new usuario(Session["idEmpresa"].ToString());
                dataTable = _usuario.ObtenerEmpleadosRestriccionEmpresas();
                Cargar(dataTable, this.DropDownList_usuario, "Id_Usuario", "NOMBRE_EMPLEADO");

                parametro _parametro = new parametro(Session["idEmpresa"].ToString());
                dataTable = _parametro.ObtenerParametrosPorTabla(tabla.PARAMETROS_UNIDAD_NEGOCIO);
                Cargar(dataTable, this.DropDownList_unidad_negocio, "codigo", "descripcion");

                Cargar(GridView_unidades_negocio);
                break;

        }
        if (dataTable == null) dataTable.Dispose();
    }
    private void CargarEmpleadoInicial(Decimal ID_EMPLEADO)
    {
        usuario _usuario = new usuario(Session["idEmpresa"].ToString());

        DataTable tablaDatos = _usuario.ObtenerEmpleadoPorIdEmpleado(ID_EMPLEADO);

        if (tablaDatos.Rows.Count <= 0)
        {
            Ocultar(Acciones.Inicio);
            Desactivar(Acciones.Inicio);
            Mostrar(Acciones.Inicio);
            Cargar(Acciones.Inicio);

            if (_usuario.MensajeError != null)
            {
                Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, _usuario.MensajeError, Proceso.Error);
            }
            else
            {
                Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, "No se encontró información del Empleado parametrizado.", Proceso.Error);
            }
        }
        else
        {
            DataRow filaDatos = tablaDatos.Rows[0];

            Decimal ID_SOLICITUD = Convert.ToDecimal(filaDatos["ID_SOLICITUD"]);
            Decimal ID_CONTRATO = Convert.ToDecimal(filaDatos["ID_CONTRATO"]);
            Decimal ID_EMPRESA = Convert.ToDecimal(filaDatos["ID_EMPRESA"]);
            Decimal ID_OCUPACION = Convert.ToDecimal(filaDatos["ID_OCUPACION"]);
            String ID_CIUDAD = filaDatos["ID_CIUDAD"].ToString().Trim();

            Cargar(ID_SOLICITUD, ID_CONTRATO, ID_EMPLEADO, ID_EMPRESA, ID_OCUPACION, ID_CIUDAD);
        }
    }
Esempio n. 39
0
 public void Save(usuario oUsuario)
 {
     cooperativaEntities bd = new cooperativaEntities();
     bd.usuario.AddObject(oUsuario);
     bd.SaveChanges();
 }
Esempio n. 40
0
 public void Update(usuario oUsuario)
 {
     using (cooperativaEntities bd = new cooperativaEntities())
     {
         var editar = (from p in bd.usuario
                       where p.id_usuario == oUsuario.id_usuario
                       select p).Single();
         editar.nombre = oUsuario.nombre;
         editar.login = oUsuario.login;
         editar.password = oUsuario.password;
         editar.modificarDatos = oUsuario.modificarDatos;
         editar.facturacion_anulacion = oUsuario.facturacion_anulacion;
         editar.impresion_reimpresion = oUsuario.impresion_reimpresion;
         editar.cobranza_cierreCaja = oUsuario.cobranza_cierreCaja;
         editar.listados_reportes = oUsuario.listados_reportes;
         editar.avisosDeuda_listadosCortes=oUsuario.avisosDeuda_listadosCortes;
         editar.reparar_optimizar_respaldo = oUsuario.reparar_optimizar_respaldo;
         editar.configurar = oUsuario.configurar;
         editar.administracion = oUsuario.administracion;
         editar.autorizarCobroSI = oUsuario.autorizarCobroSI;
         editar.autorizarConvenios = oUsuario.autorizarConvenios;
         editar.listados_padrones = oUsuario.listados_padrones;
         editar.judicial_codene = oUsuario.judicial_codene;
         editar.mantenimiento = oUsuario.mantenimiento;
         editar.activo = oUsuario.activo;
         bd.SaveChanges();
     }
 }
    private void CargarDatosUsuarioConectado()
    {
        usuario _usu = new usuario(Session["idEmpresa"].ToString());

        DataTable tablaUsu = _usu.ObtenerUsuarioPorUsuLog(Session["USU_LOG"].ToString());

        if (tablaUsu.Rows.Count <= 0)
        {
            if (_usu.MensajeError != null)
            {
                Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, _usu.MensajeError, Proceso.Error);
            }
            else
            {
                Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, "No se encontró información del USUARIO seleccionado.", Proceso.Advertencia);
            }

            Panel_Formulario.Visible = false;
        }
        else
        {
            DataRow filaUsu = tablaUsu.Rows[0];

            TextBox_USU_LOG.Text = Session["USU_LOG"].ToString();

            if ((DBNull.Value.Equals(filaUsu["USU_MAIL"]) == false))
            {
                if ((filaUsu["USU_MAIL"].ToString().ToUpper() == "*****@*****.**") || (filaUsu["USU_MAIL"].ToString().ToUpper() == "*****@*****.**"))
                {
                    TextBox_USU_MAIL.Text = "";
                }
                else
                {
                    TextBox_USU_MAIL.Text = filaUsu["USU_MAIL"].ToString();
                }
            }
            else
            {
                TextBox_USU_MAIL.Text = "";
            }

            TextBox_USU_PSW_ANT.Text = "";
            TextBox_USU_PSW_NEW.Text = "";
            TextBox_USU_PSW_NEW_CONF.Text = "";
        }
    }
    /// <summary>
    /// hecho por cesar pulido
    /// el dia 19 de diciembre de 2012
    /// para generar el archivo del contrato
    /// </summary>
    /// <param name="filaInfoContrato"></param>
    /// <returns></returns>
    private byte[] ImprimirContratoO_L_COMPLETO(DataRow filaInfoContrato)
    {
        tools _tools = new tools();

        Boolean CarnetIncluido = false;

        //En esta variable cargamos el documento plantilla segun la empresa de session
        StreamReader archivo;

        if (Session["idEmpresa"].ToString() == "1")
        {
            if (CarnetIncluido == true)
            {
                archivo = new StreamReader(Server.MapPath(@"~\plantillas_reportes\contrato_sertempo_obra_labor.htm"));
            }
            else
            {
                archivo = new StreamReader(Server.MapPath(@"~\plantillas_reportes\contrato_sertempo_obra_labor_carnet_aparte.htm"));
            }
        }
        else
        {
            if (CarnetIncluido == true)
            {
                archivo = new StreamReader(Server.MapPath(@"~\plantillas_reportes\contrato_eys_labor_contratada.htm"));
            }
            else
            {
                archivo = new StreamReader(Server.MapPath(@"~\plantillas_reportes\contrato_eys_labor_contratada_carnet_aparte.htm"));
            }
        }

        String html = archivo.ReadToEnd();

        archivo.Dispose();
        archivo.Close();

        if (Session["idEmpresa"].ToString() == "1")
        {
            html = html.Replace("[DIR_LOGO_EMPLEADOR]", tabla.DIR_IMAGENES_PARA_PDF + "/logo_sertempo.png");
            html = html.Replace("[MENSAJE_LOGO]", "SERVICIOS TEMPORALES PROFESIONALES");
            html = html.Replace("[NOMBRE_EMPLEADOR]", tabla.VAR_NOMBRE_SERTEMPO);
            html = html.Replace("[DOMICILO_EMPLEADOR]", tabla.VAR_DOMICILIO_SERTEMPO);
            html = html.Replace("[DESCRIPCION_CARGO]", filaInfoContrato["DSC_FUNCIONES"].ToString().Trim().ToUpper());
            html = html.Replace("[SERVICIO_RESPECTIVO]", filaInfoContrato["DESCRIPCION"].ToString().Trim().ToUpper());
            html = html.Replace("[EMPRESA_USUARIA]", filaInfoContrato["RAZ_SOCIAL"].ToString().Trim().ToUpper());
            html = html.Replace("[DIR_FIRMA_EMPLEADOR]", tabla.DIR_IMAGENES_PARA_PDF + "/firma_contrato_empleador_sertempo.jpg");
        }
        else
        {
            html = html.Replace("[DIR_LOGO_EMPLEADOR]", tabla.DIR_IMAGENES_PARA_PDF + "/logo_eficiencia.jpg");
            html = html.Replace("[NOMBRE_EMPLEADOR]", tabla.VAR_NOMBRE_EYS);
            html = html.Replace("[DOMICILO_EMPLEADOR]", tabla.VAR_DOMICILIO_EYS);
            html = html.Replace("[FUNCION_CARGO]", filaInfoContrato["DSC_FUNCIONES"].ToString().Trim().ToUpper());
            html = html.Replace("[ACTIVIDAD_CONTRATADA]", filaInfoContrato["DSC_FUNCIONES"].ToString().Trim().ToUpper());
            html = html.Replace("[EMPRESA_DESTACA]", filaInfoContrato["RAZ_SOCIAL"].ToString().Trim().ToUpper());
            html = html.Replace("[DIR_FIRMA_EMPLEADOR]", tabla.DIR_IMAGENES_PARA_PDF + "/firma_contrato_empleador_eys.jpg");
        }

        html = html.Replace("[CARGO_TRABAJADOR]", filaInfoContrato["NOM_OCUPACION"].ToString().Trim().ToUpper());
        html = html.Replace("[NOMBRE_TRABAJADOR]", filaInfoContrato["APELLIDOS"].ToString().Trim().ToUpper() + " " + filaInfoContrato["NOMBRES"].ToString().Trim().ToUpper());
        html = html.Replace("[TIPO_DOCUMENTO_IDENTIDAD]", filaInfoContrato["TIP_DOC_IDENTIDAD"].ToString().Trim().ToUpper());
        html = html.Replace("[DOC_IDENTIFICACION]", filaInfoContrato["NUM_DOC_IDENTIDAD"].ToString().Trim().ToUpper());
        html = html.Replace("[SALARIO]", Convert.ToDecimal(filaInfoContrato["SALARIO"]).ToString());
        html = html.Replace("[PERIODO_PAGO]", "??");
        html = html.Replace("[FECHA_INICIACION]", Convert.ToDateTime(filaInfoContrato["FECHA_INICIA"]).ToLongDateString());
        html = html.Replace("[CARNE_VALIDO_HASTA]", Convert.ToDateTime(filaInfoContrato["FECHA_TERMINA"]).ToLongDateString());

        //esto es para obtener la ciudad de impresión del contrato
        //OBTENEMOS LA CIUDAD DE FIRMA, DESDE LA CIUDAD DEL USU_LOG
        usuario _usuario = new usuario(Session["idEmpresa"].ToString());
        DataTable tablaInfoUsuario = _usuario.ObtenerInicioSesionPorUsuLog(Session["USU_LOG"].ToString());
        if (tablaInfoUsuario.Rows.Count <= 0)
        {
            html = html.Replace("[CIUDAD_FIRMA]", "Desconocida");
        }
        else
        {
            DataRow filaInfoUsuario = tablaInfoUsuario.Rows[0];
            html = html.Replace("[CIUDAD_FIRMA]", filaInfoUsuario["NOMBRE_CIUDAD"].ToString());
        }

        DateTime fechaHoy = DateTime.Now;
        html = html.Replace("[DIAS_FIRMA]", fechaHoy.Day.ToString());
        html = html.Replace("[MES_FIRMA]", _tools.obtenerNombreMes(fechaHoy.Month));
        html = html.Replace("[ANNO_FIRMA]", fechaHoy.Year.ToString());

        //creamos un configuramos el documento de pdf
        //(tamaño de la hoja,margen izq, margen der, margin arriba margen abajo)
        iTextSharp.text.Document document = new iTextSharp.text.Document(new Rectangle(612, 936), 15, 15, 5, 15);

        using (MemoryStream streamArchivo = new MemoryStream())
        {
            iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(document, streamArchivo);

            // Our custom Header and Footer is done using Event Handler
            pdfEvents PageEventHandler = new pdfEvents();
            writer.PageEvent = PageEventHandler;

            PageEventHandler.tipoDocumento = "contrato";

            document.Open();

            //capturamos el archivo temporal del response
            String tempFile = Path.GetTempFileName();

            //y lo llenamos con el html de la plantilla
            using (StreamWriter tempwriter = new StreamWriter(tempFile, false))
            {
                tempwriter.Write(html);
            }

            //leeemos el archivo temporal y lo colocamos en el documento de pdf
            List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StreamReader(tempFile), new StyleSheet());

            foreach (IElement element in htmlarraylist)
            {
                if (element.Chunks.Count > 0)
                {
                    if (element.Chunks[0].Content == "linea para paginacion de pdf")
                    {
                        document.NewPage();
                    }
                    else
                    {
                        document.Add(element);
                    }
                }
                else
                {
                    document.Add(element);
                }
            }

            //limpiamos todo
            document.Close();

            writer.Close();

            return streamArchivo.ToArray();
        }
    }
    protected void CheckBox_PSICOLOGO_CheckedChanged(object sender, EventArgs e)
    {
        if(CheckBox_PSICOLOGO.Checked)
        {
            Panel_PARAMETROS.Visible = true;
            Panel_psicologo.Visible = true;

            DropDownList_PSICOLOGO.Items.Clear();

            usuario _usuario = new usuario(Session["idEmpresa"].ToString());
            DataTable tablaPsicologos = _usuario.ObtenerEmpleadosPorIdRol(usuario.Rol.Psicologo);

            ListItem item = new ListItem("Seleccione Psicologo", "");
            DropDownList_PSICOLOGO.Items.Add(item);

            foreach (DataRow fila in tablaPsicologos.Rows)
            {
                item = new ListItem(fila["NOMBRE_EMPLEADO"].ToString(), fila["ID_EMPLEADO"].ToString());
                DropDownList_PSICOLOGO.Items.Add(item);
            }

            DropDownList_PSICOLOGO.DataBind();
        }
        else
        {
            Panel_PARAMETROS.Visible = true;
            Panel_psicologo.Visible = false;
        }
    }
    private void EnviarCorreoAComercial()
    {
        tools _tools = new tools();
        Decimal ID_EMPRESA = Convert.ToDecimal(HiddenField_ID_EMPRESA.Value);

        seguridad _seguridad = new seguridad(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablaUsuariosEmpresa = _seguridad.ObtenerUsuariosPorEmpresa(ID_EMPRESA);

        if (tablaUsuariosEmpresa.Rows.Count <= 0)
        {
            if (_seguridad.MensajeError != null)
            {
                Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, _seguridad.MensajeError, Proceso.Error);
            }
            else
            {
                Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, "La ubicación seleccionada NO posee CONDICIONES COMERCIALES. Puede continuar con el proceso, pero debe informar personalmente a un Representante Comercial para que ingrese las CONDICIONES COMERCIALES para esta empresa.", Proceso.Advertencia);
            }
        }
        else
        {
            StreamReader archivo_original = new StreamReader(Server.MapPath(@"~\plantillas_reportes\email_conf_condiciones_comerciales.htm"));
            String html_formato_plantilla_email = archivo_original.ReadToEnd();
            archivo_original.Dispose();
            archivo_original.Close();

            String html_tabla_ubicacion_perfil = "<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" width=\"400px\" style=\"font-size:11px; line-height:13px;\">";
            if (DropDownList_SUB_CENTRO.SelectedIndex > 0)
            {
                html_tabla_ubicacion_perfil += "<tr>";
                html_tabla_ubicacion_perfil += "<td width=\"30%\" valign=\"middle\" style=\"text-align: left; font-weight: bold;\">";
                html_tabla_ubicacion_perfil += "CIUDAD:";
                html_tabla_ubicacion_perfil += "</td>";
                html_tabla_ubicacion_perfil += "<td width=\"70%\" valign=\"middle\" style=\"text-align: justify;\">";
                html_tabla_ubicacion_perfil += DropDownList_CIUDAD.SelectedItem.Text;
                html_tabla_ubicacion_perfil += "</td>";
                html_tabla_ubicacion_perfil += "</tr>";

                html_tabla_ubicacion_perfil += "<tr>";
                html_tabla_ubicacion_perfil += "<td width=\"30%\" valign=\"middle\" style=\"text-align: left; font-weight: bold;\">";
                html_tabla_ubicacion_perfil += "CENTRO DE COSTO:";
                html_tabla_ubicacion_perfil += "</td>";
                html_tabla_ubicacion_perfil += "<td width=\"70%\" valign=\"middle\" style=\"text-align: justify;\">";
                html_tabla_ubicacion_perfil += DropDownList_CENTRO_COSTO.SelectedItem.Text;
                html_tabla_ubicacion_perfil += "</td>";
                html_tabla_ubicacion_perfil += "</tr>";

                html_tabla_ubicacion_perfil += "<tr>";
                html_tabla_ubicacion_perfil += "<td width=\"30%\" valign=\"middle\" style=\"text-align: left; font-weight: bold;\">";
                html_tabla_ubicacion_perfil += "SUB CENTRO:";
                html_tabla_ubicacion_perfil += "</td>";
                html_tabla_ubicacion_perfil += "<td width=\"70%\" valign=\"middle\" style=\"text-align: justify;\">";
                html_tabla_ubicacion_perfil += DropDownList_SUB_CENTRO.SelectedItem.Text;
                html_tabla_ubicacion_perfil += "</td>";
                html_tabla_ubicacion_perfil += "</tr>";
            }
            else
            {
                if (DropDownList_CENTRO_COSTO.SelectedIndex > 0)
                {
                    html_tabla_ubicacion_perfil += "<tr>";
                    html_tabla_ubicacion_perfil += "<td width=\"30%\" valign=\"middle\" style=\"text-align: left; font-weight: bold;\">";
                    html_tabla_ubicacion_perfil += "CIUDAD:";
                    html_tabla_ubicacion_perfil += "</td>";
                    html_tabla_ubicacion_perfil += "<td width=\"70%\" valign=\"middle\" style=\"text-align: justify;\">";
                    html_tabla_ubicacion_perfil += DropDownList_CIUDAD.SelectedItem.Text;
                    html_tabla_ubicacion_perfil += "</td>";
                    html_tabla_ubicacion_perfil += "</tr>";

                    html_tabla_ubicacion_perfil += "<tr>";
                    html_tabla_ubicacion_perfil += "<td width=\"30%\" valign=\"middle\" style=\"text-align: left; font-weight: bold;\">";
                    html_tabla_ubicacion_perfil += "CENTRO DE COSTO:";
                    html_tabla_ubicacion_perfil += "</td>";
                    html_tabla_ubicacion_perfil += "<td width=\"70%\" valign=\"middle\" style=\"text-align: justify;\">";
                    html_tabla_ubicacion_perfil += DropDownList_CENTRO_COSTO.SelectedItem.Text;
                    html_tabla_ubicacion_perfil += "</td>";
                    html_tabla_ubicacion_perfil += "</tr>";
                }
                else
                {
                    html_tabla_ubicacion_perfil += "<tr>";
                    html_tabla_ubicacion_perfil += "<td width=\"30%\" valign=\"middle\" style=\"text-align: left; font-weight: bold;\">";
                    html_tabla_ubicacion_perfil += "CIUDAD:";
                    html_tabla_ubicacion_perfil += "</td>";
                    html_tabla_ubicacion_perfil += "<td width=\"70%\" valign=\"middle\" style=\"text-align: justify;\">";
                    html_tabla_ubicacion_perfil += DropDownList_CIUDAD.SelectedItem.Text;
                    html_tabla_ubicacion_perfil += "</td>";
                    html_tabla_ubicacion_perfil += "</tr>";
                }
            }
            html_tabla_ubicacion_perfil += "</table>";

            html_formato_plantilla_email = html_formato_plantilla_email.Replace("[RAZ_SOCIAL]", Label_INFO_ADICIONAL_MODULO.Text);
            html_formato_plantilla_email = html_formato_plantilla_email.Replace("[TABLA_UBICACION]", html_tabla_ubicacion_perfil);
            html_formato_plantilla_email = html_formato_plantilla_email.Replace("[NOM_OCUPACION]", Label_NOM_OCUPACION.Text);
            html_formato_plantilla_email = html_formato_plantilla_email.Replace("[EDAD_MIN]", Label_EDAD_MIN.Text);
            html_formato_plantilla_email = html_formato_plantilla_email.Replace("[EDAD_MAX]", Label_EDAD_MAX.Text);
            html_formato_plantilla_email = html_formato_plantilla_email.Replace("[NIVEL_ACADEMICO]", Label_NIVEL_ACADEMICO.Text);
            html_formato_plantilla_email = html_formato_plantilla_email.Replace("[EXPERIENCIA]", Label_EXPERIENCIA.Text);
            html_formato_plantilla_email = html_formato_plantilla_email.Replace("[SEXO]", Label_SEXO.Text);

            usuario _usuario = new usuario(Session["idEmpresa"].ToString());
            DataTable tablaUsuario = _usuario.ObtenerUsuarioPorUsuLog(Session["USU_LOG"].ToString());
            DataRow filaUsuario = tablaUsuario.Rows[0];

            if (filaUsuario["USU_TIPO"].ToString().ToUpper() == "PLANTA")
            {
                html_formato_plantilla_email = html_formato_plantilla_email.Replace("[NOMBRE_USUARIO]", filaUsuario["NOMBRES"].ToString().Trim() + " " + filaUsuario["APELLIDOS"].ToString().Trim());
            }
            else
            {
                html_formato_plantilla_email = html_formato_plantilla_email.Replace("[NOMBRE_USUARIO]", filaUsuario["NOMBRES_EXTERNO"].ToString().Trim() + " " + filaUsuario["APELLIDOS_EXTERNO"].ToString().Trim());
            }

            Int32 contadorEnvioEmail = 0;
            Int32 contadorErrores = 0;
            foreach (DataRow fila in tablaUsuariosEmpresa.Rows)
            {
                if (fila["UNIDAD_NEGOCIO"].ToString().Trim().Contains("REP. COMERCIAL") == true)
                {
                    if (DBNull.Value.Equals(fila["USU_MAIL"]) == false)
                    {
                        try
                        {
                            _tools.enviarCorreoConCuerpoHtml(fila["USU_MAIL"].ToString().Trim(), "CONFIGURACIÓN DE CONDICIONES COMERCIALES", html_formato_plantilla_email);
                            contadorEnvioEmail += 1;
                        }
                        catch
                        {
                            contadorErrores += 1;
                        }
                    }
                }
            }

            if (contadorEnvioEmail <= 0)
            {
                if (contadorErrores <= 0)
                {
                    Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, "La ubicación seleccionada NO posee CONDICIONES COMERCIALES. Puede continuar con el proceso, pero debe informar personalmente a un Representante Comercial para que ingrese las CONDICIONES COMERCIALES para esta empresa.", Proceso.Advertencia);
                }
                else
                {
                    Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, "La ubicación seleccionada NO posee CONDICIONES COMERCIALES. Puede continuar con el proceso, pero debe informar personalmente a un Representante Comercial para que ingrese las CONDICIONES COMERCIALES para esta empresa. (Problema con envío de Emails)", Proceso.Advertencia);
                }
            }
        }
    }
    /// <summary>
    /// HECHO POR CESAR PULIDO
    /// EL DIA 18 DE DICIMEBRE DE 2012
    /// PARA GENERAR LA ENTRVISTA CON O SIN COMPETENCIAS
    /// </summary>
    /// <returns></returns>
    public byte[] GenerarPDFEntrevista(Decimal ID_SOLICITUD, Decimal ID_PERFIL)
    {
        //ok
        tools _tools = new tools();

        radicacionHojasDeVida _radicacionHojasDeVida = new radicacionHojasDeVida(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablaSolicitud = _radicacionHojasDeVida.ObtenerRegSolicitudesingresoPorIdSolicitud(Convert.ToInt32(ID_SOLICITUD));
        DataRow filaSolicitud = tablaSolicitud.Rows[0];

        String NOMBRE_ASPIRANTE = filaSolicitud["NOMBRES"].ToString().Trim() + " " + filaSolicitud["APELLIDOS"].ToString().Trim();

        String DOC_IDENTIDAD_ASPIRANTE = filaSolicitud["TIP_DOC_IDENTIDAD"].ToString().Trim() + " " + filaSolicitud["NUM_DOC_IDENTIDAD"].ToString().Trim();

        int EDAD_ASPIRANTE = 0;
        if (DBNull.Value.Equals(filaSolicitud["FCH_NACIMIENTO"]) == false)
        {
            try
            { EDAD_ASPIRANTE = _tools.ObtenerEdadDesdeFechaNacimiento(Convert.ToDateTime(filaSolicitud["FCH_NACIMIENTO"])); }
            catch { EDAD_ASPIRANTE = 0; }
        }

        String TIPO_VIVIENDA_ASPIRANTE = "Desconocida";
        if(DBNull.Value.Equals(filaSolicitud["TIPO_VIVIENDA"]) == false)
        {
            TIPO_VIVIENDA_ASPIRANTE = filaSolicitud["TIPO_VIVIENDA"].ToString().Trim();
        }

        String CIUDAD_ASPIRANTE = "Desconocida";
        if (DBNull.Value.Equals(filaSolicitud["NOMBRE_CIUDAD"]) == false)
        {
            CIUDAD_ASPIRANTE = filaSolicitud["NOMBRE_CIUDAD"].ToString().Trim();
        }

        String DIRECCION_ASPIRANTE = filaSolicitud["DIR_ASPIRANTE"].ToString().Trim();

        String SECTOR_ASPIRANTE = filaSolicitud["SECTOR"].ToString().Trim();

        String ESTRATO_ASPIRANTE = "Desconocido";
        if (DBNull.Value.Equals(filaSolicitud["ESTRATO"]) == false) { ESTRATO_ASPIRANTE = filaSolicitud["ESTRATO"].ToString().Trim(); }

        String TELEFONOS_ASPIRANTE = filaSolicitud["TEL_ASPIRANTE"].ToString();

        String ASPIRACION_SALARIAL_ASPIRANTE;
        try { ASPIRACION_SALARIAL_ASPIRANTE = Convert.ToInt32(filaSolicitud["ASPIRACION_SALARIAL"]).ToString(); }
        catch { ASPIRACION_SALARIAL_ASPIRANTE = "Desconocido."; }

        String ESTADO_CIVIL = "Desconocido";
        if (DBNull.Value.Equals(filaSolicitud["ESTADO_CIVIL"]) == false)
        {
            ESTADO_CIVIL = filaSolicitud["ESTADO_CIVIL"].ToString().Trim();
        }

        String EMAIL_ASPIRANTE = filaSolicitud["E_MAIL"].ToString().Trim();

        //FEMENINO, MASCULINO
        String SEXO = "Desconocido.";
        String LIBRETA_MILITAR = "Desconocida.";
        if (DBNull.Value.Equals(filaSolicitud["SEXO"]) == false)
        {
            if (filaSolicitud["SEXO"].ToString().ToUpper() == "F")
            {
                SEXO = "Femenino";
                LIBRETA_MILITAR = "No Aplica";
            }
            else
            {
                if (filaSolicitud["SEXO"].ToString().ToUpper() == "M")
                {
                    SEXO = "Masculino";
                    LIBRETA_MILITAR = filaSolicitud["LIB_MILITAR"].ToString();
                }
            }
        }

        //cargo al que aspira el candidato (cargo generico)
        String CARGO_APLICA = "Desconocido";
        Decimal ID_OCUPACION = 0;
        perfil _perfil = new perfil(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablaPerfil = new DataTable();
        Decimal ID_ASSESMENT_CENTER = 0;

        if (ID_PERFIL <= 0)
        {
            CARGO_APLICA = "Entrevista por Producción.";
            ID_ASSESMENT_CENTER = 0;
        }
        else
        {
            tablaPerfil = _perfil.ObtenerPorRegistro(ID_PERFIL);
            if (tablaPerfil.Rows.Count <= 0)
            {
                CARGO_APLICA = "Desconocido.";
                ID_ASSESMENT_CENTER = 0;
            }
            else
            {
                DataRow filaPerfil = tablaPerfil.Rows[0];
                try
                {
                    ID_OCUPACION = Convert.ToDecimal(filaPerfil["ID_OCUPACION"]);
                }
                catch
                {
                    ID_OCUPACION = 0;
                }

                if (ID_OCUPACION > 0)
                {
                    cargo _cargo = new cargo(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
                    DataTable tablaOcupacionAspira = _cargo.ObtenerOcupacionPorIdOcupacion(ID_OCUPACION);

                    if (tablaOcupacionAspira.Rows.Count > 0)
                    {
                        DataRow filaOcupacionAspira = tablaOcupacionAspira.Rows[0];
                        CARGO_APLICA = filaOcupacionAspira["NOM_OCUPACION"].ToString().Trim();
                    }
                }

                //DETERMINAMOS SI SE TIENE UN ID_ASSESMENT_CENTER ASOCIADO AL PERFIL
                if(filaPerfil["TIPO_ENTREVISTA"].ToString().Trim() == "A")
                {
                    try
                    {
                        ID_ASSESMENT_CENTER = Convert.ToDecimal(filaPerfil["ID_ASSESMENT_CENTAR"]);
                    }
                    catch
                    {
                        ID_ASSESMENT_CENTER = 0;
                    }
                }
                else
                {
                    ID_ASSESMENT_CENTER = 0;
                }
            }
        }

        //si la entrevista basica existe ya
        hojasVida _hojasVida = new hojasVida(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablaEntrevista = _hojasVida.ObtenerSelRegEntrevistasPorIdSolicitud(ID_SOLICITUD);

        String FECHA_ENTREVISTA = "Desconocida.";
        String COMPOSICION_FAMILIAR_ASPIRANTE = "Desconocida.";
        String INFO_ACADEMICA_ASPIRANTE = "Desconocida.";
        String EXPERIENCIA_LAB_ASPIRANTE = "Desconocida.";
        String CONCEPTO_GENERAL = "Desconodido.";
        String USUARIO_ENTREVISTADOR = Session["USU_LOG"].ToString();

        Decimal ID_ENTREVISTA = 0;

        if (tablaEntrevista.Rows.Count > 0)
        {
            DataRow filaEntrevista = tablaEntrevista.Rows[0];

            ID_ENTREVISTA = Convert.ToDecimal(filaEntrevista["REGISTRO"]);

            try
            {
                FECHA_ENTREVISTA = Convert.ToDateTime(filaEntrevista["FCH_ENTREVISTA"]).ToShortDateString();
            }
            catch
            {
                FECHA_ENTREVISTA = "Desconocida.";
            }

            COMPOSICION_FAMILIAR_ASPIRANTE = filaEntrevista["COM_C_FAM"].ToString().Trim();
            INFO_ACADEMICA_ASPIRANTE = filaEntrevista["COM_C_ACA"].ToString().Trim();
            EXPERIENCIA_LAB_ASPIRANTE = filaEntrevista["COM_F_LAB"].ToString().Trim();
            CONCEPTO_GENERAL = filaEntrevista["COM_C_GEN"].ToString().Trim();

            if (DBNull.Value.Equals(filaEntrevista["USU_MOD"]) == false)
            {
                USUARIO_ENTREVISTADOR = filaEntrevista["USU_MOD"].ToString().Trim();
            }
            else
            {
                USUARIO_ENTREVISTADOR = filaEntrevista["USU_CRE"].ToString().Trim();
            }
        }

        String NIVEL_ESCOLARIDAD = "Desconocido";
        if (DBNull.Value.Equals(filaSolicitud["NIVEL_ESCOLARIDAD"]) == false)
        {
            if (filaSolicitud["NIVEL_ESCOLARIDAD"].ToString().Trim() == "NO REQUERIDO")
            {
                NIVEL_ESCOLARIDAD = "NO APLICA";
            }
            else
            {
                NIVEL_ESCOLARIDAD = filaSolicitud["NIVEL_ESCOLARIDAD"].ToString().Trim();
            }
        }

        String PROFESION_ASPIRANTE = "Desconocida";
        if (DBNull.Value.Equals(filaSolicitud["ID_NUCLEO_FORMACION"]) == false)
        {
            PROFESION_ASPIRANTE = filaSolicitud["ID_NUCLEO_FORMACION"].ToString().Trim();
        }

        String ESPECIALIZACION_ASPIRANTE = "Desconocida";
        if (DBNull.Value.Equals(filaSolicitud["AREA_INTERES"]) == false)
        {
            ESPECIALIZACION_ASPIRANTE = filaSolicitud["AREA_INTERES"].ToString().Trim().ToUpper();
        }

        String CABEZA_FAMILIA = "Desconocido";
        if (DBNull.Value.Equals(filaSolicitud["C_FMLIA"]) == false)
        {
            if (filaSolicitud["C_FMLIA"].ToString().Trim() == "S")
            {
                CABEZA_FAMILIA = "SI";
            }
            else
            {
                CABEZA_FAMILIA = "NO";
            }
        }

        String NUM_HIJOS = "Desconocido";
        if (DBNull.Value.Equals(filaSolicitud["NRO_HIJOS"]) == false)
        {
            NUM_HIJOS = filaSolicitud["NRO_HIJOS"].ToString().Trim();
        }

        /*
         * Generación del archi de informe de selección
         * Stream con el contenido del pdf.
        */
        String html_encabezado = "<html>";
        html_encabezado += "<head>";
        html_encabezado += "</head>";
        html_encabezado += "<body>";

        String html_pie = "</body>";
        html_pie += "</html>";

        //para el concepto general en entrevista o resultado de competencias.
        String html_concepto = "<div style=\"text-align: left; margin: 0 0 0 20px; text-decoration: underline; font-weight: bold;\">";
        html_concepto += "CONCEPTO DEL ENTREVISTADOR";
        html_concepto += "</div>";
        html_concepto += "<br />";
        html_concepto += "<div style=\"text-align: justify;\">";
        html_concepto += "[CONCEPTO_GENERAL]";
        html_concepto += "</div>";

        //En esta variable cargamos el documento plantilla
        StreamReader archivo_original = new StreamReader(Server.MapPath(@"~\plantillas_reportes\entrevista.htm"));

        String html_formato_entrevista = html_encabezado + archivo_original.ReadToEnd();

        archivo_original.Dispose();
        archivo_original.Close();

        // -----------------------------------
        html_formato_entrevista = html_formato_entrevista.Replace("[CARGO_APLICA]", CARGO_APLICA);
        html_formato_entrevista = html_formato_entrevista.Replace("[FECHA_ENTREVISTA]", FECHA_ENTREVISTA);
        // -----------------------------------

        // -----------------------------------
        html_formato_entrevista = html_formato_entrevista.Replace("[NOMBRE_ASPIRANTE]", NOMBRE_ASPIRANTE);

        html_formato_entrevista = html_formato_entrevista.Replace("[DOC_IDENTIDAD_ASPIRANTE]", DOC_IDENTIDAD_ASPIRANTE);

        if (EDAD_ASPIRANTE > 0) { html_formato_entrevista = html_formato_entrevista.Replace("[EDAD_ASPIRANTE]", EDAD_ASPIRANTE.ToString() + " Años."); }
        else { html_formato_entrevista = html_formato_entrevista.Replace("[EDAD_ASPIRANTE]", "Desconocida."); }

        html_formato_entrevista = html_formato_entrevista.Replace("[DIRECCION_ASPIRANTE]", DIRECCION_ASPIRANTE);

        html_formato_entrevista = html_formato_entrevista.Replace("[TIPO_VIVIENDA_ASPIRANTE]", TIPO_VIVIENDA_ASPIRANTE);

        html_formato_entrevista = html_formato_entrevista.Replace("[CIUDAD_ASPIRANTE]", CIUDAD_ASPIRANTE);

        html_formato_entrevista = html_formato_entrevista.Replace("[SECTOR_ASPIRANTE]", SECTOR_ASPIRANTE);

        html_formato_entrevista = html_formato_entrevista.Replace("[ESTRATO_ASPIRANTE]", ESTRATO_ASPIRANTE);

        html_formato_entrevista = html_formato_entrevista.Replace("[TELEFONOS_ASPIRANTE]", TELEFONOS_ASPIRANTE);

        html_formato_entrevista = html_formato_entrevista.Replace("[ASPIRACION_SALARIAL_ASPIRANTE]", ASPIRACION_SALARIAL_ASPIRANTE);

        html_formato_entrevista = html_formato_entrevista.Replace("[ESTADO_CIVIL_ASPIRANTE]", ESTADO_CIVIL);

        html_formato_entrevista = html_formato_entrevista.Replace("[EMAIL_ASPIRANTE]", EMAIL_ASPIRANTE);

        html_formato_entrevista = html_formato_entrevista.Replace("[LIBRETA_MILITAR]", LIBRETA_MILITAR);
        // -----------------------------------

        // -----------------------------------
        html_formato_entrevista = html_formato_entrevista.Replace("[COMPOSICION_FAMILIAR_ASPIRANTE]", COMPOSICION_FAMILIAR_ASPIRANTE);
        html_formato_entrevista = html_formato_entrevista.Replace("[INFO_ACADEMICA_ASPIRANTE]", INFO_ACADEMICA_ASPIRANTE);
        html_formato_entrevista = html_formato_entrevista.Replace("[EXPERIENCIA_LAB_ASPIRANTE]", EXPERIENCIA_LAB_ASPIRANTE);
        // -----------------------------------

        // -----------------------------------
        html_formato_entrevista = html_formato_entrevista.Replace("[NIVEL_ESCOLARIDAD]", NIVEL_ESCOLARIDAD);
        html_formato_entrevista = html_formato_entrevista.Replace("[PROFESION_ASPIRANTE]", PROFESION_ASPIRANTE);
        html_formato_entrevista = html_formato_entrevista.Replace("[ESPECIALIZACION_ASPIRANTE]", ESPECIALIZACION_ASPIRANTE);
        html_formato_entrevista = html_formato_entrevista.Replace("[CABEZA_FAMILIA]", CABEZA_FAMILIA);
        html_formato_entrevista = html_formato_entrevista.Replace("[NUM_HIJOS]", NUM_HIJOS);
        // -----------------------------------

        //TABLA DE COMPOSICION FAMILIAR
        String html_tabla_composicion_familiar = "<table border=\"1\" cellpadding=\"1\" cellspacing=\"0\" width=\"100%\" align=\"center\" style=\"font-size:8px; line-height:9px;\">";
        html_tabla_composicion_familiar += "<tr>";
        html_tabla_composicion_familiar += "<td width=\"14%\" style=\"text-align:center; font-weight: bold;\">";
        html_tabla_composicion_familiar += "PARENTESCO";
        html_tabla_composicion_familiar += "</td>";
        html_tabla_composicion_familiar += "<td width=\"25%\" style=\"text-align:center; font-weight: bold;\">";
        html_tabla_composicion_familiar += "NOMBRES Y APELLIDOS";
        html_tabla_composicion_familiar += "</td>";
        html_tabla_composicion_familiar += "<td width=\"10%\" style=\"text-align:center; font-weight: bold; \">";
        html_tabla_composicion_familiar += "EDAD";
        html_tabla_composicion_familiar += "</td>";
        html_tabla_composicion_familiar += "<td width=\"20%\" style=\"text-align:center; font-weight: bold; \">";
        html_tabla_composicion_familiar += "¿A QUÉ SE DEDICA?";
        html_tabla_composicion_familiar += "</td>";
        html_tabla_composicion_familiar += "<td width=\"19%\" style=\"text-align:center; font-weight: bold; \">";
        html_tabla_composicion_familiar += "VIVE EN";
        html_tabla_composicion_familiar += "</td>";
        html_tabla_composicion_familiar += "<td width=\"12%\" style=\"text-align:center; font-weight: bold;\">";
        html_tabla_composicion_familiar += "VIVE CON EL CANDIDATO";
        html_tabla_composicion_familiar += "</td>";
        html_tabla_composicion_familiar += "</tr>";

        DataTable tablainfofamiliar = _hojasVida.ObtenerSelRegComposicionFamiliar(ID_ENTREVISTA);

        foreach(DataRow filaComposicion in tablainfofamiliar.Rows)
        {
            html_tabla_composicion_familiar += "<tr>";
            html_tabla_composicion_familiar += "<td width=\"14%\" style=\"text-align:left;\">";
            html_tabla_composicion_familiar += filaComposicion["ID_TIPO_FAMILIAR"].ToString().Trim();
            html_tabla_composicion_familiar += "</td>";
            html_tabla_composicion_familiar += "<td width=\"25%\" style=\"text-align:left;\">";
            html_tabla_composicion_familiar += filaComposicion["NOMBRES"].ToString().Trim() + " " + filaComposicion["APELLIDOS"].ToString().Trim();
            html_tabla_composicion_familiar += "</td>";
            html_tabla_composicion_familiar += "<td width=\"10%\" style=\"text-align:center;\">";
            try
            {
                html_tabla_composicion_familiar += _tools.ObtenerEdadDesdeFechaNacimiento(Convert.ToDateTime(filaComposicion["FECHA_NACIMIENTO"]));
            }
            catch
            {
                html_tabla_composicion_familiar += "Desconocida";
            }
            html_tabla_composicion_familiar += "</td>";
            html_tabla_composicion_familiar += "<td width=\"20%\" style=\"text-align:left;\">";
            html_tabla_composicion_familiar += filaComposicion["PROFESION"].ToString().Trim();
            html_tabla_composicion_familiar += "</td>";
            html_tabla_composicion_familiar += "<td width=\"19%\" style=\"text-align:left;\">";
            if (filaComposicion["ID_CIUDAD"].ToString().Trim() == "EXTRA")
            {
                html_tabla_composicion_familiar += "Extranjero";
            }
            else
            {
                html_tabla_composicion_familiar += filaComposicion["NOMBRE_CIUDAD"].ToString().Trim();
            }
            html_tabla_composicion_familiar += "</td>";
            html_tabla_composicion_familiar += "<td width=\"12%\" style=\"text-align:center;\">";
            if(filaComposicion["VIVE_CON_EL"].ToString().Trim().ToUpper() == "TRUE")
            {
                html_tabla_composicion_familiar += "SI";
            }
            else
            {
                html_tabla_composicion_familiar += "NO";
            }
            html_tabla_composicion_familiar += "</td>";
            html_tabla_composicion_familiar += "</tr>";
        }

        html_tabla_composicion_familiar += "</table>";
        html_formato_entrevista = html_formato_entrevista.Replace("[TABLA_COMPOSICION_FAMILIAR]", html_tabla_composicion_familiar);

        //EDUCACION FORMAL
        String html_tabla_educacion_formal = "<table border=\"1\" cellpadding=\"1\" cellspacing=\"0\" width=\"100%\" align=\"center\" style=\"font-size:8px; line-height:9px;\">";
        html_tabla_educacion_formal += "<tr>";
        html_tabla_educacion_formal += "<td width=\"40%\" style=\"text-align:center; font-weight: bold;\">";
        html_tabla_educacion_formal += "Grado de Instrucción alcanzado:<\br>Especialización, Profesional, Bachiller.";
        html_tabla_educacion_formal += "</td>";
        html_tabla_educacion_formal += "<td width=\"25%\" style=\"text-align:center; font-weight: bold;\">";
        html_tabla_educacion_formal += "Institución";
        html_tabla_educacion_formal += "</td>";
        html_tabla_educacion_formal += "<td width=\"12%\" style=\"text-align:center; font-weight: bold; \">";
        html_tabla_educacion_formal += "Año";
        html_tabla_educacion_formal += "</td>";
        html_tabla_educacion_formal += "<td width=\"23%\" style=\"text-align:center; font-weight: bold; \">";
        html_tabla_educacion_formal += "Observaciones";
        html_tabla_educacion_formal += "</td>";
        html_tabla_educacion_formal += "</tr>";

        DataTable tablaEducacionFormal = _hojasVida.ObtenerSelRegInformacionAcademica(ID_ENTREVISTA, "FORMAL");

        foreach (DataRow filaEducacionFormal in tablaEducacionFormal.Rows)
        {
            html_tabla_educacion_formal += "<tr>";
            html_tabla_educacion_formal += "<td width=\"40%\" style=\"text-align:left;\">";
            html_tabla_educacion_formal += filaEducacionFormal["NOMBRE_NIVEL_ACADEMICO"].ToString().Trim();
            html_tabla_educacion_formal += "</td>";
            html_tabla_educacion_formal += "<td width=\"25%\" style=\"text-align:left;\">";
            html_tabla_educacion_formal += filaEducacionFormal["INSTITUCION"].ToString().Trim();
            html_tabla_educacion_formal += "</td>";
            html_tabla_educacion_formal += "<td width=\"12%\" style=\"text-align:center;\">";
            html_tabla_educacion_formal += filaEducacionFormal["ANNO"].ToString().Trim();
            html_tabla_educacion_formal += "</td>";
            html_tabla_educacion_formal += "<td width=\"23%\" style=\"text-align:justify;\">";
            html_tabla_educacion_formal += filaEducacionFormal["OBSERVACIONES"].ToString().Trim();
            html_tabla_educacion_formal += "</td>";
            html_tabla_educacion_formal += "</tr>";
        }

        html_tabla_educacion_formal += "</table>";
        html_formato_entrevista = html_formato_entrevista.Replace("[TABLA_EDUCACION_FORMAL]", html_tabla_educacion_formal);

        //EDUCACION NO FORMAL
        String html_tabla_educacion_no_formal = "<table border=\"1\" cellpadding=\"1\" cellspacing=\"0\" width=\"100%\" align=\"center\" style=\"font-size:8px; line-height:9px;\">";
        html_tabla_educacion_no_formal += "<tr>";
        html_tabla_educacion_no_formal += "<td width=\"40%\" style=\"text-align:center; font-weight: bold;\">";
        html_tabla_educacion_no_formal += "Cursos libres - Diplomados";
        html_tabla_educacion_no_formal += "</td>";
        html_tabla_educacion_no_formal += "<td width=\"25%\" style=\"text-align:center; font-weight: bold;\">";
        html_tabla_educacion_no_formal += "Institución";
        html_tabla_educacion_no_formal += "</td>";
        html_tabla_educacion_no_formal += "<td width=\"12%\" style=\"text-align:center; font-weight: bold; \">";
        html_tabla_educacion_no_formal += "Duración";
        html_tabla_educacion_no_formal += "</td>";
        html_tabla_educacion_no_formal += "<td width=\"23%\" style=\"text-align:center; font-weight: bold; \">";
        html_tabla_educacion_no_formal += "Observaciones";
        html_tabla_educacion_no_formal += "</td>";
        html_tabla_educacion_no_formal += "</tr>";

        DataTable tablaEducacionNoFormal = _hojasVida.ObtenerSelRegInformacionAcademica(ID_ENTREVISTA, "NO FORMAL");

        foreach (DataRow filaEducacionNoFormal in tablaEducacionNoFormal.Rows)
        {
            html_tabla_educacion_no_formal += "<tr>";
            html_tabla_educacion_no_formal += "<td width=\"40%\" style=\"text-align:left;\">";
            html_tabla_educacion_no_formal += filaEducacionNoFormal["CURSO"].ToString().Trim();
            html_tabla_educacion_no_formal += "</td>";
            html_tabla_educacion_no_formal += "<td width=\"25%\" style=\"text-align:left;\">";
            html_tabla_educacion_no_formal += filaEducacionNoFormal["INSTITUCION"].ToString().Trim();
            html_tabla_educacion_no_formal += "</td>";
            html_tabla_educacion_no_formal += "<td width=\"12%\" style=\"text-align:center;\">";
            html_tabla_educacion_no_formal += filaEducacionNoFormal["DURACION"].ToString().Trim() + " " + filaEducacionNoFormal["UNIDAD_DURACION"].ToString().Trim();
            html_tabla_educacion_no_formal += "</td>";
            html_tabla_educacion_no_formal += "<td width=\"23%\" style=\"text-align:justify;\">";
            html_tabla_educacion_no_formal += filaEducacionNoFormal["OBSERVACIONES"].ToString().Trim();
            html_tabla_educacion_no_formal += "</td>";
            html_tabla_educacion_no_formal += "</tr>";
        }

        html_tabla_educacion_no_formal += "</table>";
        html_formato_entrevista = html_formato_entrevista.Replace("[TABLA_EDUCACION_NO_FORMAL]", html_tabla_educacion_no_formal);

        //EXPERIENCIA LABORAL
        String html_tabla_experiencia_laboral = "";
        DataTable tablaExperiencia = _hojasVida.ObtenerSelRegExperienciaLaboral(ID_ENTREVISTA);

        Int32 contador = 1;
        foreach (DataRow filaExperienciaLaboral in tablaExperiencia.Rows)
        {
            if (contador == 1)
            {
                html_tabla_experiencia_laboral += "<table border=\"1\" cellpadding=\"1\" cellspacing=\"0\" width=\"100%\" align=\"center\" style=\"font-size:8px; line-height:9px;\">";
            }
            else
            {
                html_tabla_experiencia_laboral += "<br><table border=\"1\" cellpadding=\"1\" cellspacing=\"0\" width=\"100%\" align=\"center\" style=\"font-size:8px; line-height:9px;\">";
            }

            html_tabla_experiencia_laboral += "<tr>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += contador.ToString() + ". EMPRESA:";
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += filaExperienciaLaboral["EMPRESA"].ToString().Trim();
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "</tr>";

            html_tabla_experiencia_laboral += "<tr>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += "CARGO DESEMPEÑADO:";
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += filaExperienciaLaboral["CARGO"].ToString().Trim();
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "</tr>";

            html_tabla_experiencia_laboral += "<tr>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += "FUNCIONES REALIZADAS:";
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += filaExperienciaLaboral["FUNCIONES"].ToString().Trim();
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "</tr>";

            html_tabla_experiencia_laboral += "<tr>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += "FECHA INGRESO:";
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += Convert.ToDateTime(filaExperienciaLaboral["FECHA_INGRESO"]).ToShortDateString();
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "</tr>";

            html_tabla_experiencia_laboral += "<tr>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += "FECHA RETIRO:";
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            try
            {
                html_tabla_experiencia_laboral += Convert.ToDateTime(filaExperienciaLaboral["FECHA_RETIRO"]).ToShortDateString();
            }
            catch
            {
                html_tabla_experiencia_laboral += "";
            }
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "</tr>";

            html_tabla_experiencia_laboral += "<tr>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += "TIEMPO TRABAJADO:";
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            Boolean correcto = true;
            DateTime fechaIngreso;
            DateTime fechaRetiro;
            try
            {
                fechaIngreso = Convert.ToDateTime(filaExperienciaLaboral["FECHA_INGRESO"]);
            }
            catch
            {
                correcto = false;
                fechaIngreso = new DateTime();
            }

            if (correcto == true)
            {
                Boolean conContratoVigente = true;
                try
                {
                    fechaRetiro = Convert.ToDateTime(filaExperienciaLaboral["FECHA_RETIRO"]);
                    conContratoVigente = false;
                }
                catch
                {
                    conContratoVigente = true;
                    fechaRetiro = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                }

                if (fechaRetiro < fechaIngreso)
                {
                    html_tabla_experiencia_laboral += "Error en fechas.";
                }
                else
                {
                    if (conContratoVigente == true)
                    {
                        html_tabla_experiencia_laboral += "Lleva trabajando: " + _tools.DiferenciaFechas(fechaRetiro, fechaIngreso);
                    }
                    else
                    {
                        html_tabla_experiencia_laboral += "Trabajó: " + _tools.DiferenciaFechas(fechaRetiro, fechaIngreso);
                    }
                }
            }
            else
            {
                html_tabla_experiencia_laboral += "Desconocido.";
            }
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "</tr>";

            html_tabla_experiencia_laboral += "<tr>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += "MOTIVO_RETIRO:";
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += filaExperienciaLaboral["MOTIVO_RETIRO"].ToString().Trim();
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "</tr>";

            html_tabla_experiencia_laboral += "<tr>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += "ULTIMO SALARIO:";
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "<td width=\"50%\" style=\"text-align:left;\">";
            html_tabla_experiencia_laboral += String.Format("$ {0:N2}", Convert.ToDecimal(filaExperienciaLaboral["ULTIMO_SALARIO"]));
            html_tabla_experiencia_laboral += "</td>";
            html_tabla_experiencia_laboral += "</tr>";

            html_tabla_experiencia_laboral += "</table>";

            contador += 1;
        }

        html_formato_entrevista = html_formato_entrevista.Replace("[TABLA_EXPERIENCIA_LABORAL]", html_tabla_experiencia_laboral);

        //ahora: si es entrevista por produccion se debe determinar que pruebas se han aplicado al candidato
        //y mostrarlas en el informe de seleccion
        //lo mismo con habilidades / competencias

        pruebaPerfil _pruebaPerfil = new pruebaPerfil(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        FabricaAssesment _fabrica = new FabricaAssesment(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());

        DataTable tablaPruebas = new DataTable();
        DataTable tablaAssesmentCenter = new DataTable();
        DataTable tablaCompetencias = new DataTable();
        String TIPO_ENTREVISTA = String.Empty;
        if (ID_PERFIL <= 0)
        {
            //ES ENTREVISTA POR PRODUCCION
            tablaPruebas = _pruebaPerfil.ObtenerAplicadasAIdSolicitudConResultados(ID_SOLICITUD);
            tablaCompetencias = _fabrica.ObtenerAplicacionCompetenciasPorSolicitudIngreso(ID_SOLICITUD);
            if (tablaCompetencias.Rows.Count <= 0)
            {
                TIPO_ENTREVISTA = "B";
            }
            else
            {
                TIPO_ENTREVISTA = "A";
            }
        }
        else
        {
            //es entrevista asociada a perfil entonces cargamos lo pertinente a ese perfil
            tablaPruebas = _pruebaPerfil.ObtenerPorIdPerfilConResultadosIdSolicitud(ID_PERFIL, ID_SOLICITUD);

            if (ID_ASSESMENT_CENTER > 0)
            {
                TIPO_ENTREVISTA = "A";
                //se tiene un assesmentcenter associado
                tablaAssesmentCenter = _fabrica.ObtenerAssesmentCentePorId(ID_ASSESMENT_CENTER);
                tablaCompetencias = _fabrica.ObtenerCompetenciasAssesmentCenteActivos(ID_ASSESMENT_CENTER, ID_SOLICITUD);
            }
            else
            {
                TIPO_ENTREVISTA = "B";
            }
        }

        //AHORA SI SEGUN LOS ObTENIDOS DE LAS TABLAS SE MUESTRA EN EL INFORME.
        if (tablaPruebas.Rows.Count > 0)
        {
            String html_resultados_pruebas;
            html_resultados_pruebas = "<br />";
            html_resultados_pruebas += "<div style=\"text-align: left; margin: 0 0 0 20px; text-decoration: underline; font-weight: bold;\">";
            html_resultados_pruebas += "RESULTADO DE PRUEBAS PSICOTÉCNICAS";
            html_resultados_pruebas += "</div>";

            for (int i = 0; i < tablaPruebas.Rows.Count; i++)
            {
                DataRow filaPrueba = tablaPruebas.Rows[i];

                String NOM_PRUEBA = filaPrueba["NOM_PRUEBA"].ToString().Trim();
                String RESULTADO = filaPrueba["RESULTADOS"].ToString().Trim();

                html_resultados_pruebas += "<br />";
                html_resultados_pruebas += "<div style=\"text-align: left; margin: 0 0 0 20px; font-weight: bold; font-size:9px;\">";
                html_resultados_pruebas += NOM_PRUEBA;
                html_resultados_pruebas += "</div>";
                html_resultados_pruebas += "<div style=\"text-align: justify;\">";
                if (String.IsNullOrEmpty(RESULTADO) == false)
                {
                    html_resultados_pruebas += RESULTADO;
                }
                else
                {
                    html_resultados_pruebas += "Desconocido.";
                }
                html_resultados_pruebas += "</div>";
            }

            html_resultados_pruebas += "<br />";
            html_formato_entrevista = html_formato_entrevista.Replace("[TABLA_RESULTADO_PRUEBAS]", html_resultados_pruebas);
        }
        else
        {
            html_formato_entrevista = html_formato_entrevista.Replace("[TABLA_RESULTADO_PRUEBAS]", "<br />");
        }

        //FORMATO DE ASSESMENT CENTER
        if (TIPO_ENTREVISTA.Contains("A") == true)
        {
            String NOMBRE_ASSESMENT = "";
            if (tablaAssesmentCenter.Rows.Count > 0)
            {
                DataRow filaAssesment = tablaAssesmentCenter.Rows[0];
                NOMBRE_ASSESMENT = filaAssesment["NOMBRE_ASSESMENT"].ToString().Trim();
            }

            //En esta variable cargamos el documento plantilla por habilidades
            archivo_original = new StreamReader(Server.MapPath(@"~\plantillas_reportes\formato_evaluacion_assesmentcenter.htm"));

            String html_formato_assesment_center = archivo_original.ReadToEnd();

            archivo_original.Dispose();
            archivo_original.Close();

            String html_tabla_assesment = "<table border=\"1\" cellpadding=\"1\" cellspacing=\"0\" width=\"100%\" align=\"center\" style=\"font-size:8px; line-height:9px;\">";
            html_tabla_assesment += "<tr>";
            html_tabla_assesment += "<td width=\"25%\" style=\"text-align:center; font-weight: bold;\">";
            html_tabla_assesment += "COMPETENCIA / HABILIDAD";
            html_tabla_assesment += "</td>";
            html_tabla_assesment += "<td width=\"35%\" style=\"text-align:center; font-weight: bold;\">";
            html_tabla_assesment += "CALIFICACIÓN";
            html_tabla_assesment += "</td>";
            html_tabla_assesment += "<td width=\"40%\" style=\"text-align:center; font-weight: bold; \">";
            html_tabla_assesment += "OBSERVACIONES";
            html_tabla_assesment += "</td>";
            html_tabla_assesment += "</tr>";

            foreach (DataRow filaCalificacionCompetencias in tablaCompetencias.Rows)
            {
                html_tabla_assesment += "<tr>";
                html_tabla_assesment += "<td width=\"25%\" style=\"text-align:left; \">";
                html_tabla_assesment += filaCalificacionCompetencias["COMPETENCIA"].ToString().Trim();
                html_tabla_assesment += "</td>";
                html_tabla_assesment += DevuelveTdsConCalificacionSegunDataRow(filaCalificacionCompetencias);
                html_tabla_assesment += "<td width=\"40%\" style=\"text-align:justify; \">";
                html_tabla_assesment += filaCalificacionCompetencias["OBSERVACIONES"].ToString().Trim();
                html_tabla_assesment += "</td>";
            }

            html_tabla_assesment += "</table>";

            html_formato_assesment_center = html_formato_assesment_center.Replace("[NOMBRE_ASSESMENT]", NOMBRE_ASSESMENT);
            html_formato_assesment_center = html_formato_assesment_center.Replace("[TABLA_DE_ASSESMENT_CENTER]", html_tabla_assesment);
            html_formato_entrevista = html_formato_entrevista.Replace("[FORMATO_EVALUACION_ASSESMENTCENTER]", html_formato_assesment_center);
        }
        else
        {
            html_formato_entrevista = html_formato_entrevista.Replace("[FORMATO_EVALUACION_ASSESMENTCENTER]", "");
        }

        // concepto general
        html_concepto = html_concepto.Replace("[CONCEPTO_GENERAL]", CONCEPTO_GENERAL);
        // concepto general
        html_formato_entrevista = html_formato_entrevista.Replace("[CONCEPTO_GENERAL]", html_concepto);

        // USUARIO QUE HIZO LA ENTREVISTA
        usuario _usuario = new usuario(Session["idEmpresa"].ToString());
        DataTable tablaUsuario = _usuario.ObtenerUsuarioPorUsuLog(USUARIO_ENTREVISTADOR); //ACA VA ES EL DE LA ENTREVISTA
        DataRow filaUsuario = tablaUsuario.Rows[0];

        if (filaUsuario["USU_TIPO"].ToString().ToUpper() == "PLANTA")
        {
            html_formato_entrevista = html_formato_entrevista.Replace("[NOMBRE_PSICOLOGO]", filaUsuario["NOMBRES"].ToString().Trim() + " " + filaUsuario["APELLIDOS"].ToString().Trim());
        }
        else
        {
            html_formato_entrevista = html_formato_entrevista.Replace("[NOMBRE_PSICOLOGO]", filaUsuario["NOMBRES_EXTERNO"].ToString().Trim() + " " + filaUsuario["APELLIDOS_EXTERNO"].ToString().Trim());
        }

        html_formato_entrevista = html_formato_entrevista.Replace("[CARGO_SICOLOGO]", "Psicólogo de Selección");

        html_formato_entrevista += html_pie;

        //creamos un configuramos el documento de pdf
        //(tamaño de la hoja,margen izq, margen der, margin arriba margen abajo)
        iTextSharp.text.Document document = new iTextSharp.text.Document(new Rectangle(595, 842), 50, 50, 80, 45);

        using (MemoryStream streamArchivo = new MemoryStream())
        {
            iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(document, streamArchivo);

            // Our custom Header and Footer is done using Event Handler
            pdfEvents PageEventHandler = new pdfEvents();
            writer.PageEvent = PageEventHandler;

            // Define the page header
            // Define the page header
            if (Session["idEmpresa"].ToString() == "1")
            {
                PageEventHandler.dirImagenHeader = Server.MapPath("~/imagenes/reportes/logo_sertempo.png");
            }
            else
            {
                PageEventHandler.dirImagenHeader = Server.MapPath("~/imagenes/reportes/logo_eficiencia.png");
            }

            PageEventHandler.fechaImpresion = DateTime.Now;
            PageEventHandler.tipoDocumento = "entrevista";

            document.Open();

            //capturamos el archivo temporal del response
            String tempFile = Path.GetTempFileName();

            //y lo llenamos con el html de la plantilla
            using (StreamWriter tempwriter = new StreamWriter(tempFile, false))
            {
                tempwriter.Write(html_formato_entrevista);
            }

            //leeemos el archivo temporal y lo colocamos en el documento de pdf
            List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StreamReader(tempFile), new StyleSheet());

            foreach (IElement element in htmlarraylist)
            {
                if (element.Chunks.Count > 0)
                {
                    if (element.Chunks[0].Content == "linea para paginacion de pdf")
                    {
                        document.NewPage();
                    }
                    else
                    {
                        document.Add(element);
                    }
                }
                else
                {
                    document.Add(element);
                }
            }

            //limpiamos todo
            document.Close();

            writer.Close();

            return streamArchivo.ToArray();
        }
    }
Esempio n. 46
0
 public static void Autenticar(usuario usuario)
 {
     HttpContext.Current.Session.Add("UsuarioLogado", usuario);
     //HttpContext.Current.Session.Add("GrupoUsuarioLogado", usuario.GRUPO);
     //HttpContext.Current.Session.Add("ListMenuUsuario", MenuModel.ObterMenuUsuario(usuario));
 }
    /// <summary>
    /// HECHO POR CESAR PULIDO
    /// EL DIA 18 DE DICIEMBRE DE 2012
    /// PARA GENERAR LA REFERENCIA
    /// </summary>
    /// <returns></returns>
    public byte[] GenerarPDFReferencia(Decimal ID_REFERENCIA, Decimal ID_SOLICITUD)
    {
        tools _tools = new tools();

        String html_encabezado = "<html>";
        html_encabezado += "<body>";

        String html_pie = "</body>";
        html_pie += "</html>";

        radicacionHojasDeVida _radicacionHojasDeVida = new radicacionHojasDeVida(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablaSolicitud = _radicacionHojasDeVida.ObtenerRegSolicitudesingresoPorIdSolicitud(Convert.ToInt32(ID_SOLICITUD));
        DataRow filaSolicitud = tablaSolicitud.Rows[0];

        referencia _referencia = new referencia(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablaReferencia = _referencia.ObtenerPorIdReferencia(ID_REFERENCIA);
        DataRow filaReferencia = tablaReferencia.Rows[0];

        String NOMBRE_CANDIDATO = filaSolicitud["NOMBRES"].ToString().Trim() + " " + filaSolicitud["APELLIDOS"].ToString().Trim();
        String NUM_DOC_IDENTIDAD_CANDIDATO = filaSolicitud["NUM_DOC_IDENTIDAD"].ToString().Trim();

        String EMPRESA_DONDE_TRABAJO_CANDIDATO = filaReferencia["EMPRESA_TRABAJO"].ToString().Trim();
        String TELEFONO_EMPRESA = filaReferencia["NUM_TELEFONO"].ToString().Trim();

        String EMPRESA_TEMPORAL = filaReferencia["EMPRESA_TEMPORAL"].ToString().Trim();
        String NUM_TELEFONO_TEMPORAL = filaReferencia["NUM_TELEFONO_TEMPOAL"].ToString().Trim();

        String TIPO_CONTRATO = filaReferencia["TIPO_CONTRATO"].ToString().Trim();

        String FECHA_INGRESO_CANDIDATO = "";
        if (DBNull.Value.Equals(filaReferencia["FECHA_INGRESO"]) == false)
        {
            FECHA_INGRESO_CANDIDATO = Convert.ToDateTime(filaReferencia["FECHA_INGRESO"]).ToShortDateString();
        }
        String FECHA_RETIRO_CANDIDATO = "";
        if (DBNull.Value.Equals(filaReferencia["FECHA_RETIRO"]) == false)
        {
            FECHA_RETIRO_CANDIDATO = Convert.ToDateTime(filaReferencia["FECHA_RETIRO"]).ToShortDateString();
        }

        String ULTIMO_CARGO_CANDIDATO = filaReferencia["ULTIMO_CARGO"].ToString().Trim();

        String NOMBRE_INFORMANTE = filaReferencia["NOMBRE_INFORMANTE"].ToString().Trim();
        String CARGO_INFORMANTE = filaReferencia["CARGO_INFORMANTE"].ToString().Trim();

        String NOMBRE_JEFE = filaReferencia["NOMBRE_JEFE"].ToString().Trim();
        String CARGO_JEFE = filaReferencia["CARGO_JEFE"].ToString().Trim();

        String ULTIMO_SALARIO_CANDIDATO = "Desconocido.";
        try
        {
            ULTIMO_SALARIO_CANDIDATO = Convert.ToDecimal(filaReferencia["ULTIMO_SALARIO"]).ToString();
        }
        catch
        {
            ULTIMO_SALARIO_CANDIDATO = "Desconocido.";
        }

        String COMISIONES = filaReferencia["COMISIONES"].ToString().Trim();
        String BONOS = filaReferencia["BONOS"].ToString().Trim();

        String MOTIVO_RETIRO = filaReferencia["MOTIVO_RETIRO"].ToString().Trim();

        String USUARIO_REFERENCIADOR = Session["USU_LOG"].ToString();
        String NOMBRE_REFERENCIADOR = "Desconocido.";
        if (DBNull.Value.Equals(filaReferencia["USU_MOD"]) == false)
        {
            USUARIO_REFERENCIADOR = filaReferencia["USU_MOD"].ToString().Trim();
        }
        else
        {
            USUARIO_REFERENCIADOR = filaReferencia["USU_CRE"].ToString().Trim();
        }

        String CUALIDADES_CALIFICACION = filaReferencia["CUALIDADES_CALIFICACION"].ToString().Trim();

        usuario _usuario = new usuario(Session["idEmpresa"].ToString());
        DataTable tablaUsuario = _usuario.ObtenerUsuarioPorUsuLog(USUARIO_REFERENCIADOR);
        DataRow filaUsuario = tablaUsuario.Rows[0];
        if (filaUsuario["USU_TIPO"].ToString().ToUpper() == "PLANTA")
        {
            NOMBRE_REFERENCIADOR = filaUsuario["NOMBRES"].ToString().Trim() + " " + filaUsuario["APELLIDOS"].ToString().Trim();
        }
        else
        {
            NOMBRE_REFERENCIADOR = filaUsuario["NOMBRES_EXTERNO"].ToString().Trim() + " " + filaUsuario["APELLIDOS_EXTERNO"].ToString().Trim();
        }

        //En esta variable cargamos el documento plantilla
        StreamReader archivo_original = new StreamReader(Server.MapPath(@"~\plantillas_reportes\referencia.htm"));

        String html_formato_referencia = html_encabezado + archivo_original.ReadToEnd();

        archivo_original.Dispose();
        archivo_original.Close();

        html_formato_referencia = html_formato_referencia.Replace("[NOMBRE_CANDIDATO]", NOMBRE_CANDIDATO);
        html_formato_referencia = html_formato_referencia.Replace("[NUM_DOC_IDENTIDAD_CANDIDATO]", NUM_DOC_IDENTIDAD_CANDIDATO);

        html_formato_referencia = html_formato_referencia.Replace("[EMPRESA_DONDE_TRABAJO_CANDIDATO]", EMPRESA_DONDE_TRABAJO_CANDIDATO);
        html_formato_referencia = html_formato_referencia.Replace("[TELEFONO_EMPRESA]", TELEFONO_EMPRESA);

        html_formato_referencia = html_formato_referencia.Replace("[EMPRESA_TEMPORAL]", EMPRESA_TEMPORAL);
        html_formato_referencia = html_formato_referencia.Replace("[TELEFONO_TEMPORAL]", NUM_TELEFONO_TEMPORAL);

        if (TIPO_CONTRATO == "OBRA O LABOR")
        {
            html_formato_referencia = html_formato_referencia.Replace("[OBRA_LABOR]", " X ");
            html_formato_referencia = html_formato_referencia.Replace("[FIJO]", "___");
            html_formato_referencia = html_formato_referencia.Replace("[INDEFINIDO]", "___");
        }
        else
        {
            if (TIPO_CONTRATO == "FIJO")
            {
                html_formato_referencia = html_formato_referencia.Replace("[OBRA_LABOR]", "___");
                html_formato_referencia = html_formato_referencia.Replace("[FIJO]", " X ");
                html_formato_referencia = html_formato_referencia.Replace("[INDEFINIDO]", "___");
            }
            else
            {
                if (TIPO_CONTRATO == "INDEFINIDO")
                {
                    html_formato_referencia = html_formato_referencia.Replace("[OBRA_LABOR]", "___");
                    html_formato_referencia = html_formato_referencia.Replace("[FIJO]", "___");
                    html_formato_referencia = html_formato_referencia.Replace("[INDEFINIDO]", " X ");
                }
                else
                {
                    html_formato_referencia = html_formato_referencia.Replace("[OBRA_LABOR]", "___");
                    html_formato_referencia = html_formato_referencia.Replace("[FIJO]", "___");
                    html_formato_referencia = html_formato_referencia.Replace("[INDEFINIDO]", "___");
                }
            }
        }

        html_formato_referencia = html_formato_referencia.Replace("[FECHA_INGRESO_CANDIDATO]", FECHA_INGRESO_CANDIDATO);
        html_formato_referencia = html_formato_referencia.Replace("[FECHA_RETIRO_CANDIDATO]", FECHA_RETIRO_CANDIDATO);

        html_formato_referencia = html_formato_referencia.Replace("[ULTIMO_CARGO_CANDIDATO]", ULTIMO_CARGO_CANDIDATO);

        html_formato_referencia = html_formato_referencia.Replace("[NOMBRE_INFORMANTE]", NOMBRE_INFORMANTE);
        html_formato_referencia = html_formato_referencia.Replace("[CARGO_INFORMANTE]", CARGO_INFORMANTE);

        html_formato_referencia = html_formato_referencia.Replace("[NOMBRE_JEFE]", NOMBRE_JEFE);
        html_formato_referencia = html_formato_referencia.Replace("[CARGO_JEFE]", CARGO_JEFE);

        html_formato_referencia = html_formato_referencia.Replace("[ULTIMO_SALARIO_CANDIDATO]", ULTIMO_SALARIO_CANDIDATO);
        html_formato_referencia = html_formato_referencia.Replace("[COMISIONES]", COMISIONES);
        html_formato_referencia = html_formato_referencia.Replace("[BONOS]", BONOS);

        html_formato_referencia = html_formato_referencia.Replace("[MOTIVO_RETIRO]", MOTIVO_RETIRO);

        html_formato_referencia = html_formato_referencia.Replace("[NOMBRE_REFERENCIADOR]", NOMBRE_REFERENCIADOR);

        if (DBNull.Value.Equals(filaReferencia["FCH_MOD"]) == false)
        {
            html_formato_referencia = html_formato_referencia.Replace("[FECHA_REFERECIA]", Convert.ToDateTime(filaReferencia["FCH_MOD"]).ToShortDateString());
        }
        else
        {
            html_formato_referencia = html_formato_referencia.Replace("[FECHA_REFERECIA]", Convert.ToDateTime(filaReferencia["FCH_CRE"]).ToShortDateString());
        }

        //ya esta la informacion de la referecia basica ahora le adicionadmos al informe los datos de las preguntas
        DataTable tablaPreguntasRespuestas = _referencia.ObtenerPreguntasRespuestasReferencia(ID_REFERENCIA);
        if (tablaPreguntasRespuestas.Rows.Count > 0)
        {
            int contadorPreguntas = 0;
            //recorrido por las preguntas
            String html_tabla_preguntas = "";
            html_tabla_preguntas += "<table border=\"1\" cellpadding=\"1\" cellspacing=\"0\" width=\"100%\" align=\"center\">";
            html_tabla_preguntas += "<tr>";
            html_tabla_preguntas += "<td width=\"15%\" style=\"text-align:center; font-weight: bold;\">";
            html_tabla_preguntas += "#";
            html_tabla_preguntas += "</td>";
            html_tabla_preguntas += "<td style=\"text-align:center; font-weight: bold;\">";
            html_tabla_preguntas += "CUESTIONARIO";
            html_tabla_preguntas += "</td>";
            html_tabla_preguntas += "<td style=\"text-align:center; font-weight: bold;\">";
            html_tabla_preguntas += "RESPUESTA";
            html_tabla_preguntas += "</td>";
            html_tabla_preguntas += "</tr>";
            for (int i = 0; i < tablaPreguntasRespuestas.Rows.Count; i++)
            {
                DataRow filaPregunta = tablaPreguntasRespuestas.Rows[i];

                contadorPreguntas += 1;

                String textoPregunta = filaPregunta["CONTENIDO"].ToString().Trim();
                String textoRespuesta = filaPregunta["RESPUESTA"].ToString().Trim();

                html_tabla_preguntas += "<tr>";
                html_tabla_preguntas += "<td width=\"15%\" style=\"text-align:center;\">";
                html_tabla_preguntas += contadorPreguntas.ToString();
                html_tabla_preguntas += "</td>";
                html_tabla_preguntas += "<td style=\"text-align:justify;\">";
                html_tabla_preguntas += textoPregunta;
                html_tabla_preguntas += "</td>";
                html_tabla_preguntas += "<td style=\"text-align:center;\">";
                html_tabla_preguntas += textoRespuesta;
                html_tabla_preguntas += "</td>";
                html_tabla_preguntas += "</tr>";
            }
            html_tabla_preguntas += "</table>";

            html_formato_referencia = html_formato_referencia.Replace("[TABLA_CUESTIONARIO]", html_tabla_preguntas);
        }

        if (String.IsNullOrEmpty(CUALIDADES_CALIFICACION) == false)
        {
            String html_tabla_preguntas = "";
            html_tabla_preguntas += "<table border=\"1\" cellpadding=\"1\" cellspacing=\"0\" width=\"80%\" align=\"center\">";
            html_tabla_preguntas += "<tr>";
            html_tabla_preguntas += "<td width=\"50%\" style=\"text-align:center; font-weight: bold;\">";
            html_tabla_preguntas += "CUALIDAD";
            html_tabla_preguntas += "</td>";
            html_tabla_preguntas += "<td width=\"12%\" style=\"text-align:center; font-weight: bold;\">";
            html_tabla_preguntas += "EXCELENTE";
            html_tabla_preguntas += "</td>";
            html_tabla_preguntas += "<td width=\"13%\" style=\"text-align:center; font-weight: bold;\">";
            html_tabla_preguntas += "BUENO";
            html_tabla_preguntas += "</td>";
            html_tabla_preguntas += "<td width=\"12%\" style=\"text-align:center; font-weight: bold;\">";
            html_tabla_preguntas += "REGULAR";
            html_tabla_preguntas += "</td>";
            html_tabla_preguntas += "<td width=\"13%\" style=\"text-align:center; font-weight: bold;\">";
            html_tabla_preguntas += "MALO";
            html_tabla_preguntas += "</td>";
            html_tabla_preguntas += "</tr>";

            String[] cualidadesCalificacionesArray = CUALIDADES_CALIFICACION.Split(';');

            foreach(String cualidadCalificacion in cualidadesCalificacionesArray)
            {
                String CUALIDAD = cualidadCalificacion.Split(':')[0];
                String CALIFICACION = cualidadCalificacion.Split(':')[1];

                html_tabla_preguntas += "<tr>";
                html_tabla_preguntas += "<td width=\"50%\" style=\"text-align:left;\">";
                html_tabla_preguntas += CUALIDAD;
                html_tabla_preguntas += "</td>";
                html_tabla_preguntas += "<td width=\"12%\" style=\"text-align:justify;\">";
                if(CALIFICACION == "EXCELENTE")
                {
                    html_tabla_preguntas += "X";
                }
                html_tabla_preguntas += "</td>";

                html_tabla_preguntas += "<td width=\"13%\" style=\"text-align:center;\">";
                if (CALIFICACION == "BUENO")
                {
                    html_tabla_preguntas += "X";
                }
                html_tabla_preguntas += "</td>";
                html_tabla_preguntas += "<td width=\"12%\" style=\"text-align:center;\">";
                if (CALIFICACION == "REGULAR")
                {
                    html_tabla_preguntas += "X";
                }
                html_tabla_preguntas += "</td>";
                html_tabla_preguntas += "<td width=\"13%\" style=\"text-align:center;\">";
                if (CALIFICACION == "MALO")
                {
                    html_tabla_preguntas += "X";
                }
                html_tabla_preguntas += "</td>";
                html_tabla_preguntas += "</tr>";
            }

            html_tabla_preguntas += "</table>";

            html_formato_referencia = html_formato_referencia.Replace("[TABLA_CUALIDADES]", html_tabla_preguntas);
        }

        html_formato_referencia += html_pie;

        //creamos un configuramos el documento de pdf
        //(tamaño de la hoja,margen izq, margen der, margin arriba margen abajo)
        iTextSharp.text.Document document = new iTextSharp.text.Document(new Rectangle(595, 842), 50, 50, 80, 45);

        using (MemoryStream streamArchivo = new MemoryStream())
        {
            iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(document, streamArchivo);

            // Our custom Header and Footer is done using Event Handler
            pdfEvents PageEventHandler = new pdfEvents();
            writer.PageEvent = PageEventHandler;

            // Define the page header
            // Define the page header
            if (Session["idEmpresa"].ToString() == "1")
            {
                PageEventHandler.dirImagenHeader = Server.MapPath("~/imagenes/reportes/logo_sertempo.png");
            }
            else
            {
                PageEventHandler.dirImagenHeader = Server.MapPath("~/imagenes/reportes/logo_eficiencia.png");
            }

            PageEventHandler.fechaImpresion = DateTime.Now;
            PageEventHandler.tipoDocumento = "referencia";

            document.Open();

            //capturamos el archivo temporal del response
            String tempFile = Path.GetTempFileName();

            //y lo llenamos con el html de la plantilla
            using (StreamWriter tempwriter = new StreamWriter(tempFile, false))
            {
                tempwriter.Write(html_formato_referencia);
            }

            //leeemos el archivo temporal y lo colocamos en el documento de pdf
            List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StreamReader(tempFile), new StyleSheet());

            foreach (IElement element in htmlarraylist)
            {
                if (element.Chunks.Count > 0)
                {
                    if (element.Chunks[0].Content == "linea para paginacion de pdf")
                    {
                        document.NewPage();
                    }
                    else
                    {
                        document.Add(element);
                    }
                }
                else
                {
                    document.Add(element);
                }
            }

            //limpiamos todo
            document.Close();

            writer.Close();

            return streamArchivo.ToArray();
        }
    }
Esempio n. 48
0
        async Task LoadLoginAPIempty()
        {
            this.IsRunning = true;

            try
            {
                //se conecta a AWS para verificar si el usuario existe en la base de datos de Amazon
                var servicio  = DependencyService.Get <IServiceUser>();
                var resultado = servicio.validarUsuarioAmazon(this.Usuario, this.Password);
                if (resultado == null)
                {
                    await Application.Current.MainPage.DisplayAlert("Error",
                                                                    "No existe el usuario",
                                                                    "Aceptar");
                }
                else
                {
                    //comienza a almacenar los datos del AWS en la base sqlite
                    using (DataAccess datos = new DataAccess())
                    {
                        estadoSqlite eqlite = new estadoSqlite();
                        eqlite.ESTADO_ESTADOSQLITE  = "Datos";
                        eqlite.CAMBIOS_ESTADOSQLITE = false;
                        eqlite.USUARIO_USUARIO      = resultado.USUARIO_USUARIO;
                        eqlite.CONTRASENIA_USUARIO  = resultado.CONTRASENIA_USUARIO;
                        eqlite.SALT_USUARIO         = resultado.SALT_USUARIO;
                        eqlite.ID_USUARIO           = resultado.ID_USUARIO;

                        datos.setEstadoSqlite(eqlite);
                        datos.Insert(resultado.PERSONA_PERSONA);
                        datos.Insertusuario(resultado);
                        datos.InsertipoUser(resultado.TipoUsuario_PERSONA);
                        usuario usresult = new usuario()
                        {
                            ID_USUARIO          = resultado.ID_USUARIO,
                            USUARIO_USUARIO     = resultado.USUARIO_USUARIO,
                            ID_TIPOUSUARIO      = resultado.ID_TIPOUSUARIO,
                            ID_PERSONA          = resultado.ID_PERSONA,
                            CONTRASENIA_USUARIO = resultado.CONTRASENIA_USUARIO,
                            EMPRESA_USUARIO     = resultado.EMPRESA_USUARIO,
                            SALT_USUARIO        = resultado.SALT_USUARIO
                        };
                        var servicioForm = DependencyService.Get <IServiceForm>();
                        // await Application.Current.MainPage.DisplayAlert("AWS",
                        //"IdU" + resultado.ID_USUARIO + "idP" + resultado.ID_PERSONA + "idTp" + resultado.ID_TIPOUSUARIO,
                        //"Accept");
                        List <formulario> resultadoForms = servicioForm.listarFormularios(usresult.ID_USUARIO);
                        // await Application.Current.MainPage.DisplayAlert("AWS",
                        //"form" + resultadoForms.ToString()+"iduser"+ usresult.ID_USUARIO,
                        //"Accept");
                        if (resultadoForms != null)
                        {
                            List <formularioAll> resultadoFormsAll = new List <formularioAll>();

                            foreach (formulario i in resultadoForms)
                            {
                                datos.Insertformulario(i);
                                resultadoFormsAll.Add(servicioForm.listarFormulariosAll(i.ID_FORMULARIO, i.CODIGO_FORMULARIO, i.ID_IULOTE));
                                //await Application.Current.MainPage.DisplayAlert("result all form>",
                                //   i + ">"+resultadoFormsAll.ToString()+"codigo form para all"+i.CODIGO_FORMULARIO,
                                //   "Accept");
                            }
                            foreach (formularioAll i in resultadoFormsAll)
                            {
                                //await Application.Current.MainPage.DisplayAlert("All form >",
                                //      "cvnew"+ i + ">" + i.identificacionubicacionlote.CLAVECATASTRALNUEVO_IULOTE,
                                //      "Accept");
                                datos.Insertformularioall(i);
                            }
                        }
                    }
                    usuar = resultado;

                    MainViewModel.GetInstance().IsEnabledSincronizacion = true;
                    MainViewModel.GetInstance().EstadoSincronizacion    = "Sincronizar";
                    MainViewModel.GetInstance().User                  = usuar;
                    MainViewModel.GetInstance().Formularioall         = new formularioAll();
                    MainViewModel.GetInstance().EstadoConnection      = true;
                    MainViewModel.GetInstance().MessageTypeConnection = "Online";
                    MainViewModel.GetInstance().LoadMenuLoggedin();
                    MainViewModel.GetInstance().LoadMap();
                    MainViewModel.GetInstance().GraficosPredio              = new ViewsModelsForm.GraficosPredioModel();
                    MainViewModel.GetInstance().ElementosConstructivos      = new ViewsModelsForm.ElementosConstructivosModel();
                    MainViewModel.GetInstance().HomePageLoggedin            = new HomePageModelLoggedin();
                    MainViewModel.GetInstance().AvancesFormsLoggedin        = new AvancesFormsLoggedin();
                    MainViewModel.GetInstance().IdentificacionUbicacionPart = new IdentificacionUbicacionlModel();

                    await Application.Current.MainPage.DisplayAlert("Bienvenido",
                                                                    "Usuario:" + resultado.USUARIO_USUARIO,
                                                                    "Aceptar");

                    navigationService.SetMainPage("MasterPage1Loggedin");
                }
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error",
                                                                "No se inicio sesión, Intentelo de nuevo",
                                                                "Aceptar");
            }
        }
Esempio n. 49
0
 public FormPrincipal(usuario u)
 {
     InitializeComponent();
     customizeDising();
     user = u;
 }
        public HttpResponseMessage Actualizar(proveedor Entidad, ModelStateDictionary modelo)
        {
            DbContextTransaction tran = null;

            try
            {
                if (modelo.IsValid)
                {
                    usuario aux = mgr.FindById(Entidad.usuario.Id);
                    if (aux != null)
                    {
                        contexto.Entry(aux).State             = EntityState.Detached;
                        Entidad.usuario_id                    = Entidad.usuario.Id;
                        contexto.Entry(Entidad).State         = EntityState.Modified;
                        contexto.Entry(Entidad.usuario).State = EntityState.Modified;
                        tran = contexto.Database.BeginTransaction();
                        Entidad.usuario.PasswordHash         = aux.PasswordHash;
                        Entidad.usuario.EmailConfirmed       = aux.EmailConfirmed;
                        Entidad.usuario.SecurityStamp        = aux.SecurityStamp;
                        Entidad.usuario.PhoneNumberConfirmed = aux.PhoneNumberConfirmed;
                        Entidad.usuario.TwoFactorEnabled     = aux.TwoFactorEnabled;
                        Entidad.usuario.LockoutEnabled       = aux.LockoutEnabled;
                        Entidad.usuario.LockoutEndDateUtc    = aux.LockoutEndDateUtc;
                        Entidad.usuario.AccessFailedCount    = aux.AccessFailedCount;
                        IdentityResult result = mgr.Update(Entidad.usuario);
                        if (!result.Succeeded)
                        {
                            if (contexto.Database.CurrentTransaction != null)
                            {
                                tran.Rollback();
                            }

                            resp.Codigo      = (int)Codigos.ERROR_DE_VALIDACION;
                            resp.Mensaje     = Enum.GetName(typeof(Codigos), (int)Codigos.ERROR_DE_VALIDACION);
                            resp.Objetoerror = result.Errors;
                            return(resp.ObjectoRespuesta());
                        }
                        contexto.Entry(Entidad.usuario).State = EntityState.Detached;
                        contexto.SaveChanges();
                        tran.Commit();
                        resp.Codigo  = (int)Codigos.OK;
                        resp.Mensaje = Enum.GetName(typeof(Codigos), (int)Codigos.OK);
                        return(resp.ObjectoRespuesta());
                    }
                    else
                    {
                        resp.Codigo        = (int)Codigos.REGISTRO_NO_ENCONTRADO;
                        resp.Mensaje       = Enum.GetName(typeof(Codigos), (int)Codigos.OK);
                        resp.Mensaje_error = String.Format(Errores.error1, Entidad.usuario.Id);
                        return(resp.ObjectoRespuesta());
                    }
                }
                else
                {
                    resp.Codigo      = (int)Codigos.ERROR_DE_VALIDACION;
                    resp.Mensaje     = Enum.GetName(typeof(Codigos), (int)Codigos.ERROR_DE_VALIDACION);
                    resp.Objetoerror = modelo;
                    return(resp.ObjectoRespuesta());
                }
            }
            catch (Exception ex)
            {
                if (contexto.Database.CurrentTransaction != null)
                {
                    tran.Rollback();
                }

                resp.Codigo    = (int)Codigos.ERROR_DE_SERVIDOR;
                resp.Mensaje   = Enum.GetName(typeof(Codigos), (int)Codigos.ERROR_DE_SERVIDOR);
                resp.Excepcion = Excepcion.Create(ex);
                return(resp.ObjectoRespuesta());
            }
        }
Esempio n. 51
0
        private void cmdEntrar_Click(object sender, EventArgs e)
        {
            if (PodeEntrar())
            {
                try
                {
                    usuarioCTL CUsuario = new usuarioCTL();

                    string sLogin = PontoBr.Utilidades.String.RemoverCaracterInvalido(txtLogin.Text);
                    string sSenha = PontoBr.Utilidades.String.RemoverCaracterInvalido(txtSenha.Text);
                    string sRamal = PontoBr.Utilidades.String.RemoverCaracterInvalido(txtRamal.Text);

                    int iIDUsuario = CUsuario.RetornarUsuario(sLogin, sSenha, 1);
                    if (iIDUsuario != 0)
                    {
                        //Cadastra ou atualiza o ramal de acordo com o DNS da máquina
                        CadastrarRamal();

                        Usuario = CUsuario.RetornarUsuario(iIDUsuario);
                        if (Usuario.IDUsuario == 0)
                        {
                            MessageBox.Show("O usuário não está vinculado à nenhuma Campanha.", "Tabulare", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        Usuario        = CUsuario.RetornarUsuario(sLogin, sSenha, sRamal);
                        Usuario.Agente = txtRamal.Text;
                        string sPerfil = Usuario.Perfil;

                        //De acordo com o Usuário do Agent (PlanetFone), retorna o NroAgente
                        if (fLogin.Configuracao.TipoPabx == "PlanetFone")
                        {
                            if (Usuario.Perfil == "Operador")
                            {
                                try
                                {
                                    RetornarNroAgente();

                                    CUsuario.AtualizarNroAgente(Usuario.IDUsuario, operador.fAtendimento.NroAgente);

                                    //Libera a tela do Operador porque o robô envia contato mesmo não logado no Tabulare
                                    if (fLogin.Usuario.TipoDiscador != "Power")
                                    {
                                        //Deixa o IDProspect = NULL - Para liberar a tela do Operador (Preditivo)
                                        CUsuario = new usuarioCTL();
                                        CUsuario.PausaAgente(fLogin.Usuario.IDUsuario, 0);

                                        //1 = Tabulare Logado (Necessário Preditivo) | 0 = Tabulare não Logado
                                        CUsuario.TabulareLogado(fLogin.Usuario.IDUsuario, 1);
                                    }
                                }
                                catch (Exception ex) /*Quando não conseguir integrar */
                                {
                                    PontoBr.Utilidades.Diversos.ExibirAlertaWindowsForm(ex.Message + "\n\nNão foi possível conectar no PlanetFone.\n\nO Tabulare irá funcionar sem a integração com o PABX.", "Tabulare Software");
                                }
                            }
                        }

                        //Licença
                        if (Usuario.Perfil == "Operador")
                        {
                            if (CUsuario.RetornarQuantidadeOperadores() > fLogin.iNumeroOperadores)
                            {
                                string sMensagem = "Sua licença execedeu o limite de usuários (perfil Operador).";
                                sMensagem += " Atualmente seu limite é de " + fLogin.iNumeroOperadores.ToString() + " operadores.";
                                sMensagem += "\n\nPeça o supervisor para acessar o Tabulare e, dentro do Módulo de Usuários, gerenciar a quantidade de operadores.";

                                PontoBr.Utilidades.Diversos.ExibirAlertaWindowsForm(sMensagem, "Tabulare Software");
                                return;
                            }
                        }

                        // int user = Convert.ToInt32(fLogin.iNumeroOperadores.ToString()) - CUsuario.RetornarQuantidadeOperadores();

                        if (VerificarVersaoDiscador() == true)
                        {
                            Logar(Usuario.Perfil);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Login e/ou Senha inválido(s).", "Tabulare", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtLogin.Text = "";
                        txtSenha.Text = "";
                        txtLogin.Focus();
                    }
                }
                catch (Exception ex)
                {
                    PontoBr.Utilidades.Diversos.ExibirAlertaWindowsForm(ex.Message, "Tabulare Software");
                }
            }
        }
Esempio n. 52
0
 /// <summary>
 /// Deprecated Method for adding a new object to the usuario EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddTousuario(usuario usuario)
 {
     base.AddObject("usuario", usuario);
 }
Esempio n. 53
0
        async Task LoadLoginLocal()
        {
            this.IsRunning = true;

            using (DataAccess datos = new DataAccess())
            {
                try
                {
                    estadosqlite = datos.getEstadoSqlite();
                    if (estadosqlite != null)
                    {
                        int saltus = estadosqlite.SALT_USUARIO;
                        usuar = datos.getUsuario(sha256.ComputeSha256Hash(saltus + this.Password), this.Usuario);
                    }
                    else
                    {
                        await Application.Current.MainPage.DisplayAlert("Error, no existe usuarios almacenados",
                                                                        "Deber iniciar sesion en modo online y cargar un usuario primero.",
                                                                        "Aceptar");

                        return;
                    }
                }
                catch (Exception ex)
                {
                    await Application.Current.MainPage.DisplayAlert("Error",
                                                                    "No se inicio sesión, Intentelo de nuevo",
                                                                    "Aceptar");
                }
            }

            if (usuar == null)
            {
                this.IsRunning = false;
                this.IsEnabled = true;

                await Application.Current.MainPage.DisplayAlert("Error",
                                                                "Usuario o Contraseña incorrectos",
                                                                "Aceptar");

                this.Password = string.Empty;
                this.Usuario  = string.Empty;
                return;
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Bienvenido",
                                                                "Usuario:" + usuar.USUARIO_USUARIO,
                                                                "Aceptar");

                MainViewModel.GetInstance().IsEnabledSincronizacion = true;
                MainViewModel.GetInstance().EstadoSincronizacion    = "Sincronizar";
                MainViewModel.GetInstance().User                  = usuar;
                MainViewModel.GetInstance().Formularioall         = new formularioAll();
                MainViewModel.GetInstance().EstadoConnection      = true;
                MainViewModel.GetInstance().MessageTypeConnection = "Offline";
                MainViewModel.GetInstance().LoadMenuLoggedin();
                MainViewModel.GetInstance().LoadMap();
                MainViewModel.GetInstance().GraficosPredio              = new ViewsModelsForm.GraficosPredioModel();
                MainViewModel.GetInstance().ElementosConstructivos      = new ViewsModelsForm.ElementosConstructivosModel();
                MainViewModel.GetInstance().HomePageLoggedin            = new HomePageModelLoggedin();
                MainViewModel.GetInstance().IdentificacionUbicacionPart = new IdentificacionUbicacionlModel();

                navigationService.SetMainPage("MasterPage1Loggedin");
            }
        }
    private void previsualizar_clausula(Decimal ID_CON_REG_CLAUSULAS_PERFIL)
    {
        condicionesContratacion _condicionesContratacion = new condicionesContratacion(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablaInfoClausula = _condicionesContratacion.obtenerClausulasPorIdCluasula(ID_CON_REG_CLAUSULAS_PERFIL);
        DataRow filaInfo = tablaInfoClausula.Rows[0];

        StreamReader archivo = new StreamReader(Server.MapPath(@"~\plantillas_reportes\clausulas.htm"));

        tools _tools = new tools();

        String html_completo = "<html><body>";
        html_completo += archivo.ReadToEnd();
        html_completo += "</body></html>";

        archivo.Dispose();
        archivo.Close();

        if (Session["idEmpresa"].ToString() == "1")
        {
            html_completo = html_completo.Replace("[NOMBRE_EMPRESA]", tabla.VAR_NOMBRE_SERTEMPO);
        }
        else
        {
            html_completo = html_completo.Replace("[NOMBRE_EMPRESA]", tabla.VAR_NOMBRE_EYS);
        }
        html_completo = html_completo.Replace("[NOMBRE_TRABAJADOR]", "NOMBRE DEL TRABAJADOR");
        html_completo = html_completo.Replace("[NOMBRE_CLAUSULA]", filaInfo["NOMBRE"].ToString());
        html_completo = html_completo.Replace("[ENCABEZADO_CLAUSULA]", filaInfo["ENCABEZADO"].ToString());
        html_completo = html_completo.Replace("[CONTENIDO_CLAUSULA]", filaInfo["DESCRIPCION"].ToString());

        usuario _usuario = new usuario(Session["idEmpresa"].ToString());
        DataTable tablaInfoUsuario = _usuario.ObtenerInicioSesionPorUsuLog(Session["USU_LOG"].ToString());
        if (tablaInfoUsuario.Rows.Count <= 0)
        {
            html_completo = html_completo.Replace("[CIUDAD_FIRMA]", "Desconocida");
        }
        else
        {
            DataRow filaInfoUsuario = tablaInfoUsuario.Rows[0];
            html_completo = html_completo.Replace("[CIUDAD_FIRMA]", filaInfoUsuario["NOMBRE_CIUDAD"].ToString());
        }

        html_completo = html_completo.Replace("[DIAS]", DateTime.Now.Day.ToString());
        html_completo = html_completo.Replace("[MES]", _tools.obtenerNombreMes(DateTime.Now.Month));
        html_completo = html_completo.Replace("[ANNO]", DateTime.Now.Year.ToString());

        String filename = "previsulizador_clausula";

        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;FileName=" + filename + ".pdf");

        Response.Clear();
        Response.ContentType = "application/pdf";

        iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 80, 40);

        iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);

        pdfEvents PageEventHandler = new pdfEvents();
        writer.PageEvent = PageEventHandler;

        if (Session["idEmpresa"].ToString() == "1")
        {
            PageEventHandler.dirImagenHeader = Server.MapPath("~/imagenes/reportes/logo_sertempo.png");
        }
        else
        {
            PageEventHandler.dirImagenHeader = Server.MapPath("~/imagenes/reportes/logo_eficiencia.png");
        }

        PageEventHandler.fechaImpresion = DateTime.Now;
        PageEventHandler.tipoDocumento = "clausula";

        document.Open();

        String tempFile = Path.GetTempFileName();

        using (StreamWriter tempwriter = new StreamWriter(tempFile, false))
        {
            tempwriter.Write(html_completo);
        }

        List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StreamReader(tempFile), new StyleSheet());
        foreach (IElement element in htmlarraylist)
        {
            document.Add(element);
        }

        document.Close();
        writer.Close();

        Response.End();

        File.Delete(tempFile);
    }
    private void ImprimirContratoO_L_COMPLETO(DataRow filaInfoContrato)
    {
        tools _tools = new tools();

        Boolean CarnetIncluido = CheckBox_CON_CARNET_APARTE.Checked;

        StreamReader archivo;

        if (Session["idEmpresa"].ToString() == "1")
        {
            if (CarnetIncluido == true)
            {
                archivo = new StreamReader(Server.MapPath(@"~\plantillas_reportes\contrato_sertempo_obra_labor.htm"));
            }
            else
            {
                archivo = new StreamReader(Server.MapPath(@"~\plantillas_reportes\contrato_sertempo_obra_labor_carnet_aparte.htm"));
            }
        }
        else
        {
            if (CarnetIncluido == true)
            {
                archivo = new StreamReader(Server.MapPath(@"~\plantillas_reportes\contrato_eys_labor_contratada.htm"));
            }
            else
            {
                archivo = new StreamReader(Server.MapPath(@"~\plantillas_reportes\contrato_eys_labor_contratada_carnet_aparte.htm"));
            }
        }

        String html = archivo.ReadToEnd();

        archivo.Dispose();
        archivo.Close();

        String filename;

        if (Session["idEmpresa"].ToString() == "1")
        {
            html = html.Replace("[DIR_LOGO_EMPLEADOR]", tabla.DIR_IMAGENES_PARA_PDF + "/logo_sertempo.png");
            html = html.Replace("[MENSAJE_LOGO]", "SERVICIOS TEMPORALES PROFESIONALES");
            html = html.Replace("[NOMBRE_EMPLEADOR]", tabla.VAR_NOMBRE_SERTEMPO);
            html = html.Replace("[DOMICILO_EMPLEADOR]", tabla.VAR_DOMICILIO_SERTEMPO);
            html = html.Replace("[DESCRIPCION_CARGO]", filaInfoContrato["DSC_FUNCIONES"].ToString().Trim().ToUpper());
            html = html.Replace("[SERVICIO_RESPECTIVO]", filaInfoContrato["DESCRIPCION"].ToString().Trim().ToUpper());
            html = html.Replace("[EMPRESA_USUARIA]", filaInfoContrato["RAZ_SOCIAL"].ToString().Trim().ToUpper());
            html = html.Replace("[DESCRIPCION_SALARIO]", filaInfoContrato["DESCRIPCION_SALARIO"].ToString().Trim().ToUpper());
            html = html.Replace("[DIR_FIRMA_EMPLEADOR]", tabla.DIR_IMAGENES_PARA_PDF + "/firma_autos_recomendacion.jpg");
            filename = "contrato_sertempo";
        }
        else
        {
            html = html.Replace("[DIR_LOGO_EMPLEADOR]", tabla.DIR_IMAGENES_PARA_PDF + "/logo_eficiencia.jpg");
            html = html.Replace("[NOMBRE_EMPLEADOR]", tabla.VAR_NOMBRE_EYS);
            html = html.Replace("[DOMICILO_EMPLEADOR]", tabla.VAR_DOMICILIO_EYS);
            html = html.Replace("[FUNCION_CARGO]", filaInfoContrato["DSC_FUNCIONES"].ToString().Trim().ToUpper());
            html = html.Replace("[ACTIVIDAD_CONTRATADA]", filaInfoContrato["DSC_FUNCIONES"].ToString().Trim().ToUpper());
            html = html.Replace("[EMPRESA_DESTACA]", filaInfoContrato["RAZ_SOCIAL"].ToString().Trim().ToUpper());
            html = html.Replace("[DESCRIPCION_SALARIO]", filaInfoContrato["DESCRIPCION_SALARIO"].ToString().Trim().ToUpper());
            html = html.Replace("[DIR_FIRMA_EMPLEADOR]", tabla.DIR_IMAGENES_PARA_PDF + "/firma_autos_recomendacion.jpg");
            filename = "contrato_eys";
        }

        html = html.Replace("[CARGO_TRABAJADOR]", filaInfoContrato["NOM_OCUPACION"].ToString().Trim().ToUpper());
        html = html.Replace("[NOMBRE_TRABAJADOR]", filaInfoContrato["APELLIDOS"].ToString().Trim().ToUpper() + " " + filaInfoContrato["NOMBRES"].ToString().Trim().ToUpper());
        html = html.Replace("[TIPO_DOCUMENTO_IDENTIDAD]", filaInfoContrato["TIP_DOC_IDENTIDAD"].ToString().Trim().ToUpper());
        html = html.Replace("[DOC_IDENTIFICACION]", filaInfoContrato["NUM_DOC_IDENTIDAD"].ToString().Trim().ToUpper());
        html = html.Replace("[SALARIO]", String.Format("$ {0:N2}", Convert.ToDecimal(filaInfoContrato["SALARIO"]).ToString()));
        html = html.Replace("[PERIODO_PAGO]", DropDownList_PERIODO_PAGO.SelectedItem.Text);
        html = html.Replace("[FECHA_INICIACION]", Convert.ToDateTime(filaInfoContrato["FECHA_INICIA"]).ToLongDateString());
        html = html.Replace("[CARNE_VALIDO_HASTA]", Convert.ToDateTime(filaInfoContrato["FECHA_TERMINA"]).ToLongDateString());

        usuario _usuario = new usuario(Session["idEmpresa"].ToString());
        DataTable tablaInfoUsuario = _usuario.ObtenerInicioSesionPorUsuLog(Session["USU_LOG"].ToString());
        if (tablaInfoUsuario.Rows.Count <= 0)
        {
            html = html.Replace("[CIUDAD_FIRMA]", "Desconocida");
        }
        else
        {
            DataRow filaInfoUsuario = tablaInfoUsuario.Rows[0];
            html = html.Replace("[CIUDAD_FIRMA]", filaInfoUsuario["NOMBRE_CIUDAD"].ToString());
        }

        DateTime fechaHoy = DateTime.Now;
        html = html.Replace("[DIAS_FIRMA]", fechaHoy.Day.ToString());
        html = html.Replace("[MES_FIRMA]", _tools.obtenerNombreMes(fechaHoy.Month));
        html = html.Replace("[ANNO_FIRMA]", fechaHoy.Year.ToString());

        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;FileName=" + filename + ".pdf");

        Response.Clear();
        Response.ContentType = "application/pdf";

        iTextSharp.text.Document document = new iTextSharp.text.Document(new Rectangle(612, 936), 15, 15, 10, 10);

        iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);

        pdfEvents PageEventHandler = new pdfEvents();
        writer.PageEvent = PageEventHandler;

        PageEventHandler.tipoDocumento = "contrato";

        document.Open();

        String tempFile = Path.GetTempFileName();

        using (StreamWriter tempwriter = new StreamWriter(tempFile, false))
        {
            tempwriter.Write(html);
        }

        List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StreamReader(tempFile), new StyleSheet());
        foreach (IElement element in htmlarraylist)
        {
            document.Add(element);
        }

        document.Close();
        writer.Close();

        Response.End();

        File.Delete(tempFile);
    }
 public Result SalvarUsuario(usuario usuario)
 {
     Result retorno = serviceUsuario.Salvar(usuario);
     return retorno;
 }
Esempio n. 57
0
        public ActionResult Create([Bind(Include = "id,grupo, permisos")] grupos grupos, ICollection <int> permiso, int profesores, int cursos, int CantidadUsuarios)
        {
            if (ModelState.IsValid)
            {
                foreach (int permisoSeleccionado in permiso)
                {
                    permiso permisoobj = db.permisos.Find(permisoSeleccionado);
                    grupos.permisos.Add(permisoobj);
                }
                usuario usuario = db.usuarios.Find(profesores);
                grupos.usuarios.Add(usuario);
                curso curso = db.cursos.Find(cursos);
                curso.usuarios.Add(usuario);
                grupos.curso = curso;
                List <string> destinatarios = new List <string>();
                destinatarios.Add(usuario.correo);
                if (usuario.correo_2 != null || usuario.correo_2 != "")
                {
                    destinatarios.Add(usuario.correo_2);
                }
                if (CantidadUsuarios > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 1; i <= CantidadUsuarios; i++)
                    {
                        usuario estudiante = new usuario();
                        estudiante.apellidos = Guid.NewGuid().ToString().Substring(0, 2);
                        estudiante.nombre    = Guid.NewGuid().ToString().Substring(0, 3);
                        estudiante.correo    = Guid.NewGuid().ToString().Substring(0, 3);
                        estudiante.telefono  = 0;
                        estudiante.username  = Guid.NewGuid().ToString().Substring(0, 10);
                        while (db.usuarios.Where(u => u.username.Equals(estudiante.username)).Count() > 0)
                        {
                            estudiante.username = Guid.NewGuid().ToString().Substring(0, 10);
                        }
                        estudiante.password = Guid.NewGuid().ToString().Substring(0, 10);
                        sb.AppendLine("Username = "******" Password = "******"Recursos", "logo-peq.png")));
                    celImagen.Border = 0;

                    PdfPCell celTitulo = new PdfPCell(new Phrase("Plataforma de Contenidos Digitales" +
                                                                 "\n" + DateTime.Today.ToShortDateString().ToString() +
                                                                 "\nReporte de usuarios generados",
                                                                 new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD)));
                    celTitulo.HorizontalAlignment = Element.ALIGN_CENTER;
                    celTitulo.Colspan             = 4;
                    celTitulo.Border = 0;

                    table.AddCell(celImagen);
                    table.AddCell(celTitulo);
                    MemoryStream s = new MemoryStream();

                    Document  pdfDoc    = new Document(PageSize.A4, 25, 10, 25, 10);
                    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, s);
                    pdfDoc.Open();
                    pdfDoc.AddTitle("Reporte de usuarios generados");
                    pdfDoc.Add(table);
                    Paragraph Text = new Paragraph("\n\n" + sb.ToString());
                    pdfDoc.Add(Text);
                    pdfWriter.CloseStream = false;
                    pdfDoc.Close();
                    s = new MemoryStream(s.ToArray());
                    Utilitarios.EnviarCorreoAdjunto(destinatarios, "Datos de usuarios generados: ",
                                                    "Adjunto encontrarás un documento PDF con los datos de acceso para los usuarios generados el dia " + DateTime.Today, s);
                    s.Close();
                    //Utilitarios.EnviarCorreo(destinatarios, "Datos de usuarios del grupo: " + grupos.grupo, sb.ToString());
                }
                db.grupos.Add(grupos);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(grupos));
        }
 public List<usuario> FiltrarUsuario(usuario usuario)
 {
     return serviceUsuario.Filtrar(usuario);
 }
    private Boolean EnviarArchivo(String prefijoNombreArchivo, SeccionEnvio seccion, Dictionary<String, byte[]> listaArchivos)
    {
        String archiveName;
        if(seccion == SeccionEnvio.Seleccion)
        {
            archiveName = String.Format(prefijoNombreArchivo + "DOCUMENTACION_SELECCION_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd"));
        }
        else
        {
            archiveName = String.Format(prefijoNombreArchivo + "DOCUMENTACION_CONTRATACION_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd"));
        }

        MemoryStream streamArchivoAEnviar = new MemoryStream();

        ZipOutputStream s = new ZipOutputStream(streamArchivoAEnviar);
            s.SetLevel(9);

            foreach (KeyValuePair<String, byte[]> archivo in listaArchivos)
            {
                ZipEntry entry = new ZipEntry(archivo.Key);

                entry.DateTime = DateTime.Now;
                s.PutNextEntry(entry);

                s.Write(archivo.Value, 0, (int)archivo.Value.Length);
            }

        StreamReader archivo_mensaje_correo = new StreamReader(Server.MapPath(@"~\plantillas_reportes\email_envio_docs_trabajador.htm"));

        String html_mensaje_correo = archivo_mensaje_correo.ReadToEnd();

        archivo_mensaje_correo.Dispose();
        archivo_mensaje_correo.Close();

        html_mensaje_correo = html_mensaje_correo.Replace("[NOMBRE_CLIENTE]", Label_EMPRESA_TRABAJADOR.Text.Trim());
        html_mensaje_correo = html_mensaje_correo.Replace("[NUMERO_CONTRATO]", HiddenField_ID_CONTRATO.Value);
        html_mensaje_correo = html_mensaje_correo.Replace("[NOMBRE_TRABAJADOR]", TextBox_NOMBRES.Text.Trim() + " " + TextBox_APELLIDOS.Text.Trim());
        html_mensaje_correo = html_mensaje_correo.Replace("[NUM_DOC_IDENTIDAD]", DropDownList_TIP_DOC_IDENTIDAD.SelectedItem.Text + " " + TextBox_NUM_DOC_IDENTIDAD.Text.Trim());
        if (seccion == SeccionEnvio.Seleccion)
        {
            html_mensaje_correo = html_mensaje_correo.Replace("[NOMBRE_CONTACTO_CLIENTE]", Label_NOMBRE_CONTACTO_SELECCION.Text.Trim());
        }
        else
        {
            html_mensaje_correo = html_mensaje_correo.Replace("[NOMBRE_CONTACTO_CLIENTE]", Label_NOMBRE_CONTACTO_CONTRATACION.Text.Trim());
        }

        usuario _usuario = new usuario(Session["idEmpresa"].ToString());
        DataTable tablaUsuario = _usuario.ObtenerUsuarioPorUsuLog(Session["USU_LOG"].ToString());
        DataRow filaUsuario = tablaUsuario.Rows[0];

        if (filaUsuario["USU_TIPO"].ToString().ToUpper() == "PLANTA")
        {
            html_mensaje_correo = html_mensaje_correo.Replace("[USUARIO_ENVIO]", filaUsuario["NOMBRES"].ToString().Trim() + " " + filaUsuario["APELLIDOS"].ToString().Trim());
        }
        else
        {
            html_mensaje_correo = html_mensaje_correo.Replace("[USUARIO_ENVIO]", filaUsuario["NOMBRES_EXTERNO"].ToString().Trim() + " " + filaUsuario["APELLIDOS_EXTERNO"].ToString().Trim());
        }

        tools _tools = new tools();

        if (seccion == SeccionEnvio.Seleccion)
        {
            if (_tools.enviarCorreoConCuerpoHtmlyArchivoAdjunto(TextBox_EMAIL_SELECCION.Text, "DOCUMENTACION: CONTRATO " + HiddenField_ID_CONTRATO.Value + " - " + DropDownList_TIP_DOC_IDENTIDAD.SelectedItem.Text.Trim() + " " + TextBox_NUM_DOC_IDENTIDAD.Text.Trim() + " - " + TextBox_NOMBRES.Text.Trim() + " " + TextBox_APELLIDOS.Text.Trim(), html_mensaje_correo, streamArchivoAEnviar, archiveName) == false)
            {
                Informar(Panel_MENSAJE_ENVIOARCHOVOS, Label_MENSAJE_ENVIOARCHIVOS, "Error al intentar enviar el correo al contácto de selección: " + _tools.MensajError, Proceso.Error);
                return false;
            }
            else
            {
                return true;
            }
        }
        else
        {
            if (_tools.enviarCorreoConCuerpoHtmlyArchivoAdjunto(TextBox_EMAIL_CONTRATACION.Text, "DOCUMENTACION: CONTRATO " + HiddenField_ID_CONTRATO.Value + " - " + DropDownList_TIP_DOC_IDENTIDAD.SelectedItem.Text.Trim() + " " + TextBox_NUM_DOC_IDENTIDAD.Text.Trim() + " - " + TextBox_NOMBRES.Text.Trim() + " " + TextBox_APELLIDOS.Text.Trim(), html_mensaje_correo, streamArchivoAEnviar, archiveName) == false)
            {
                Informar(Panel_MENSAJE_ENVIOARCHOVOS, Label_MENSAJE_ENVIOARCHIVOS, "Error al intentar enviar el correo al contácto de contratación: " + _tools.MensajError, Proceso.Error);
                return false;
            }
            else
            {
                return true;
            }
        }

        s.Finish();

        s.Close();
    }
    private DataRow obtenerDatosEmpleado(Decimal ID_EMPLEADO)
    {
        DataRow resultado = null;

        usuario _usuario = new usuario(Session["idEmpresa"].ToString());

        DataTable tablaDatosEjecutivo = _usuario.ObtenerEmpleadoPorIdEmpleado(ID_EMPLEADO);

        if (tablaDatosEjecutivo.Rows.Count > 0)
        {
            resultado = tablaDatosEjecutivo.Rows[0];
        }

        return resultado;
    }