Ejemplo n.º 1
0
        public async Task <IHttpActionResult> Edit(Correos model)
        {
            try
            {
                var result = new AjaxResult();

                if (ModelState.IsValid)
                {
                    db.Entry(model).State = EntityState.Modified;
                    await db.SaveChangesAsync();

                    AddLog("", model.Id, model);

                    return(Ok(result.True("Record Updated")));
                }
                else
                {
                    //return InternalServerError(new Exception("Error, All field are required"));
                    string s = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
                    return(Ok(result.False(s)));
                }
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Ejemplo n.º 2
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                td.Insert(Convert.ToInt32(grdYourTickets.SelectedRow.Cells[1].Text), DateTime.Now, 2, txtAnswer.InnerText);
                grdYourTicketDetails.DataBind();
                Correos     Cr    = new Correos();
                var         Email = Convert.ToString(grdYourTickets.SelectedRow.Cells[4].Text);
                MailMessage mnsj  = new MailMessage();

                mnsj.Subject = "Sistema de Iscripción de Becas";

                mnsj.To.Add(new MailAddress(Email.ToString()));

                mnsj.From = new MailAddress("*****@*****.**", "UJComputers");

                mnsj.Body = " UJComputers\n Support Center  \n Hi " + Convert.ToString(grdYourTickets.SelectedRow.Cells[3].Text) + ". \n Your problem has been answered by one of our supporters. \n\n Please visit our page with your code you will see the answers yo your problem.\n\n Have a good day.";


                /* Enviar */
                Cr.MandarCorreo(mnsj);
                txtAnswer.InnerText = "";
            }

            catch
            {
                System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Error sending the message, please try again');", true);
            }
        }
Ejemplo n.º 3
0
    public void Activa_Correo(string matricula, int folio,int Zona,int plantel)
    {
        DbCorreosDataContext dbCorreos = new DbCorreosDataContext();

        Correos Correo = (from C in dbCorreos.Correos
                          where C.matricula.ToString() == matricula
                          select C).FirstOrDefault();
        if (Correo != null)
        {
            Correo.situacion = -1;
            Correo.folio = folio;
            dbCorreos.SubmitChanges();
        }
        else {

            string cuenta = Zona.ToString() + plantel.ToString().PadLeft(3, '0') + folio.ToString();

            Correo = new Correos();
            Correo.situacion = -2;
            Correo.matricula = Convert.ToInt32(matricula);
            Correo.cuenta = cuenta;
            Correo.folio = folio;

            dbCorreos.Correos.InsertOnSubmit(Correo);

            dbCorreos.SubmitChanges();

        }
    }
Ejemplo n.º 4
0
        public ActionResult DetallesDeOfertasDeDonaciones(string Email, int Id, string descripcion)
        {
            var     Usuario = _context.Usuario.FirstOrDefault(user => user.Id == Id);
            Correos c       = new Correos();

            if (Usuario != null)
            {
                string solicitante = Usuario.Email.ToString();
                string objeto      = descripcion;

                string to      = Email;
                string subject = "Possible petitioner";

                //Mejorar este mensaje y ponerlo con HTML
                string body = "Hello, the user: "******" is interested in taking your request: " + objeto + ", that you posted in our page, please send him an email him with the details to the place were you can deal the donation.";

                c.enviarCorreo(to, subject, body);

                return(RedirectToAction("HomePage", "Home", new { flag = 5, UsuarioId = Usuario.Id, Usuario.Email }));
            }
            else
            {
                //Enviar VB de usuario no registrado
            }
            return(View());
        }
Ejemplo n.º 5
0
        public ActionResult RecuperarContraseña(string Email)
        {
            Encriptacion e       = new Encriptacion();
            Correos      c       = new Correos();
            var          Usuario = _context.Usuario.FirstOrDefault(user => user.Email == Email);

            if (Usuario != null)
            {
                string strToken = Usuario.Email.ToString();
                //ACÁ SE DEBERÍA ENCRIPTAR EL EMAIL
                string claveCompartida = "limoncitoconron";
                string strEncrypted    = e.EncryptStringAES(strToken, claveCompartida);

                var address = "http://freecycle-001-site1.btempurl.com/Usuarios/CambiarContraseña/?tkn=" + strEncrypted;

                string to      = Email;
                string subject = "Password recovery";

                //Mejorar este mensaje y ponerlo con HTML
                string body = "Hello, in the following link you will be able to change your password to recover your account: " + address;

                c.enviarCorreo(to, subject, body);

                //No es necesario se puede manejar con una flag tipica
                ViewBag.Email = Email;
            }
            else
            {
                //Enviar VB de usuario no registrado
            }
            return(View());
        }
        public async Task <IActionResult> Edit(int id, [Bind("IdCorreo,DescripcionCorreo,IdEstadoFk,IdInstitucionFk")] Correos correos)
        {
            if (id != correos.IdCorreo)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(correos);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CorreosExists(correos.IdCorreo))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["IdEstadoFk"]      = new SelectList(_context.Estados, "IdEstado", "DescripcionEstado", correos.IdEstadoFk);
            ViewData["IdInstitucionFk"] = new SelectList(_context.Instituciones, "IdInstitucion", "DescripcionInstitucion", correos.IdInstitucionFk);
            return(View(correos));
        }
    public void enviarCorreo(string clienteSocio,string emailSocio)
    {
        string datos = ConvertToHtmlFile();
        string msg = "";
        string script = "";
        try
        {
            Correos Cr = new Correos();
            System.Net.Mail.MailMessage mnsj = new MailMessage();
            mnsj.Subject = "Comprobante de Pago de Cuenta FacilitoOnline";
            string email = emailSocio;
            mnsj.To.Add(new MailAddress(email));
            mnsj.From = new MailAddress("*****@*****.**", "Administrador");
            string ruta = HttpContext.Current.Request.MapPath("~/img/iconos/gracias.gif");
            mnsj.Attachments.Add(new Attachment(ruta));
            mnsj.Body = "AVISO DE VENCIMIENTO - FACILITOONLINE \n\n\n" + "Estimado(a) Socio(a) :" + clienteSocio + "\n" + datos;
            mnsj.IsBodyHtml = true;
            Cr.MandarCorreo(mnsj);
            msg = "La Factura mensual ha sido enviada a los socios correctamente" + " Listo!!";
        }
        catch (Exception ex)
        {
            msg = ex.Message;

        }
        script = @"<script type='text/javascript'> alert('{0}'); </script>";
        script = string.Format(script, msg);
        ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, false);
        btnEnviarATodos.Enabled = false;
    }
Ejemplo n.º 8
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                Tickets.Insert(DateTime.Now, Convert.ToInt32(ddlTopic.SelectedValue.ToString()), Convert.ToInt32(ddlPriority.SelectedValue.ToString()), txtName.Text, txtEmail.Text, txtPhone.Text, txtCompany.Text, txtSummary.Text, TxtDetails.InnerText, 0, 1);
                var LastID = Tickets.MaxID();
                td.Insert((int)LastID, DateTime.Now, 0, "Your problem is going to be resolved in the next few hours");
                System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Ticket created successfully. Your ticket ID has been sent to your Email');", true);
                Correos     Cr   = new Correos();
                MailMessage mnsj = new MailMessage();

                mnsj.Subject = "UJComputers Support Center";

                mnsj.To.Add(new MailAddress(txtEmail.Text));

                mnsj.From = new MailAddress("*****@*****.**", "UJComputers");

                mnsj.Body = " UJComputers\n Support Center  \n Thanks " + txtName.Text + " for using the Ticket Support Center. \n Your problem will be solved in the next 24 hours  \n Here is your ticket ID, you can use your ticket status in our Support Center Ticket Status page.\n\n Your Ticket ID is: " + LastID.ToString() + "\n Have a good day.";

                /* Enviar */
                Cr.MandarCorreo(mnsj);
                lblCorreo.Text = "Correo Enviado";
                txtName.Text   = "";
                txtName.Text   = "";
                txtName.Text   = "";
                txtName.Text   = "";
                txtName.Text   = "";
            }
            catch
            {
                System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Error Creating your ticket ');", true);
            }
        }
Ejemplo n.º 9
0
    private void enviarCorreo(DataMedico med)
    {
        try
        {
            // Instanciamos la clase Correo
            Correos correo = new Correos();
            // Iniciallizamos el mensaje del correo electrónico
            MailMessage mnsj = new MailMessage();
            // Establecemos el Asunto
            mnsj.Subject = "¡Hola! Gracias por suscribirse. Revisaremos su solictud";
            // Aqui el Correo de destino
            string email = med.Email_med;
            mnsj.To.Add(new MailAddress(email));
            // Aqui el Correo de origen
            mnsj.From = new MailAddress("*****@*****.**", "CuidateYa");
            // Aquí si desea adjuntar algún archivo

            /*string ruta = HttpContext.Current.Request.MapPath("~/App/Images/check.png");
             * mnsj.Attachments.Add(new Attachment(ruta));*/
            // Aqui el contenido del mensaje
            mnsj.Body       = plantillaMedico(med);
            mnsj.IsBodyHtml = true;
            // Enviamos el correo
            correo.MandarCorreo(mnsj);
            lblMensaje.Text = "El correo se ha enviado correctamente";
        }
        catch (Exception ex)
        {
            lblMensaje.Text = "Ocurrio un error al intentar enviar el correo: " + ex.Message;
        }
    }
