Esempio n. 1
0
        public bool AlteraçoesEvento(MotivoCancelamentoEvento motivo)
        {
            bool result            = false;
            var  eventoSelecionado = Db.Evento.Find(motivo.EventoId);

            var eventosParticipante = Db.ParticipanteEvento.Where(x => x.EventoId == eventoSelecionado.Id).ToList();

            if (eventoSelecionado == null)
            {
                return(false);
            }

            foreach (var item in eventosParticipante)
            {
                var usuario = Db.Usuario.Find(item.ParticipanteId);

                GmailEmailService gmail = new GmailEmailService();
                EmailMessage      msg   = new EmailMessage
                {
                    Body    = $"<html><head> </head> <body>  <form> <h1>Aviso</h1><h3>Olá {usuario.Nome}</h3><p>{motivo.Descricao}</p> </form></body> </html>",
                    IsHtml  = true,
                    Subject = "Cancelamento de Evento",
                    ToEmail = usuario.Email
                };

                result = gmail.SendEmailMessage(msg);
            }

            if (result)
            {
                return(true);
            }

            return(false);
        }
        public ActionResult Sindicos(string email, string nome, string cpf, string data, string numeroape, string telefone, string celular, string codigo)
        {
            Sindico sin = new Sindico();

            sin.Email                 = email;
            sin.Sin_Nome              = nome;
            sin.Sin_Cpf               = cpf;
            sin.Tipo                  = "S";
            sin.Sin_DataNascimento    = data;
            sin.Sin_NumeroApartamento = Convert.ToInt32(numeroape);
            sin.Sin_Telefone          = telefone;
            sin.Sin_Celular           = celular;
            sin.ApeId                 = Convert.ToInt32(codigo);

            var callbackUrl = Url.Action("CadastrarSenha", "Landing", new { mandaemail = Funcoes.Base64Codifica(email) }, protocol: Request.Url.Scheme);


            GmailEmailService gmail = new GmailEmailService();
            EmailMessage      msg   = new EmailMessage();

            msg.Body    = "Bem vindo Confirme a sua senha clicando aqui: " + callbackUrl;
            msg.IsHtml  = false;
            msg.Subject = "Bem vindo a AdminLar (Confirmação de Cadastro)";
            msg.ToEmail = email;
            gmail.SendEmailMessage(msg);

            db.Sindicos.Add(sin);

            if (db.SaveChanges() > 0)
            {
                return(Json(true));
            }

            return(Json(false));
        }
