将两种方法合二为一

时间:2016-08-11 22:31:23

标签: c# asp.net methods

将两个保存到数据库中的方法结合起来是否可行?

第一种方法:

 protected void btnGuardar_Click(object sender, EventArgs e)
    {

        MembershipUserDefined ObjMembershipUserDefined = new MembershipUserDefined();

        try
        {

            rcCaptcha.Validate();


            if (rcCaptcha.IsValid)
            {

                var persona = PersonaClass.GetById(this.txtCorreoElectronico.Text);
                if (persona != null)
                {
                    //si ya exisitia porque lo habia registrado un consultor entonces borra sus datos de la BD 
                    if (!persona.RegistroCandidato)
                    {
                        using (BolsaEntities ef = new BolsaEntities())
                        {
                            try
                            {

                                var borraruser = ef.sp_Elimina_Registro_Usuario(this.txtCorreoElectronico.Text).ToList();

                                if (!Convert.ToBoolean(borraruser.FirstOrDefault().Value))
                                {
                                    throw new Exception("El candidato ya existe..");
                                }

                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }
                    }
                }

                /*Validar RFC*/
                //var eDatoPersonal = DatoPersonalClass.GetById(this.txtCorreoElectronico.Text);
                var eDatoPersonalRFC = DatoPersonalClass.ExistRFC(this.txtRFC.Text);

                //Si el rfc existe retornamos mensaje de rfc en uso
                if (eDatoPersonalRFC != null)
                {
                    ucError.SetMessage(AlertType.Warning, "Creación de cuenta",
                        "Lo sentimos ya existe una cuenta con el RFC ingresado. Vuelve a intentarlo.");
                    return;
                }
                //if (eDatoPersonal != null ? eDatoPersonal.Rfc.Equals(this.txtRFC.Text) : false)
                //{
                //    ucError.SetMessage(AlertType.Warning, "Creación de cuenta", "Lo sentimos ya existe una cuenta con el RFC ingresado. Vuelve a intentarlo.");
                //    return;
                //}

                //Creamos el objetivo de tipo Membership
                ObjMembershipUserDefined.UserName = this.txtCorreoElectronico.Text;
                ObjMembershipUserDefined.EMail = this.txtCorreoElectronico.Text;
                ObjMembershipUserDefined.ProviderKey = System.Guid.Empty;

                MembershipTools.Insert(ObjMembershipUserDefined, this.txtContrasena.Text, new string[] {"Candidato"},
                    false);

                /*agregar objeto en persona*/
                var ObjPersona = PersonaClass.GetById(ObjMembershipUserDefined.UserName);

                //Si ya existe registro para ese usuario no puede aprovisionar
                if (ObjPersona != null)
                {
                    //Error en aprovisionamiento
                    ucError.SetMessage(AlertType.Warning, "Creación de cuenta",
                        "Sorry you cant ");
                    return;
                }
                else
                {
                    //aprovisionamos el registro
                    ObjPersona = new Persona();
                    ObjPersona.UserName = ObjMembershipUserDefined.UserName;
                    //ObjPersona.FechaCreacion = ObjMembershipUser.CreationDate;
                    ObjPersona.FechaCreacion = DateTime.Now;
                    //ObjPersona.FechaActivacion = DateTime.Now;
                    //ObjPersona.EstaEnListaNegra = false; ERC
                    ObjPersona.StageCaptura = 99;
                    ObjPersona.EsBuscable = false;
                    ObjPersona.CapturaConcluida = false;
                    ObjPersona.IdEstatus = 1145; //Estatus disponble
                    ObjPersona.RegistroCandidato = true;

                    //new PersonaClass().Add(ObjPersona);

                    ///*agregar objeto en dato personal*/
                    var ObjDatoPersonal = new DatoPersonal()
                    {
                        UserName = ObjMembershipUserDefined.UserName,
                        Nombre = this.txtNombre.Text,
                        ApellidoPaterno = this.txtApellidoPaterno.Text,
                        ApellidoMaterno = this.txtApellidoMaterno.Text,
                        Rfc = this.txtRFC.Text,

                    };

                    IntegraS3.BR.Bolsa.Utilities.Transaccion.BeginTransactionRegister(ObjPersona, ObjDatoPersonal);
                }
                /*===========================================================================================================*/

                try
                {

                    Mailing.SendMail(txtCorreoElectronico.Text, string.Empty, "Creación de cuenta",
                        Server.MapPath("~/MailDefinitions/CreatedAccount.html"),
                        GetReplacementValues(ObjMembershipUserDefined.ProviderKey, ObjMembershipUserDefined.UserName,
                            this.txtContrasena.Text));

                }
                catch (Exception oe)
                {
                    if (oe.ToString().ToLower().Contains("mailbox unavailable. the server response was"))
                    {
                        Membership.DeleteUser(this.txtCorreoElectronico.Text);
                        ucError.SetMessage(AlertType.Warning, "Creación de cuenta",
                            "Tu cuenta no ha sido creada debido a que el correo electrónico que proporcionaste no es válido.");
                        return;
                    }
                    else
                    {
                        throw oe;
                    }
                }

            }
            else
            {

                ucError.SetMessage(AlertType.Warning, "Creación de cuenta",
                    "Los caracteres no coinciden con la imagen. Vuelve a intentarlo.");
                return;

            }

            this.ucError.SetMessage(AlertType.Information, "Creación de cuenta",
                string.Format(
                    "sorry you cant",
                    this.txtCorreoElectronico.Text));
            ClearControls();

        }
        catch (Exception ex)
        {
            ucError.SetMessage(AlertType.Error, "Error", ex.ToString());
        }
    }

第二种方法:

protected void btnEnviar_Click(object sender, EventArgs e)
    {
        string especialidadEstudios = ddlEspEstudio.SelectedValue;

        try
        {

            string disponibilidadCambioRdesidencia = string.Empty;
            foreach (ListItem item in radDispuestoACambiarResidencia.Items)
            {
                if (item.Selected != false) disponibilidadCambioRdesidencia = item.Value;
            }

            string fechaNacimiento = txtFechaNacimiento.Text;
            string telefonoContacto = txtTelContacto.Text;


            decimal sueldoMensualDeseado = txtSueldoDeseado.Text.Equals("")
                ? 0
                : Convert.ToDecimal(txtSueldoDeseado.Text);
            decimal sueldoMensualActual = txtSueldoActual.Text.Equals("") ? 0 : Convert.ToDecimal(txtSueldoActual.Text);


            //string fileFoto = saveImagen(this.ObjFileImagen);
            //string fileCV = SaveCV(this.ObjFileCV);
            if (this.ObjFileImagen.FileName.Equals(string.Empty))
            {
                //this.ucMessage1.SetMessage(AlertType.Warning, "Captura rapida", "La foto es requerida");
                return;
            }

            if (this.ObjFileCV.FileName.Equals(string.Empty))
            {
               // this.ucMessage1.SetMessage(AlertType.Warning, "Captura rapida", "El o CV es requerido");
                return;
            }

            var ObjFoto = saveImagen(this.ObjFileImagen);
            var ObjCV = SaveCV(this.ObjFileCV);


            var ObjPersona = PersonaClass.GetById(this.Profile.PerfilUsuario.Username);
            if (ObjPersona != null)
            {
                //ObjPersona.PathFoto = fileFoto;
                //ObjPersona.PathArchivoCV = fileCV;
                ObjPersona.PathFoto = ObjFoto.PathFoto;
                ObjPersona.FotoArchivoId = ObjFoto.FotoArchivoId;
                ObjPersona.CVArchivoId = ObjCV.CVArchivoId;
                ObjPersona.PathArchivoCV = ObjCV.PathArchivoCV;

                ObjPersona.StageCaptura = 0;
                ObjPersona.EsCapturaRapida = false;

            }
            //DatoPersonal
            var ObjDatoPersonal = DatoPersonalClass.GetById(this.Profile.PerfilUsuario.Username);
            if (ObjDatoPersonal != null)
            {
                ObjDatoPersonal.IdEspecialidadEstudios = int.Parse(especialidadEstudios);
                ObjDatoPersonal.FechaNacimiento = Convert.ToDateTime(fechaNacimiento);
                ObjDatoPersonal.TelefonoCelular = txtTelMovil.Text;
                ObjDatoPersonal.TelefonoCasa = txtTelContacto.Text;
                ObjDatoPersonal.DisponibilidadCambioResidencia =
                    this.radDispuestoACambiarResidencia.SelectedItem.ToString() == "Si" ? 1 : 0;
            }
            //Direccion
            var ObjDireccion = new Direccion
            {
                UserName = this.Profile.PerfilUsuario.Username,
                //////////EntidadEsp = estadoResidencia,
                Calle = string.Empty,
                Numero = string.Empty
            };

            //UltimoTrabajo
            var ObjUltimoTrabajo = new UltimoTrabajo
            {
                UserName = this.Profile.PerfilUsuario.Username,
                SueldoDeseado = sueldoMensualDeseado,
                SueldoActual = sueldoMensualActual,
                DispuestoACambiarResidencia =
                    this.radDispuestoACambiarResidencia.SelectedItem.ToString() == "Si" ? true : false,
                //disponibilidadCambioRdesidencia; baja media alta
                PuestoActualOUltimo = string.Empty,
                DispuestoAViajar = false,

            };

            //Escolaridad
            var objEstudioAdicional = new EstudioAdicional
            {

                UserName = this.Profile.PerfilUsuario.Username,
                IdCatalogoEstudioAdicional = null,
                IdCatalogoEstatusEstudio = int.Parse(ddlEstatusEstudios.SelectedValue), //Nivel Licenciatura
                IdCatalogoPaisEstudio = 22, //Mexico
                IdCatalogoDisciplinaAcademica = null,
                IdCatalogoCarreraOEstudio = int.Parse(ddlEspEstudio.SelectedValue),
                IdCatalogoInstitucion = null,
                IdAnioInicio = null,
                IdMesInicio = null,
                IdAnioFin = null,
                IdMesFin = null,
                HorarioEstudio = string.Empty,
                OtroNombreCarreraOEstudio =
                    (ddlEspEstudio.SelectedItem.Value == "1442") ? txtNombreCarrera.Text : string.Empty,
                OtroNombreInstitucion = string.Empty,
                IdEspecialidadEstudios = null,
                IdSubEspecialidadEstudios = null,
                IdEspecialdadPuesto = null,

            };


            List<RelacionUltimoTrabajo> ListEstados = new List<RelacionUltimoTrabajo>();
            for (int i = 0; i < this.lstEstado.Items.Count; i++)
            {
                if (this.lstEstado.Items[i].Selected)
                {
                    RelacionUltimoTrabajo relacionUltimoTrabajo = new RelacionUltimoTrabajo();
                    relacionUltimoTrabajo.EntFedID = int.Parse(lstEstado.Items[i].Value);
                    ListEstados.Add(relacionUltimoTrabajo);

                }
            }

            if (ListEstados.Count.Equals(0))
            {
                if (radDispuestoACambiarResidencia.SelectedValue == "0") //si tiene disponibilidad
                {
                    //this.ucMessage1.SetMessage(AlertType.Warning, "Captura rapida", "Debe seleccionar mínimo un estado");
                    return;
                }

            }


            List<RelacionAreaIntere> ListAreaExperiencia = new List<RelacionAreaIntere>();
            foreach (ListItem item in this.ChekAreaExperiencia.Items)
            {
                if (item.Selected)
                {
                    RelacionAreaIntere relacionAreaExperiencia = new RelacionAreaIntere();
                    relacionAreaExperiencia.IdCatalogoInteresTrabajo = int.Parse(item.Value);
                    ListAreaExperiencia.Add(relacionAreaExperiencia);
                }

            }

            if (ListAreaExperiencia.Count == 0)
            {
               // this.ucMessage1.SetMessage(AlertType.Warning, "Áreas de experiencias",
                   // "Debe seleccionar mínimo una área de experiencia");
                return;
            }

            if (ListAreaExperiencia.Count > 3)
            {
                //this.ucMessage1.SetMessage(AlertType.Warning, "Áreas de experiencias",
                    //"Solo puedes seleccionar 3 áreas de preferencia");
                return;
            }

            IntegraS3.BR.Bolsa.Utilities.Transaccion.BeginTransactionResumen(ObjPersona, ObjDatoPersonal, ObjDireccion,
                ObjUltimoTrabajo, ListAreaExperiencia, ListEstados, objEstudioAdicional);
            this.Response.Redirect("~/Candidato/default.aspx");

        }
        catch (Exception ex)
        {
           // this.ucMessage1.SetMessage(AlertType.Error, "Captura rapida", "Error al guardar datos " + ex.ToString());
        }
    }

所以我想把这两种方法融合在一起。并保存所有数据,因为在我有两个不同的按钮之前,但现在我只有一个, 那是可行的吗?此致

0 个答案:

没有答案
相关问题