Ejemplo n.º 10
0
 private void EnviarLog()
 {
     try
     {
         string ruta = Application.StartupPath + "\\log.txt";
         if (File.Exists(ruta))
         {
             DateTime fechaArchivo = File.GetCreationTime(ruta);
             if (fechaArchivo.Date == DateTime.Now.Date.AddDays(-7))
             {
                 if (ConfiguracionXML.ExisteConfiguracion("correo"))
                 {
                     Correos c = new Correos();
                     c.Adjuntos       = new string[] { ruta };
                     c.Asunto         = "Log de errores HS FIT.";
                     c.CorreosDestino = "*****@*****.**";
                     c.EnviarCorreo();
                     System.Threading.Thread.Sleep(500);
                     File.Delete(ruta);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         FuncionesGenerales.MensajeError("Ha ocurrido un error genérico.", ex);
     }
 }
Ejemplo n.º 11
0
 public frmLoguin()
 {
     InitializeComponent();
     ConexionBD = new CConection();
     EnviarCorreo = new Correos();
     string_ArchivoConfiguracion = System.Environment.CurrentDirectory + @"\confiRed.cfg";
     login = 0;
 }
Ejemplo n.º 12
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            Correos correos = await db.Correos.FindAsync(id);

            db.Correos.Remove(correos);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index", "Paqueterias"));
        }
Ejemplo n.º 13
0
        protected void btnCorreo_Click(object sender, EventArgs e)
        {
            ac.conectar();
            string correo       = this.txtCorreo.Text;
            Random rm           = new Random();
            int    numConfirm   = rm.Next(100000, 999999);
            bool   existeCorreo = CorreoExistente();

            if (existeCorreo)
            {
                try
                {
                    Correos     cr   = new Correos();
                    MailMessage mnsj = new MailMessage();

                    mnsj.Subject = "Reestablecer contrasena";

                    mnsj.To.Add(new MailAddress(this.txtCorreo.Text));

                    mnsj.From = new MailAddress("*****@*****.**", "Fede Buroni");

                    /* Si deseamos Adjuntar algún archivo
                     * mnsj.Attachments.Add(new Attachment("C:\\archivo.pdf"));*/

                    mnsj.Body = "  Su numero de confirmacion es:" + numConfirm;

                    /* Enviar */
                    cr.MandarCorreo(mnsj);
                    string update = "update Usuarios set codpass='******' where email='" + correo + "'";

                    SqlCommand comandoUpdate = new SqlCommand(update, ac.conexion);
                    comandoUpdate.ExecuteNonQuery();
                    comandoUpdate.Dispose();
                    lblCorreoMandado.Visible             = true;
                    this.lblCorreoMandado.Text           = "Revise su casilla de correo electronico";
                    this.txtCorreo.ReadOnly              = true;
                    this.Panel1.Visible                  = true;
                    this.Panel1.Enabled                  = true;
                    this.RequiredFieldValidator1.Enabled = true;
                    this.RequiredFieldValidator2.Enabled = true;
                    this.RequiredFieldValidator3.Enabled = true;
                    this.btnEnviar.Visible               = true;
                    this.lblErrorCorreo.Visible          = false;
                }
                catch (Exception ex)
                {
                    lblErrorCorreo.Text = "El correo electronico no es correcto" + ex.Message;
                }
            }
            else
            {
                lblErrorCorreo.Text      = "El correo ingresado no existe";
                lblCorreoMandado.Visible = false;
            }

            ac.cerrarConexion();
        }
 public static void EmailPassword(string email, string password, string usuario)
 {
     try
     {
         var gestor = new Correos().EmailPassword(email, password, usuario);
     }
     catch (Exception ex)
     {
         AppLog.Write("Error Enviando Email", AppLog.LogMessageType.Error, ex, "BansatLog");
     }
 }
Ejemplo n.º 15
0
        public async Task <ActionResult> Edit([Bind(Include = "Id,PaqueteriasId,correo")] Correos correos)
        {
            if (ModelState.IsValid)
            {
                db.Entry(correos).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index", "Paqueterias"));
            }
            ViewBag.PaqueteriasId = new SelectList(db.Paqueterias, "Id", "Nombre", correos.PaqueteriasId);
            return(View(correos));
        }
    public static void EmailPassword(string email, string password, string usuario)
    {
        try
        {
            var gestor = new Correos().EmailPassword(email, password, usuario);

        }
        catch (Exception ex)
        {
            AppLog.Write("Error Enviando Email", AppLog.LogMessageType.Error, ex, "BansatLog");

        }
    }
        public async Task <IActionResult> Create([Bind("IdCorreo,DescripcionCorreo,IdEstadoFk,IdInstitucionFk")] Correos correos)
        {
            if (ModelState.IsValid)
            {
                _context.Add(correos);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["IdEstadoFk"]      = new SelectList(_context.Estados, "IdEstado", "DescripcionEstado", correos.IdEstadoFk);
            ViewData["IdInstitucionFk"] = new SelectList(_context.Instituciones, "IdInstitucion", "DescripcionInstitucion", correos.IdInstitucionFk);
            return(View(correos));
        }
 public IHttpActionResult EnviarFactura(Correos cor)
 {
     try
     {
         CorreoBLL.SendEmail(cor);
         return(Content(HttpStatusCode.Created, "Factura enviada"));
     }
     catch (Exception ex)
     {
         //MessageBox.Show("error al enviar");
         return(BadRequest(ex.Message));
     }
 }
 public IHttpActionResult Post(Correos cor)
 {
     try
     {
         CorreoBLL.GetEmail(cor);
         return(Content(HttpStatusCode.Created, "Correo enviado"));
     }
     catch (Exception ex)
     {
         //MessageBox.Show("error al enviar");
         return(BadRequest(ex.Message));
     }
 }
Ejemplo n.º 20
0
        // GET: Correos/Details/5
        public async Task <ActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Correos correos = await db.Correos.FindAsync(id);

            if (correos == null)
            {
                return(HttpNotFound());
            }
            return(View(correos));
        }
Ejemplo n.º 21
0
        // GET: Correos/Edit/5
        public async Task <ActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Correos correos = await db.Correos.FindAsync(id);

            if (correos == null)
            {
                return(HttpNotFound());
            }
            ViewBag.PaqueteriasId = new SelectList(db.Paqueterias, "Id", "Nombre", correos.PaqueteriasId);
            return(View(correos));
        }
Ejemplo n.º 22
0
        private void Inicializar()
        {
            try
            {
                CN_Correos cn_correos = new CN_Correos();
                Correos    correo     = new Correos();
                correo.Id_Emp = sesion.Id_Emp;
                correo.Id_Cd  = sesion.Id_Cd_Ver;
                cn_correos.Consultar(ref correo, sesion.Emp_Cnx);

                TxtMailSvtaAlm.Text = correo.Cor_CorreosSvtaAlm;
                TxtMailAlmCob.Text  = correo.Cor_CorreosAlmCob;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 23
0
        public static void GetEmail(Correos cor)
        {
            System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage();
            mmsg.To.Add("*****@*****.**");
            mmsg.Subject         = cor.Asunto;
            mmsg.SubjectEncoding = System.Text.Encoding.UTF8;
            mmsg.Bcc.Add(cor.Correo);
            mmsg.Body         = cor.Mensaje;
            mmsg.BodyEncoding = System.Text.Encoding.UTF8;
            mmsg.IsBodyHtml   = true;
            mmsg.From         = new System.Net.Mail.MailAddress(cor.Correo);

            System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient();
            cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "a0959743877");
            cliente.Port        = 587;
            cliente.EnableSsl   = true;
            cliente.Host        = "smtp.gmail.com";
            cliente.Send(mmsg);
        }
Ejemplo n.º 24
0
        public async Task <IHttpActionResult> Create(Correos model)
        {
            try
            {
                var result = new AjaxResult();

                if (ModelState.IsValid)
                {
                    var correo = await db.Correos.Where(c => c.Mail.Contains(model.Mail))
                                 .FirstOrDefaultAsync();

                    if (correo == null)
                    {
                        db.Correos.Add(model);
                        await db.SaveChangesAsync();

                        AddLog("", model.Id, model);
                    }
                    else
                    {
                        return(Ok(result.False("Warning, This e-Mail already exists")));
                        //return InternalServerError(new Exception("Warning, This Budget  already exists"));
                    }

                    return(Ok(result.True("Record Saved")));
                }
                else
                {
                    //return InternalServerError(new Exception("Error, All field are required"));
                    string s = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
                    return(Ok(result.False(s)));
                }
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Ejemplo n.º 25
0
        protected void rtb1_ButtonClick(object sender, Telerik.Web.UI.RadToolBarEventArgs e)
        {
            CN_Correos cn_procierremes = new CN_Correos();
            Correos    correo          = new Correos();

            correo.Id_Emp             = sesion.Id_Emp;
            correo.Id_Cd              = sesion.Id_Cd_Ver;
            correo.Cor_CorreosAlmCob  = TxtMailAlmCob.Text;
            correo.Cor_CorreosSvtaAlm = TxtMailSvtaAlm.Text;

            int verificador = 0;

            cn_procierremes.Guardar(correo, sesion.Emp_Cnx, ref verificador);

            if (verificador == 1)
            {
                Alerta("Los datos se guardaron correctamente");
            }
            else
            {
                Alerta("Error al intentar guardar");
            }
        }
Ejemplo n.º 26
0
 partial void InsertCorreos(Correos instance);
    public static object CrearUsuario(string Nombres, string Apellidos, int TIPO_IDENTIFICACION, string NUMERO_IDENTIFICACION,
        string Direccion, string telefono,
       string userName, string Email, string passwordQuestion, string SecurityAnswer)
    {
        string PERFILP = "PACIENTE";
        string Retorno = "";
        string status = "";
        MembershipUser a = Membership.GetUser(userName);

        string porEmail = string.Empty;
        porEmail = Membership.GetUserNameByEmail(Email);
        if (a == null && string.IsNullOrEmpty(porEmail))
        {
            #region ("Creacion")
            MembershipCreateStatus createStatus;
            MembershipUser newUser =
                       Membership.CreateUser(userName, NUMERO_IDENTIFICACION,
                                             Email, passwordQuestion,
                                             SecurityAnswer, true,
                                             out createStatus);

            switch (createStatus)
            {
                case MembershipCreateStatus.Success:
                    Roles.AddUserToRole(userName, PERFILP);

                    Paciente nuevoPaciente = new Paciente();
                    nuevoPaciente.nombres_paciente = Nombres;
                    nuevoPaciente.apellidos_paciente = Apellidos;
                    nuevoPaciente.ident_paciente = NUMERO_IDENTIFICACION;
                    nuevoPaciente.tipo_id = TIPO_IDENTIFICACION;
                    nuevoPaciente.genero_paciente = 2;

                    nuevoPaciente.direccion_paciente = Direccion;
                    nuevoPaciente.telefono_paciente = telefono;
                    nuevoPaciente.movil_paciente = telefono;
                    nuevoPaciente.mail_paciente = Email;
                    nuevoPaciente.userId = newUser.ProviderUserKey.ToString();
                    nuevoPaciente.fecha_nacimiento = DateTime.Now;

                    PacienteDao pd = new PacienteDao();
                    var nuevo = pd.registrarPacienteNuevo(nuevoPaciente);

                    var enviar = new Correos().EnviarEmailCreacionDeUsuario(Email);

                    status = "OK";
                    Retorno = "La cuenta del usuario, ha sido creada con exito";

                    break;

                case MembershipCreateStatus.DuplicateUserName:
                    status = "Existe";
                    Retorno = "Ya existe un usuario con ese nombre de usuario";
                    //CreateAccountResults.Text = "Ya existe un usuario con ese nombre de usuario";//"There already exists a user with this username.";
                    break;

                case MembershipCreateStatus.DuplicateEmail:
                    status = "Duplicado";
                    Retorno = "Ya existe un usuario con este email.";// "There already exists a user with this email address.";
                    break;

                case MembershipCreateStatus.InvalidEmail:
                    status = "email";
                    Retorno = "La dirección de correo electrónico que nos ha facilitado en inválida.";//"There email address you provided in invalid.";
                    break;

                case MembershipCreateStatus.InvalidPassword:
                    status = "password";
                    Retorno = "La contraseña que ha proporcionado no es válido. Debe ser de siete caracteres y tener al menos un carácter no alfanumérico.";//"The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";
                    break;

                default:
                    status = "Error";
                    Retorno = "Hubo un error desconocido, la cuenta de usuario no fue creado.";//"There was an unknown error; the user account was NOT created.";
                    break;
            }
            #endregion
        }
        else
        {
            if (a != null)
            {
                status = "Existe";
                Retorno = "El nombre de usuario ya existe.";
            }
            //        CreateAccountResults.Text = "El usuario ya existe";

            if (!string.IsNullOrEmpty(porEmail))
            {
                status = "EmailCambiar";
                Retorno = "Ingrese por favor una dirección de correo electrónico diferente.";
            }
        }
        return new
        {
            status = status,
            mensaje = Retorno
        };
    }
    protected void btnRegistrar_Click(object sender, EventArgs e)
    {
        string datos = ConvertToHtmlFile();

        DataCliente cli = new DataCliente();

        string[] correos = { "@hotmail.com", "@live.com", "@gmail.com" };
        usuario = txtEmail.Text;
        clave = txtEmail.Text;
        foreach (string correo in correos)
        {
            usuario = usuario.Replace(correo, "@facilito.com");
            clave = clave.Replace(correo, "");
        }

        cli.Membresia = usuario;
        cli.Clave = clave;

        cli.Contacto = txtContacto.Text;
        cli.Email = txtEmail.Text;
        cli.Cargo = int.Parse(cboCargo.SelectedValue);
        cli.RazonSocial = txtRazonSocial.Text;
        cli.Calle = txtCalle.Text;
        cli.NumeroExterior = txtNumeroExterior.Text;
        cli.NumeroInterior = txtNumeroInterior.Text;
        cli.Municipio = txtMunicipio.Text;
        cli.CodigoPostal = txtCodigoPostal.Text;
        cli.Ciudad = txtCiudad.Text;
        cli.Pais = cboPais.SelectedValue;
        cli.Estado = int.Parse(cboEstado.SelectedValue);
        cli.SitioWeb = txtSitioWeb.Text;
        cli.ActividadPreponderante = txtActividadPreponderante.Text;
        cli.ListadoProductos = txtListarProductos.Text;
        cli.TipoCliente = int.Parse(cboTipoCliente.SelectedValue);

        string msg1 = c.registrarCliente(cli);

        // Enviar correo
        try
        {
            // Instanciar Correos
            Correos Cr = new Correos();
            // Iniciallizar el msg de correo electrónico
            MailMessage mnsj = new MailMessage();
            // Establecemos el Asunto
            mnsj.Subject = "Confirmación de Cuenta FacilitoOnline";
            // Aqui el Correo de destino
            string email = txtEmail.Text;
            mnsj.To.Add(new MailAddress(email));
            // Aqui el Correo de origen
            mnsj.From = new MailAddress("*****@*****.**", "Administrador");
            // Adjuntar algún archivo
            string ruta = HttpContext.Current.Request.MapPath("~/img/iconos/gracias.gif");
            mnsj.Attachments.Add(new Attachment(ruta));
            // El contenido del mensaje
            mnsj.Body = datos;
            mnsj.IsBodyHtml = true;
            // Enviar
            Cr.MandarCorreo(mnsj);
            Enviado = true;
            // Mostrar mensaje y retornar
            string script = @"<script type='text/javascript'>
                                    alert('El Mail se ha Enviado a su correo electrónico Correctamente. Listo!!');
                                    window.location = 'Restaurantes.aspx';
                              </script>";
            ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, false) ;
        }
        catch (Exception ex)
        {
            msg1 = ex.Message;
            string script = @"<script type='text/javascript'> alert('{0}'); </script>";
            script = string.Format(script, msg1);
            ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, false);
        }

        lblMensaje.Text = msg1;
        btnRegistrar.Enabled = false;
    }
Ejemplo n.º 29
0
        private void BtnEnvioMasora_Click(object sender, EventArgs e)
        {
            DialogResult Opcion = MessageBox.Show("Si desea imprimir por pantalla, seleccione la opcion SI" + Environment.NewLine + "Si desea enviar email al operador, seleccione la opcion NO" + Environment.NewLine + "Seleccione Cancelar para no hacer nada", "Confirmacion", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3);

            if (Opcion == DialogResult.Yes)
            {
                string ArchivoPdf = "GrupoMasora.pdf";
                Frm_LiquidacionConsolidadaGrupoMasora Forma = new Frm_LiquidacionConsolidadaGrupoMasora();
                Forma.Logo1      = Convertir.ImagenEnByte(this.PtbLogo1.Image);
                Forma.Logo2      = Convertir.ImagenEnByte(this.PtbLogo2.Image);
                Forma.Periodo    = Convert.ToInt32(this.CmbPeriodos.SelectedValue);
                Forma.Mina       = Convert.ToString(this.dataGridView1.CurrentRow.Cells[1].Value);
                Forma.NombreMina = ArchivoPdf;
                Forma.Show();
            }

            if (Opcion == DialogResult.No)
            {
                #region Trallendo los parametros de envio mail
                string  Smtp       = "";
                string  Credencial = "";
                string  Password   = "";
                int     Puerto     = 0;
                bool    SSL        = true;
                DataSet DS         = DatosEntidad.Dataset("ConsultaMails", "", 0, 0.00);
                if (DS.Tables[0].Rows.Count > 0)
                {
                    Smtp       = Convert.ToString(DS.Tables[0].Rows[0]["Smtp"]).Trim();
                    Credencial = Convert.ToString(DS.Tables[0].Rows[0]["Credencial"]).Trim();
                    Password   = Convert.ToString(DS.Tables[0].Rows[0]["Password"]).Trim();
                    Puerto     = Convert.ToInt32(DS.Tables[0].Rows[0]["Puerto"]);
                    SSL        = Convert.ToBoolean(DS.Tables[0].Rows[0]["SSL"]);
                }
                #endregion

                string ArchivoPdf = "GrupoMasora.pdf";
                Frm_LiquidacionConsolidadaGrupoMasora Forma = new Frm_LiquidacionConsolidadaGrupoMasora();
                Forma.Logo1      = Convertir.ImagenEnByte(this.PtbLogo1.Image);
                Forma.Logo2      = Convertir.ImagenEnByte(this.PtbLogo2.Image);
                Forma.Periodo    = Convert.ToInt32(this.CmbPeriodos.SelectedValue);
                Forma.Mina       = Convert.ToString(this.dataGridView1.CurrentRow.Cells[1].Value);
                Forma.NombreMina = ArchivoPdf;
                Forma.Show();
                string      RutaFile = Directory.GetCurrentDirectory() + "\\" + ArchivoPdf.Trim();
                MailMessage mnsj     = new MailMessage();
                mnsj.Subject = "Relación de Liquidación: Grupo Masora " + this.CmbPeriodos.Text.Trim();

                #region Llenado a quien se le va enviar el email
                DataSet DsMailPara = DatosEntidad.Dataset("MailOperadores", "039", 0, 0.00);
                if (DsMailPara.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow RegistroTo in DsMailPara.Tables[0].Rows)
                    {
                        mnsj.To.Add(RegistroTo[0].ToString());
                    }
                }
                #endregion

                #region Llenado a quien se le va Copiar el email
                DataSet DsMailCopia = DatosEntidad.Dataset("CopiaLiquidacion", "", 0, 0.00);
                if (DsMailCopia.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow RegistroCC in DsMailCopia.Tables[0].Rows)
                    {
                        mnsj.CC.Add(RegistroCC[0].ToString());
                    }
                }
                #endregion

                mnsj.From = new MailAddress(Credencial);
                mnsj.Attachments.Add(new Attachment(RutaFile));
                mnsj.Body = this.RtbBodyMail.Text.Trim() + Environment.NewLine + Environment.NewLine + "Enviado desde mi aplicacion DBMETAL.";
                Correos.Enviar(Smtp, Puerto, Credencial, Password, SSL, mnsj);

                MessageBox.Show("Mail Enviado con exito.");
            }
        }