Esempio n. 3
0
        public string CancelarConfimacaoPresenca(ConfimacaoParticipanteEvento confimacao)
        {
            try
            {
                var participante = Db.Participante.Find(confimacao.UsuarioId);

                var usuario = Db.Usuario.Find(participante.Id);

                var evento = Db.Evento.Find(confimacao.EventoId);

                var agenda = Db.AgendaEvento.Find(evento.AgendaEventoId);

                if (usuario == null)
                {
                    throw new Exception("Usuario não encontrado.");
                }
                if (evento == null)
                {
                    throw new Exception("Evento não encontrado.");
                }
                if (agenda == null)
                {
                    throw new Exception("Agenda não encontrada.");
                }

                var ExisteParticpanteInscrito = Db.ParticipanteEvento.Count(x => x.ParticipanteId == confimacao.UsuarioId &&
                                                                            x.EventoId == confimacao.EventoId && x.InscricaoPrevia == true) > 0;

                if (ExisteParticpanteInscrito)
                {
                    var eventoIscricao = Db.ParticipanteEvento.FirstOrDefault(x => x.ParticipanteId == confimacao.UsuarioId &&
                                                                              x.EventoId == confimacao.EventoId);

                    eventoIscricao.ConfirmacaoPresenca = false;
                    Db.Entry(eventoIscricao).State     = EntityState.Modified;
                    Db.SaveChanges();

                    GmailEmailService gmail = new GmailEmailService();
                    EmailMessage      msg   = new EmailMessage
                    {
                        Body    = $"<html><head> </head> <body>  <form method='POST'><h1>Aviso</h1><h3>Olá { usuario.Nome}</h3><p>Sua confimarçao de presença no evento {evento.Nome} foi cancelada!</p></form></body> </html>",
                        IsHtml  = true,
                        Subject = "Confirmação de presença",
                        ToEmail = usuario.Email
                    };
                    gmail.SendEmailMessage(msg);
                    return("OK");
                }
                throw new Exception("Usuario não inscrito nesse evento.");
            }

            catch (Exception e)
            {
                return(e.Message);
            }
        }
        public async System.Threading.Tasks.Task <ActionResult> SendMailResult(MailModel mailModel, int?id, HttpPostedFileBase uploadFile)
        {
            var user = Helpers.GetCurrentUser(this.User);

            //var id=Url.RequestContext.RouteData.Values["id"];
            if (id == null || user.Role == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ThesisForm thesisForm = db.Thesises.Find(id);

            if (thesisForm == null)
            {
                return(HttpNotFound());
            }

            //This what a mail will contain
            var body    = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
            var message = new MailMessage();

            message.To.Add(new MailAddress(mailModel.Email)); //replace with valid value
            message.Subject = mailModel.Subject;
            message.From    = (new MailAddress(user.Email));
            //sending the Professor's mail
            if (user.Role == "Professor")
            {
                message.Body = string.Format(body, "AegeanThesis", user.Email, "User " + user.Name + " is wants approve for this thesis <a href =\"http://localhost:61006/ThesisForms/Details/" + id + ">localhost:61006/ThesisForms/Details/</a>" + "\n" + mailModel.Notes);
            }
            else //ortherwise the user is Student so we send his mail
            {
                message.Body = string.Format(body, "AegeanThesis", user.Email, mailModel.Notes);
            }

            message.IsBodyHtml = true;
            if (uploadFile != null)
            {
                string fileName = Path.GetFileName(uploadFile.FileName);
                message.Attachments.Add(new Attachment(uploadFile.InputStream, fileName));
            }
            //using the Gmail service used before for user validation
            using (var smtp = new GmailEmailService())
            {
                await smtp.SendMailAsync(message);
            }
            //Showing each page respectively
            if (user.Role == "Professor")
            {
                return(View("BoardSent"));
            }
            else
            {
                return(View("MailProfessor"));
            }
        }
        public async Task SendAsync(IdentityMessage message)
        {
            MailMessage email = new MailMessage(new MailAddress("*****@*****.**", "noreply@TeeShirtEmporium"),
                                                new MailAddress(message.Destination));

            email.Subject = message.Subject;
            email.Body    = message.Body;

            email.IsBodyHtml = true;

            GmailEmailService mailClient = new GmailEmailService();
            await mailClient.SendMailAsync(email);
        }
Esempio n. 6
0
        public async Task SendAsync(IdentityMessage message)
        {
            MailMessage email = new MailMessage(new MailAddress("*****@*****.**", "TRAEKTORIA"),
                                                new MailAddress(message.Destination));

            email.Subject    = message.Subject;
            email.Body       = message.Body;
            email.IsBodyHtml = true;

            using (var mailClient = new GmailEmailService())
            {
                await mailClient.SendMailAsync(email);
            }
        }
Esempio n. 7
0
        public ActionResult EnviaEmail(string nome, string email, string assunto, string mensagem)
        {
            GmailEmailService gmail = new GmailEmailService();
            EmailMessage      msg   = new EmailMessage();

            msg.Body    = "Nome do Usuário: " + nome + "\n\n Email do Usuário: " + email + "\n\n Assunto: " + mensagem;
            msg.IsHtml  = false;
            msg.Subject = assunto;
            msg.ToEmail = "*****@*****.**";
            gmail.SendEmailMessage(msg);



            return(Json(true));
        }
Esempio n. 8
0
        public async Task SendAsync(IdentityMessage message)
        {
            MailMessage email = new MailMessage(new MailAddress("*****@*****.**", "Chợ Xe"),
                                                new MailAddress(message.Destination));

            email.Subject = message.Subject;
            email.Body    = message.Body;

            email.IsBodyHtml = true;

            using (var mailClient = new GmailEmailService())
            {
                //In order to use the original from email address, uncomment this line:
                //email.From = new MailAddress(mailClient.UserName, "(do not reply)");
                await mailClient.SendMailAsync(email);
            }
        }
Esempio n. 9
0
        public async Task NotifyAdminByEmail(string subject, string body)
        {
            using (var mailClient = new GmailEmailService())
            {
                MailMessage email = new MailMessage(new MailAddress("*****@*****.**", "(do not reply)"),
                                                    new MailAddress(mailClient.UserName));

                email.Subject = subject;
                email.Body    = body;

                email.IsBodyHtml = true;
                //In order to use the original from email address, uncomment this line:
                //                email.From = new MailAddress(mailClient.UserName, "(do not reply)");

                await mailClient.SendMailAsync(email);
            }
        }
Esempio n. 10
0
        // Use NuGet to install SendGrid (Basic C# client lib)
        private async Task configSendGridasync(IdentityMessage message)
        {
            MailMessage email = new MailMessage(new MailAddress("*****@*****.**", "(Do not reply)"),
                                                new MailAddress(message.Destination));

            email.Subject = message.Subject;
            email.Body    = message.Body;

            email.IsBodyHtml = true;

            using (var mailClient = new GmailEmailService())
            {
                //In order to use the original from email address, uncomment this line:
                email.From = new MailAddress(mailClient.UserName, "(do not reply)");

                await mailClient.SendMailAsync(email);
            }
        }
Esempio n. 11
0
        public ActionResult DeleteConfirmed(int id)
        {
            Anuncio anuncio = db.Anuncios.Find(id);
            Locador locador = db.Locadores.Find(anuncio.LocadorID);
            //Inserir envio de email de aviso ao locador
            GmailEmailService gmail = new GmailEmailService();
            EmailMessage      msg   = new EmailMessage();

            msg.Body    = "<!DOCTYPE HTML><html><body><p>Caro(a) " + locador.NomeLocador + ",</p><p>Seu anúncio " + anuncio.Descricao + " foi deletado da platafoma Movin!</p><p>Caso essa ação tenha sido feita por você desconsidere o e-mail, caso não, entre em contado com a Administração da Movin poís seu anúncio pode ter sido deletado por alguma infração as normas de uso da plataforma.<p>Atenciosamente,<br/>Administração Movin.</p></body></html>";
            msg.IsHtml  = true;
            msg.Subject = "Anúncio Deletado - MOVIN";
            msg.ToEmail = locador.EmailLocador;
            gmail.SendEmailMessage(msg);
            db.Anuncios.Remove(anuncio);
            db.SaveChanges();

            return(RedirectToAction("Index"));
        }
Esempio n. 12
0
        public string CancelarEvento(MotivoCancelamentoEvento motivo)
        {
            try
            {
                bool result            = false;
                var  eventoSelecionado = Db.Evento.Find(motivo.EventoId);

                if (eventoSelecionado == null)
                {
                    throw new Exception("Evento não encontrado.");
                }

                eventoSelecionado.Cancelado = true;

                Db.Evento.Attach(eventoSelecionado);
                Db.Entry(eventoSelecionado).State = EntityState.Modified;
                Db.SaveChanges();


                var eventosParticipante = Db.ParticipanteEvento.Where(x => x.EventoId == eventoSelecionado.Id).ToList();

                foreach (var item in eventosParticipante)
                {
                    var usuario = Db.Usuario.Find(item.ParticipanteId);

                    GmailEmailService gmail = new GmailEmailService();
                    EmailMessage      msg   = new EmailMessage
                    {
                        Body    = $"<html><head> </head> <body>  <form> <h1>Aviso</h1><h3>Olá {usuario.Nome}</h3><p>{motivo.Descricao}</p> </form></body> </html>",
                        IsHtml  = true,
                        Subject = "O Evento " + eventoSelecionado.Nome + "foi cancelado",
                        ToEmail = usuario.Email
                    };

                    result = gmail.SendEmailMessage(msg);
                }

                return("OK");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Esempio n. 13
0
        public async Task SendAsync(IdentityMessage message)
        {
            MailMessage email = new MailMessage(new MailAddress("*****@*****.**", "(do not reply)"),
                                                new MailAddress(message.Destination))
            {
                Subject = message.Subject,
                Body    = message.Body,

                IsBodyHtml = true
            };

            using (var mailClient = new GmailEmailService())
            {
                //In order to use the original from email address, uncomment this line:
                email.From = new MailAddress(mailClient.UserName, "(do not reply)");

                await mailClient.SendMailAsync(email);
            }
        }
Esempio n. 14
0
        public ActionResult HomePage([Bind(Include = "CadastroID,Nome,Email,Assunto,Mensagem")] Contato contato)
        {
            if (ModelState.IsValid)
            {
                db.Contatos.Add(contato);
                db.SaveChanges();

                GmailEmailService gmail = new GmailEmailService();
                EmailMessage      msg   = new EmailMessage();
                msg.Body    = "<!DOCTYPE HTML><html><body><p>Mensagem de: <b>" + contato.Nome + "</b><br /><br /> " + contato.Mensagem + "</p><p>Contato do remetente para retorno: " + contato.Email + "</p></body></html>";
                msg.IsHtml  = true;
                msg.Subject = contato.Assunto;
                msg.ToEmail = "*****@*****.**";
                gmail.SendEmailMessage(msg);

                return(RedirectToAction("Index"));
            }

            return(View(contato));
        }
Esempio n. 15
0
        private void button4_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(textBox1.Text) && !string.IsNullOrWhiteSpace(textBox2.Text) && !string.IsNullOrWhiteSpace(textBox3.Text) && !string.IsNullOrWhiteSpace(textBox4.Text) && !string.IsNullOrWhiteSpace(textBox5.Text))
            {
                GmailEmailService gmail = new GmailEmailService(textBox1.Text, textBox2.Text);
                EmailMessage      msg   = new EmailMessage();
                msg.Body    = textBox4.Text;
                msg.IsHtml  = true;
                msg.Subject = textBox3.Text;

                foreach (ListViewItem listViewItem in this.listView1.Items)
                {
                    msg.ToEmail = listViewItem.SubItems[1].Text;
                    gmail.SendEmailMessage(msg);
                    Thread.Sleep(Convert.ToInt32(textBox5.Text));
                }
            }
            else
            {
                MessageBox.Show("Insira Valores Validos, para que o email seja Enviado!");
            }
        }
        // GET: ThesisForms/Interested
        public async System.Threading.Tasks.Task <ActionResult> Interested(int?id)
        {
            var user = Helpers.GetCurrentUser(this.User);

            ThesisForm thesisForm = db.Thesises.Find(id);

            if (user.Role.Equals("Professor"))
            {
                return(RedirectToAction("InterestedMessage"));
            }
            else if (user.Role.Equals("Student"))
            {
                //This what a mail will contain
                var body    = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
                var message = new MailMessage();
                message.To.Add(new MailAddress(thesisForm.Supervisor + "@aegean.gr")); //replace with valid value
                message.Subject    = "Your email subject";
                message.From       = (new MailAddress("*****@*****.**"));
                message.Body       = string.Format(body, "AegeanThesis", "*****@*****.**", "User " + user.Email + " is interested about thesis " + thesisForm.Title);
                message.IsBodyHtml = true;
                //using the Gmail service used before for user validation
                using (var smtp = new GmailEmailService())
                {
                    await smtp.SendMailAsync(message);
                }
                return(RedirectToAction("InterestedSent"));
            }
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            if (thesisForm == null)
            {
                return(HttpNotFound());
            }
            return(View());
        }
        public ActionResult Inadimplencias([Bind(Include = "InaId,valor,Status,Codigo,ApeId")] Inadimplencia inadimplencia, string codigo)
        {
            Sindico usuario = AdminLar.Repositories.Funcoes.GetUsuario();

            if (usuario != null)
            {
                inadimplencia.Codigo = Convert.ToInt32(codigo);
                inadimplencia.Status = "Devendo";
                inadimplencia.ApeId  = usuario.ApeId;
                db.Inadimplecias.Add(inadimplencia);


                var converte = Convert.ToInt32(codigo);

                //pega o email do condomino inadimplete

                var email = db.Usuarios.Where(x => x.Codigo == converte).Select(x => x.Email).FirstOrDefault();

                var nome = db.Usuarios.OfType <Condomino>().Where(x => x.Codigo == converte).Select(x => x.Con_Nome).FirstOrDefault();

                var ape = db.Sindicos.Where(x => x.Codigo == usuario.Codigo).Select(x => x.Apartamento.NomeApe).First();

                GmailEmailService gmail = new GmailEmailService();
                EmailMessage      msg   = new EmailMessage();
                msg.Body    = "Prezado(a) " + nome + "\n\n encontramos no nosso sistema pendências em seu nome. \n\n Entre em contato com o Síndico ou caso você já tenha efetuado o pagamento desconsidere essa mensagem \n\n Atenciosamente " + ape;
                msg.IsHtml  = false;
                msg.Subject = "Pendência";
                msg.ToEmail = Convert.ToString(email);
                gmail.SendEmailMessage(msg);

                if (db.SaveChanges() > 0)
                {
                    return(RedirectToAction("Index", "Inadimplencia"));
                }
            }

            return(Json(false));
        }
Esempio n. 18
0
        public Task Execute(string strSubject, string strMessage, string strEmailTo)
        {
            MailMessage email = new MailMessage(new MailAddress(Options.From, "(do not reply)"),
                                                new MailAddress(strEmailTo));

            email.Subject = strSubject;
            email.Body    = strMessage;

            email.IsBodyHtml = true;

            var mailClient = new GmailEmailService(Options.Server, Options.Port, Options.SSL, Options.Username, Options.Password);
            {
                //In order to use the original from email address, uncomment this line:
                //email.From = new MailAddress(mailClient.UserName, "(do not reply)");

                return(mailClient.SendMailAsync(email));
            }



            /*
             * var client = new SendGridClient(apiKey);
             * var msg = new SendGridMessage()
             * {
             *  From = new EmailAddress("*****@*****.**", Options.SendGridUser),
             *  Subject = subject,
             *  PlainTextContent = message,
             *  HtmlContent = message
             * };
             * msg.AddTo(new EmailAddress(email));
             *
             * // Disable click tracking.
             * // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
             * msg.SetClickTracking(false, false);
             *
             * return client.SendEmailAsync(msg);
             */
        }
Esempio n. 19
0
        public ActionResult ReportarProblemas([Bind(Include = "AnuncioID,Descricao,QuartoSolteiro,QuartoCasal,QuartoComunitario,QtdCama,QtdBanheiro,NumHospedes,ValorDiaria,Rua,Bairro,Complemento,Numero,Cidade,UF,Cep,Foto1,Foto2,ArCondicionado,Ventilador,Banheira,Internet,TvCabo,Animais,Fumante,Ativo,Problemas,LocadorID")] Anuncio anuncio)
        {
            if (ModelState.IsValid)
            {
                Locador locador = db.Locadores.Find(anuncio.LocadorID);

                GmailEmailService gmail = new GmailEmailService();
                EmailMessage      msg   = new EmailMessage();
                msg.Body    = "<!DOCTYPE HTML><html><body><p>Foi identificado um reporte de problema por um usuário.</p><p>O anúncio reportado foi " + anuncio.Descricao + ". O mesmo recebeu a seguinte mensagem: </p><p><strong>" + anuncio.Problemas + "</strong></p><p>Entre em contato com o locador para possivel aviso. <strong>" + locador.NomeLocador + "</strong> / <strong>" + locador.EmailLocador + "</strong></p><br/>Administração Movin.</p></body></html>";
                msg.IsHtml  = true;
                msg.Subject = "REPORTE DE PROBLEMA - MOVIN";
                msg.ToEmail = "*****@*****.**";
                gmail.SendEmailMessage(msg);

                anuncio.Problemas = "";

                db.Entry(anuncio).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.LocadorID = new SelectList(db.Locadores, "LocadorID", "NomeLocador", anuncio.LocadorID);
            return(View(anuncio));
        }
Esempio n. 20
0
        public async Task SendAsync(IdentityMessage message)
        {
            // Plug in your email service here to send an email.

            MailMessage email = new MailMessage(new MailAddress("*****@*****.**", "(do not reply)"),
                                                new MailAddress(message.Destination));

            email.Subject = message.Subject;
            email.Body    = message.Body;

            email.IsBodyHtml = true;

            using (var mailClient = new GmailEmailService())
            {
                //In order to use the original from email address, uncomment this line:
                email.From = new MailAddress(mailClient.UserName, "(do not reply)");

                await mailClient.SendMailAsync(email);
            }


            //return Task.FromResult(0);
        }
Esempio n. 21
0
        public ViewResult FecharPedido(Carrinho carrinho, Pedido pedido)
        {
            if (!carrinho.ItensCarrinho.Any())
            {
                ModelState.AddModelError("", "Não foi possivel concluir o pedido, seu carrinho esta vazio");
            }
            if (ModelState.IsValid)
            {
                GmailEmailService gmail = new GmailEmailService();
                EmailMessage      msg   = new EmailMessage();
                msg.Body    = gmail.CorpoEmail(carrinho, pedido);
                msg.IsHtml  = true;
                msg.Subject = "Pedido Processado";
                msg.ToEmail = pedido.Email;
                gmail.SendEmailMessage(msg);

                carrinho.LimparCarrinho();
                return(View("PedidoConcluido"));
            }
            else
            {
                return(View(pedido));
            }
        }
        public ActionResult EsqueciSenha([Bind(Include = "StartupCadastroID,Nome,Email,Senha,Cep,Rua,Bairro,Numero,Complemento,Cidade,Estado,Sobre,Objetivo,DataFundacao,TamanhoTime,Logotipo,ImagemLocal1,ImagemLocal2,ImagemMVP1,ImagemMVP2,ImagemMVP3,ImagemMVP4,Hash,SegmentacaoID")] StartupCadastro empresaCadastro,
                                         HttpPostedFileBase logoTipo, HttpPostedFileBase imagemLocal1, HttpPostedFileBase imagemLocal2, HttpPostedFileBase imagemMVP1, HttpPostedFileBase imagemMVP2, HttpPostedFileBase imagemMVP3, HttpPostedFileBase imagemMVP4)
        {
            EmpresaCadastro e = db.EmpresaCadastros.Where(s => s.Email == empresaCadastro.Email).ToList().SingleOrDefault();

            string hash = (e.Email + e.Numero);

            e.Hash = hash;

            ((IObjectContextAdapter)db).ObjectContext.Detach(e);
            db.Entry(e).State = EntityState.Modified;
            db.SaveChanges();

            GmailEmailService gmail = new GmailEmailService();
            EmailMessage      msg   = new EmailMessage();

            msg.Body    = "<!DOCTYPE HTML><html><body><p>Olá!</p><p>Clique no link abaixo para redefinir senha:<br/><a href= http://localhost:50072/LogonEmpresa/ValidarHash?h=" + hash + ">Redefinir Senha</a></p><p>Aconselhamos que por segurança você altere sua senha para uma mais forte!</p><p>Atenciosamente,<br/>StarToUp.</p></body></html>";
            msg.IsHtml  = true;
            msg.Subject = "Redefinir Senha - StarToUp";
            msg.ToEmail = empresaCadastro.Email;
            gmail.SendEmailMessage(msg);

            return(View());
        }
Esempio n. 23
0
        public ActionResult Create([Bind(Include = "StartupCadastroID,Nome,Email,Senha,DataCadastro,Cep,Rua,Bairro,Numero,Complemento,Cidade,Estado,Sobre,Objetivo,DataFundacao,TamanhoTime,Logotipo,ImagemLocal1,ImagemLocal2,ImagemMVP1,ImagemMVP2,ImagemMVP3,ImagemMVP4,LinkInstagram,LinkFacebook,LinkLinkedin,TermoUso,Hash,SegmentacaoID")] StartupCadastro startupCadastro,
                                   HttpPostedFileBase logoTipo, HttpPostedFileBase imagemLocal1, HttpPostedFileBase imagemLocal2, HttpPostedFileBase imagemMVP1, HttpPostedFileBase imagemMVP2, HttpPostedFileBase imagemMVP3, HttpPostedFileBase imagemMVP4)
        {
            ViewBag.FotoMensagem = "";
            try
            {
                if (ModelState.IsValid && startupCadastro.TermoUso == true)
                {
                    string fileName    = "";
                    string contentType = "";
                    string path        = "";

                    if (logoTipo != null && logoTipo.ContentLength > 0)
                    {
                        fileName    = System.IO.Path.GetFileName(logoTipo.FileName);
                        contentType = logoTipo.ContentType;
                        path        = System.Configuration.ConfigurationManager.AppSettings["PathFiles"] + "\\PerfilStartup\\" + fileName;
                        logoTipo.SaveAs(path);
                        startupCadastro.Logotipo = fileName;
                    }

                    if (imagemLocal1 != null && imagemLocal1.ContentLength > 0)
                    {
                        fileName    = System.IO.Path.GetFileName(imagemLocal1.FileName);
                        contentType = imagemLocal1.ContentType;
                        path        = System.Configuration.ConfigurationManager.AppSettings["PathFiles"] + "\\PerfilStartup\\" + fileName;
                        imagemLocal1.SaveAs(path);
                        startupCadastro.ImagemLocal1 = fileName;
                    }

                    if (imagemLocal2 != null && imagemLocal2.ContentLength > 0)
                    {
                        fileName    = System.IO.Path.GetFileName(imagemLocal2.FileName);
                        contentType = imagemLocal2.ContentType;
                        path        = System.Configuration.ConfigurationManager.AppSettings["PathFiles"] + "\\PerfilStartup\\" + fileName;
                        imagemLocal2.SaveAs(path);
                        startupCadastro.ImagemLocal2 = fileName;
                    }

                    if (imagemMVP1 != null && imagemMVP1.ContentLength > 0)
                    {
                        fileName    = System.IO.Path.GetFileName(imagemMVP1.FileName);
                        contentType = imagemMVP1.ContentType;
                        path        = System.Configuration.ConfigurationManager.AppSettings["PathFiles"] + "\\PerfilStartup\\" + fileName;
                        imagemMVP1.SaveAs(path);
                        startupCadastro.ImagemMVP1 = fileName;
                    }

                    if (imagemMVP2 != null && imagemMVP2.ContentLength > 0)
                    {
                        fileName    = System.IO.Path.GetFileName(imagemMVP2.FileName);
                        contentType = imagemMVP2.ContentType;
                        path        = System.Configuration.ConfigurationManager.AppSettings["PathFiles"] + "\\PerfilStartup\\" + fileName;
                        imagemMVP2.SaveAs(path);
                        startupCadastro.ImagemMVP2 = fileName;
                    }

                    if (imagemMVP3 != null && imagemMVP3.ContentLength > 0)
                    {
                        fileName    = System.IO.Path.GetFileName(imagemMVP3.FileName);
                        contentType = imagemMVP3.ContentType;
                        path        = System.Configuration.ConfigurationManager.AppSettings["PathFiles"] + "\\PerfilStartup\\" + fileName;
                        imagemMVP3.SaveAs(path);
                        startupCadastro.ImagemMVP3 = fileName;
                    }

                    if (imagemMVP4 != null && imagemMVP4.ContentLength > 0)
                    {
                        fileName    = System.IO.Path.GetFileName(imagemMVP4.FileName);
                        contentType = imagemMVP4.ContentType;
                        path        = System.Configuration.ConfigurationManager.AppSettings["PathFiles"] + "\\PerfilStartup\\" + fileName;
                        imagemMVP4.SaveAs(path);
                        startupCadastro.ImagemMVP4 = fileName;
                    }

                    startupCadastro.DataCadastro = DateTime.Now;
                    db.StartupCadastros.Add(startupCadastro);
                    db.SaveChanges();

                    GmailEmailService gmail = new GmailEmailService();
                    EmailMessage      msg   = new EmailMessage();
                    msg.Body    = "<!DOCTYPE HTML><html><body><p>" + startupCadastro.Nome + ",<br/>Seja bem-vinda(o)!</p><p>Sua decolagem está prestes a iniciar!<br/>Clique no link abaixo para finalizar seu cadastro:</p><a href= http://localhost:50072/Logon/Logar/" + "> Faça seu login aqui!</a><p>Esperamos que você decole com a gente!</p><p>Atenciosamente,<br/>StarToUp.</p></body></html>";
                    msg.IsHtml  = true;
                    msg.Subject = "E-mail de Confirmação - StarToUp";
                    msg.ToEmail = startupCadastro.Email;
                    gmail.SendEmailMessage(msg);

                    var response = Request["g-recaptcha-response"];
                    //chave secreta que foi gerada no site
                    const string secret = "6Ldjv5gUAAAAAE8AgNayyITU99Lexs-BEeZU4imx";
                    var          client = new WebClient();
                    var          reply  =
                        client.DownloadString(

                            string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
                                          secret, response));
                    var captchaResponse = JsonConvert.DeserializeObject <CaptchaResponse>(reply);
                    //Response false – devemos ver qual a mensagem de erro
                    if (!captchaResponse.Success)
                    {
                        if (captchaResponse.ErrorCodes.Count <= 0)
                        {
                            return(View());
                        }
                        var error = captchaResponse.ErrorCodes[0].ToLower();
                        switch (error)
                        {
                        case ("missing-input-secret"):
                            ViewBag.Message = "The secret parameter is missing.";
                            break;

                        case ("invalid-input-secret"):
                            ViewBag.Message = "The secret parameter is invalid or malformed.";
                            break;

                        case ("missing-input-response"):
                            ViewBag.Message = "The response parameter is missing.";
                            break;

                        case ("invalid-input-response"):
                            ViewBag.Message = "The response parameter is invalid or malformed.";
                            break;

                        default:
                            ViewBag.Message = "Error occured. Please try again";
                            break;
                        }
                        return(View());
                    }
                    else
                    {
                        ViewBag.Message = "Valid";
                        return(RedirectToAction("../Home/Principal"));
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.FotoMensagem = "Não foi possível salvar a foto";
            }
            ViewBag.SegmentacaoID     = new SelectList(db.Segmentacoes, "SegmentacaoID", "Descricao", startupCadastro.SegmentacaoID);
            ViewBag.StartupCadastroID = new SelectList(db.StartupCadastros, "StartupCadastroID", "Nome", startupCadastro.StartupCadastroID);
            return(View(startupCadastro));
        }
Esempio n. 24
0
        //Action para recuperar senha

        public ActionResult Recupera(string email)
        {
            if (db.Usuarios.Any(x => x.Email == email))
            {
                var response = Request["g-recaptcha-response"];

                //chave secreta que foi gerada no site

                const string secret = "6LfK1j4UAAAAAHtP7zXZbgSE8XT8Zm25pFm0sSUZ";

                var client = new WebClient();
                var reply  =
                    client.DownloadString(

                        string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
                                      secret, response));
                var captchaResponse = JsonConvert.DeserializeObject <CaptchaResponse>(reply);

                //Response false – devemos ver qual a mensagem de erro

                if (!captchaResponse.Success)
                {
                    if (captchaResponse.ErrorCodes.Count <= 0)
                    {
                        return(View());
                    }

                    var error = captchaResponse.ErrorCodes[0].ToLower();

                    switch (error)
                    {
                    case ("missing-input-secret"):
                        ViewBag.Message = "The secret parameter is missing.";
                        break;

                    case ("invalid-input-secret"):
                        ViewBag.Message = "The secret parameter is invalid or malformed.";
                        break;

                    case ("missing-input-response"):
                        ViewBag.Message = "The response parameter is missing.";
                        break;

                    case ("invalid-input-response"):
                        ViewBag.Message = "The response parameter is invalid or malformed.";
                        break;

                    default:
                        ViewBag.Message = "Error occured. Please try again";
                        break;
                    }
                    TempData["Error"] = "Certifique-se que você não é um robô";
                }

                else
                {
                    var callbackUrl = Url.Action("Recuperar", "Landing", new { recupera = Funcoes.Base64Codifica(email) }, protocol: Request.Url.Scheme);


                    GmailEmailService gmail = new GmailEmailService();
                    EmailMessage      msg   = new EmailMessage();
                    msg.Body    = "Link para redefinir a senha \n\n clicando aqui: " + callbackUrl;
                    msg.IsHtml  = false;
                    msg.Subject = "Redefinir senha";
                    msg.ToEmail = email;
                    gmail.SendEmailMessage(msg);

                    TempData["Sucesso"] = "Um link para redefinir sua senha foi enviado para o seu email";
                }
            }
            else
            {
                TempData["Error"] = "Email não encontrado no sistema";
            }

            return(RedirectToAction("RecuperarSenha", "Landing"));
        }
Esempio n. 25
0
        public string Editar(EventoViewModel entity)
        {
            try
            {
                string path = HttpContext.Current.Server.MapPath("~/Imagens/Eventos/");

                var bits = Convert.FromBase64String(entity.PathImagem);

                string nomeImagem = Guid.NewGuid().ToString() + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".jpg";

                string imgPath = Path.Combine(path, nomeImagem);

                File.WriteAllBytes(imgPath, bits);

                entity.PathImagem = nomeImagem;

                var eventoModel = entity;

                var eventoSalvo         = Db.Evento.FirstOrDefault(x => x.Id == entity.Id);
                var eventosParticipante = Db.ParticipanteEvento.Where(x => x.EventoId == entity.Id).ToList();


                if (eventoSalvo.Local != eventoModel.Local ||
                    eventoSalvo.DataInicio != eventoModel.DataInicio)
                {
                    var descricao = "O evento <b>" + eventoSalvo.Nome + "</b>, no qual você está inscrito, teve alteração na sua data e/ou local. Ele agora ocorrerá <b>" +
                                    eventoModel.DataInicio.ToLongDateString() + "</b> no(a) <b>" + eventoModel.Local + "</b>. Estaremos esperando por você :)";

                    foreach (var item in eventosParticipante)
                    {
                        var usuario = Db.Usuario.Find(item.ParticipanteId);

                        GmailEmailService gmail = new GmailEmailService();
                        EmailMessage      msg   = new EmailMessage
                        {
                            Body    = $"<html><head> </head> <body>  <form> <h1>Notificação Konoha</h1><h3>Olá {usuario.Nome}</h3><p>{descricao}</p> </form></body> </html>",
                            IsHtml  = true,
                            Subject = "Notificação sobre o evento: " + eventoModel.Nome,
                            ToEmail = usuario.Email
                        };

                        gmail.SendEmailMessage(msg);
                    }
                }

                var existeFoto = Path.Combine(path, eventoSalvo.PathImagem);

                eventoSalvo.Local            = eventoModel.Local;
                eventoSalvo.Nome             = eventoModel.Nome;
                eventoSalvo.NumeroVagas      = eventoModel.NumeroVagas;
                eventoSalvo.PathImagem       = eventoModel.PathImagem;
                eventoSalvo.Descricao        = eventoModel.Descricao;
                eventoSalvo.DataInicio       = eventoModel.DataInicio;
                eventoSalvo.DataEncerramento = eventoModel.DataEncerramento;
                eventoSalvo.CargaHoraria     = eventoModel.CargaHoraria;
                eventoSalvo.Apresentador     = eventoModel.Apresentador;
                eventoSalvo.AgendaEventoId   = eventoModel.AgendaEventoId;


                foreach (var item in entity.Funcionario)
                {
                    EventoFuncionario e = new EventoFuncionario
                    {
                        EventoId      = eventoModel.Id,
                        FuncionarioId = item.Id
                    };

                    var isModerador = Db.EventoFuncionario.Where(x => x.EventoId == eventoModel.Id && x.FuncionarioId == item.Id).ToList();

                    if (isModerador.Count() == 0)
                    {
                        Db.EventoFuncionario.Add(e);
                        Db.SaveChanges();
                    }
                }


                if (File.Exists(existeFoto))
                {
                    File.Delete(existeFoto);
                }

                //Db.Entry(eventoModel).State = EntityState.Modified;
                Db.SaveChanges();
                return("OK");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }