Exemplo n.º 1
0
        public void Update(User user)
        {
            Exception ex = new UserRepositorio().Update(user);

            if (ex != null)
            {
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 2
0
        public static void SetupUserRole(ref User user)
        {
            LinkedList<Role> roles = new RolesServicio().GetRoles();

            foreach (var r in roles)
            {
                if (r.ID == (user.Rol.Tipo))
                {
                    user.Rol = r;

                    break;
                }
            }
        }
Exemplo n.º 3
0
        protected void gvUsuarios_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Activar"))
            {
                int selectedRowIndex = Convert.ToInt32(e.CommandArgument);

                GridViewRow selectedRow = gvUsuarios.Rows[selectedRowIndex];

                Entidad.User selectedUser = new User();

                LinkedList<User> users = (LinkedList<User>)ViewState["Users"];

                for (int i = 0; i < users.Count; i++)
                {
                    if (selectedRow.Cells[0].Text.Equals(users.ElementAt(i).Email))
                    {
                        selectedUser = users.ElementAt(i);

                        break;
                    }
                }

                if (selectedUser.Active)
                {
                    selectedUser.Active = false;

                    ((LinkButton)selectedRow.Cells[3].Controls[0]).Text = "Activar";
                }

                else
                {
                    selectedUser.Active = true;

                    ((LinkButton)selectedRow.Cells[3].Controls[0]).Text = "Desactivar";
                }

                UserServicio.SetupUserRole(ref selectedUser);

                new UserServicio().Update(selectedUser);
            }
        }
Exemplo n.º 4
0
        protected void Guardar_Click(object sender, EventArgs e)
        {            
            int[] err = new int[23];

            err[0] = 0; /////////////////////////////////////////////////////////////////// EAF /////////////////////////////////////////////////////////////
            
            if (err[0] == 0)
            {
                string TipoExc = "";
                if (RB1.Checked) TipoExc = "1";
                if (RB2.Checked) TipoExc = "2";
                if (RB3.Checked) TipoExc = "3";

                string cs = ConfigurationManager.ConnectionStrings["EXC"].ConnectionString;

                using (SqlConnection conn = new SqlConnection(cs))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.CommandType = CommandType.Text;

                        User _user = new Entidad.User()
                        {
                            EmpresaID = string.IsNullOrEmpty(Request.QueryString["EmpName"])
                            ? string.Empty : Request.QueryString["EmpName"].Replace("amp;", string.Empty).Replace("@AND", "&")
                        };

                        var existingCompany = new SolicitudesInicialesServicio().GetCompany(_user);

                        if (string.IsNullOrWhiteSpace(_user.EmpresaID))
                        {
                            #region Create

                            cmd.CommandText = "INSERT INTO Empresas VALUES (" +
                                            "@TipoExcavador, @NombreEmpresa, @RepresentanteAutorizado," +
                                            "@UrbBarrioCond, @ApartBoxCalle, @Municipio, @Sector, @EstadoPais, @CodigoPostal," +
                                            "@EsOperador, @TelOficina, @TelCampoTrabajo, @Celular, @UrbBarrioCondDF, @ApartBoxCalleDF," +
                                            "@MunicipioDF, @SectorDF, @EstadoPaisDF, @CodigoPostalDF, @Comentarios, @CorreoElectronico);";

                            cmd.CommandText += @"UPDATE Usuarios SET EmpresaID = @NombreEmpresa WHERE CorreoElectronico = @UserCorreoElectronico;";

                            //cmd.CommandText += @"UPDATE Usuarios SET EmpresaID = @NombreEmpresa WHERE EmpresaID = @NombreEmpresa;";

                            if (esOperador.Checked)
                            {
                                cmd.CommandText += @"INSERT INTO Operadores VALUES(@Operador, @CorreoElectronico);";

                                cmd.Parameters.AddWithValue("Operador", NombreEmpresa.Text.ToUpper());
                            }

                            cmd.Parameters.AddWithValue("UserCorreoElectronico", (string)Session["Email"]); 

                            #endregion
                        }

                        else
                        {
                            #region Edit

                            cmd.CommandText = "UPDATE Empresas SET" +
                                            " TipoExcDem = @TipoExcavador, NombreEmpresa = @NombreEmpresa, RepresentanteAutorizado= @RepresentanteAutorizado," +
                                            "UrbBarrioCond = @UrbBarrioCond, ApartBoxCalle = @ApartBoxCalle, Municipio = @Municipio, Sector = @Sector, EstadoPais = @EstadoPais, CodigoPostal = @CodigoPostal," +
                                            "EsOperador = @EsOperador, TelOficina = @TelOficina, TelTrabajo = @TelCampoTrabajo, Celular = @Celular, UrbBarrioCondDF = @UrbBarrioCondDF, ApartBoxCalleDF = @ApartBoxCalleDF," +
                                            @"MunicipioDF = @MunicipioDF, SectorDF = @SectorDF, EstadoPaisDF = @EstadoPaisDF, CodigoPostalDF = @CodigoPostalDF, Comentarios = @Comentarios,
                          CorreoElectronico = @CorreoElectronico WHERE EmpresaID = @EmpresaID;

                         UPDATE Usuarios SET EmpresaID = @NombreEmpresa WHERE EmpresaID = @CompanyName;";

                            Operador operadorExistenteByName = new SolicitudesInicialesServicio().GetOperadorByName(existingCompany.Nombre),
                                operadorExistenteByEmail = SolicitudesInicialesServicio.GetOperadorByEmail(existingCompany.CorreoElectronico);

                            if (esOperador.Checked)
                            {
                                if (string.IsNullOrWhiteSpace(operadorExistenteByName.Nombre) && string.IsNullOrWhiteSpace(operadorExistenteByEmail.Email))
                                {
                                    cmd.CommandText += @"INSERT INTO Operadores VALUES(@Operador, @CorreoElectronico);";

                                    cmd.Parameters.AddWithValue("Operador", NombreEmpresa.Text.ToUpper());
                                }

                                else
                                {
                                    string where = "Operador = @CompanyName";

                                    if (!string.IsNullOrWhiteSpace(operadorExistenteByEmail.Email))
                                        where = string.Format("CorreoElectronico = '{0}'", operadorExistenteByEmail.Email);

                                    cmd.CommandText += @"UPDATE Operadores SET Operador = @NombreEmpresa, CorreoElectronico = @CorreoElectronico WHERE 
                                                     @WHERE".Replace("@WHERE", where);
                                }
                            }

                            cmd.Parameters.AddWithValue("CompanyName", existingCompany.Nombre);

                            cmd.Parameters.AddWithValue("EmpresaID", existingCompany.EmpresaID); 

                            #endregion
                        }

                        cmd.Parameters.AddWithValue("@TipoExcavador", TipoExc);

                        cmd.Parameters.AddWithValue("@NombreEmpresa", NombreEmpresa.Text.ToUpper());

                        cmd.Parameters.AddWithValue("@RepresentanteAutorizado", RepresentanteAutorizado.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@UrbBarrioCond", UrbBarrioCond.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@ApartBoxCalle", ApartBoxCalle.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@Municipio", Municipio.SelectedValue.ToString());
                        cmd.Parameters.AddWithValue("@Sector", Sector.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@EstadoPais", EstadoPais.SelectedValue.ToString());
                        cmd.Parameters.AddWithValue("@CodigoPostal", CodigoPostal.Text);
                        cmd.Parameters.AddWithValue("@EsOperador", esOperador.Checked);
                        cmd.Parameters.AddWithValue("@TelOficina", TelOficina.Text);
                        cmd.Parameters.AddWithValue("@TelCampoTrabajo", TelCampoTrabajo.Text);
                        cmd.Parameters.AddWithValue("@Celular", Celular.Text);
                        cmd.Parameters.AddWithValue("@UrbBarrioCondDF", UrbBarrioCondDF.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@ApartBoxCalleDF", ApartBoxCalleDF.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@MunicipioDF", MunicipioDF.SelectedValue.ToString());
                        cmd.Parameters.AddWithValue("@SectorDF", SectorDF.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@EstadoPaisDF", EstadoPaisDF.SelectedValue.ToString().ToUpper());
                        cmd.Parameters.AddWithValue("@CodigoPostalDF", CodigoPostalDF.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@Comentarios", Comentarios.Text.ToUpper());

                        cmd.Parameters.AddWithValue("CorreoElectronico", CorreoElectronico.Text);

                        try
                        {
                            ClientScript.RegisterStartupScript(GetType(), "leavingMsg", "", true);

                            conn.Open();
                            int recordsAffected = cmd.ExecuteNonQuery();     
                        } 
                        catch (Exception ex)
                        {
                            var er = ex.Message;// error here
                        }
                        finally
                        {
                            conn.Close();

                            Session["shoulLogOut"] = true;

                            if (!string.IsNullOrWhiteSpace(existingCompany.Nombre))
                            {
                                //Update user session if updated company
                                User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

                                user.EmpresaID = NombreEmpresa.Text;

                                Session["UserObj"] = user;

                                Response.Redirect("~/Default.aspx");                                
                            }                            

                            Response.Redirect("~/Account/Ingresar.aspx");
                        }
                    }
                }
            }
       
        }     
Exemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            bool shouldLogOut = Session["shoulLogOut"] == null ? true : (bool)Session["shoulLogOut"];

            if (shouldLogOut)
            {
                Response.Redirect("~/Account/Ingresar.aspx");
            }

            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            //title.Text = "hi";

            title.InnerText = Title;

            if (!IsPostBack)
            {
                User _user = new Entidad.User()
                {
                    EmpresaID = string.IsNullOrEmpty(Request.QueryString["EmpName"])
                    ? string.Empty : Request.QueryString["EmpName"].Replace("amp;", string.Empty).Replace("@AND", "&") //remove garbage
                };

                var company = new SolicitudesInicialesServicio().GetCompany(_user);

                if (!string.IsNullOrEmpty(company.Nombre))
                {
                    #region Edit

                    esOperador.Checked = company.EsOperador;

                    if (company.TipoExcavador > 2)
                    {
                        RB3.Checked = true;
                    }

                    else if (company.TipoExcavador > 1)
                    {
                        RB2.Checked = true;
                    }

                    else
                    {
                        RB1.Checked = true;
                    }

                    NombreEmpresa.Text = company.Nombre;

                    RepresentanteAutorizado.Text = company.RepresentanteAutorizado;

                    if (company.EsOperador)
                    {
                        esOperador_CheckedChanged(esOperador, EventArgs.Empty);
                    }

                    CorreoElectronico.Text = company.CorreoElectronico;

                    TelCampoTrabajo.Text = company.TelTrabajo;

                    TelOficina.Text = company.TelOficina;

                    Celular.Text = company.Celular;

                    string[] direccionPostal = company.DireccionPostal.Split(','),
                        direccionFisica = company.DireccionFisica.Split(',');

                    UrbBarrioCond.Text = direccionPostal[0].Trim();

                    ApartBoxCalle.Text = direccionPostal[1].Trim();

                    Municipio.DataBind();

                    Municipio.SelectedValue = company.Municipio;

                    Sector.Text = direccionPostal[2].Trim();

                    EstadoPais.DataBind();

                    EstadoPais.SelectedValue = direccionPostal[3].Trim();

                    CodigoPostal.Text = company.CodigoPostal;

                    UrbBarrioCondDF.Text = direccionFisica[0].Trim();

                    ApartBoxCalleDF.Text = direccionFisica[1].Trim();

                    MunicipioDF.DataBind();

                    MunicipioDF.SelectedValue = direccionFisica[2].Trim();

                    SectorDF.Text = direccionFisica[3].Trim();

                    EstadoPaisDF.DataBind();

                    EstadoPaisDF.SelectedValue = direccionFisica[4].Trim();

                    CodigoPostalDF.Text = direccionFisica[5].Trim();

                    Comentarios.Text = company.Comentario; 
                    #endregion
                }

                else
                {
                    #region Leaving msg

                    ClientScript.RegisterStartupScript(GetType(), "leavingMsg", @"window.onbeforeunload = LeavingMsg;

                function LeavingMsg()
                {
                    debugger;

                    txt = document.getElementById('" + NombreEmpresa.ClientID + @"');  

                    //txtVal = txt.value.trim();                                                                                    

                    //if(txtVal.length === 0) //if string is empty
                    //{
                    return 'Recuerde registrar su entidad antes de navegar fuera de esta pagina';   
                    //}                                                                                     
                }", true); 
                    #endregion
                }

                if (company.EsOperador)
                {
                    CorreoElectronico.Attributes["style"] = "display:normal;";

                    emailLbl.Attributes["style"] = "display:normal; text-align:right";

                    emailREV.Enabled = true;

                    emailRFV.Enabled = true;
                }

                else
                {
                    CorreoElectronico.Attributes["style"] = "display:none;";

                    emailLbl.Attributes["style"] = "display:none; text-align:right";

                    emailREV.Enabled = false;

                    emailRFV.Enabled = false;
                }
            }

            else
            {
                ClientScript.RegisterStartupScript(GetType(), "leavingMsg", "", true);
            }
        }
Exemplo n.º 6
0
        public SolicitudAviso()
        {
            PuedeCrearPrimeraExt = false;

            PuedeCrearSegundaExt = false;

            FechaRespuestaSolicitadas = string.Empty;

            FechaExpiracionExplosivo = DateTime.MaxValue;

            Usuario = new User();

            FechaDocsIncompletos = Convert.ToDateTime(@"01/01/1900");

            Coordinador = new Coordinador();

            Inspector = new Inspector();

            Averias = new LinkedList<Averia>();

            Emergencia = false;

            Documentos = new LinkedList<DocumentoRequerido>();

            StatusMsgs = new Dictionary<string, Color>();

            StatusMsgs.Add("1", Color.FromArgb(232, 232, 0));

            StatusMsgs.Add("2", Color.FromArgb(232, 232, 0));

            StatusMsgs.Add("3", Color.DarkRed);

            StatusMsgs.Add("4", Color.FromArgb(232, 232, 0));

            StatusMsgs.Add("5", Color.FromArgb(232, 232, 0));

            StatusMsgs.Add("6", Color.FromArgb(152, 174, 90));

            StatusMsgs.Add("7", Color.DarkRed);

            NumeroControl = new Entidad.NumeroControl
            {
                NumControl = 0,

                Year = DateTime.MinValue.Year,

                NumControlText = String.Empty
            };     

            TipoAviso = ((int)TiposAvisos.Excavacion).ToString();

            LetraStatus = "S";

            EstatusId = string.Empty;

            NombreContacto = String.Empty;

            CelularContacto = String.Empty;

            DireccionPostalContacto = String.Empty;

            NombreEmpresa = String.Empty;

            AreaDept = String.Empty;

            RepresentanteAutorizado = String.Empty;

            TelOficina = String.Empty;       

            TelCampoTrabajo = String.Empty;        

            Fax = String.Empty;

            TelCelular = String.Empty;

            CorreoElectronico = String.Empty;

            DireccionPostal = String.Empty;

            MunicipioId = 0;

            CodigoPostal = String.Empty;

            Subcontratista = String.Empty;

            AreaDeptSub = String.Empty;

            RepresentanteAutorizadoSub = String.Empty;

            TelOficinaSub = String.Empty;

            TelCampoTrabajoSub = String.Empty;

            FaxSub = String.Empty;

            TelCelularSub = String.Empty;

            CorreoElectronicoSub = String.Empty;

            DireccionPostalSub = String.Empty;

            MunicipioIdSub = 0;

            CodigoPostalSub = String.Empty;

            Zona = false;

            BoUrb = String.Empty;

            SectorCalle = String.Empty;

            Carretera = String.Empty;

            KM = 0;

            HM = 0;

            MunicipioIdTrab = 0;

            Referencias = String.Empty;

            FechaPropuesta = DateTime.Parse("01/01/1900");

            FechaComienzo = DateTime.Parse("01/01/1900");

            FechaExpiracion = DateTime.Parse("01/01/1900");

            TiempoDuracion = string.Empty;

            Horario = String.Empty;

            Maquinaria = false;

            TipoMaquinaria = String.Empty;

            Explosivos = false;

            LicenciaExplosivo = String.Empty;

            AreaMarcada = false;

            TipoExcavacion = false;

            RazonTrabajos = String.Empty;

            ProfundidadPies = 0;

            ProfundidadPulgadas = 0;

            LongitudPies = 0;

            LongitudPulgadas = 0;

            CoordenadaX = 0m;

            CoordenadaY = 0m;

            EnCasoEmergencia = String.Empty;

            TramitadoPor = String.Empty;

            FechaTramite = DateTime.Parse("01/01/1900");

            ExtensionID = (int)TiposExtensiones.Inicial;

            SolicitudStatusID = 0;

            Observaciones = string.Empty;
        }
Exemplo n.º 7
0
        protected void Guardar_Click(object sender, EventArgs e)
        {
            //UsuarioID = CorreoElectronico.Text;
            
            int[] err = new int[23];

            //// TipoExcavador err[1]
            //if (NombreEmpresa.Text.Equals("")) { err[2] = 1; err[0] = 1; }
            //if (RepresentanteAutorizado.Text.Equals("")) { err[3] = 1; err[0] = 1; }
            //if (CorreoElectronico.Text.Equals("")) { err[4] = 1; err[0] = 1; }
            //if (UrbBarrioCond.Text.Equals("")) { err[5] = 1; err[0] = 1; }
            //// ApartBoxCalle err[6]
            //if (Municipio.SelectedIndex == 0) { err[7] = 1; err[0] = 1; }
            //// Sector err[8]
            //if (EstadoPais.SelectedIndex == 0) { err[9] = 1; err[0] = 1; }
            //if (CodigoPostal.Text.Equals("")) { err[10] = 1; err[0] = 1; }
            //// EsOperador err[11]
            //if (TelOficina.Text.Equals("")) { err[12] = 1; err[0] = 1; }
            //// TelCampoTrabajo err[13]
            //// Celular err[14]
            //if (UrbBarrioCondDF.Text.Equals("")) { err[15] = 1; err[0] = 1; }
            //// ApartBoxCalleDF err[16]
            //if (MunicipioDF.SelectedIndex == 0) { err[17] = 1; err[0] = 1; }
            //// SectorDF err[18]
            //if (EstadoPaisDF.SelectedIndex == 0) { err[19] = 1; err[0] = 1; }
            //if (CodigoPostalDF.Text.Equals("")) { err[20] = 1; err[0] = 1; }
            //// Comentarios err[21]
            //// UsuarioID err[22]

            err[0] = 0; /////////////////////////////////////////////////////////////////// EAF /////////////////////////////////////////////////////////////
            
            if (err[0] == 0)
            {
                string TipoExc = "";
                if (RB1.Checked) TipoExc = "1";
                if (RB2.Checked) TipoExc = "2";
                if (RB3.Checked) TipoExc = "3";

                string cs = ConfigurationManager.ConnectionStrings["EXC"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(cs))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.CommandType = CommandType.Text;

                        User _user = new Entidad.User()
                        {
                            EmpresaID = string.IsNullOrEmpty(Request.QueryString["EmpName"])
                            ? string.Empty : Request.QueryString["EmpName"].Replace("amp;", string.Empty).Replace("@AND", "&")
                        };

                        var existingCompany = new SolicitudesInicialesServicio().GetCompany(_user);

                        if (string.IsNullOrWhiteSpace(_user.EmpresaID))
                        {
                            cmd.CommandText = "INSERT INTO Empresas VALUES (" +
                        "@TipoExcavador, @NombreEmpresa, @RepresentanteAutorizado," +
                        "@UrbBarrioCond, @ApartBoxCalle, @Municipio, @Sector, @EstadoPais, @CodigoPostal," +
                        "@EsOperador, @TelOficina, @TelCampoTrabajo, @Celular, @UrbBarrioCondDF, @ApartBoxCalleDF," +
                        "@MunicipioDF, @SectorDF, @EstadoPaisDF, @CodigoPostalDF, @Comentarios, @CorreoElectronico);";

                            cmd.CommandText += @"UPDATE Usuarios SET EmpresaID = @NombreEmpresa WHERE CorreoElectronico = @UserCorreoElectronico;";

                            if (esOperador.Checked)
                            {
                                cmd.CommandText += @"INSERT INTO Operadores VALUES(@Operador, @CorreoElectronico);";

                                cmd.Parameters.AddWithValue("Operador", NombreEmpresa.Text.ToUpper());
                            }

                            cmd.Parameters.AddWithValue("UserCorreoElectronico", (string)Session["Email"]);
                        }

                        else
                        {     
                            cmd.CommandText = "UPDATE Empresas SET" +
                        " TipoExcDem = @TipoExcavador, NombreEmpresa = @NombreEmpresa, RepresentanteAutorizado= @RepresentanteAutorizado," +
                        "UrbBarrioCond = @UrbBarrioCond, ApartBoxCalle = @ApartBoxCalle, Municipio = @Municipio, Sector = @Sector, EstadoPais = @EstadoPais, CodigoPostal = @CodigoPostal," +
                        "EsOperador = @EsOperador, TelOficina = @TelOficina, TelTrabajo = @TelCampoTrabajo, Celular = @Celular, UrbBarrioCondDF = @UrbBarrioCondDF, ApartBoxCalleDF = @ApartBoxCalleDF," +
                        @"MunicipioDF = @MunicipioDF, SectorDF = @SectorDF, EstadoPaisDF = @EstadoPaisDF, CodigoPostalDF = @CodigoPostalDF, Comentarios = @Comentarios,
                          CorreoElectronico = @CorreoElectronico WHERE EmpresaID = @EmpresaID;

                         UPDATE Usuarios SET EmpresaID = @NombreEmpresa WHERE EmpresaID = @CompanyName;";

                            Operador operadorExistente = new SolicitudesInicialesServicio().GetOperador(existingCompany.NombreEmpresa);

                            if (esOperador.Checked)
                            {
                                if (string.IsNullOrWhiteSpace(operadorExistente.Nombre))
                                {
                                    cmd.CommandText += @"INSERT INTO Operadores VALUES(@Operador, @CorreoElectronico);";

                                    cmd.Parameters.AddWithValue("Operador", NombreEmpresa.Text.ToUpper());
                                }

                                else
                                {
                                    cmd.CommandText += @"UPDATE Operadores SET Operador = @NombreEmpresa, CorreoElectronico = @CorreoElectronico WHERE 
                                                     Operador = @CompanyName;";
                                }
                            }

                            cmd.Parameters.AddWithValue("CompanyName", existingCompany.NombreEmpresa);

                            cmd.Parameters.AddWithValue("EmpresaID", existingCompany.EmpresaID);
                        }

                        

                        
                        //(SELECT E.NombreEmpresa 
//						                                            FROM Empresas AS E 
//						                                            INNER JOIN Usuarios AS U 
//						                                            ON E.UsuarioID = U.CorreoElectronico 
//						                                            WHERE E.UsuarioID = @UsuarioID)
//                                              FROM Usuarios AS U 
//                                              INNER JOIN Empresas AS E
//                                              ON U.CorreoElectronico = E.UsuarioID 
//                                              WHERE U.CorreoElectronico = @UsuarioID;";

                        cmd.Parameters.AddWithValue("@TipoExcavador", TipoExc);
                        cmd.Parameters.AddWithValue("@NombreEmpresa", NombreEmpresa.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@RepresentanteAutorizado", RepresentanteAutorizado.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@UrbBarrioCond", UrbBarrioCond.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@ApartBoxCalle", ApartBoxCalle.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@Municipio", Municipio.SelectedValue.ToString());
                        cmd.Parameters.AddWithValue("@Sector", Sector.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@EstadoPais", EstadoPais.SelectedValue.ToString());
                        cmd.Parameters.AddWithValue("@CodigoPostal", CodigoPostal.Text);
                        cmd.Parameters.AddWithValue("@EsOperador", esOperador.Checked);
                        cmd.Parameters.AddWithValue("@TelOficina", TelOficina.Text);
                        cmd.Parameters.AddWithValue("@TelCampoTrabajo", TelCampoTrabajo.Text);
                        cmd.Parameters.AddWithValue("@Celular", Celular.Text);
                        cmd.Parameters.AddWithValue("@UrbBarrioCondDF", UrbBarrioCondDF.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@ApartBoxCalleDF", ApartBoxCalleDF.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@MunicipioDF", MunicipioDF.SelectedValue.ToString());
                        cmd.Parameters.AddWithValue("@SectorDF", SectorDF.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@EstadoPaisDF", EstadoPaisDF.SelectedValue.ToString().ToUpper());
                        cmd.Parameters.AddWithValue("@CodigoPostalDF", CodigoPostalDF.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@Comentarios", Comentarios.Text.ToUpper());

                        cmd.Parameters.AddWithValue("CorreoElectronico", CorreoElectronico.Text);

                        try
                        {
                            ClientScript.RegisterStartupScript(GetType(), "leavingMsg", "", true);

                            conn.Open();
                            int recordsAffected = cmd.ExecuteNonQuery();                           

                            //if (recordsAffected > 0) //Status.Text = "Empresa añadida al sistema...";
                            //System.Threading.Thread.Sleep(2000);
                        } 
                        catch (Exception ex)
                        {
                            var er = ex.Message;// error here
                        }
                        finally
                        {
                            //command.CommandText = "SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]";
                            conn.Close();
                            //Update_User(sender, e);
                            //Cancelar_Click(sender, e);

                            Session["shoulLogOut"] = true;

                            if (!string.IsNullOrWhiteSpace(existingCompany.NombreEmpresa))
                            {
                                //Update user session if updated company
                                User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

                                user.EmpresaID = NombreEmpresa.Text;

                                Session["UserObj"] = user;

                                Response.Redirect("~/Default.aspx");                                
                            }                            

                            Response.Redirect("~/Account/Ingresar.aspx");
                        }
                    }
                }
            }
       
        }     
Exemplo n.º 8
0
        protected void Guardar_Click(object sender, EventArgs e)
        {
            entidadRFV.Enabled = true;

            Page.Validate();


            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            if (user == null)
            {
                user = new User();
            }

            //entidadRFV.Enabled = true;

            //Page.Validate();

            if(Page.IsValid)
            {
                emailHF.Value = CorreoElectronico.Text;

                //string allTextBoxValues = ""};
                //foreach (Control c in Page.Controls)
                //{
                //    foreach (Control childc in c.Controls)
                //    {
                //        if (childc is TextBox)
                //        {
                //            allTextBoxValues += ((TextBox)childc).Text + ","};
                //        }
                //    }
                //}
                //if (allTextBoxValues != "")
                //{
                //    // Label1.Text = allTextBoxValues};
                //}


                int[] err = new int[12];

                //string Contrasena = Page.Request.Form["Contrasena"];
                //string ConfirmarContrasena = Page.Request.Form["ConfirmarContrasena"];

                //if (NombreUsuario.Text.Equals("")) { err[1] = 1; err[0] = 1; }
                //if (Inicial.Text.Equals("")) { err[2] = 1; err[0] = 1; }
                //if (ApellidoPaterno.Text.Equals("")) { err[3] = 1; err[0] = 1; }
                //if (ApellidoMaterno.Text.Equals("")) { err[4] = 1; err[0] = 1; }
                //if (CorreoElectronico.Text.Equals("")) { err[5] = 1; err[0] = 1; }
                //if (ConfirmarCorreoElectronico.Text.Equals("")) { err[6] = 1; err[0] = 1; }
                //if (Contrasena.Equals("")) { err[7] = 1; err[0] = 1; }
                //if (ConfirmarContrasena.Equals("")) { err[8] = 1; err[0] = 1; }
                //if (PreguntaSeguridad.SelectedIndex == 0) { err[9] = 1; err[0] = 1; }
                //if (RespuestaSeguridad.Text.Equals("")) { err[10] = 1; err[0] = 1; }
                //if (Telefono.Text.Equals("")) { err[11] = 1; err[0] = 1; }

                err[0] = 0; ////////////////////////////// EAF ///////////////////////////////////
                if (err[0] == 0)
                {
                    string cs = ConfigurationManager.ConnectionStrings["EXC"].ConnectionString;
                    using (SqlConnection conn = new SqlConnection(cs))
                    {
                        using (SqlCommand command = new SqlCommand())
                        {
                            command.Connection = conn;
                            command.CommandType = CommandType.Text;

                            var role = roles.Where(x => x.Nombre == roleDDL.SelectedValue).First();

                            var inspectores = new LinkedList<Inspector>();

                           
                            if (string.IsNullOrWhiteSpace(Request.QueryString["Email"]))
                            {
                                #region Create

                                //command.CommandText = @"DELETE FROM Usuarios WHERE CorreoElectronico = @CorreoElectronico;";

                                command.CommandText += @"INSERT INTO Usuarios VALUES (@NombreUsuario, @Inicial, @ApellidoPaterno, @ApellidoMaterno,
                                                       @CorreoElectronico, @ConfirmarCorreoElectronico, @Contrasena, @ConfirmarContrasena, @PreguntaSeguridad, 
                                                       @RespuestaSeguridad, @Telefono, @UsuarioInterno, @EmpresaID, @Rol);";

                                if (user.Rol.ID == (int)Role.TipoRoles.Admin)
                                {
                                    if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                    {
                                        inspectores = new SolicitudesInicialesServicio().GetInspectores();

                                        int ultimaPlaca = Convert.ToInt32(inspectores.ElementAt(inspectores.Count - 1).NumeroPlacaID);

                                        command.CommandText += @"INSERT INTO Inspectores VALUES (@PlacaInspector, @NombreCompleto, @CorreoElectronico);";

                                        command.Parameters.AddWithValue("@PlacaInspector", (ultimaPlaca + 1).ToString("D3"));

                                        command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else if (role.ID == (int)Role.TipoRoles.Coordinador)
                                    {
                                        command.CommandText += @"INSERT INTO Coordinadores VALUES (@NombreCompleto);";

                                        command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else if (role.ID == (int)Role.TipoRoles.Admin 
                                        || role.ID == (int)Role.TipoRoles.SuperInspector
                                        || role.ID == (int)Role.TipoRoles.Director)
                                    {
                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else
                                    {
                                        command.Parameters.AddWithValue("@UsuarioInterno", false);
                                    }

                                    //command.Parameters.AddWithValue("@Rol", role.ID);
                                }

                                else
                                {
                                    //command.Parameters.AddWithValue("@Rol", ((int)Role.TipoRoles.Excavador - 1));

                                    command.Parameters.AddWithValue("@UsuarioInterno", false);
                                }

                                #endregion
                            }                             

                            else
                            {
                                #region Edit
                                command.CommandText += @"UPDATE Usuarios SET NombreUsuario = @NombreUsuario,
                                                                             Inicial = @Inicial,
                                                                             ApellidoPaterno = @ApellidoPaterno,
                                                                            ApellidoMaterno = @ApellidoMaterno,
                                                                            CorreoElectronico = @CorreoElectronico,
                                                                            ConfirmarCorreoElectronico = @ConfirmarCorreoElectronico,
                                                                            Contrasena = @Contrasena,
                                                                            ConfirmarContrasena = @ConfirmarContrasena,
                                                                            PreguntaSeguridad = @PreguntaSeguridad, 
                                                                            RespuestaSeguridad = @RespuestaSeguridad,
                                                                            Telefono = @Telefono,
                                                                            UsuarioInterno = @UsuarioInterno,
                                                                            EmpresaID = @EmpresaID,
                                                                            Rol = @Rol
                                                                            WHERE CorreoElectronico = @OldEmail;";

                                command.Parameters.AddWithValue("@OldEmail", (string)Session["UserEmail"]);

                                if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                {
                                    inspectores = new SolicitudesInicialesServicio().GetInspectores();

                                    string placaInspector = inspectores.Where(x => x.CorreoElectronico.Equals((string)Session["UserEmail"])).First().NumeroPlacaID;

                                    command.CommandText += @"UPDATE Inspectores SET NombreInspector = @NombreCompleto
                                                                                    , CorreoElectronico = @CorreoElectronico 
                                                                WHERE PlacaInspector = @PlacaInspector;";

                                    command.Parameters.AddWithValue("@PlacaInspector", placaInspector);

                                    command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else if (role.ID == (int)Role.TipoRoles.Coordinador)
                                {
                                    command.CommandText += @"UPDATE Coordinadores SET NombreCoordinador = @NombreCompleto WHERE NombreCoordinador = @NombreCoordinador;";

                                    command.Parameters.AddWithValue("@NombreCoordinador", (string)Session["Username"]);

                                    command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else if (role.ID == (int)Role.TipoRoles.Admin
                                        || role.ID == (int)Role.TipoRoles.SuperInspector
                                        || role.ID == (int)Role.TipoRoles.Director)
                                {
                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else
                                {
                                    command.Parameters.AddWithValue("@UsuarioInterno", false);
                                }

                                #endregion
                            }

                            command.Parameters.AddWithValue("@Rol", role.ID);  

                            command.Parameters.AddWithValue("@NombreUsuario", NombreUsuario.Text.ToUpper());                                                  

                            command.Parameters.AddWithValue("@Inicial", Inicial.Text.ToUpper());
                            command.Parameters.AddWithValue("@ApellidoPaterno", ApellidoPaterno.Text.ToUpper());
                            command.Parameters.AddWithValue("@ApellidoMaterno", ApellidoMaterno.Text.ToUpper()); ;
                            command.Parameters.AddWithValue("@CorreoElectronico", CorreoElectronico.Text.ToLower());
                            command.Parameters.AddWithValue("@ConfirmarCorreoElectronico", ConfirmarCorreoElectronico.Text.ToLower());

                            if (string.IsNullOrWhiteSpace(ConfirmarContrasena.Value))
                            {
                                string oldEmail = (string)Session["UserEmail"];

                                if(oldEmail.Equals(user.Email))
                                {                                
                                    command.Parameters.AddWithValue("@Contrasena", user.Password );

                                    command.Parameters.AddWithValue("@ConfirmarContrasena", user.Password);
                                }

                                else
                                {
                                    User selectedUser = new SolicitudesInicialesServicio().GetUser(Request.QueryString["Email"].Replace("%40", "@"));

                                    command.Parameters.AddWithValue("@Contrasena", selectedUser.Password);

                                    command.Parameters.AddWithValue("@ConfirmarContrasena", selectedUser.Password);
                                }
                            }

                            else
                            {
                                command.Parameters.AddWithValue("@Contrasena", Contrasena.Value);

                                command.Parameters.AddWithValue("@ConfirmarContrasena", Contrasena.Value);
                            }

                            //command.Parameters.AddWithValue("@Contrasena", string.IsNullOrWhiteSpace(ConfirmarContrasena.Value) 
                            //    ? user.Password : Contrasena.Value );
                            //command.Parameters.AddWithValue("@ConfirmarContrasena", string.IsNullOrWhiteSpace(ConfirmarContrasena.Value)
                            //    ? user.Password : Contrasena.Value);
                            command.Parameters.AddWithValue("@PreguntaSeguridad", PreguntaSeguridad.SelectedValue.ToString());
                            command.Parameters.AddWithValue("@RespuestaSeguridad", RespuestaSeguridad.Text.ToUpper());
                            command.Parameters.AddWithValue("@Telefono", Telefono.Text);
                            //command.Parameters.AddWithValue("@UsuarioInterno", false);
                            command.Parameters.AddWithValue("@EmpresaID", ddlEmpresas.SelectedValue);

                            try
                            {
                                conn.Open();
                                int recordsAffected = command.ExecuteNonQuery();

                                if (string.IsNullOrWhiteSpace(Request.QueryString["Email"]))
                                {   
                                    #region Create user document directories

                                    Directory.CreateDirectory(Server.MapPath(string.Format("{0}/{1}",
                                                                    new DocumentoRequerido().DocumentosInicialesSavePath, CorreoElectronico.Text)));

                                    if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                    {
                                        Directory.CreateDirectory(Server.MapPath(string.Format("{0}/{1}",
                                        new DocumentoRequerido().DocumentosInspeccionesSavePath, CorreoElectronico.Text)));
                                    } 

                                    Directory.CreateDirectory(Server.MapPath(string.Format("{0}/{1}",
                                        new DocumentoRequerido().DocumentosPrimerasSavePath, CorreoElectronico.Text)));

                                    Directory.CreateDirectory(Server.MapPath(string.Format("{0}/{1}",
                                        new DocumentoRequerido().DocumentosSegundasSavePath, CorreoElectronico.Text)));

                                    #endregion

                                    Response.Redirect("~/Account/Ingresar.aspx");

                                    //Cancelar_Click(sender, e);
                                }                                    

                                else
                                {
                                    Entidad.User updatedUser = new SolicitudesInicialesServicio().GetUser(CorreoElectronico.Text);

                                    #region Update current user variable

                                    if (updatedUser.Email.Equals(user.Email))
                                    {
                                        foreach (var r in roles)
                                        {
                                            if (r.ID == (user.Rol.Tipo))
                                            {
                                                user.Rol = r;

                                                Session["UserObj"] = user;

                                                break;
                                            }
                                        }
                                    }
                                    #endregion

                                    Response.Redirect("~/Default.aspx");
                                }

                                //command.ExecuteNonQuery();

                                //if (recordsAffected == 1)
                                //{
                                
                                //}

                                //else
                                //{
                                //    throw new Exception();
                                //}
                            }
                            catch (Exception ex)
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "sqlerr()", true);
                            }
                            finally
                            {
                                conn.Close();
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            if (user == null)
            {
                user = new User(); 
            }

            if (!user.Rol.VerRegistrar)
            {
                if (!Request.QueryString["Email"].Replace("%40", "@").Equals(user.Email))
                Response.Redirect("~/Default.aspx");
            }

            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            title.InnerText = Title;

            #region Fill Roles ddl

            //LinkedList<Role> roles = new RolesServicio().GetRoles();

            foreach (var r in roles)
            {
                roleDDL.Items.Add(r.Nombre);
            } 

            #endregion

            #region Fill company
            var companies = new SolicitudesInicialesServicio().GetCompanies();

            ddlEmpresas.Items.Add("Seleccionar Entidad");

            foreach (var c in companies)
            {
                ddlEmpresas.Items.Add(c.NombreEmpresa);
            }
            #endregion

            #region Fill pregunta seguridad

            using (var conn = new SQL().GetLocalConnection())
            {
                var cmd = new SqlCommand("SELECT PreguntaSeg FROM PreguntasSeg", conn);

                conn.Open();

                SqlDataReader reader = cmd.ExecuteReader();

                //cmd.ExecuteNonQuery();

                //DataTable dt = new DataTable();

                //using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                //{
                //    adapter.Fill(dt);
                //}

                PreguntaSeguridad.DataSource = reader;

                PreguntaSeguridad.DataBind();
            }

            #endregion

           

            //lblId.Text = Request.QueryString["ID"].ToString();   
            if (!IsPostBack)
            {
                if (user.Rol.ID == (int)Role.TipoRoles.Admin)
                {
                    rolTR.Style.Add("display", "normal");

                    ddlEmpresas.Items.Add("DTOP");

                    ddlEmpresas.SelectedValue = "DTOP";
                }

                if (!string.IsNullOrWhiteSpace(Request.QueryString["Email"]))
                {
                    //Evitar que entren a pagina usando query string sin ser user auth, actual user o teniendo el permiso
                    if (!Request.QueryString["Email"].Replace("%40", "@").Equals(user.Email)) //Check edit user permission goes here*/)
                    {
                        if (user.Rol.ID != (int)Role.TipoRoles.Admin)
                        Response.Redirect("~/Account/Ingresar.aspx");
                    }

                    //Hacer esto despues del page load o quiza hacerle load a los ddl antes

                    User selectedUser = new SolicitudesInicialesServicio().GetUser(Request.QueryString["Email"].Replace("%40", "@"));

                    NombreUsuario.Text = selectedUser.Nombre;

                    //if (ddlEmpresas.Items.FindByValue(selectedUser.EmpresaID) == null)
                    //{
                    //    ddlEmpresas.Items.Add(selectedUser.EmpresaID);

                    //    ddlEmpresas.SelectedValue = selectedUser.EmpresaID;
                    //}

                    //else
                    //{
                    //    ddlEmpresas.SelectedValue = selectedUser.EmpresaID;
                    //}

                    Session["Username"] = selectedUser.Nombre;

                    Inicial.Text = selectedUser.Inicial;

                    ApellidoPaterno.Text = selectedUser.ApellidoPaterno;

                    ApellidoMaterno.Text = selectedUser.ApellidoMaterno;

                    CorreoElectronico.Text = selectedUser.Email;

                    ConfirmarCorreoElectronico.Text = selectedUser.Email;

                    CorreoElectronico.Enabled = false; 

                    ConfirmarCorreoElectronico.Enabled = false;

                    Session["UserEmail"] = selectedUser.Email;

                    Contrasena.Disabled = true;

                    passRFV.Enabled = false;

                    ConfirmarContrasena.Disabled = true;

                    confirmarPassRFV.Enabled = false;

                    confirmarPassCV.Enabled = false;

                    changePasswordBtn.Visible = true;

                    if (PreguntaSeguridad.Items.FindByValue(selectedUser.PreguntaSeguridad) == null)
                    {
                        PreguntaSeguridad.Items.Add(selectedUser.PreguntaSeguridad);
                    }

                    PreguntaSeguridad.SelectedValue = selectedUser.PreguntaSeguridad;

                    //Session["PreSeg"] = user.PreguntaSeguridad;

                    RespuestaSeguridad.Text = selectedUser.RespuestaSeguridad;

                    Telefono.Text = selectedUser.Tel;

                    for (int i = 0; i < roles.Count; i++)
                    {
                        if (roles.ElementAt(i).ID == selectedUser.Rol.Tipo)
                        {
                            roleDDL.SelectedValue = roles.ElementAt(i).Nombre;

                            break;
                        }
                    }

                    //roleDDL.SelectedIndex = selectedUser.Rol.Tipo;
                    
                    //Session["Empresa"] = user.EmpresaID;

                    if (ddlEmpresas.Items.FindByValue(selectedUser.EmpresaID) == null 
                        && !string.IsNullOrEmpty(selectedUser.EmpresaID))
                    {
                        ddlEmpresas.Items.Add(selectedUser.EmpresaID);

                        ddlEmpresas.SelectedValue = selectedUser.EmpresaID;
                    }

                    else if (ddlEmpresas.Items.FindByValue(selectedUser.EmpresaID) == null
                        && string.IsNullOrEmpty(selectedUser.EmpresaID))
                    {
                        ddlEmpresas.SelectedIndex = 0;
                    }

                    else if (ddlEmpresas.Items.FindByValue(selectedUser.EmpresaID) != null)
                    {
                        ddlEmpresas.SelectedValue = selectedUser.EmpresaID;
                    }

                    if (ddlEmpresas.SelectedValue.Equals("DTOP") && user.Rol.ID != (int)Role.TipoRoles.Admin)
                    {
                        ddlEmpresas.Enabled = false;
                    }
                }
            }
        }
Exemplo n.º 10
0
        public User GetUser(string email)
        {
            //using (SqlConnection conn = new SQL().GetConnection())
            using (SqlConnection conn = new SQL().GetLocalConnection())
            {
                SqlCommand cmd = new SqlCommand(@"SELECT CorreoElectronico, NombreUsuario, Inicial, ApellidoMaterno, ApellidoPaterno 
                                                  , Contrasena, PreguntaSeguridad, RespuestaSeguridad, Telefono, EmpresaID, Rol, UsuarioInterno 
                                                  FROM Usuarios WHERE CorreoElectronico = @CorreoElectronico", conn);

                cmd.Parameters.AddWithValue("CorreoElectronico", email);

                conn.Open();

                cmd.ExecuteNonQuery();

                SqlDataReader reader = cmd.ExecuteReader();

                User user = new User();

                while (reader.Read())
                {
                    int col = 0;

                    user = new User()
                    {
                        Email = reader[col++].ToString(),

                        Nombre = reader[col++].ToString(),

                        Inicial = reader[col++].ToString(),

                        ApellidoMaterno = reader[col++].ToString(),

                        ApellidoPaterno = reader[col++].ToString(),

                        Password = reader[col++].ToString(),

                        PreguntaSeguridad = reader[col++].ToString(),

                        RespuestaSeguridad = reader[col++].ToString(),

                        Tel = reader[col++].ToString(),

                        EmpresaID = reader[col++].ToString(),

                        Rol = new Role()
                        {
                            Tipo = reader.GetInt32(col++)
                        },

                        Interno = reader.GetBoolean(col++)
                    };
                }

                return user;
            }
        }
Exemplo n.º 11
0
        public Company GetCompany(User user)
        {
            Company company = new Company();

            //using (SqlConnection conn = new SQL().GetConnection())
            using (SqlConnection conn = new SQL().GetLocalConnection())
            {
                SqlCommand cmd = new SqlCommand(@"SELECT TipoExcDem,  EsOperador, CorreoElectronico, EmpresaID, NombreEmpresa, UrbBarrioCond + ', ' + ApartBoxCalle 
                                                + ', ' + Sector + ', ' + EstadoPais, UrbBarrioCondDF + ', ' + ApartBoxCalleDF + ', ' + MunicipioDF
                                                + ', ' + SectorDF + ', ' + EstadoPaisDF + ', ' + CodigoPostalDF, RepresentanteAutorizado
                                                , TelOficina, TelTrabajo, Celular, CodigoPostal, Municipio, Comentarios 
                                                FROM Empresas WHERE NombreEmpresa = @NombreEmpresa;", conn);

                cmd.Parameters.AddWithValue("NombreEmpresa", user.EmpresaID);

                //cmd.Parameters.AddWithValue("UsuarioID", "*****@*****.**"); //Test only

                conn.Open();

                cmd.ExecuteNonQuery();

                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    int col = 0;

                    company = new Company()
                    {     
                        TipoExcavador = Convert.ToInt32(reader.GetString(col++)),

                        EsOperador = reader.GetBoolean(col++),

                        CorreoElectronico = reader.GetString(col++),

                        EmpresaID = reader.GetInt32(col++),

                        NombreEmpresa = reader.GetString(col++),

                        DireccionPostal = reader.GetString(col++),

                        DireccionFisica = reader.GetString(col++),

                        RepresentanteAutorizado = reader.GetString(col++),

                        TelOficina = reader.GetString(col++),

                        TelTrabajo = reader.GetString(col++),

                        Celular = reader.GetString(col++),

                        CodigoPostal = reader.GetString(col++),

                        Municipio = reader.GetString(col++),

                        Comentario = reader.GetString(col++)
                    };
                }
            }

            return company;
        }
 public Company GetCompany(User user)
 {
     return repository.GetCompany(user);
 }
Exemplo n.º 13
0
        protected void Guardar_Click(object sender, EventArgs e)
        {
            #region Evita issue donde deja crear user sin entidad

            entidadRFV.Enabled = true;

            Page.Validate(); 

            #endregion

            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            if (user == null)
            {
                user = new User();
            }

            Page.Validate();

            if(Page.IsValid)
            {
                emailHF.Value = CorreoElectronico.Text;

                int[] err = new int[12];

                err[0] = 0; ////////////////////////////// EAF ///////////////////////////////////

                if (err[0] == 0)
                {
                    string cs = ConfigurationManager.ConnectionStrings["EXC"].ConnectionString;

                    using (SqlConnection conn = new SqlConnection(cs))
                    {
                        using (SqlCommand command = new SqlCommand())
                        {
                            command.Connection = conn;
                            command.CommandType = CommandType.Text;

                            var role = roles.Where(x => x.Nombre == roleDDL.SelectedValue).First();

                            var inspectores = new LinkedList<Inspector>();

                           
                            if (string.IsNullOrWhiteSpace(Request.QueryString["Email"]))
                            {
                                #region Create

                                command.CommandText += @"INSERT INTO Usuarios VALUES (@NombreUsuario, @Inicial, @ApellidoPaterno, @ApellidoMaterno,
                                                       @CorreoElectronico, @ConfirmarCorreoElectronico, @Contrasena, @ConfirmarContrasena, @PreguntaSeguridad, 
                                                       @RespuestaSeguridad, @Telefono, @UsuarioInterno, @EmpresaID, @Rol, @Activo);";

                                if (user.Rol.ID == (int)Role.TipoRoles.Admin)
                                {
                                    if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                    {
                                        inspectores = new SolicitudesInicialesServicio().GetInspectores();

                                        int ultimaPlaca = Convert.ToInt32(inspectores.ElementAt(inspectores.Count - 1).NumeroPlacaID);

                                        command.CommandText += @"INSERT INTO Inspectores VALUES (@PlacaInspector, @NombreCompleto, @CorreoElectronico);";

                                        command.Parameters.AddWithValue("@PlacaInspector", (ultimaPlaca + 1).ToString("D3"));

                                        command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else if (role.ID == (int)Role.TipoRoles.Coordinador)
                                    {
                                        command.CommandText += @"INSERT INTO Coordinadores VALUES (@NombreCompleto);";

                                        command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else if (role.ID == (int)Role.TipoRoles.Admin 
                                        || role.ID == (int)Role.TipoRoles.SuperInspector
                                        || role.ID == (int)Role.TipoRoles.Director)
                                    {
                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else
                                    {
                                        command.Parameters.AddWithValue("@UsuarioInterno", false);
                                    }
                                }

                                else
                                {
                                    command.Parameters.AddWithValue("@UsuarioInterno", false);
                                }

                                #endregion
                            }                             

                            else
                            {
                                #region Edit
                                command.CommandText += @"UPDATE Usuarios SET NombreUsuario = @NombreUsuario,
                                                                             Inicial = @Inicial,
                                                                             ApellidoPaterno = @ApellidoPaterno,
                                                                            ApellidoMaterno = @ApellidoMaterno,
                                                                            CorreoElectronico = @CorreoElectronico,
                                                                            ConfirmarCorreoElectronico = @ConfirmarCorreoElectronico,
                                                                            Contrasena = @Contrasena,
                                                                            ConfirmarContrasena = @ConfirmarContrasena,
                                                                            PreguntaSeguridad = @PreguntaSeguridad, 
                                                                            RespuestaSeguridad = @RespuestaSeguridad,
                                                                            Telefono = @Telefono,
                                                                            UsuarioInterno = @UsuarioInterno,
                                                                            EmpresaID = @EmpresaID,
                                                                            Rol = @Rol,
                                                                            Activo = @Activo
                                                                            WHERE CorreoElectronico = @OldEmail;";

                                command.Parameters.AddWithValue("@OldEmail", (string)ViewState["UserEmail"]);

                                if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                {
                                    inspectores = new SolicitudesInicialesServicio().GetInspectores();

                                    string placaInspector = inspectores.Where(x => x.CorreoElectronico.Equals((string)ViewState["UserEmail"])).First().NumeroPlacaID;

                                    command.CommandText += @"UPDATE Inspectores SET NombreInspector = @NombreCompleto
                                                                                    , CorreoElectronico = @CorreoElectronico 
                                                                WHERE PlacaInspector = @PlacaInspector;";

                                    command.Parameters.AddWithValue("@PlacaInspector", placaInspector);

                                    command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else if (role.ID == (int)Role.TipoRoles.Coordinador)
                                {
                                    command.CommandText += @"UPDATE Coordinadores SET NombreCoordinador = @NombreCompleto WHERE NombreCoordinador = @NombreCoordinador;";

                                    command.Parameters.AddWithValue("@NombreCoordinador", (string)Session["Username"]);

                                    command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else if (role.ID == (int)Role.TipoRoles.Admin
                                        || role.ID == (int)Role.TipoRoles.SuperInspector
                                        || role.ID == (int)Role.TipoRoles.Director)
                                {
                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else
                                {
                                    command.Parameters.AddWithValue("@UsuarioInterno", false);
                                }

                                #endregion
                            }

                            command.Parameters.AddWithValue("@Rol", role.ID);

                            command.Parameters.AddWithValue("@Activo", true); 

                            command.Parameters.AddWithValue("@NombreUsuario", NombreUsuario.Text.ToUpper());                                                  

                            command.Parameters.AddWithValue("@Inicial", Inicial.Text.ToUpper());
                            command.Parameters.AddWithValue("@ApellidoPaterno", ApellidoPaterno.Text.ToUpper());
                            command.Parameters.AddWithValue("@ApellidoMaterno", ApellidoMaterno.Text.ToUpper()); ;
                            command.Parameters.AddWithValue("@CorreoElectronico", CorreoElectronico.Text.ToLower());
                            command.Parameters.AddWithValue("@ConfirmarCorreoElectronico", ConfirmarCorreoElectronico.Text.ToLower());

                            //Si el pass es empty y el logged user esta updating su profile then use pass from logged user
                            if (string.IsNullOrWhiteSpace(ConfirmarContrasena.Value))
                            {
                                string oldEmail = (string)ViewState["UserEmail"];

                                if(oldEmail.Equals(user.Email))
                                {                                
                                    command.Parameters.AddWithValue("@Contrasena", user.Password );

                                    command.Parameters.AddWithValue("@ConfirmarContrasena", user.Password);
                                }

                                    //No uses pass del logged user sino, Get pass del user que se esta updating
                                else
                                {
                                    User selectedUser = new SolicitudesInicialesServicio().GetUser(Request.QueryString["Email"].Replace("%40", "@"));

                                    command.Parameters.AddWithValue("@Contrasena", selectedUser.Password);

                                    command.Parameters.AddWithValue("@ConfirmarContrasena", selectedUser.Password);
                                }
                            }

                            else
                            {
                                command.Parameters.AddWithValue("@Contrasena", Contrasena.Value);

                                command.Parameters.AddWithValue("@ConfirmarContrasena", Contrasena.Value);
                            }

                            command.Parameters.AddWithValue("@PreguntaSeguridad", PreguntaSeguridad.SelectedValue.ToString());
                            command.Parameters.AddWithValue("@RespuestaSeguridad", RespuestaSeguridad.Text.ToUpper());
                            command.Parameters.AddWithValue("@Telefono", Telefono.Text);
                            command.Parameters.AddWithValue("@EmpresaID", ddlEmpresas.SelectedValue);

                            try
                            {
                                conn.Open();
                                int recordsAffected = command.ExecuteNonQuery();

                                if (string.IsNullOrWhiteSpace(Request.QueryString["Email"]))
                                {
                                    CreateUserDir(role, CorreoElectronico.Text);

                                    Response.Redirect("~/Account/Ingresar.aspx");
                                }                                    

                                else
                                {
                                    string oldEmail = (string)ViewState["UserEmail"];

                                    #region Update user dir

                                    if (!oldEmail.Equals(CorreoElectronico.Text))
                                    {
                                        Directory.Move(Server.MapPath(string.Format("{0}/{1}",
                                                                           new DocumentoRequerido().DocumentosInicialesSavePath, oldEmail)),
                                                                           Server.MapPath(string.Format("{0}/{1}", new DocumentoRequerido().DocumentosInicialesSavePath,
                                                                           CorreoElectronico.Text)));

                                        Directory.Move(Server.MapPath(string.Format("{0}/{1}",
                                            new DocumentoRequerido().DocumentosPrimerasSavePath, oldEmail)),
                                            Server.MapPath(string.Format("{0}/{1}", new DocumentoRequerido().DocumentosPrimerasSavePath,
                                            CorreoElectronico.Text)));

                                        Directory.Move(Server.MapPath(string.Format("{0}/{1}",
                                            new DocumentoRequerido().DocumentosSegundasSavePath, oldEmail)),
                                            Server.MapPath(string.Format("{0}/{1}", new DocumentoRequerido().DocumentosSegundasSavePath,
                                            CorreoElectronico.Text)));

                                        if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                        {
                                            Directory.Move(Server.MapPath(string.Format("{0}/{1}",
                                                new DocumentoRequerido().DocumentosInspeccionesSavePath, oldEmail)),
                                                Server.MapPath(string.Format("{0}/{1}", new DocumentoRequerido().DocumentosInspeccionesSavePath,
                                                CorreoElectronico.Text)));
                                        }
                                    }
 
                                    #endregion

                                    #region Update current user variable

                                    if (oldEmail.Equals(user.Email))
                                    {
                                        foreach (var r in roles)
                                        {
                                            if (r.ID == (user.Rol.Tipo))
                                            {
                                                user.Rol = r;

                                                user.Email = CorreoElectronico.Text;

                                                user.EmpresaID = ddlEmpresas.SelectedValue;

                                                Session["UserObj"] = user;

                                                break;
                                            }
                                        }
                                    }
                                    #endregion

                                    Response.Redirect("~/Default.aspx");
                                }
                            }
                            catch (Exception)
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "sqlerr()", true);
                            }
                            finally
                            {
                                conn.Close();
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 14
0
        public Exception Update(User user)
        {
            using (SqlConnection conn = new SQL().GetLocalConnection())
            {
                #region Sql command

                SqlCommand cmd = new SqlCommand(@"UPDATE Usuarios SET NombreUsuario = @NombreUsuario,
                                                                             Inicial = @Inicial,
                                                                             ApellidoPaterno = @ApellidoPaterno,
                                                                            ApellidoMaterno = @ApellidoMaterno,
                                                                            CorreoElectronico = @CorreoElectronico,
                                                                            ConfirmarCorreoElectronico = @ConfirmarCorreoElectronico,
                                                                            Contrasena = @Contrasena,
                                                                            ConfirmarContrasena = @ConfirmarContrasena,
                                                                            PreguntaSeguridad = @PreguntaSeguridad, 
                                                                            RespuestaSeguridad = @RespuestaSeguridad,
                                                                            Telefono = @Telefono,
                                                                            UsuarioInterno = @UsuarioInterno,
                                                                            EmpresaID = @EmpresaID,
                                                                            Rol = @Rol,
                                                                            Activo = @Activo
                                                                            WHERE CorreoElectronico = @CorreoElectronico;", conn);

                #endregion

                #region Command Parameteres

                cmd.Parameters.AddWithValue("@Rol", user.Rol.ID);

                cmd.Parameters.AddWithValue("@Activo", user.Active);

                cmd.Parameters.AddWithValue("@NombreUsuario", user.Nombre);

                cmd.Parameters.AddWithValue("@Inicial", user.Inicial);

                cmd.Parameters.AddWithValue("@ApellidoPaterno", user.ApellidoPaterno);

                cmd.Parameters.AddWithValue("@ApellidoMaterno", user.ApellidoMaterno);

                cmd.Parameters.AddWithValue("@CorreoElectronico", user.Email);

                cmd.Parameters.AddWithValue("@ConfirmarCorreoElectronico", user.Email);

                cmd.Parameters.AddWithValue("@Contrasena", user.Password);

                cmd.Parameters.AddWithValue("@ConfirmarContrasena", user.Password);

                cmd.Parameters.AddWithValue("@PreguntaSeguridad", user.PreguntaSeguridad);

                cmd.Parameters.AddWithValue("@RespuestaSeguridad", user.RespuestaSeguridad);

                cmd.Parameters.AddWithValue("@Telefono", user.Tel);

                cmd.Parameters.AddWithValue("@EmpresaID", user.EmpresaID);

                cmd.Parameters.AddWithValue("@UsuarioInterno", user.Interno);

                #endregion

                conn.Open();

                using (SqlTransaction transaction = conn.BeginTransaction())
                {
                    cmd.Transaction = transaction;

                    try
                    {
                        cmd.ExecuteNonQuery();

                        transaction.Commit();

                        return null;
                    }

                    catch (SqlException ex)
                    {
                        transaction.Rollback();

                        String errorLog = "Date: " + DateTime.Now.ToLongDateString() + "\r\n User email:" + user.Email
                            + "\r\n Message: " + ex.Message + "\r\n Source: "
                            + ex.Source + "\r\n Stacktrace: " + ex.StackTrace + "\r\n TargetSite: " + ex.TargetSite.ToString() + "\r\n\r\n";

                        //File.WriteAllText("SolicitudInicLog.txt", errorLog);

                        return ex;
                    }
                }
            }
        }