Ejemplo n.º 30
0
 public void EnviarCorreo()
 {
     this.cr = new Correos();
     this.cr.Enviar_Correo(Usuarios.CorreoCompra, "Factura de Tienda Cronos", "Numero de factura '" + factura + "'Fecha de compra: '" + DateTime.Now + "'descripcion:Consola, Precio'" + precio + "' '" + "" + "'" +
                           "cantidad:  '" + this.cp.Cantidad + "',Impuesto:13% ya Agregado Descueno:" + this.cp.Descuento + "' Usuario que efectuo la compra:'" + Usuarios.Usuario + "' Total a Pagar: '" + this.cp.Total_pagar + "'");
 }
Ejemplo n.º 31
0
    public static object CrearUsuario(string NombresI, string NombresII, string ApellidosI, string ApellidosII, int TIPO_IDENTIFICACION, string NUMERO_IDENTIFICACION,

        int MunExpedicion, string fechaExpedicion, string Genero, string fechaNacimiento, int MunNacimiento, int Nacionalidad, int munResidencia, string DireccionResidencia,

        string telefono,
       string Email, string passwordQuestion, string SecurityAnswer)
    {
        string PERFILP = "USUARIOS";
        string Retorno = "";
        string status = "";
        Centralizador.Service1Client serviciocentralizador = new Centralizador.Service1Client();
        Centralizador.Entity.Usuario nuevoUsuario = new Centralizador.Entity.Usuario();

        nuevoUsuario.primerNombre = NombresI;
        nuevoUsuario.segundoNombre = NombresII;
        nuevoUsuario.segundoApellido = ApellidosII;
        nuevoUsuario.primerApellido = ApellidosI;
        nuevoUsuario.idTipoIdentificacion = TIPO_IDENTIFICACION;
        nuevoUsuario.numeroIdentificacion = NUMERO_IDENTIFICACION;
        nuevoUsuario.idMunicipioExpedicionDocumento = MunExpedicion;

        nuevoUsuario.fechaExpedicion = Convert.ToDateTime(fechaExpedicion,CultureInfo.InvariantCulture);
        nuevoUsuario.genero = Genero;
        nuevoUsuario.fechaNacimiento = Convert.ToDateTime(fechaNacimiento,CultureInfo.InvariantCulture);
        nuevoUsuario.idMunicipioNacimiento = MunNacimiento;

        nuevoUsuario.idPaisNacionalidad = Nacionalidad;
        nuevoUsuario.idMunicipioResidencia = munResidencia;
        nuevoUsuario.idMunicipioNotificacionCorrespondencia = munResidencia;
        nuevoUsuario.direccionNotificacionCorrespondencia = DireccionResidencia;
        nuevoUsuario.direccionResidencia = DireccionResidencia;
        nuevoUsuario.idMunicipioLaboral = munResidencia;
        nuevoUsuario.estadoCivil = "S";
        nuevoUsuario.correoElectronico = Email;
        nuevoUsuario.telefono = telefono;
        nuevoUsuario.idOperador = 1;
        var resultado = serviciocentralizador.ValidarExistenciaUsuario(nuevoUsuario);

        if (!resultado)
        {

            #region creacion de usuario en en sistema operador
            //

            MembershipUser a = Membership.GetUser(NUMERO_IDENTIFICACION);

            string porEmail = string.Empty;
            porEmail = Membership.GetUserNameByEmail(Email);
            if (a == null && string.IsNullOrEmpty(porEmail))
            {
                #region ("Creacion")
                MembershipCreateStatus createStatus;
                MembershipUser newUser =
                           Membership.CreateUser(NUMERO_IDENTIFICACION, NUMERO_IDENTIFICACION,
                                                 Email, passwordQuestion,
                                                 SecurityAnswer, true,
                                                 out createStatus);

                switch (createStatus)
                {
                    case MembershipCreateStatus.Success:
                        Roles.AddUserToRole(NUMERO_IDENTIFICACION, PERFILP);

                        Paciente nuevoPaciente = new Paciente();
                        nuevoPaciente.nombres_paciente = NombresI;
                        nuevoPaciente.apellidos_paciente = ApellidosI;
                        nuevoPaciente.ident_paciente = NUMERO_IDENTIFICACION;
                        nuevoPaciente.tipo_id = TIPO_IDENTIFICACION;
                        nuevoPaciente.genero_paciente = 2;

                        nuevoPaciente.direccion_paciente = DireccionResidencia;
                        nuevoPaciente.telefono_paciente = telefono;
                        nuevoPaciente.movil_paciente = telefono;
                        nuevoPaciente.mail_paciente = Email;
                        nuevoPaciente.userId = newUser.ProviderUserKey.ToString();
                        nuevoPaciente.fecha_nacimiento = DateTime.Now;

                       // PacienteDao pd = new PacienteDao();
                        //var nuevo = pd.registrarPacienteNuevo(nuevoPaciente);
                        var Usuarioregistrado = serviciocentralizador.RegistrarUsuario(nuevoUsuario);
                        DaoUsuario registroAPP = new DaoUsuario();
                        var usuaripoRegistrarApp =  registroAPP.RegistrarUsuario(nuevoPaciente.userId, Usuarioregistrado.UUID.ToString());

                        var enviar = new Correos().EnviarEmailCreacionDeUsuario(Email);

                        status = "OK";
                        Retorno = "La cuenta del usuario, ha sido creada con exito";

                        break;

                    case MembershipCreateStatus.DuplicateUserName:
                        status = "Existe";
                        Retorno = "Ya existe un usuario con ese nombre de usuario";
                        //CreateAccountResults.Text = "Ya existe un usuario con ese nombre de usuario";//"There already exists a user with this username.";
                        break;

                    case MembershipCreateStatus.DuplicateEmail:
                        status = "Duplicado";
                        Retorno = "Ya existe un usuario con este email.";// "There already exists a user with this email address.";
                        break;

                    case MembershipCreateStatus.InvalidEmail:
                        status = "email";
                        Retorno = "La dirección de correo electrónico que nos ha facilitado en inválida.";//"There email address you provided in invalid.";
                        break;

                    case MembershipCreateStatus.InvalidPassword:
                        status = "password";
                        Retorno = "La contraseña que ha proporcionado no es válido. Debe ser de siete caracteres y tener al menos un carácter no alfanumérico.";//"The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";
                        break;

                    default:
                        status = "Error";
                        Retorno = "Hubo un error desconocido, la cuenta de usuario no fue creado.";//"There was an unknown error; the user account was NOT created.";
                        break;
                }
                #endregion
            }
            else
            {
                if (a != null)
                {
                    status = "Existe";
                    Retorno = "El nombre de usuario ya existe.";
                }
                //        CreateAccountResults.Text = "El usuario ya existe";

                if (!string.IsNullOrEmpty(porEmail))
                {
                    status = "EmailCambiar";
                    Retorno = "Ingrese por favor una dirección de correo electrónico diferente.";
                }
            }
        #endregion

        }
        else
        {

            Retorno = "El usuario Se encuentra registrado en el centralizador";
            status = "RegistradoCentralizador";

        }
        return new
        {
            status = status,
            mensaje = Retorno
        };
    }
