public ActionResult checkout(Order_Model obj) { List <Item> cart = (List <Item>)Session["cart"]; decimal totalSum = 0; StringBuilder body = new StringBuilder(); try { if (cart.Count() != 0) { body.AppendLine("Order:"); body.AppendLine("<table font-family= arial, sans-serif, border-collapse = collapse, width= 100% >"); body.AppendLine("<tr>"); body.AppendLine("<td><b>Article</b></td>"); body.AppendLine("<td><b>Title</b></td>"); body.AppendLine("<td><b>Size</b></td>"); body.AppendLine("<td><b>Color</b></td>"); body.AppendLine("<td><b>Quantity</b></td>"); body.AppendLine("<td><b>Price</b></td>"); body.AppendLine("</tr>"); foreach (Item items in (List <Item>)Session["cart"]) { totalSum = totalSum + Convert.ToDecimal(items.Products.p_price * items.Quantity); body.AppendLine("<tr>"); body.AppendLine("<td>"); body.AppendLine(items.Products.p_article_no); body.AppendLine("</td>"); body.AppendLine("<td>"); body.AppendLine(items.Products.p_title); body.AppendLine("</td>"); body.AppendLine("<td>"); body.AppendLine("size"); body.AppendLine("</td>"); body.AppendLine("<td>"); body.AppendLine("color"); body.AppendLine("</td>"); body.AppendLine("<td>"); body.AppendLine("quantity"); body.AppendLine("</td>"); body.AppendLine("<td>"); body.AppendLine(items.Products.p_price.ToString()); body.AppendLine("</td>"); } body.AppendLine("</table>"); } } catch (Exception) { } try { if (ModelState.IsValid) { WebMail.Send( "*****@*****.**", "New Order", body + "<br/><br/>" + "<b>" + "Total Amount: " + "</b>" + totalSum + "<br/><br/>" + "<b>" + "Information of Buyer:" + "</b>" + "<br/>" + "Name: " + obj.First_Name + " " + obj.Last_Name + "<br/>" + "Email: " + obj.Email + "<br/>" + "Phone: " + obj.Phone + "<br/>" + "City: " + obj.City + "<br/>" + "Address: " + obj.Address + "<br/><br/>", null, null, null, true, null, null, null, null, null, obj.Email ); return(RedirectToAction("Index", "Home")); } } catch (Exception) { ViewBag.Error = "Problems sending Email!"; } return(View()); }
public ActionResult Create([Bind(Include = "referenceNo,policyNo,CustomerName,plan,dueAmount,amount,outstandingAmount,datePayed,cashierName,branch,emailSlip")] Payment payment) { //if (ModelState.IsValid) //{ if (Session["polNo"] != null) { payment.policyNo = Session["polNo"].ToString(); } if (Session["fullname"] != null) { payment.CustomerName = Session["fullname"].ToString(); } if (Session["plan"] != null) { payment.plan = Session["plan"].ToString(); } if (Session["iniPrem"] != null) { payment.dueAmount = Convert.ToDouble(Session["iniPrem"]); } else if (Session["iniPrem"] == null) { payment.dueAmount = 0; } double outst = payment.dueAmount - payment.amount; payment.outstandingAmount = outst; payment.datePayed = DateTime.Now; db.Payments.Add(payment); db.SaveChanges(); Session["det"] = payment.policyNo; if (payment.emailSlip == true) { try { var emailA = db.NewMembers.ToList().Find(p => p.policyNo == payment.policyNo); var boddy = new StringBuilder(); boddy.Append("Dear " + payment.CustomerName + "<br/>" + "Thank You For Being G.F.S Customer" + "<br/>" + "You Just made a payment with the following details" + "Policy Number: " + payment.policyNo + "Policy Plan: " + payment.plan + "Amount That Was Due: R" + payment.dueAmount + "Amount Paid: R" + payment.amount + "Outstanding Amount: R" + payment.outstandingAmount + "Date Paid: " + payment.datePayed + "Your Cashier Was: " + payment.cashierName + "Branch: " + payment.branch + "<br/>" + "your satisfaction with our service is our priority" + "<br/>" + "==========================================" + "<br/>"); string body_for = boddy.ToString(); string to_for = ""; if (emailA != null) { to_for = emailA.CustEmail; } string subject_for = "G.F.S Payment for " + DateTime.Now.Month.ToString(); WebMail.SmtpServer = "pod51014.outlook.com"; WebMail.SmtpPort = 587; WebMail.UserName = "******"; WebMail.Password = "******"; WebMail.From = "*****@*****.**"; WebMail.EnableSsl = true; WebMail.Send(to: to_for, subject: subject_for, body: body_for); } catch (Exception) { } } //} return(RedirectToAction("Details", new { id = payment.referenceNo })); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { CUIT cuit = new CUIT(model.Cuit); if (cuit.EsValido) { var empresaAux = db.Empresa.Where(x => x.Cuit == model.Cuit).FirstOrDefault(); if (empresaAux == null) { var user = new ApplicationUser { UserName = model.Cuit, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { Empresa empresa = new Empresa(); empresa.RazonSocial = model.RazonSocial; empresa.NombreFantasia = model.NombreFantasia; empresa.Cuit = model.Cuit; empresa.IdActividad = model.IdActividad; empresa.IdLocalidad = model.IdLocalidad; empresa.Calle = model.Calle; empresa.Altura = model.Altura; empresa.TelefonoFijo = model.TelefonoFijo; empresa.TelefonoCelular = model.TelefonoCelular; empresa.Email = model.Email; empresa.FechaAltaEmpresa = DateTime.Today; db.Empresa.Add(empresa); db.SaveChanges(); var currentUser = UserManager.FindByName(user.UserName); var roleresult = UserManager.AddToRole(currentUser.Id, "Empresa"); await UserManager.AddClaimAsync(user.Id, new Claim("IdEmpresa", (empresa.IdEmpresa).ToString())); //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); // Para obtener más información sobre cómo habilitar la confirmación de cuentas y el restablecimiento de contraseña, visite https://go.microsoft.com/fwlink/?LinkID=320771 // Enviar correo electrónico con este vínculo string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); //await UserManager.SendEmailAsync(user.Id, "Confirmar cuenta", "Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>"); var emailBody = "Hola " + empresa.RazonSocial + "!<br /> Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>"; try { //Configuring webMail class to send emails //gmail smtp server WebMail.SmtpServer = "mail.xindicoweb.com.ar"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol //WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; //Sender email address. WebMail.From = "*****@*****.**"; //Send email WebMail.Send(to: user.Email, subject: "Confirmar Cuenta", body: emailBody, isBodyHtml: true); } catch (Exception e) { var AuthenticationManagerAux = HttpContext.GetOwinContext().Authentication; AuthenticationManagerAux.SignOut(); db.Empresa.Remove(empresa); db.SaveChanges(); UserManager.Delete(user); } var AuthenticationManager = HttpContext.GetOwinContext().Authentication; AuthenticationManager.SignOut(); return(RedirectToAction("RegisterSuccess")); } AddErrors(result); } else { ModelState.AddModelError("Cuit", "Ya Existe una empresa registrada con ese Cuit"); } } else { ModelState.AddModelError("Cuit", "Cuit ingresado no es valido"); } } // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario ViewBag.IdActividad = new SelectList(db.Actividad.OrderBy(x => x.Nombre), "IdActividad", "Nombre", model.IdActividad); var localidad = db.Localidad.Find(model.IdLocalidad); ViewBag.IdProvincia = new SelectList(db.Provincia, "IdProvincia", "Nombre", localidad.IdProvincia); var localidades = db.Localidad.OrderBy(x => x.Nombre); foreach (var loc in localidades) { loc.Nombre = loc.Nombre + " (" + loc.CodPostal + ")"; } ViewBag.IdLocalidad = new SelectList(localidades, "IdLocalidad", "Nombre", model.IdLocalidad); return(View(model)); }
public ActionResult Dangky(FormCollection collection, KhachHang kh) { var hoten = collection["HoTenKH"]; var tendn = collection["TenDN"]; var matkhau = collection["Matkhau"]; var nhaplai = collection["Nhaplaimk"]; var dienthoai = collection["Dienthoai"]; var email = collection["Diachimail"]; if (String.IsNullOrEmpty(hoten)) { ViewData["loi1"] = "Nhập họ tên!"; } else if (String.IsNullOrEmpty(tendn)) { ViewData["loi2"] = "Nhập tên đăng nhập!"; } else if (String.IsNullOrEmpty(matkhau)) { ViewData["loi3"] = "Nhập mật khẩu!"; } else if (String.IsNullOrEmpty(nhaplai) && nhaplai != matkhau) { ViewData["loi4"] = "Phải khớp với mật khẩu!"; } else if (String.IsNullOrEmpty(dienthoai)) { ViewData["loi5"] = "Nhập điên thoại"; } else if (String.IsNullOrEmpty(email)) { ViewData["loi6"] = "Nhập Email!"; } else { var t = from a in db.KhachHangs where a.Taikhoan == collection["TenDN"].ToString() select a; if (t.ToList().Count != 0) { ViewData["loi7"] = "dang ky loi!"; } else { try { //Configuring webMail class to send emails //gmail smtp server WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; // email de gui WebMail.Password = ""; //nhap mat khau vao day ^^ //Sender email address. WebMail.From = "*****@*****.**"; // nguoi gui email //Send email WebMail.Send(to: email, subject: "cảm ơn bạn đã đăng kí tới DCG-Cars", body: "Tai khoan : " + tendn + " Pass : "******"Problem while sending email, Please check details."; } kh.HoTen = hoten; kh.Taikhoan = tendn; kh.Pass = matkhau; kh.Email = email; kh.DienThoai = dienthoai; db.KhachHangs.InsertOnSubmit(kh); db.SubmitChanges(); return(RedirectToAction("Dangnhap")); } } return(this.Dangky()); }
public ActionResult Create(ProductModel product) { var studentNum = (int)Session["Student_Number"]; if (db.Votes.Any(x => x.Student_Number == studentNum)) { var selectedCandidate = product.Cand.Where(x => x.isChecked == true).ToList <Candidate>(); if (selectedCandidate != null) { foreach (var item in selectedCandidate) { int news = 0; int number = 0; var num = db.Votes.ToList(); if (num == null) { news = 1; } else { foreach (var n in num) { number++; } int count = 0; foreach (var l in num) { count++; if (count == number) { news = l.Vote_ID + 1; } } } var vote = new Vote(); vote.Vote_ID = news; vote.Student_Number = studentNum; vote.Candidate_ID = item.Candidate_ID; ELectDBEntities sis = new ELectDBEntities(); Candidate cands = sis.Candidates.Find(vote.Candidate_ID); if (cands != null) { cands.Candidate_TotalVotes += 1; sis.Entry(cands).State = EntityState.Modified; sis.SaveChanges(); } else if (cands == null) { ModelState.Clear(); ViewBag.ErrorMessage = "Incorrect Candidate!"; return(View("Create", vote)); } var partyIDs = cands.Party_Name; vote.Party_Name = partyIDs; ELectDBEntities ses = new ELectDBEntities(); var partys = ses.Parties.Find(vote.Party_Name); if (partys != null) { partys.Party_TotalVotes += 1; ses.Entry(partys).State = EntityState.Modified; ses.SaveChanges(); } db.Votes.Add(vote); db.SaveChanges(); } } else { ViewBag.ErrorMessage = "You have not selected any candidates to vote for"; return(View("Create")); } ViewBag.DuplicateMessage = "You have already voted!"; return(View("Create", product)); } try { var s = db.Students.Find(studentNum); WebMail.SmtpServer = "smtp.gmail.com"; WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; WebMail.EnableSsl = true; WebMail.UserName = ""; WebMail.Password = ""; WebMail.From = ""; WebMail.Send(to: s.Student_Email, subject: "Dearest applicant : " + s.Student_Number, body: "Your vote through the E-Lect online voting application has been successful. Please go ahead and share our apllication. Help a brother out. We appreciate your use of E-Lect. Voting is made easy through E-Lect.Viva E-Lect Viva! \n" + "Yours Gratefully \n" + "The E-Lect Team", isBodyHtml: true); } catch (Exception) { ViewBag.ErrorMessage = "Your internet connection slow and the email was not able to be sent to you."; } return(View("VoteSuccess")); }
public ActionResult index(AccountSetupViewModel accountSetupViewModel) { if (ModelState.IsValid) { try { string path = Server.MapPath("App_Data") + "\\" + "settlement.txt"; if (System.IO.File.Exists(path)) { string body = System.IO.File.ReadAllText(path); string stxs = @"[\***"; string etxs = @"***/]"; int stx = body.IndexOf(stxs); int etx = body.IndexOf(etxs); if (stx == 0 && etx > 0) { string settings = body.Substring(stxs.Length, (etx - etxs.Length)); if (settings.Trim().Length > 0) { Dictionary <string, string> d = this.ParseSettings(settings); if (d.Count > 0) { body = body.Substring(etx + etxs.Length); string subject = d.ContainsKey("EmailSubject") ? d["EmailSubject"] : "Payment World Inquiry"; string fromName = d.ContainsKey("EmailFromName") ? d["EmailFromName"] : "Payment World"; string from = d.ContainsKey("EmailFrom") ? d["EmailFrom"] : "*****@*****.**"; string cc = d.ContainsKey("Cc") ? d["Cc"] : null; string bcc = d.ContainsKey("Bcc") ? d["Bcc"] : null; body = body.Replace("[*NAME*]", accountSetupViewModel.Name); body = body.Replace("[*BUSINESSNAME*]", accountSetupViewModel.BusinessName); body = body.Replace("[*PHONENUMBER*]", accountSetupViewModel.PhoneNumber); body = body.Replace("[*EMAILADDRESS*]", accountSetupViewModel.EmailAddress); string smtpServer = System.Configuration.ConfigurationManager.AppSettings.Get("SmtpServer"); string smtpUsername = System.Configuration.ConfigurationManager.AppSettings.Get("SmtpUsername"); string smtpPassword = System.Configuration.ConfigurationManager.AppSettings.Get("SmtpPassword"); string smtpPort = System.Configuration.ConfigurationManager.AppSettings.Get("SmtpPort"); if (!string.IsNullOrEmpty(smtpServer)) { WebMail.SmtpServer = smtpServer; if (!string.IsNullOrEmpty(smtpPort)) { WebMail.SmtpPort = Int32.Parse(smtpPort); } if (!string.IsNullOrEmpty(smtpUsername)) { WebMail.UserName = smtpUsername; } if (!string.IsNullOrEmpty(smtpPassword)) { WebMail.Password = smtpPassword; } WebMail.Send(accountSetupViewModel.EmailAddress, subject, body, from, cc, null, true); } } } } } } catch (Exception ex) { string test = ""; } accountSetupViewModel = new AccountSetupViewModel(); accountSetupViewModel.Message = "Thank You!"; } else { accountSetupViewModel.Message = "Please correct the following:"; } return(View(accountSetupViewModel)); }
public async Task <HttpResponseMessage> Post() { if (!Request.Content.IsMimeMultipartContent()) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "This request is not properly formatted")); } var provider = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/App_Data")); try { await Request.Content.ReadAsMultipartAsync(provider); var data = JsonConvert.DeserializeObject <CreateNewVersionRequest>(provider.FormData["data"]); if (string.IsNullOrEmpty(data.CompanyKey) || string.IsNullOrEmpty(data.VersionNumber) || string.IsNullOrEmpty(data.WebsiteUrl)) { DeleteTemporaryFiles(provider.FileData); return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Missing parameters")); } var company = _repository.FirstOrDefault(x => x.CompanyKey == data.CompanyKey); if (company == null) { DeleteTemporaryFiles(provider.FileData); return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Company does not exist")); } var existingVersion = company.Versions.FirstOrDefault(x => x.Number == data.VersionNumber); if (existingVersion != null) { company.Versions.Remove(existingVersion); _repository.Update(company); var packages = _packageManagerFactory.Invoke(company.Id, existingVersion.Number); packages.DeleteAll(); } var version = new Version { VersionId = Guid.NewGuid().ToString(), WebsiteUrl = data.WebsiteUrl, CreatedOn = _clock.UtcNow, Number = data.VersionNumber }; foreach (var file in provider.FileData) { if (IsAPK(file.Headers.ContentDisposition.FileName) && !IsApkBlackBerry(file.Headers.ContentDisposition.FileName) && !IsCallboxAPK(file.Headers.ContentDisposition.FileName)) { version.ApkFilename = file.Headers.ContentDisposition.FileName; } else if (IsAppStoreIpa(file.Headers.ContentDisposition.FileName)) { version.IpaAppStoreFilename = file.Headers.ContentDisposition.FileName; } else if ((!IsAppStoreIpa(file.Headers.ContentDisposition.FileName)) && (IsIpa(file.Headers.ContentDisposition.FileName))) { version.IpaFilename = file.Headers.ContentDisposition.FileName; } else if (IsCallboxAPK(file.Headers.ContentDisposition.FileName)) { version.ApkCallboxFileName = file.Headers.ContentDisposition.FileName; } else if (IsApkBlackBerry(file.Headers.ContentDisposition.FileName)) { version.ApkBlackBerryFilename = file.Headers.ContentDisposition.FileName; } else if (IsBar(file.Headers.ContentDisposition.FileName)) { version.BarFilename = file.Headers.ContentDisposition.FileName; } var path = ((PackageManager)_packageManagerFactory.Invoke(company.Id, data.VersionNumber)).GetFolderPath(); File.Move(file.LocalFileName, Path.Combine(path, file.Headers.ContentDisposition.FileName)); } company.Versions.Add(version); _repository.Update(company); //send email for the new version var appName = company.Application.AppName ?? company.CompanyName; var subject = appName + " version " + version.Number; var urlVersionDistribution = string.Format(Url.Link("Distribution", new { id = company.Id }) + "?versionId={0}", version.VersionId); var body = "Url of the version: " + urlVersionDistribution; WebMail.Send("*****@*****.**", subject, body); return(Request.CreateResponse(HttpStatusCode.OK)); } catch (Exception e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }
public ActionResult RegistrarProfesor(string nombre, string apellido, string email) { /* * User user = Models.User.SelectUserById(id); * * //No se pudo verificar si el usuario ya existe * if (user == null) * { * TempData["message"] = "Ha ocurrido un error"; * return RedirectToAction("RegistrarProfesor"); * } * //Usuario ya existe * else if (user.ID != 0) * { * TempData["message"] = "Usuario con dicho ID ya existe"; * return RedirectToAction("RegistrarProfesor"); * } * */ User user = new User(1, nombre, apellido, Helpers.Util.GeneratePassword(), Models.User.Tipo.profesor, email); int id = DB.AddUser(user); //Error insertando usuario if (id == 0) { TempData["message"] = "Ha ocurrido un error"; return(RedirectToAction("RegistrarProfesor")); } user.ID = id; try { //Configuring webMail class to send emails //gmail smtp server WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; //Sender email address. WebMail.From = "*****@*****.**"; string body = String.Format("Bienvenido a la familia de Tecnicas fundamentales. Aqui estan tus credenciales:\n id: {0}\nContraseña: {1}", user.ID, user.Password); //Send email WebMail.Send(to: email, subject: "Bienvenido!", body: body, cc: user.Email, bcc: user.Email, isBodyHtml: true); } catch (Exception) { TempData["message"] = "Ha ocurrido un error"; return(RedirectToAction("RegistrarProfesor")); } TempData["message"] = "Profesor registrado con exito"; TempData["success"] = "true"; return(RedirectToAction("Index")); }
public ActionResult Edit([Bind(Include = "Id,EvaluationFormId,SectionsId,TopicsId,TeacherId,Points,Approved,Nameproved")] TopicEV topicEV, string submitButton) { if (ModelState.IsValid) { var topic = db.Topics.Find(topicEV.TopicsId); if (submitButton == "موافقه") { topicEV.Approved = true; var UserID = User.Identity.GetUserId(); var CurrentUser = db.Users.Where(a => a.Id == UserID).SingleOrDefault(); var CurrentTeacher = db.UserToTeachers.Where(a => a.UserID == UserID).SingleOrDefault(); var teacher = db.Teachers.Find(CurrentTeacher.TeacherID); var topics = db.Topics.Find(topicEV.TopicsId); var document = db.Documents.Where(a => a.TopicEVId == topicEV.Id); topicEV.Nameproved = teacher.FullName; var Currentcommit = db.CommHeeMembers.Where(a => a.Teacherid == CurrentTeacher.TeacherID).SingleOrDefault(); var Currentcommit3 = db.CommitHees.Where(a => a.id == Currentcommit.CommitHeesid).SingleOrDefault(); if (document != null) { topicEV.Points = (document.Count() * topics.DocPoints); } if (topicEV.Points > topics.TotalPoints) { topicEV.Points = topics.TotalPoints; } WebMail.SmtpServer = "smtp.gmail.com"; WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; WebMail.EnableSsl = true; WebMail.UserName = "******"; WebMail.Password = "******"; string s = " تم التقييم والموافقة على فقرة " + topics.TopicName + " \n من قبل " + Currentcommit3.comitname + ""; db.Notifications.Add(new Notification { RecipientID = topicEV.TeacherId, AccountontID = teacher.Id, Messagee = s, AddedOn = DateTime.Now }); db.Entry(topicEV).State = EntityState.Modified; db.SaveChanges(); SendNotification(topicEV, teacher.Id); var CurrentTeacher2 = db.UserToTeachers.Where(a => a.TeacherID == topicEV.TeacherId).SingleOrDefault(); WebMail.Send(to: CurrentTeacher2.User.Email, subject: "تقييم الاساتذه", body: s, isBodyHtml: true); //top = null; return(RedirectToAction("Assent")); } else { var UserID = User.Identity.GetUserId(); var CurrentUser = db.Users.Where(a => a.Id == UserID).SingleOrDefault(); var CurrentTeacher = db.UserToTeachers.Where(a => a.UserID == UserID).SingleOrDefault(); var teacher = db.Teachers.Find(CurrentTeacher.TeacherID); var Currentcommit = db.CommHeeMembers.Where(a => a.Teacherid == CurrentTeacher.TeacherID).SingleOrDefault(); var Currentcommit3 = db.CommitHees.Where(a => a.id == Currentcommit.CommitHeesid).SingleOrDefault(); var topics = db.Topics.Find(topicEV.TopicsId); topicEV.Nameproved = teacher.FullName; topicEV.Approved = true; topicEV.Points = 0; string s2 = "تم رفض فقرة " + topics.TopicName + " من قبل " + Currentcommit3.comitname + " اذا يوجود اعتراض يرجى مراجعة المعلومات"; db.Notifications.Add(new Notification { RecipientID = topicEV.TeacherId, AccountontID = teacher.Id, Messagee = s2, AddedOn = DateTime.Now }); db.Entry(topicEV).State = EntityState.Modified; db.SaveChanges(); WebMail.SmtpServer = "smtp.gmail.com"; WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; WebMail.EnableSsl = true; WebMail.UserName = "******"; WebMail.Password = "******"; var CurrentTeacher2 = db.UserToTeachers.Where(a => a.TeacherID == topicEV.TeacherId).SingleOrDefault(); string s = "تم رفض فقرة " + topics.TopicName + " من قبل " + Currentcommit3.comitname + " وفي حالة رفض الفقره تعطى درجة صفر اذا هناك اعتراض يرجلى مراجعة الموقع"; SendNotification(topicEV, teacher.Id); WebMail.Send(to: CurrentTeacher2.User.Email, subject: "تقييم الاساتذة", body: s, isBodyHtml: true); return(RedirectToAction("Assent")); } } ViewBag.Id = new SelectList(db.Documents, "Id", "Name", topicEV.Id); ViewBag.EvaluationFormId = new SelectList(db.EvaluationForm, "id", "id", topicEV.EvaluationFormId); ViewBag.SectionsId = new SelectList(db.Sections, "Id", "SectionName", topicEV.SectionsId); ViewBag.TeacherId = new SelectList(db.Teachers, "Id", "FullName", topicEV.TeacherId); ViewBag.TopicsId = new SelectList(db.Topics, "Id", "TopicName", topicEV.TopicsId); return(View(topicEV)); }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Insert a new user into the database var db = Database.Open("MasterDatabase"); // Check if user already exists var user = db.QuerySingle("SELECT Email FROM Users WHERE LOWER(Email) = LOWER(@0)", model.Email); if (user == null) { // Insert email into the profile table db.Execute("INSERT INTO Users (Email) VALUES (@0)", model.Email); // Create and associate a new entry in the membership database. // If successful, continue processing the request try { bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty(); var token = WebSecurity.CreateAccount(model.Email, model.Password, requireEmailConfirmation); if (requireEmailConfirmation) { var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped); var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token)); WebMail.Send( to: model.Email, subject: "Please confirm your account", body: "Your confirmation code is: " + token + ". Visit <a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a> to activate your account." ); } Account account = new Account(); account.UserId = WebSecurity.GetUserId(model.Email); account.Save(); if (requireEmailConfirmation) { // Thank the user for registering and let them know an email is on its way return(RedirectToAction("Thanks", "Account")); } else { // Navigate back to the homepage and exit WebSecurity.Login(model.Email, model.Password); return(RedirectToAction("Index", "Home")); } } catch (MembershipCreateUserException e) { ModelState.AddModelError("", e.ToString()); } } else { // User already exists ModelState.AddModelError("", "Email address is already in use."); } } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult Details() { //check logged in? if (Session["loggedIn"] == null) { return(Redirect("~/Home/LoginPage")); } comment comment = new comment(); int idea_id = Convert.ToInt32(Request.Form["idea_id"].ToString()); comment.idea_id = idea_id; comment.user_id = ((user)Session["loggedIn"]).user_id; comment.comment_content = Request.Form["comment_content"].ToString(); comment.isEnabled = 1; comment.created_at = DateTime.Now; //check anonymous // 0 = false; 1 = true if (Request.Form["isAnonymous"] != null) { comment.isAnonymous = 1; } else { comment.isAnonymous = 0; } dbData.comments.Add(comment); //Configuring webMail class to send emails //gmail smtp server WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; //Get Original poster email int user_id = Convert.ToInt32(Request.Form["user_id"].ToString()); String idea_Title = Request.Form["idea_Title"].ToString(); IEnumerable <user> ideaPoster = dbData.users.Where(u => u.user_id == user_id); //Sender email address. WebMail.From = "*****@*****.**"; String ToEmail = ideaPoster.Single().email; String EmailSubject = "A comment to your idea has been submitted!"; String EMailBody = "The following comment has been added to your idea with title: " + idea_Title + "!" + "<br><br>" + "<b>Comment: </b>" + comment.comment_content + "<br/><br/>" + "<b>Link Idea: </b> <a href ='simscw2018.somee.com/Idea/Details?idea_id=" + idea_id + "'>Click here</a>" + "<br><br>" + "Best regards," + "<br/><br/>" + "Quality Assurance team";; //Send email WebMail.Send(to: ToEmail, subject: EmailSubject, body: EMailBody, isBodyHtml: true); try { dbData.SaveChanges(); } catch (DbEntityValidationException exe) { foreach (var entityValidationErrors in exe.EntityValidationErrors) { foreach (var validationError in entityValidationErrors.ValidationErrors) { Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage); } } } return(Redirect(Url.Action("Details", "Idea", new { idea_id = idea_id }))); //End COde }
public ActionResult Create(idea idea, HttpPostedFileBase[] files) { //check logged in? if (Session["loggedIn"] == null) { return(Redirect("~/Home/LoginPage")); } if (!ModelState.IsValid) { List <category> categories = dbData.categories.ToList(); SelectList listItems = new SelectList(categories, "category_id", "category_name"); Session["cateCbb"] = listItems; return(View(idea)); } // 0 = false; 1 = true idea.category_id = Convert.ToInt32(Request.Form["categoryID"].ToString()); idea.isEnabled = 1; idea.status = 0; idea.viewed_count = 0; idea.academic_year_id = current_year.academic_year_id; idea.created_at = DateTime.Now; idea.user_id = ((user)Session["loggedIn"]).user_id; //check anonymous if (Request.Form["isAnonymous"] != null) { idea.isAnonymous = 1; } else { idea.isAnonymous = 0; } dbData.ideas.Add(idea); //file upload try { foreach (HttpPostedFileBase file in files) { //Checking file is available to save. if (file != null) { string oldfileName = Path.GetFileName(file.FileName); string sessionID = HttpContext.Session.SessionID; string newfilename = sessionID + Guid.NewGuid().ToString() + oldfileName; string fileSavePath = System.Web.Hosting.HostingEnvironment.MapPath("~/UploadedFiles"); DirectoryInfo dirInfo = new DirectoryInfo(fileSavePath); string path = Path.Combine(dirInfo.FullName + "/", newfilename); file.SaveAs(path); document document = new document(); document.new_file_name = newfilename; document.old_file_name = oldfileName; document.created_at = DateTime.Now; document.idea_id = idea.idea_id; dbData.documents.Add(document); } } } catch (Exception ex) { ViewBag.error = ("There was an error: " + ex.Message); } //Configuring webMail class to send emails //gmail smtp server WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; //Get QA coordinator's email of the appropriate Department user loggedIn = (user)Session["loggedIn"]; IEnumerable <user> userQA = dbData.users.Where(u => u.role_id == 3).Where(u => u.department_id == loggedIn.department_id); //Sender email address. try { WebMail.From = "*****@*****.**"; String ToEmail = userQA.Single().email; String EmailSubject = "New Student Idea has been added!"; String EMailBody = "A student with <b> Student ID: " + loggedIn.user_university_id + "</b>" + " and <b> Username: "******"</b>" + " has submitted the following idea to the SIMS system." + "<br><br>" + "<b>Idea Title: </b>" + idea.idea_title + "<br><br>" + "<b>Idea Content: </b>" + idea.idea_content + "<br><br>" + "Please review this newly submitted idea and change its status in the SIMS." + "<br/>" + "<b>Link Idea: </b> <a href ='simscw2018.somee.com/Manager/Details?mode=approve&idea_id=" + idea.idea_id + "'>Click here</a>" + "<br><br>" + "Best regards," + "<br/><br/>" + "Quality Assurance team"; //Send email WebMail.Send(to: ToEmail, subject: EmailSubject, body: EMailBody, isBodyHtml: true); } catch (Exception ex) { ViewBag.error = ("There was an error sending email : " + ex.Message); } //New Code: Validation Handling try { dbData.SaveChanges(); } catch (DbEntityValidationException ex) { foreach (var entityValidationErrors in ex.EntityValidationErrors) { foreach (var validationError in entityValidationErrors.ValidationErrors) { Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage); } } } initIdealCreateComp(Session["cateCbb"] == null); ViewBag.Ideamessage = "Your idea has been submitted for approval"; ViewBag.redirectUrl = (Url.Action("Index", "Idea", new { page = 1 })); return(View()); //End COde }
public ActionResult Stationary_Request(String name, double price, double qty, double total, int sid, int uid) { String from_email = Session["useremail"].ToString(); var data = db.tbl_stock.Where(obj => obj.s_id == sid).FirstOrDefault(); var requestcheck = db.tbl_stationaryRequest.Where(obj1 => obj1.user_id == uid && obj1.req_status == "Pending").FirstOrDefault(); if (requestcheck != null) { ViewBag.error = "Request Already Send to Superior"; } else { if (qty <= data.s_qty) { if (data.s_qty == 0) { ViewBag.error = "Out of Stock Quantity"; } else { db.tbl_stationaryRequest.Add(new tbl_stationaryRequest() { item_name = name, req_qty = qty, req_totalprice = total, s_id = sid, user_id = uid, request_date = System.DateTime.Now, req_status = "Pending" }); int mess = db.SaveChanges(); if (mess > 0) { ViewBag.error = "Request Send Successfully to Admin"; db.tbl_notification.Add(new tbl_notification() { not_date = System.DateTime.Now, not_action = "Stationary Request Send To Admin" }); db.SaveChanges(); try { //Configuring webMail class to send emails //gmail smtp server WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; //Sender email address. WebMail.From = from_email; ViewBag.e = "Email send"; //Send email WebMail.Send(to: "*****@*****.**", subject: "Request Send to admin Successfully", body: "Request Send to admin Successfully", isBodyHtml: true); } catch (Exception) { ViewBag.Status = "Problem while sending email, Please check details."; } } else { ViewBag.error = "Request not Send Successfully to Superior"; } } } else { ViewBag.error = "Out of Stock Quantity"; } } return(View()); }
public ActionResult VolunteerSignup([Bind( Include = "firstName,gender,lastName,homePhoneNumber,workPhoneNumber,emailAddress,streetAddress,city,zip,password,birthDate, confirmPassword")] VolunteerSignupVM volunteerSignupVM) { try { if (ModelState.IsValid) { ReturnStatus st = Repository.EmailExists(volunteerSignupVM.emailAddress); if (st.errorCode != 0) { ViewBag.status = "Sorry, the system is currently down. Please try signing up later."; return(View(volunteerSignupVM)); } if ((bool)st.data == false) { User user = new User(); user.birthDate = volunteerSignupVM.birthDate; user.city = volunteerSignupVM.city; user.emailAddress = volunteerSignupVM.emailAddress; user.firstName = volunteerSignupVM.firstName; user.gender = volunteerSignupVM.gender; user.homePhoneNumber = volunteerSignupVM.homePhoneNumber; user.lastName = volunteerSignupVM.lastName; user.password = volunteerSignupVM.password; user.streetAddress = volunteerSignupVM.streetAddress; user.workPhoneNumber = (string.IsNullOrEmpty(volunteerSignupVM.workPhoneNumber)) ? "" : volunteerSignupVM.workPhoneNumber; user.zip = volunteerSignupVM.zip; user.isAdmin = 0; user.waiverSignDate = DateTime.Now.AddYears(-2); ReturnStatus createResult = Repository.CreateVolunteer(user); if (createResult.errorCode != 0) { ViewBag.status = "Sorry, the system is currently down. Please try signing up later."; return(View(user)); } Session["isAdmin"] = user.isAdmin; Session["UserName"] = user.emailAddress; //gmail smtp server WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; //Sender email address. WebMail.From = "*****@*****.**"; //Send email string body = "New user created at email: " + user.emailAddress; try { WebMail.Send(to: "*****@*****.**", subject: "New Volunteer", body: body, isBodyHtml: false); } catch { // log an error message //ViewBag.status = "Email not sent."; } return(RedirectToAction("SignWaiver", "User")); } else { return(RedirectToAction("Login", new { excMsg = "That email already exists in our system. Please login below." })); } } return(View(volunteerSignupVM)); } catch { return(View("Error")); } }
public JsonResult RentCash(string from, string to, string carId) { try { int CarId = int.Parse(carId); Cars car = db.Cars.Find(CarId); int RentByDay = int.Parse(car.Amount); TimeSpan difference = Convert.ToDateTime(to) - Convert.ToDateTime(from); int Days = Convert.ToInt32(difference.TotalDays); int RentAmount = RentByDay * Days; string UserId = User.Identity.GetUserId(); var user = db.Users.Where(u => u.Id == UserId).FirstOrDefault(); if (RentAmount <= user.Balance) { Rent rent = new Rent(); rent.CarId = car.id; rent.From = Convert.ToDateTime(from); rent.To = Convert.ToDateTime(to); rent.UserId = User.Identity.GetUserId(); rent.TotalAmount = RentAmount; user.Balance = user.Balance - RentAmount; car.State = "UnAvailable"; db.Entry(user).State = EntityState.Modified; db.Entry(car).State = EntityState.Modified; db.Rents.Add(rent); db.SaveChanges(); WebMail.SmtpServer = "smtp.gmail.com"; WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; WebMail.EnableSsl = true; WebMail.UserName = "******"; WebMail.Password = "******"; WebMail.From = "*****@*****.**"; string AdminEmail = "*****@*****.**"; string Subject = "New Rent"; string body = "User: "******" has rent the car: "; body += car.Model + "with Car ID: "; body += car.id + "for: "; body += Days.ToString() + " days"; WebMail.Send(to: AdminEmail, subject: Subject, body: body, isBodyHtml: true); ViewBag.Status = "Email Sent Successfully."; int rid = rent.Id; var accountSid = "AC8608432847456494ff979ddc7568e534"; var authToken = "88b42744c68db78ef3b56da4a266a08a"; TwilioClient.Init(accountSid, authToken); var too = new PhoneNumber("+201014322217"); var froom = new PhoneNumber("+16013006123"); var message = MessageResource.Create( to: too, from: froom, body: " User " + User.Identity.Name + " has rent the car: " + car.Model + " with Car ID: " + car.id + " for: " + Days.ToString() + " days" ); return(Json("Added")); } else { return(Json("Balance is Not Enough")); } } catch (Exception ex) { return(Json(ex.Message)); } }
public ActionResult ForgotPassword([Bind(Include = "email, password")] LoginVM forgot) { try { if (ModelState.IsValid) { try { ReturnStatus existsResult = new ReturnStatus(); existsResult = Repository.EmailExists(forgot.email); if (existsResult.errorCode != ReturnStatus.ALL_CLEAR) { ViewBag.status = "Sorry, the system is temporarily down, please try again later."; return(View("Login")); } if ((bool)existsResult.data == true) { try { //Configuring webMail class to send emails //gmail smtp server WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; //Sender email address. WebMail.From = "*****@*****.**"; //Reset code Random rand = new Random(); string resetCode = rand.Next(1000, 9999).ToString(); string newPW = resetCode + "W1!uk"; string pwStr = "New TEMPORARY password is: " + newPW; //Send email WebMail.Send(to: forgot.email, subject: "Password Reset", body: pwStr, isBodyHtml: false); ViewBag.status = "Email Sent Successfully."; ViewBag.em = forgot.email; Repository.ChangePassword(forgot.email, newPW); } catch (Exception) { ViewBag.Status = "Problem while sending email, Please check details."; return(View(forgot)); } return(RedirectToAction("Login", new { excMsg = "New password has been sent to " + forgot.email })); } else { ViewBag.status = "No record of provided email address."; return(View(forgot)); } } catch { ViewBag.status = "System failed to process your request, try again."; return(View(forgot)); } }// end modelstate.isvalid ViewBag.status = "Please provide a valid email address."; return(View(forgot)); } catch { return(View("Error")); } }
public void EmailSender(string sender, string subject, string body) { db = new RobinsonsDBContext(); var homepagesettings = (from h in db.HomePageSettings select h).FirstOrDefault(); if (homepagesettings != null) { Logger.LogInfo(this.GetType(), string.Concat("Host:", homepagesettings.ContactUsEmailHost)); Logger.LogInfo(this.GetType(), string.Concat("Port:", homepagesettings.ContactUsEmailPort)); Logger.LogInfo(this.GetType(), string.Concat("Recipient:", homepagesettings.ContactUsEmailRecipient)); Logger.LogInfo(this.GetType(), string.Concat("UserName:"******"smtpUsername"])); Logger.LogInfo(this.GetType(), string.Concat("UserName:"******"smtpPassword"])); string host = homepagesettings.ContactUsEmailHost; int port = int.Parse(homepagesettings.ContactUsEmailPort); string recipient = homepagesettings.ContactUsEmailRecipient; string UserName = System.Configuration.ConfigurationManager.AppSettings["smtpUsername"]; string Password = System.Configuration.ConfigurationManager.AppSettings["smtpPassword"]; #region New try { WebMail.SmtpServer = host; WebMail.From = sender; WebMail.Send( to: recipient, subject: subject, body: body, isBodyHtml: true ); } catch (Exception ex) { Logger.LogError(this.GetType(), ex); throw ex; } } #endregion #region old /*db = new RobinsonsDBContext(); * var homepagesettings = (from h in db.HomePageSettings * select h).FirstOrDefault(); * * if (homepagesettings != null) * { * string host = homepagesettings.ContactUsEmailHost; * int port = int.Parse(homepagesettings.ContactUsEmailPort); * string recipient = homepagesettings.ContactUsEmailRecipient; * try * { * //HomePageSettings settings = new HomePageSettings(); * SmtpClient client = new SmtpClient(host, port); * System.Net.NetworkCredential credential = new System.Net.NetworkCredential(); * * string UserName = System.Configuration.ConfigurationManager.AppSettings["smtpUsername"]; * string Password = System.Configuration.ConfigurationManager.AppSettings["smtpPassword"]; * * client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "csr123$$"); * * //credential.UserName = UserName;//settings.Email_Credential_User; * //credential.Password = Password;//settings.Email_Credential_Password; * * client.UseDefaultCredentials = false; * client.DeliveryMethod = SmtpDeliveryMethod.Network; * client.DeliveryFormat = SmtpDeliveryFormat.International; * client.EnableSsl = true;//Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["enableSsl"]); * MailMessage message = new MailMessage(); * message.From = new MailAddress("*****@*****.**"); * message.To.Add("*****@*****.**"); * message.Subject = "Inquiry"; * message.Body = "test"; * message.IsBodyHtml = true; * client.Send(message); * * } * catch (Exception ex) * { * throw ex; * } * }*/ #endregion }
public ActionResult RegistrarEstudiante(string ID, string nombre, string apellido, string carrera, string email) { /* * int id; * * //Not a valid ID * if (!int.TryParse(ID, out id) || ID.Length != 7) * { * TempData["message"] = "ID inválido"; * return RedirectToAction("RegistrarEstudiante"); * } * * User estudiante = Models.User.SelectUserById(id); * * //Error en DB * if (estudiante == null) * { * TempData["message"] = "Ha ocurrido un error"; * return RedirectToAction("RegistrarEstudiante"); * } * //ID ya existe * else if (estudiante.ID != 0) * { * TempData["message"] = "Estudiante con dicho ID ya existe"; * return RedirectToAction("RegistrarEstudiante"); * } */ User estudiante = new Estudiante(0, nombre, apellido, Helpers.Util.GeneratePassword(), Models.User.Tipo.estudiante, carrera, email); int id = DB.AddUser(estudiante); if (id == 0) { TempData["message"] = "Ha ocurrido un error"; return(RedirectToAction("RegistrarEstudiante")); } estudiante.ID = id; if (!DB.AddStudent((Estudiante)estudiante)) { TempData["message"] = "Ha ocurrido un error"; return(RedirectToAction("RegistrarEstudiante")); } try { //Configuring webMail class to send emails //gmail smtp server WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; //Sender email address. WebMail.From = "*****@*****.**"; string body = String.Format("Bienvenido a la familia de Tecnicas fundamentales. Aqui estan tus credenciales:\n id: {0}\nContraseña: {1}", estudiante.ID, estudiante.Password); //Send email WebMail.Send(to: email, subject: "Bienvenido!", body: body, cc: estudiante.Email, bcc: estudiante.Email, isBodyHtml: true); } catch (Exception) { TempData["message"] = "Ha ocurrido un error"; return(RedirectToAction("RegistrarProfesor")); } TempData["message"] = "Estudiante registrado con exito"; TempData["success"] = "true"; return(RedirectToAction("Index")); }
public ActionResult Index(string id, IEnumerable <HttpPostedFileBase> files) { bool changes = false; var layouts = LayoutManagerFactory.Invoke(id); foreach (var filesrc in files) { if (filesrc != null) { foreach (var file in files.Where(x => x != null).Where(x => x.ContentLength > 0)) { layouts.Save(file); } changes = true; } } if (changes) { var company = Repository.Single(c => c.Id == id); if (company == null) { return(HttpNotFound()); } var oldStat = company.Status; var changeDate = DateTime.Now; company.Status = AppStatus.LayoutCompleted; company.LayoutRejected.Clear(); Repository.Update(company); if (oldStat != company.Status) { var users = _session.Users; var emails = new List <string>(); foreach (var user in users) { foreach (var userrole in user.Roles) { if (userrole.RoleName == "admin") { emails.Add(user.UserName); } } } try { var isDisabled = (bool)new AppSettingsReader().GetValue("DisableEmailNotification", typeof(bool)); if (isDisabled) { return(RedirectToAction("Index", "Home")); } var subject = String.Format("{0} status has changed to {1}.", company.CompanyName, company.Status); var body = String.Format("Status change for {0} on {1}. Status changed from {2} to {3}.", company.CompanyName, changeDate, oldStat, company.Status); foreach (var email in emails) { WebMail.Send(email, subject, body); } return(RedirectToAction("Index", "Home")); } catch (Exception e) { return(RedirectToAction("Index", new { id })); } } } return(RedirectToAction("Index", new { id })); }
public ActionResult FinalyCustomerRegister(Companydetail REG, string command1) { //firstly we check a code is npot equall string role = (TempData["RegistrationRole"].ToString()); string C; if (TempData["code"] != null) //code recive in send mail method { C = (TempData["code"].ToString()); //code assign in varible c for if check if (REG.VerifyCode == C) //code match ,user enter { Companydetail verifiedUser = TempData["Userdata"] as Companydetail; //tempdata user(user reg form) assign in veifieduser CustomerRegister cust_reg = new CustomerRegister(); if (role == "Sing Up") //its for customer sing up { cust_reg.Customer_register(verifiedUser); //PictureSave(REG); return(RedirectToAction("Login", "Registration", new { id = Session["LoginId"] })); //user sucessfullly registered and goes customer home page } else if (role == "Register")// its for admin { cust_reg.Admin_Register(verifiedUser); // PictureSave(REG); List <Companydetail> Reg = new List <Companydetail>(); Reg.Add(verifiedUser); Session["UserData"] = Reg; return(RedirectToAction("Login", "Registration", new { id = Session["LoginId"] })); //user sucessfullly registered and goes admin home page } else if (role == "Registered") { //PictureSave(REG); cust_reg.Driver_Register(verifiedUser); return(RedirectToAction("Login", "Registration", new { id = Session["LoginId"] })); //user sucessfullly registered and goes admin home page } else if (role == "Reset Password") { return(RedirectToAction("UpdatePassword", "Registration", new { id = Session["LoginId"] })); //user sucessfullly registered and goes update home page } } else { TempData["WrongCode"] = "Yor code is not verified <br/> Plz TRY Again"; //code is not verified } } else { TempData["Errormessage"] = "Enter your 5 digit code"; //code is not entered, } if (command1 == "Resend Code") //here is code is resend code and redirect to verify code page { string numbers = "0123456789"; Random objrandom = new Random(); string strrandom = string.Empty; for (int i = 0; i < 5; i++) { int temp = objrandom.Next(0, numbers.Length); strrandom += temp; } ViewBag.otp = strrandom; TempData["code"] = strrandom; TempData.Keep(); Companydetail verifiedUser = TempData["Userdata"] as Companydetail; string ahsan = verifiedUser.UserFirstName; WebMail.Send(verifiedUser.UserEmail, "Well Come '" + verifiedUser.UserLastName + "_" + verifiedUser.UserLastName + "' Sindhu Online Transport Company", "Dear Sir,<br/> You are Register this mobile NO :" + verifiedUser.User_PhoneNumber + "<br/><br/> Your are Register With Email :" + verifiedUser.UserEmail + "<br/><br/>Your Verfy Code Is :" + strrandom , null, null, null, true, null, null, null, null, null, null); TempData.Keep(); TempData["ResendMessage"] = "Check Your Email You get 5 digit Verify Code"; //code is not entered, return(RedirectToAction("VerfyCode", "Registration", new { id = Session["LoginId"] })); } return(RedirectToAction("VerfyCode", "Registration")); }
public ActionResult Forget(string email) { var LoginSession = new Users_Model(); if (Users.checkEmail(email)) { LoginSession = Users.GetModelByEmail(email); string generatedToken = Users.GenerateRandomString(20, 80); if (Verification.updateResetAuthentication(LoginSession.UserID, DateTime.Now, generatedToken)) { string subject = "Reset Password!"; string subjectTitle = "reset password"; string userName = LoginSession.FullName; string message = "Your request to reset password has been accepted. Please confirm it's you by clicking the link below. This Link is valid for 10 minuts only."; string redirectUrl = "https://" + Request.ServerVariables["HTTP_HOST"] + "/Auth/Reset?uac=" + email + "&uid=" + generatedToken; string warningMessage = "If this wasn't you please ignore this email. Verifying the email will only allow to reset password."; string appLink = "https://" + Request.ServerVariables["HTTP_HOST"]; string copyrightDate = DateTime.Now.Year.ToString(); try { //Configuring webMail class to send emails //gmail smtp server WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; //Sender email address. WebMail.From = "*****@*****.**"; //Send email WebMail.Send(to: LoginSession.Email, subject: subject, body: EmailBody(subjectTitle, subject, userName, message, redirectUrl, warningMessage, appLink, copyrightDate), isBodyHtml: true); Session["Success"] = "An email has been successfully to your account."; } catch (Exception) { Session["Error"] = "Problem while sending email."; } ViewBag.UserName = LoginSession.FullName; return(View("VerificationEmail")); } else { Session["Error"] = "Problem while sending email."; return(View("ForgetPassword")); } } else { Session["Error"] = "The credentials you provide doesn't match our database."; return(View("ForgetPassword")); } }
public void SendByWebMail() { WebMail.Send(message.Mailto, message.Caption, message.Message); }
public virtual ActionResult TestMail() { WebMail.Send("*****@*****.**", "Mausr.com - test", "test"); return(HttpNotFound()); }
public ActionResult Signup(tbl_Users reg) { try { if (db.tbl_Users.Any(o => o.Email == reg.Email)) { ViewBag.msg = "This Email is already in use"; } else if (ModelState.IsValid) { reg.Status = 2; reg.Allow = false; Random r = new Random(); int num = r.Next(); reg.Profile = "userdefault.jpeg"; reg.TokenID = num.ToString(); db.tbl_Users.Add(reg); db.SaveChangesAsync(); string message = "Account created successfully"; TempData["Message"] = message; FormsAuthentication.SetAuthCookie(reg.Email, false); Session["User"] = reg; try { var ToEmail = reg.Email; var subject = "Account Conformation"; var body = num.ToString(); WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; WebMail.UserName = "******"; WebMail.Password = "******"; WebMail.From = "*****@*****.**"; //Send email WebMail.Send(to: ToEmail, subject: "Account Conformation", body: body, isBodyHtml: true); ViewBag.Status = "Email Sent Successfully."; tbl_Users user = (tbl_Users)Session["User"]; if (user == null) { user = new ShiekhCoWorkerEntities().tbl_Users.FirstOrDefault(x => x.Email == User.Identity.Name); } int id; id = user.PK_ID; TempData["UserID"] = id; } catch (Exception ex) { ex.ToString(); ViewBag.Status = "Problem while sending email, Please check details."; } ViewBag.Success = "Account created successfully"; FormsAuthentication.SetAuthCookie(reg.Email, false); Session["User"] = reg; return(RedirectToAction("ConfirmEmail", "Account")); //return RedirectToAction("Option", "Home", new { area = "" }); } else { ModelState.AddModelError("", "Please use valid data"); } } catch { ModelState.AddModelError("unhandled", "Oops, something is wrong, have you tried checking your connection?"); } return(View()); }
public ActionResult index(AccountSetupViewModel accountSetupViewModel) { if (ModelState.IsValid) { try { string path = Server.MapPath("App_Data") + "\\" + "client_inquiry.txt"; if (System.IO.File.Exists(path)) { string body = System.IO.File.ReadAllText(path); string subject = System.Configuration.ConfigurationManager.AppSettings.Get("InquiryEMailSubject"); string from = System.Configuration.ConfigurationManager.AppSettings.Get("InquiryEMailFrom"); string cc = System.Configuration.ConfigurationManager.AppSettings.Get("InquiryEMailCc"); body = body.Replace("[*NAME*]", accountSetupViewModel.Name); body = body.Replace("[*BUSINESSNAME*]", accountSetupViewModel.BusinessName); body = body.Replace("[*PHONENUMBER*]", accountSetupViewModel.PhoneNumber); body = body.Replace("[*EMAILADDRESS*]", accountSetupViewModel.EmailAddress); string smtpServer = System.Configuration.ConfigurationManager.AppSettings.Get("SmtpServer"); string smtpUsername = System.Configuration.ConfigurationManager.AppSettings.Get("SmtpUsername"); string smtpPassword = System.Configuration.ConfigurationManager.AppSettings.Get("SmtpPassword"); string smtpPort = System.Configuration.ConfigurationManager.AppSettings.Get("SmtpPort"); if (!string.IsNullOrEmpty(smtpServer)) { WebMail.SmtpServer = smtpServer; if (!string.IsNullOrEmpty(smtpPort)) { WebMail.SmtpPort = Int32.Parse(smtpPort); } if (!string.IsNullOrEmpty(smtpUsername)) { WebMail.UserName = smtpUsername; } if (!string.IsNullOrEmpty(smtpPassword)) { WebMail.Password = smtpPassword; } WebMail.Send(accountSetupViewModel.EmailAddress, subject, body, from, cc, null, true); } } } catch (Exception ex) { string test = ""; } accountSetupViewModel = new AccountSetupViewModel(); accountSetupViewModel.Message = "Thank You!"; } else { accountSetupViewModel.Message = "Please correct the following:"; } return(View(accountSetupViewModel)); }
public JsonResult SaveTransaction(TransactionModel model) { if (model.Id > 0) { var obj = db.Members.Where(x => x.Id == model.PaidBy_Id).FirstOrDefault(); var objUser = db.Users.Where(x => x.UserName == User.Identity.Name).FirstOrDefault(); DateTime dateObj = DateTime.Now; Transaction transDB = db.Transactions.Find(model.Id); transDB.AmountPaid = model.Amount; db.Entry(transDB).State = EntityState.Modified; db.SaveChanges(); Message = "Transaction is Successfull"; } else { DateTime month = model.BillingFromDate; //model.Billing_Date = model.BillingFromDate; while (month <= model.BillingToDate) { var obj = db.Members.Where(x => x.Id == model.PaidBy_Id).FirstOrDefault(); var objUser = db.Users.Where(x => x.UserName == User.Identity.Name).FirstOrDefault(); DateTime dateObj = DateTime.Now; Transaction transDB = new Transaction(); transDB.PaidBy_Id = model.PaidBy_Id; transDB.ReceivedBy_Id = objUser.Id; transDB.Organization_Id = obj.Organization_Id; transDB.Billing_Date = month; transDB.Received_Date = DateTime.Now; transDB.AmountPaid = model.Amount; //transDB.Amount_Id = model.Amount_Id; transDB.MonthlyFee = model.PaymentFee; transDB.Status = true; db.Transactions.Add(transDB); db.SaveChanges(); month = month.AddMonths(1); } Message = "Transaction is Successfull"; try { WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; //Sender email address. WebMail.From = "*****@*****.**"; //Send email WebMail.Send(to: model.Email, subject: "Transaction", body: model.Amount + "BDT Successfully Recieved" + ", Thank You"); } catch (Exception ex) { Message = ex.Message; } } return(Json(new { Message }, JsonRequestBehavior.AllowGet)); }
public ActionResult CreatedMeetings(MeetingViewModels obj, string subject, string place, string date, string creatorMail, string reicevMail, List <string> times, List <string> mails) { //Configuring webMail class to send emails //gmail smtp server WebMail.SmtpServer = "smtp.gmail.com"; //gmail port to send emails WebMail.SmtpPort = 587; WebMail.SmtpUseDefaultCredentials = true; //sending emails with secure protocol WebMail.EnableSsl = true; //EmailId used to send emails from application WebMail.UserName = "******"; WebMail.Password = "******"; DataContext db = new DataContext(); UserRepository ur = new UserRepository(); MeetingRepository mr = new MeetingRepository(); var meetingModel = new Meeting { Subject = subject, Place = place, Date = date, }; var creator = ur.GetUserByEmail(creatorMail); var invitationModel = new Invitation { //Meeting = meetingModel, Date = DateTime.Now, MeetingID = meetingModel.MID, //ApplicationUser = creator, UserID = creator.Id, }; var f = db.Users.Single(x => x.Id == invitationModel.UserID); WebMail.From = f.Email; List <RecieveMeetingInvitation> RMInviteList = new List <RecieveMeetingInvitation>(); RecieveMeetingInvitation receiver = new RecieveMeetingInvitation(); string allTimes = ""; foreach (string time in times) { allTimes += time + "<br>"; } foreach (string mail in mails) { var RMInvite = new RecieveMeetingInvitation { InvitationID = invitationModel.IID, UserID = ur.GetUserByEmail(mail).Id }; RMInviteList.Add(RMInvite); var t = db.Users.Single(x => x.Id == RMInvite.UserID); string body = String.Format("Du är inbjuden till mötet på/i {0} den {1} med dessa tidsförslag : <br> {2} <br> Vänligen logga in på <a href = 'https://github.com/'>hemsidan</a> för att svara på inbjudan. <hr> Det här är en automatisk inbjudan från Informatiks webbtjänst. <br> Svara inte på detta mejl.", place, date, allTimes); WebMail.Send(from: f.Email, to: t.Email, subject: obj.Subject, body: body, isBodyHtml: true); } List <TimeSuggestion> timeList = new List <TimeSuggestion>(); List <TimeAnswer> timeAnswerList = new List <TimeAnswer>(); foreach (string time in times) { var timeSuggestionModel = new TimeSuggestion { MeetingID = meetingModel.MID, Suggestion = time }; foreach (string mail in mails) { var user = ur.GetUserByEmail(mail); var timeAnswerModel = new TimeAnswer { UserID = user.Id, TimeID = timeSuggestionModel.TID }; timeAnswerList.Add(timeAnswerModel); } timeList.Add(timeSuggestionModel); } mr.AddMeeting(meetingModel, invitationModel, RMInviteList, timeList, timeAnswerList); return(RedirectToAction("ViewMeetings")); }