Ejemplo n.º 32
0
 partial void UpdateCorreos(Correos instance);
Ejemplo n.º 33
0
        private void BtnEnviarMail_Click(object sender, EventArgs e)
        {
            int Envio = 0;

            if (this.ChbOmitirDamasa.Checked == false)
            {
                DialogResult Opcion = MessageBox.Show("Tiene DesMarcada la opcion de Omitir los proyectos del Grupo Damasa," + Environment.NewLine + "desea enviar los email con esta condicion.", "Confirmacion", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                if (Opcion == DialogResult.No)
                {
                    Envio = 1;
                }
            }

            if (this.ChbOmitirMasora.Checked == false)
            {
                DialogResult Opcion = MessageBox.Show("Tiene DesMarcada la opcion de Omitir los proyectos del Grupo Masora," + Environment.NewLine + "desea enviar los email con esta condicion.", "Confirmacion", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                if (Opcion == DialogResult.No)
                {
                    Envio = 1;
                }
            }

            if (Envio == 0)
            {
                #region Trallendo los parametros de envio mail
                string  Smtp       = "";
                string  Credencial = "";
                string  Password   = "";
                int     Puerto     = 0;
                bool    SSL        = true;
                DataSet DS         = DatosEntidad.Dataset("ConsultaMails", "", 0, 0.00);
                if (DS.Tables[0].Rows.Count > 0)
                {
                    Smtp       = Convert.ToString(DS.Tables[0].Rows[0]["Smtp"]).Trim();
                    Credencial = Convert.ToString(DS.Tables[0].Rows[0]["Credencial"]).Trim();
                    Password   = Convert.ToString(DS.Tables[0].Rows[0]["Password"]).Trim();
                    Puerto     = Convert.ToInt32(DS.Tables[0].Rows[0]["Puerto"]);
                    SSL        = Convert.ToBoolean(DS.Tables[0].Rows[0]["SSL"]);
                }
                #endregion

                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    if (Convert.ToBoolean(row.Cells[0].Value) == true)
                    {
                        string ArchivoPdf           = Convert.ToString(row.Cells[2].Value).Trim() + ".pdf";
                        Frm_LiquidacionMinera Forma = new Frm_LiquidacionMinera();
                        Forma.Logo1      = Convertir.ImagenEnByte(this.PtbLogo1.Image);
                        Forma.Logo2      = Convertir.ImagenEnByte(this.PtbLogo2.Image);
                        Forma.Periodo    = Convert.ToInt32(this.CmbPeriodos.SelectedValue);
                        Forma.Mina       = Convert.ToString(row.Cells[1].Value);
                        Forma.NombreMina = ArchivoPdf;
                        Forma.Show();
                        string      RutaFile = Directory.GetCurrentDirectory() + "\\" + ArchivoPdf.Trim();
                        MailMessage mnsj     = new MailMessage();
                        mnsj.Subject = "Relación de Liquidación: " + Convert.ToString(row.Cells[2].Value) + this.CmbPeriodos.Text.Trim();

                        #region Llenado a quien se le va enviar el email
                        DataSet DsMailPara = DatosEntidad.Dataset("MailOperadores", Convert.ToString(row.Cells[1].Value).Trim(), 0, 0.00);
                        if (DsMailPara.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow RegistroTo in DsMailPara.Tables[0].Rows)
                            {
                                mnsj.To.Add(RegistroTo[0].ToString());
                            }
                        }
                        #endregion

                        #region Llenado a quien se le va Copiar el email
                        DataSet DsMailCopia = DatosEntidad.Dataset("CopiaLiquidacion", "", 0, 0.00);
                        if (DsMailCopia.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow RegistroCC in DsMailCopia.Tables[0].Rows)
                            {
                                mnsj.CC.Add(RegistroCC[0].ToString());
                            }
                        }
                        #endregion

                        mnsj.From = new MailAddress(Credencial);
                        mnsj.Attachments.Add(new Attachment(RutaFile));
                        mnsj.Body = this.RtbBodyMail.Text.Trim() + Environment.NewLine + Environment.NewLine + "Enviado desde mi aplicacion DBMETAL.";
                        Correos.Enviar(Smtp, Puerto, Credencial, Password, SSL, mnsj);
                    }
                }
                MessageBox.Show("Mail Enviado con exito.");
            }
        }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            //Conexiones a Base de datos
            var UsuarioConexion = new Conexion <Usuario>();
            var CorreosConexion = new Conexion <Correos>();

            bool Exit = false;

            do
            {
                //Menu Opciones
                Escribir("ElielMail");
                Escribir("Menu");
                Escribir("1.Crear Usuario");
                Escribir("2.Modificar Usuario");
                Escribir("3.Iniciar Sesion");
                Escribir("4.Salir del programa");

                //Captura Respuesta
                int Res = Respuesta(Console.ReadLine());
                //Condicion Respuesta igual a Crear Usuario
                if (Res == (int)Menu.CrearUsuario)
                {
                    //Capturar datos del administrador
                    Escribir("Inserte El email Admin");
                    string adminEmail = Console.ReadLine();
                    Escribir("Inserte el Pass del admin");
                    String AdminPass = Console.ReadLine();

                    //Validar crendeciales del administrador, y si es tipo administrador
                    Usuario Admin = UsuarioConexion.GetByCondition(user =>
                                                                   user.Correo.ToLower() == adminEmail.ToLower() &&
                                                                   user.Password == AdminPass &&
                                                                   user.TipoUsuario == (int)TipoUsuario.Administrador).FirstOrDefault();

                    //Si el usuario admin existe
                    if (Admin != null)
                    {
                        bool EsCorreoExistente, repetir = false;

                        Usuario User = new Usuario();
                        Escribir("Inserte Su Nombre");
                        User.Nombre = Console.ReadLine();

                        do
                        {
                            Escribir("Inserte Su Nueva Direccion de Correo ");
                            User.Correo = Console.ReadLine();
                            //Valida si el correo existe en la base de datos
                            EsCorreoExistente = ExisteCorreo(User.Correo);

                            if (EsCorreoExistente == true)
                            {
                                Escribir("Correo ya existe, intente con otro");
                                repetir = true;
                            }
                            else
                            {
                                repetir = false;
                            }
                        } while (repetir == true);

                        Escribir("Inserte su Password");
                        User.Password    = Console.ReadLine();
                        User.TipoUsuario = (int)TipoUsuario.Normal;

                        //Crear usuario en la base de datos
                        UsuarioConexion.Create(User);
                    }
                    //Si el usuario admin no existe
                    else
                    {
                        Escribir("Usuario Admin Invalido");
                    }
                }
                //Condicion Respuesta igual a Modificar Usuario
                else if (Res == (int)Menu.ModificarUsuario)
                {
                    //Capturar datos del administrador
                    Escribir("Inserte El email Admin");
                    string adminEmail = Console.ReadLine();
                    Escribir("Inserte el Pass del admin");
                    String AdminPass = Console.ReadLine();

                    //Validar crendeciales del administrador, y si es tipo administrador
                    Usuario Admin = UsuarioConexion.GetByCondition(user =>
                                                                   user.Correo.ToLower() == adminEmail.ToLower() &&
                                                                   user.Password == AdminPass &&
                                                                   user.TipoUsuario == (int)TipoUsuario.Administrador).FirstOrDefault();

                    //Si en usuario del administrador existe
                    if (Admin != null)
                    {
                        Escribir("Escriba el correo del usuario a modificar");
                        string email = Console.ReadLine();

                        //Capturar datos de un usuario, segun su correo
                        Usuario User = UsuarioConexion.GetByCondition(u =>
                                                                      u.Correo.ToLower() == email.ToLower()).FirstOrDefault();

                        //si los datos del usuario existen
                        if (User != null)
                        {
                            bool EsCorreoExistente, repetir = false;

                            Escribir("Inserte el nombre Nuevo");
                            User.Nombre = Console.ReadLine();

                            do
                            {
                                Escribir("Inserte el Nuevo correo  ");
                                User.Correo = Console.ReadLine();

                                //Validar si el correo existe en la base de datos
                                EsCorreoExistente = ExisteCorreo(User.Correo);

                                if (EsCorreoExistente == true)
                                {
                                    Escribir("Correo ya existe, intente con otro");
                                    repetir = true;
                                }
                                else
                                {
                                    repetir = false;
                                }
                            } while (repetir == true);

                            Escribir("Inserte el nuevo Password");
                            User.Password = Console.ReadLine();

                            //Actualizar usuario en la base de datos
                            UsuarioConexion.Update(User);
                        }
                        //Si el usuario no existe
                        else
                        {
                            Escribir("Usuario no existe");
                        }
                    }
                    else
                    //Si en usuario del administrador no existe
                    {
                        Escribir("Usuario Admin Invalido");
                    }
                }
                //Condicion Respuesta igual a Iniciar Sesion Usuario
                else if (Res == (int)Menu.IniciarSesion)
                {
                    //Capturar correo y clave
                    Escribir("Inserte correo");
                    string correo = Console.ReadLine();
                    Escribir("Inserte la clave");
                    string password = Console.ReadLine();

                    //Validar credenciales del usuario
                    Usuario User = UsuarioConexion.GetByCondition(user =>
                                                                  user.Correo.ToLower() == correo.ToLower() &&
                                                                  user.Password == password).FirstOrDefault();

                    //Si existe usuario con esas credenciales
                    if (User != null)
                    {
                        bool CerrarSesion = false;
                        do
                        {
                            //SubMenu despues de iniciar sesion
                            Console.Clear();
                            Escribir("Opciones");
                            Escribir("1.Enviar correo");
                            Escribir("2.Mostrar listado de correos");
                            Escribir("3.Cerrar sesion");

                            //Capturar respuesta
                            int res2 = Respuesta(Console.ReadLine());

                            //Si la respuesta due enviar correo
                            if (res2 == (int)SubMenu.EnviarCorreo)
                            {
                                //Crear un nuevo correo
                                Correos NewCorreo = new Correos();

                                //Isertar correo origen con usuario que inicio sesion
                                NewCorreo.FromCorreo = User.Correo;

                                //capturar el correo destino
                                Escribir("Inserte el correo destino");
                                string ToCorreo = Console.ReadLine();

                                //Validar si el correo destino existe en la base dedatos
                                bool EsCorreoExistente = ExisteCorreo(ToCorreo);

                                //si el correo existe
                                if (EsCorreoExistente == true)
                                {
                                    //Capturar datos del correo
                                    NewCorreo.ToCorreo = ToCorreo;

                                    Escribir("Inserte en asunto del mensaje");
                                    NewCorreo.Asunto = Console.ReadLine();

                                    Escribir("Inserte el mensaje del correo");
                                    NewCorreo.Mensaje = Console.ReadLine();

                                    NewCorreo.Status = "Enviado";

                                    //Crear correo en base de datos
                                    CorreosConexion.Create(NewCorreo);
                                }
                                //si el correo no existe
                                else
                                {
                                    Escribir("El correo destino no existe, intente con otro correo");
                                    Console.ReadKey();
                                }
                            }
                            //Si la respuesta fue Mostrar correos
                            else if (res2 == (int)SubMenu.MostrarCorreos)
                            {
                                bool salirDeCorreos = false;

                                do
                                {
                                    //Menu para mostrar correos
                                    Console.Clear();
                                    Escribir("Opciones");
                                    Escribir("1.Leer Correos enviados");
                                    Escribir("2.Leer Correos recibidos");
                                    Escribir("3.Regresar");

                                    //Capturar respuesta
                                    int res3 = Respuesta(Console.ReadLine());

                                    //Si respuesta es igual a leer correos enviados
                                    if (res3 == (int)MenuMostrarCorreos.LeerCorreosEnviados)
                                    {
                                        //Obtener de la base de datos, la lista de correos enviados
                                        List <Correos> ListaCorreosEnviados = CorreosConexion.GetByCondition(c =>
                                                                                                             c.FromCorreo.ToLower() == User.Correo.ToLower());

                                        //utilizar metodo para mostrar la lista de correos
                                        MostrarListaDeCorreos(ListaCorreosEnviados);
                                    }
                                    //Si la respuesta es igual a leer correos recibidos
                                    else if (res3 == (int)MenuMostrarCorreos.LeerCorreosRecibidos)
                                    {
                                        //Obtener de la base de datos, la lista de correos recibidos
                                        List <Correos> ListaCorreosRecibidos = CorreosConexion.GetByCondition(c =>
                                                                                                              c.ToCorreo.ToLower() == User.Correo.ToLower());

                                        //Marcar correos como recibidos, ya que se van a leer
                                        foreach (var Email in ListaCorreosRecibidos)
                                        {
                                            Email.Status = "Recibido";
                                        }

                                        //utilizar metodo para mostrar la lista de correos
                                        MostrarListaDeCorreos(ListaCorreosRecibidos);
                                    }
                                    //Regresar al menu de despues de iniciar sesion
                                    else if (res3 == (int)MenuMostrarCorreos.Regresar)
                                    {
                                        salirDeCorreos = true;
                                    }
                                    //No se selecciono una opcon correcta en el menu
                                    else
                                    {
                                        Escribir("Eligio una opcion incorrecta, favor eligir una opcion del menu");
                                        Console.ReadKey();
                                    }
                                } while (salirDeCorreos == false);
                            }
                            //Si la opcion fue cerrar sesion
                            else if (res2 == (int)SubMenu.CerrarSesion)
                            {
                                CerrarSesion = true;
                            }
                            //Si no se eligio una opcion valida
                            else
                            {
                                Escribir("Eligio una opcion incorrecta, favor eligir una opcion del menu");
                                Console.ReadKey();
                            }
                        } while (CerrarSesion == false);
                    }
                    //Si no existe usuario con esas credenciales
                    else
                    {
                        Escribir("Correo o clave invalida, intentar nuevamente");
                    }
                }
                //Condicion Respuesta Cerrar programa
                else if (Res == (int)Menu.Salir)
                {
                    Exit = true;
                    Escribir("Cerrando ElielMail");
                }
                //De lo contrario, no selecciono una opcion valida
                else
                {
                    Escribir("Eligio una opcion incorrecta, favor eligir una opcion del menu");
                }
                Console.ReadKey();
                Console.Clear();
            } while (Exit == false);
        }
Ejemplo n.º 35
0
    public static object CrearUsuario(string NombresI, string NombresII, string ApellidosI, string ApellidosII, int TIPO_IDENTIFICACION, string NUMERO_IDENTIFICACION,

        int MunExpedicion, DateTime fechaExpedicion, string Genero, DateTime fechaNacimiento, int MunNacimiento, int Nacionalidad, int munResidencia, string DireccionResidencia,

        string telefono,
       string Email, string passwordQuestion, string SecurityAnswer)
    {
        try
        {
            var IdentificadorOperador = "identificadorOperador".GetFromAppCfg();

            string PERFILP = "USUARIOS";
            string Retorno = "";
            string status = "";
            DateTime fechExpedicion = default(DateTime);
            DateTime fechNacimiento = default(DateTime);
            try
            {

                fechExpedicion = Convert.ToDateTime(fechaExpedicion, CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                AppLog.Write(" Error convirtiendo la fecha de expedicionInicial. ", AppLog.LogMessageType.Error, ex, "OperadorCarpeta");
                status = "error";
                Retorno = "Ingrese la fecha de expedición Valida";
                return new
                {
                    status = status,
                    mensaje = Retorno
                };

            }

            try
            {

                fechNacimiento = Convert.ToDateTime(fechaExpedicion, CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                AppLog.Write(" Error convirtiendo la fecha de Nacimiento. ", AppLog.LogMessageType.Error, ex, "OperadorCarpeta");

                status = "error";
                Retorno = "Ingrese la fecha de nacimiento Valida";
                return new
                {
                    status = status,
                    mensaje = Retorno
                };

            }

            #region ("Registro")

            Centralizador.Service1Client serviciocentralizador = new Centralizador.Service1Client();
            Centralizador.Usuario nuevoUsuario = new Centralizador.Usuario();

            nuevoUsuario.primerNombre = NombresI;
            nuevoUsuario.segundoNombre = NombresII;
            nuevoUsuario.segundoApellido = ApellidosII;
            nuevoUsuario.primerApellido = ApellidosI;
            nuevoUsuario.idTipoIdentificacion = TIPO_IDENTIFICACION;
            nuevoUsuario.numeroIdentificacion = NUMERO_IDENTIFICACION;
            nuevoUsuario.idMunicipioExpedicionDocumento = MunExpedicion;

            nuevoUsuario.fechaExpedicion = fechExpedicion;
            nuevoUsuario.genero = Genero;
            nuevoUsuario.fechaNacimiento = fechNacimiento;
            nuevoUsuario.idMunicipioNacimiento = MunNacimiento;

            nuevoUsuario.idPaisNacionalidad = Nacionalidad;
            nuevoUsuario.idMunicipioResidencia = munResidencia;
            nuevoUsuario.idMunicipioNotificacionCorrespondencia = munResidencia;
            nuevoUsuario.direccionNotificacionCorrespondencia = DireccionResidencia;
            nuevoUsuario.direccionResidencia = DireccionResidencia;
            nuevoUsuario.idMunicipioLaboral = munResidencia;
            nuevoUsuario.estadoCivil = "S";
            nuevoUsuario.correoElectronico = Email;
            nuevoUsuario.telefono = telefono;
            nuevoUsuario.idOperador = 0;
            AppLog.Write(" inicio consulta si existe el usuario. ", AppLog.LogMessageType.Info, null, "OperadorCarpeta");

            var resultado = serviciocentralizador.ValidarPorIdentificacionYTipo(nuevoUsuario.numeroIdentificacion, nuevoUsuario.idTipoIdentificacion, IdentificadorOperador);

            AppLog.Write(" fin consulta si existe el usuario Resutlado:" + resultado.ToString(), AppLog.LogMessageType.Info, null, "OperadorCarpeta");
            var prefijo = PrefijoEnumTIPO_IDENTIFICACION.EnumToTIPO_IDENTIFICACION(TIPO_IDENTIFICACION);
            string UserName = prefijo + NUMERO_IDENTIFICACION;
            if (!resultado.Existe && !resultado.MismoOperador)
            {

                #region creacion de usuario en en sistema operador
                //

                MembershipUser a = Membership.GetUser(UserName);

                string porEmail = string.Empty;
                porEmail = Membership.GetUserNameByEmail(Email);
                if (a == null && string.IsNullOrEmpty(porEmail))
                {
                    #region ("Creacion")
                    MembershipCreateStatus createStatus;
                    MembershipUser newUser =
                               Membership.CreateUser(prefijo + NUMERO_IDENTIFICACION, NUMERO_IDENTIFICACION,
                                                     Email, passwordQuestion,
                                                     SecurityAnswer, true,
                                                     out createStatus);

                    switch (createStatus)
                    {
                        case MembershipCreateStatus.Success:
                            Roles.AddUserToRole(UserName, PERFILP);

                            var Usuarioregistrado = serviciocentralizador.RegistrarUsuario(nuevoUsuario, IdentificadorOperador);
                            DaoUsuario registroAPP = new DaoUsuario();
                            var datosTIpo = new TipoidentificacionDao().obtenerTipos();
                            var tipoID = datosTIpo.Where(x => x.id_tipoId == TIPO_IDENTIFICACION).Select(x => x.abreviado_tipoId).First();
                            string CarpetaInicial = tipoID + NUMERO_IDENTIFICACION;
                            AppLog.Write(" Inicio Creacion Usuario", AppLog.LogMessageType.Info, null, "OperadorCarpeta");

                            GestorRegistro gestorRegistro = new GestorRegistro();

                            GestionUsuario gestor = new GestionUsuario();

                            try
                            {
                                var registro = gestorRegistro.RegistrarUsuario(newUser.ProviderUserKey.ToString(),
                                 Usuarioregistrado.UUID.ToString(),
                                 "OPERADOR_REPOSITORY_USER",
                                 CarpetaInicial, Usuarioregistrado.primerNombre + " " + Usuarioregistrado.segundoNombre,
                                 Usuarioregistrado.primerApellido + " " + Usuarioregistrado.segundoApellido,
                                 Usuarioregistrado.idTipoIdentificacion, Usuarioregistrado.numeroIdentificacion);

                            }
                            catch (Exception ex)
                            {
                                #region se eliminan los usuarios
                                gestor.DeleteUser(UserName);
                                serviciocentralizador.EliminarUsuario(Usuarioregistrado.UUID, IdentificadorOperador);
                                #endregion
                                AppLog.Write(" Error Creacion Usuario operador", AppLog.LogMessageType.Info, ex, "OperadorCarpeta");
                                status = "Error";
                                Retorno = "Hubo un error desconocido, la cuenta de usuario no fue creado.";
                                return new
                                {
                                    status = status,
                                    mensaje = Retorno
                                };

                            }
                            AppLog.Write(" Fin Creacion Usuario operador", AppLog.LogMessageType.Info, null, "OperadorCarpeta");

                            //var usuaripoRegistrarApp = registroAPP.RegistrarUsuario(
                            //    newUser.ProviderUserKey.ToString(),
                            //    Usuarioregistrado.UUID.ToString(),
                            //    "OPERADOR_REPOSITORY_USER",
                            //    CarpetaInicial, Usuarioregistrado.primerNombre + " " + Usuarioregistrado.segundoNombre,
                            //    Usuarioregistrado.primerApellido + " " + Usuarioregistrado.segundoApellido,
                            //    Usuarioregistrado.idTipoIdentificacion, Usuarioregistrado.numeroIdentificacion );
                            //AppLog.Write(" Fin Creacion Usuario", AppLog.LogMessageType.Info, null, "OperadorCarpeta");

                            #region crear carpeta en el servidor
                            //var fileControl = new FileControl(Int32.Parse("MaxFileSize".GetFromAppCfg()));

                            //fileControl._CreateFolderInFTP(CarpetaInicial, "OPERADOR_REPOSITORY_USER");
                            //fileControl._CreateFolderInFTP(CarpetaInicial+@"/ADJUNTOS", "OPERADOR_REPOSITORY_USER");

                            #endregion

                            #region Enviar Correo de confirmacion de creacion de cuenta.
                            var enviar = new Correos().EnviarEmailCreacionDeUsuario(Email);
                            #endregion

                            status = "OK";
                            Retorno = "La cuenta del usuario, ha sido creada con exito";

                            break;

                        case MembershipCreateStatus.DuplicateUserName:
                            status = "Existe";
                            Retorno = "Ya existe un usuario con ese nombre de usuario";
                            //CreateAccountResults.Text = "Ya existe un usuario con ese nombre de usuario";//"There already exists a user with this username.";
                            break;

                        case MembershipCreateStatus.DuplicateEmail:
                            status = "Duplicado";
                            Retorno = "Ya existe un usuario con este email.";// "There already exists a user with this email address.";
                            break;

                        case MembershipCreateStatus.InvalidEmail:
                            status = "email";
                            Retorno = "La dirección de correo electrónico que nos ha facilitado en inválida.";//"There email address you provided in invalid.";
                            break;

                        case MembershipCreateStatus.InvalidPassword:
                            status = "password";
                            Retorno = "La contraseña que ha proporcionado no es válido. Debe ser de siete caracteres y tener al menos un carácter no alfanumérico.";//"The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";
                            break;

                        default:
                            status = "Error";
                            Retorno = "Hubo un error desconocido, la cuenta de usuario no fue creado.";//"There was an unknown error; the user account was NOT created.";
                            break;
                    }
                    #endregion
                }
                else
                {
                    if (a != null)
                    {
                        status = "Existe";
                        Retorno = "El nombre de usuario ya existe.";
                    }
                    //        CreateAccountResults.Text = "El usuario ya existe";

                    if (!string.IsNullOrEmpty(porEmail))
                    {
                        status = "EmailCambiar";
                        Retorno = "Ingrese por favor una dirección de correo electrónico diferente.";
                    }
                }
                #endregion

            }
            else
            {

                Retorno = "El usuario Se encuentra registrado en el centralizador";
                status = "RegistradoCentralizador";

            }
            #endregion
            return new
            {
                status = status,
                mensaje = Retorno
            };
        }
        catch (Exception ex)
        {

            AppLog.Write(" Error Creacion de usuario en el sistema ", AppLog.LogMessageType.Error, ex, "OperadorCarpeta");
            return new
            {
                status = "error",
                mensaje = "Ha ocurrido un error inesperado intentelo nuevamente o mas tarde"
            };

        }
    }
Ejemplo n.º 36
0
        private void FrmRptProyeccionMineral_Load(object sender, EventArgs e)
        {
            // TODO: esta línea de código carga datos en la tabla 'DBMETALDataSet.Sp_Rpt_ProyeccionMineral' Puede moverla o quitarla según sea necesario.
            this.DBMETALDataSet.EnforceConstraints = false;
            this.Sp_Rpt_ProyeccionMineralTableAdapter.Fill(this.DBMETALDataSet.Sp_Rpt_ProyeccionMineral, this.Fecha);
            this.reportViewer1.RefreshReport();
            if (this.Imprimir == "1")
            {
                this.GenerateReportPdf();

                #region Trallendo los parametros de envio mail
                SqlParameter[] ParamSQL2 = new SqlParameter[4];
                ParamSQL2[0] = new SqlParameter("@Op", "ConsultaMails");
                ParamSQL2[1] = new SqlParameter("@ParametroChar", "");
                ParamSQL2[2] = new SqlParameter("@ParametroInt", "0");
                ParamSQL2[3] = new SqlParameter("@ParametroNuemric", "0");
                DataSet DS2;

                DS2 = LlenarGrid.Datos("SpConsulta_Tablas", ParamSQL2);
                if (DS2.Tables[0].Rows.Count > 0)
                {
                    this.Smtp       = Convert.ToString(DS2.Tables[0].Rows[0]["Smtp"]).Trim();
                    this.Credencial = Convert.ToString(DS2.Tables[0].Rows[0]["Credencial"]).Trim();
                    this.Password   = Convert.ToString(DS2.Tables[0].Rows[0]["Password"]).Trim();
                    this.Puerto     = Convert.ToInt32(DS2.Tables[0].Rows[0]["Puerto"]);
                    this.SSL        = Convert.ToBoolean(DS2.Tables[0].Rows[0]["SSL"]);
                }
                #endregion

                #region Trallendo los remitentes
                try
                {
                    string      RutaFile = Directory.GetCurrentDirectory() + "\\DBMETAL_BasculaMineralProyectado.pdf";
                    MailMessage mnsj     = new MailMessage();
                    mnsj.Subject = "Reporte de Mineral Proyectado a Transportar por Mina  " + this.Fecha.Trim();
                    mnsj.From    = new MailAddress(Credencial, "DBMETAL");

                    mnsj.Attachments.Add(new Attachment(RutaFile));
                    mnsj.Body = "  Proyeccion de Mineral a Ingresar/Transportar a Planta \n\n Enviado desde mi aplicacion DBMETAL\n\n *VER EL ARCHIVO ADJUNTO*";

                    SqlParameter[] ParamSQL1 = new SqlParameter[4];
                    ParamSQL1[0] = new SqlParameter("@Op", "Remitentes1");
                    ParamSQL1[1] = new SqlParameter("@ParametroChar", "");
                    ParamSQL1[2] = new SqlParameter("@ParametroInt", "0");
                    ParamSQL1[3] = new SqlParameter("@ParametroNuemric", "0");
                    DataSet DS1;

                    DS1 = LlenarGrid.Datos("SpConsulta_Tablas", ParamSQL1);
                    if (DS1.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow row in DS1.Tables[0].Rows)
                        {
                            mnsj.To.Add(row[0].ToString());
                        }
                    }
                    Correos.Enviar(Smtp, Puerto, Credencial, Password, SSL, mnsj);
                }
                catch (Exception)
                {
                    throw;
                }

                #endregion
            }
        }
Ejemplo n.º 37
0
 partial void DeleteCorreos(Correos instance);
Ejemplo n.º 38
0
        private void button2_Click(object sender, EventArgs e)
        {
            using (new CursorWait()) {
                try
                {
                    /*Tools.SendMail oMail = new Tools.SendMail(Tools.TYPE_EMAIL_SERVER.HOTMAIL);
                     * String[] config = ConfigurationManager.AppSettings["Hotmail"].ToString().Split(';');
                     * oMail.mUser = config[0];
                     * oMail.mPassword = config[1];
                     *
                     * oMail.mFrom = config[0];
                     * oMail.mTo = "*****@*****.**";
                     * oMail.mSubject = "REPORTE-" + System.DateTime.Now.ToString("MMddyy");
                     * oMail.mTextBody = DataGridtoHTML(this.grdDatos).ToString();
                     * if (oMail.send())
                     * {
                     *  MessageBox.Show("Información Enviada", "Sistema de reportes", MessageBoxButtons.OK, MessageBoxIcon.Information);
                     * }
                     * else
                     * {
                     *  MessageBox.Show("Se presento un error, información no se envio", "Sistema de reportes", MessageBoxButtons.OK, MessageBoxIcon.Information);
                     * }*/
                    bool outlook = Convert.ToBoolean(ConfigurationManager.AppSettings["Outlook"]);
                    if (outlook)
                    {
                        bool bRes = Correos.sendEmailViaOutlook(
                            "*****@*****.**",
                            ConfigurationManager.AppSettings["EmailAdmin"].ToString(), null,
                            this.cmbAlmacenes.Text + "-" + System.DateTime.Now.ToString("MMddyy"),
                            "My message body - " + DateTime.Now.ToString(),
                            BodyType.PlainText,
                            null,
                            null);
                    }
                    else
                    {
                        String[]    config = ConfigurationManager.AppSettings["Hotmail"].ToString().Split(';');
                        Correos     cr     = new Correos(config[0], config[1]);
                        MailMessage msaje  = new MailMessage();
                        msaje.Subject = "REPORTE-" + System.DateTime.Now.ToString("MMddyy");
                        msaje.To.Add(new MailAddress(ConfigurationManager.AppSettings["EmailAdmin"].ToString()));
                        msaje.From = new MailAddress(config[0], "Sistema de Gestion de Reportes");
                        //si quieres atach
                        //msaje.Attachments.Add(new Attachment("c:\\archivo.pdf"));

                        msaje.Body       = DataGridtoHTML(this.grdDatos).ToString();
                        msaje.IsBodyHtml = true;
                        cr.MandarCorreo(msaje);
                    }
                    MessageBox.Show("Información enviada");
                }
                catch (Exception ex)
                {
                    Reportes.Tools.ELog.save("ENVIO DE CORREO", ex);
                    if (ex.InnerException != null)
                    {
                        Reportes.Tools.ELog.save("ENVIO DE CORREO", ex.InnerException);
                    }
                }
            }
        }
Ejemplo n.º 39
0
    private void EnviarCorreo(string correo,string fecha,string usuario)
    {
        string datos = ConvertToHtmlFile(correo,fecha,usuario);

        string msg1="ssss";
        try
        {
            Correos Cr = new Correos();
            //Inicializar mensaje de correo
            MailMessage MM = new MailMessage();
            //Establecemso el asunto
            MM.Subject = "Confirmacion de cuenta FacilOnline";
            //Correo de destimo
            string email = correo;
            MM.To.Add(new MailAddress(email));
            //Aki correo d origen
            MM.From = new MailAddress("*****@*****.**", "Administrador");

            //Ajuntar algun archivo
            //string ruta = HttpContext.Current.Request.MapPath("~/imagen/rrohan.jpg");
            //MM.Attachments.Add(new Attachment(ruta));
            //el contenido del mensaje
            MM.Body = datos;
            MM.IsBodyHtml = true;
            // Enviar
            Cr.MandarCorreo(MM);
            //Enviado = true;

            //Mostrar mensaje
            string msg2 = "El Mail se ha Enviado a su correo electronico Correctamente" + " Listo!!";
            string script = @"<script type='text/javascript'> alert('{0}'); </script>";
            script = string.Format(script, msg2);
            ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, false);

        }
        catch (Exception ex)
        {

            msg1 = ex.Message;
            string script = @"<script type='text/javascript'> alert('{0}'); </script>";
            script = string.Format(script, msg1);
            ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, false);
        }
    }
    protected void btnRegistrar_Click(object sender, EventArgs e)
    {
        string datos = ConvertToHtmlFile();

        DataUsuario du = new DataUsuario();

        du.Email = txtEmail.Text;
        du.Clave = txtClave.Text;
        du.Nombres = txtNombres.Text;
        du.Apellidos = txtApellidos.Text;
        du.Direccion = txtDireccion.Text;
        du.FechaDeNacimiento = DateTime.Parse(txtFechaDeNacimiento.Text);
        du.TipoDeUsuario = int.Parse(cboTipoCliente.SelectedValue);

        string msg1 = u.registrarUsuario(du);

        // Enviar correo
        try
        {
            // Instanciar Correos
            Correos Cr = new Correos();
            // Iniciallizar el msg de correo electrónico
            MailMessage mnsj = new MailMessage();
            // Establecemos el Asunto
            mnsj.Subject = "Confirmación de Cuenta FacilitoOnline";
            // Aqui el Correo de destino
            string email = txtEmail.Text;
            mnsj.To.Add(new MailAddress(email));
            // Aqui el Correo de origen
            mnsj.From = new MailAddress("*****@*****.**", "Administrador");
            // Adjuntar algún archivo
            string ruta = HttpContext.Current.Request.MapPath("~/img/iconos/gracias.gif");
            mnsj.Attachments.Add(new Attachment(ruta));
            // El contenido del mensaje
            mnsj.Body = datos;
            mnsj.IsBodyHtml = true;
            // Enviar
            Cr.MandarCorreo(mnsj);
            Enviado = true;
            // Mostrar mensaje
            /*string msg2 = "El Mail se ha Enviado a su correo electronico Correctamente" + " Listo!!";
            string script = @"<script type='text/javascript'> alert('{0}'); </script>";
            script = string.Format(script, msg2);
            ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, false);*/

            // Mostrar mensaje y retornar
            string script = @"<script type='text/javascript'>
                                    alert('El Mail se ha Enviado a su correo electrónico Correctamente. Listo!!');
                                    window.location = 'Restaurantes.aspx';
                              </script>";
            ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, false);
        }
        catch (Exception ex)
        {
            msg1 = ex.Message;
            string script = @"<script type='text/javascript'> alert('{0}'); </script>";
            script = string.Format(script, msg1);
            ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, false);
        }

        lblMensaje.Text = msg1;
        btnRegistrar.Enabled = false;
    }
Ejemplo n.º 41
0
 public void EnviarCorreos()
 {
     this.c = new Correos();
     this.c.Enviar_Correo(this.txtcorreo.Text, "Registro en la tienda Cronos", "Usted se Registro en la tienda Cronos este es su nombre de usuario:'" + " " + "''" + this.txtnombreUsu.Text + "' y esta es su clave '" + this.usu.Clave + "' le sugerimos por favor cambiar la clave cuando ingrese al sistema Gracias");
 }
Ejemplo n.º 42
0
        protected void btnRegistrar_Click2(object sender, EventArgs e)
        {
            es.ehusw.Matriculas m = new es.ehusw.Matriculas();
            if (m.comprobar(txtDirCorreo.Text) == "SI")

            {
                lblCorreoInexistente.Enabled = false;
                bool       enviado         = false;
                Random     rm              = new Random();
                int        numConfirm      = rm.Next(1000000, 9999999);
                bool       correoExistente = false;
                string     select          = "select * from Usuarios where email=@correo";
                SqlCommand comando1        = new SqlCommand(select, ac.conexion);
                comando1.Parameters.AddWithValue("@correo", txtDirCorreo.Text);

                SqlDataReader dr = comando1.ExecuteReader();
                dr.Read();
                if (dr.HasRows)
                {
                    correoExistente = true;
                }
                dr.Close();
                comando1.Dispose();
                if (!correoExistente)
                {
                    try
                    {
                        Correos     cr   = new Correos();
                        MailMessage mnsj = new MailMessage();

                        mnsj.Subject = "Confirmacion de correo electronico";

                        mnsj.To.Add(new MailAddress(txtDirCorreo.Text));

                        mnsj.From = new MailAddress("*****@*****.**", "Fede Buroni");


                        mnsj.Body = "  Mensaje de Prueba \n\n Enviado desde C#\n\n http://hads18-fede.azurewebsites.net//Confirmar.aspx?correo=" + txtDirCorreo.Text + "&numconf=" + numConfirm;

                        /* Enviar */
                        cr.MandarCorreo(mnsj);
                        enviado            = true;
                        lblconfirmail.Text = "El Mail se ha Enviado Correctamente";
                    }
                    catch (Exception ex)
                    {
                        lblconfirmail.Text = ex.Message;
                        enviado            = false;
                    }
                    if (enviado)
                    {
                        int    confirm = 0;
                        int    codPass = 0;
                        string insert  = "INSERT INTO Usuarios(email,nombre,apellidos,numconfir,confirmado,tipo,pass,codpass) VALUES (@email,@nombre,@apellidos,@numconfir,@confirmado,@tipo,@pass,@codpass)";

                        SqlCommand comando = new SqlCommand(insert, ac.conexion);

                        try
                        {
                            comando.Parameters.AddWithValue("@email", this.txtDirCorreo.Text);
                            comando.Parameters.AddWithValue("@nombre", this.txtNom.Text);
                            comando.Parameters.AddWithValue("@apellidos", this.txtApe.Text);
                            comando.Parameters.AddWithValue("@numconfir", numConfirm);
                            comando.Parameters.AddWithValue("@confirmado", confirm);
                            comando.Parameters.AddWithValue("@tipo", RadioButtonList1.SelectedItem.Text);
                            comando.Parameters.AddWithValue("@pass", EncriptarMD5.MD5Hash(this.txtPassword1.Text));
                            comando.Parameters.AddWithValue("@codpass", codPass);

                            int numregs = comando.ExecuteNonQuery();
                            lblConfir.Text = numregs + " registro insertado correctamente." + "<br/>" + "" + "<br/>" + " Puede confirmarlo con el correo mandado a su email, o con el link:  <a href =\"http://hads18-fede.azurewebsites.net/Confirmar.aspx?correo=" + txtDirCorreo.Text + "&numconf=" + numConfirm + "\">Validar Correo</a>" + "<br/>" + "" + "<br/>" + "";
                            ac.cerrarConexion();
                            lblCorreoInexistente.Visible = false;
                        }
                        catch (Exception ex)
                        {
                            lblConfir.Text = ex.Message;
                        }
                    }
                    else
                    {
                        lblCorreoInexistente.Text         = "El correo ingresado no existe pero es vip";
                        this.lblCorreoInexistente.Visible = true;
                    }
                }
                else
                {
                    lblCorreoInexistente.Text    = "El correo ingresado ya existe";
                    lblCorreoInexistente.Visible = true;
                }
            }

            else
            {
                lblCorreoInexistente.Text    = "El correo ingresado no es vip";
                lblCorreoInexistente.Visible = true;
            }
        }
    public static object CrearUsuario(string Nombres, string Apellidos, int TIPO_IDENTIFICACION, string NUMERO_IDENTIFICACION,
                                      string Direccion, string telefono,
                                      string userName, string Email, string passwordQuestion, string SecurityAnswer)
    {
        string         PERFILP = "PACIENTE";
        string         Retorno = "";
        string         status  = "";
        MembershipUser a       = Membership.GetUser(userName);

        string porEmail = string.Empty;

        porEmail = Membership.GetUserNameByEmail(Email);
        if (a == null && string.IsNullOrEmpty(porEmail))
        {
            #region ("Creacion")
            MembershipCreateStatus createStatus;
            MembershipUser         newUser =
                Membership.CreateUser(userName, NUMERO_IDENTIFICACION,
                                      Email, passwordQuestion,
                                      SecurityAnswer, true,
                                      out createStatus);

            switch (createStatus)
            {
            case MembershipCreateStatus.Success:
                Roles.AddUserToRole(userName, PERFILP);

                Paciente nuevoPaciente = new Paciente();
                nuevoPaciente.nombres_paciente   = Nombres;
                nuevoPaciente.apellidos_paciente = Apellidos;
                nuevoPaciente.ident_paciente     = NUMERO_IDENTIFICACION;
                nuevoPaciente.tipo_id            = TIPO_IDENTIFICACION;
                nuevoPaciente.genero_paciente    = 2;

                nuevoPaciente.direccion_paciente = Direccion;
                nuevoPaciente.telefono_paciente  = telefono;
                nuevoPaciente.movil_paciente     = telefono;
                nuevoPaciente.mail_paciente      = Email;
                nuevoPaciente.userId             = newUser.ProviderUserKey.ToString();
                nuevoPaciente.fecha_nacimiento   = DateTime.Now;

                PacienteDao pd    = new PacienteDao();
                var         nuevo = pd.registrarPacienteNuevo(nuevoPaciente);

                var enviar = new Correos().EnviarEmailCreacionDeUsuario(Email);

                status  = "OK";
                Retorno = "La cuenta del usuario, ha sido creada con exito";

                break;

            case MembershipCreateStatus.DuplicateUserName:
                status  = "Existe";
                Retorno = "Ya existe un usuario con ese nombre de usuario";
                //CreateAccountResults.Text = "Ya existe un usuario con ese nombre de usuario";//"There already exists a user with this username.";
                break;

            case MembershipCreateStatus.DuplicateEmail:
                status  = "Duplicado";
                Retorno = "Ya existe un usuario con este email.";    // "There already exists a user with this email address.";
                break;

            case MembershipCreateStatus.InvalidEmail:
                status  = "email";
                Retorno = "La dirección de correo electrónico que nos ha facilitado en inválida.";    //"There email address you provided in invalid.";
                break;

            case MembershipCreateStatus.InvalidPassword:
                status  = "password";
                Retorno = "La contraseña que ha proporcionado no es válido. Debe ser de siete caracteres y tener al menos un carácter no alfanumérico.";    //"The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";
                break;

            default:
                status  = "Error";
                Retorno = "Hubo un error desconocido, la cuenta de usuario no fue creado.";    //"There was an unknown error; the user account was NOT created.";
                break;
            }
            #endregion
        }
        else
        {
            if (a != null)
            {
                status  = "Existe";
                Retorno = "El nombre de usuario ya existe.";
            }
            //        CreateAccountResults.Text = "El usuario ya existe";

            if (!string.IsNullOrEmpty(porEmail))
            {
                status  = "EmailCambiar";
                Retorno = "Ingrese por favor una dirección de correo electrónico diferente.";
            }
        }
        return(new
        {
            status = status,
            mensaje = Retorno
        });
    }
Ejemplo n.º 44
0
        private void Email(object sender, RoutedEventArgs e)
        {
            try
            {
                Correos Cr = new Correos();
                MailMessage mnsj = new MailMessage();
                mnsj.Subject = "Hola Mundo Prueba";
                mnsj.To.Add(new MailAddress("*****@*****.**"));
                mnsj.From = new MailAddress("*****@*****.**", "Eder Bollas Tovar");
                /* Si deseamos Adjuntar algún archivo*/
                //mnsj.Attachments.Add(new Attachment("E:\\LINEAMIENTOS.pdf"));
                mnsj.Body = "Pinche nahayote de shit";

                /* Enviar */

                Cr.MandarCorreo(mnsj);

                //Enviado = true;
                MessageBox.Show("El Mail se ha Enviado Correctamente", "Listo!!",MessageBoxButton.OK);//, System.Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Asterisk);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }