protected override void OnException(ExceptionContext filterContext) { if (Util.ServerIsDev || Util.IsBewebOffice) { // fall through to Global asax error handler - and display error onscreen - we want to see full debug info on screen filterContext.ExceptionHandled = false; } else if (filterContext.Exception is BadUrlException) { // todo - make this return a Shared View instead of a Redirect to Action // filterContext.Result = View("BadUrl", new{message=filterContext.Exception.Message}); filterContext.Result = Redirect("~/Admin/NotFound?message=" + filterContext.Exception.Message); filterContext.ExceptionHandled = true; } else if (filterContext.Exception is AdminErrorException) { SendEMail.SimpleSendEmail(SendEMail.EmailToAddress, Util.GetSiteName() + " Website Problem Notification", "Please address the following issue with the website:\n" + filterContext.Exception.Message); filterContext.Result = Redirect("~/Admin/ShowError?message=" + filterContext.Exception.Message.UrlEncode()); filterContext.ExceptionHandled = true; // fall through to Global asax error handler - and show standard error page //} else { //if (filterContext.Exception is ProgrammingErrorException) { // Beweb.Error.SendExceptionEmail(); // filterContext.Result = Redirect("~/Admin/ShowError?message=" + "A programming error occurred. Please contact the developers.".UrlEncode()); // filterContext.ExceptionHandled = true; //} else { // // fall through to Global asax error handler - and show standard error page - maybe don't need this? // filterContext.ExceptionHandled = false; } }
//Lấy lại mật khẩu public ResponseInfo ForgotPassword(SendEMail email) { ResponseInfo result = new ResponseInfo(); try { var taikhoan = context.TaiKhoans.FirstOrDefault(x => x.Email == email.email && !x.DelFlag); string Username = taikhoan.Username; string token = Common.Common.GetToken(taikhoan.Id); TblTokenResset tokenLG = new TblTokenResset { Id_TaiKhoan = taikhoan.Id, TokenReset = token, ThoiGianHetHan = DateTime.Now.AddHours(12) }; context.ResetPassWords.Add(tokenLG); context.SaveChanges(); token = BaoMat.Base64Encode(token); string Subject = "Password Reset Confirmation for " + Username; string body = "<p>There was recently a request to change the password for your account. </p>" + "<p>If you requested this password change, please reset your password here: </p>" + "<p> https://truyenda.tk/forgot?token=" + token + "</p>" + "<p>If you did not make this request, you can ignore this message and your password will remain the same.</p>"; SendMail.SendGird(email.email, body, Subject); var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.GuiEmailThanhCong); result.TypeMsgError = errorMsg.Type; result.MsgError = errorMsg.Msg; return(result); } catch (Exception e) { throw e; } }
private void SendFeedErrorEmail(Feed feed, Exception ex) { String emailBodyTxt = TextBlockCache.Get("FeedError", @" Hello Herepin Admin, An error has occurred while scrapping [--FeedType--] Feed. Error details: [--ErrorMessage--] [--FeedURL--] <a href='[--RunFeedURL--]'>Run feed</a> | <a href='[--EditFeedURL--]'>Edit feed</a> " ).BodyTextHtml; emailBodyTxt = emailBodyTxt.Replace("[--FeedType--]", feed.FeedType); emailBodyTxt = emailBodyTxt.Replace("[--ErrorMessage--]", ex.Message); emailBodyTxt = emailBodyTxt.Replace("[--FeedURL--]", feed.FeedUrl); emailBodyTxt = emailBodyTxt.Replace("[--RunFeedURL--]", Web.BaseUrl + "ScheduledTask/RunFeed?feedID=" + feed.FeedID); emailBodyTxt = emailBodyTxt.Replace("[--EditFeedURL--]", Web.BaseUrl + "Admin/FeedAdmin/Edit/" + feed.FeedID); emailBodyTxt = emailBodyTxt.Replace("\r\n", "<br>"); if (Util.ServerIsDev) { SendEMail.SimpleSendHtmlEmail("*****@*****.**", "Herepin Feed error", emailBodyTxt); } else { SendEMail.SimpleSendHtmlEmail(Util.GetSetting("EmailToAddress", "localhost"), "Herepin Feed error", emailBodyTxt); SendEMail.SimpleSendHtmlEmail("*****@*****.**", "Herepin Feed error", emailBodyTxt); SendEMail.SimpleSendHtmlEmail("*****@*****.**", "Herepin Feed error", emailBodyTxt); } }
protected void block_Click(object sender, EventArgs e) { string gid = Request.QueryString["g_id"]; SendEMail em = new SendEMail(); em.sendEMail("*****@*****.**", "nathandrake", mail.Text, "your are blocked", msg.Text); ConnectionClass mycon = new ConnectionClass(); mycon.iud("update g_create set status='BLOCKED' where g_id=" + gid); // blkgrp(); }
public ActionResult RunSpiderTask() { int numAdded = GetYoutubeVideos(); if (numAdded > 0) { string body = "We have found another " + numAdded + " videos on Youtube to be approved<br/><br/><a href='" + Web.BaseUrl + "/admin/videoAdmin/approval'>Approve Videos</a>"; //SendEMail.SimpleSendHtmlEmail(SendEMail.EmailToAddress, "Youtube Videos to approve ", body); SendEMail.SimpleSendHtmlEmail("*****@*****.**", "Youtube Videos to approve", body); } YouTubeSpiderController.LastSpiderCheck = DateTime.Now; return(Content("done")); }
public ActionResult SaveEmail() { try { if (Web.Session["Player"] == null) { throw new Exception(); } var player = UserSession.LoadPlayer(); var isWinner = Request["isWinner"] == "true"; var email = Request["email"]; if (isWinner) { var prizeTypeID = Prize.LoadByWinnerPlayerID(player.PlayerID).PrizeTypeID; var tb = TextBlockCache.Get("WinningEmail", FileSystem.ReadTextFile("~/SiteCustom/email.html"), "Steps to claim your prize"); var description = ""; if (prizeTypeID == 3) // Limited Edition Cider Glasses { description = "Wild Side glasses don’t grow on trees. They’re found underground. And with the help of the farm dog, you dug one up. If you think it looks good now, wait until you pour cider into it - it’ll still look good. All you have to do is reply to this email and let us know what address to send it to. "; } else if (prizeTypeID == 4) // $100 Restaurant Voucher { description = "You found a $100 restaurant voucher - possibly the most delicious thing ever to grow in paddock soil. Please reply with your postal address so we can get your prize out to you. "; } else if (prizeTypeID == 5) // Wild Side Bottle Opener { description = "You just found a bottle opener in the Paddock of Prizes. Of course, you did have the help of master digger, sheep enthusiast, and current world fetch champion, the farm dog. Please reply to with your postal address so we can get your prize out to you."; } SendEMail.SimpleSendHTMLEmail(email, tb.Title, tb.BodyTextHtml.Replace("[firstname]", player.FirstName).Replace("[description]", description)); } player.Email = email; player.EmailSentDate = DateTime.Now; player.Save(); Web.Session["Player"] = player; return(Content("OK")); } catch { } return(Content("ERROR")); }
public ResponseInfo Forgot(SendEMail email) { ResponseInfo response = new ResponseInfo(); try { response = new LoginModel().ForgotPassword(email); response.IsSuccess = true; response.IsValid = true; } catch (Exception e) { response.Code = (int)ConstantsEnum.CodeResponse.ServerError; var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError); response.TypeMsgError = errorMsg.Type; response.MsgError = errorMsg.Msg; response.ThongTinBoSung1 = e.Message; } return(response); }
/// <summary> /// When a new person subscribes, you need to add a Person record for them (using Models.Person) and complete all the fields you have data for, then pass it to this method. /// This method sends an email to the person asking them to click a link. /// The final part of double opt in is when the link is clicked. The link takes them back to the Subscribe page with a URL parameter of "optin=[encryptedid]", and you need to call VerificationLinkClicked(Request["optin"]). /// </summary> /// <param name="person">A Models.Person object with email address and any other fields completed.</param> /// <param name="subscribePageFileName">File name of subscribe or optin page that calls VerificationLinkClicked (may include path from site root, may start with ~)</param> public static void SendVerificationEmail(ActiveRecord person, string subscribePageFileName) { // check person record is OK AssertFieldsExist(person); string email = person["Email"].ToString(); // validate if (email.IsBlank()) { throw new Exception("NewsletterDoubleOptIn: Email address was null or empty."); } if (!email.IsEmail()) { throw new Exception("NewsletterDoubleOptIn: Email address was not valid [" + email + "]."); } // send double opt in email Models.TextBlock emailText = Models.TextBlock.LoadBySectionCode("Double_OptIn_Email"); // create if not found if (emailText == null) { emailText = new Models.TextBlock() { SectionCode = "Double_OptIn_Email", IsBodyPlainText = true, IsTitleAvailable = true, BodyTextHtml = string.Format("Please confirm that you wish to subscribe to our email newsletter.{0}{0}Click the link below if you wish to subscribe:", Environment.NewLine), Title = "Email Newsletter - Please Confirm" }; emailText.Save(); } string emailBody = emailText.BodyTextHtml; emailBody += Environment.NewLine + Web.ResolveUrlFull(subscribePageFileName) + "?optin=" + Crypto.EncryptID((int)person["PersonID"].ValueObject).UrlEncode(); SendEMail.SimpleSendEmail(email, emailText.Title, emailBody); person["DoubleOptInEmailSentDate"].ValueObject = DateTime.Now; person.Save(); }
protected void ProcessEmail(Models.Person record) { var body = Request["EmailCopy"]; body = body.Replace("[firstname]", record.FirstName); body = body.Replace("[username]", record.Email); body = body.Replace("[password]", (String.IsNullOrEmpty(Crypto.Decrypt(record.Password)) ? record.Password : Crypto.Decrypt(record.Password))); body = body.Replace("[baseurl]", Web.BaseUrl); string emailResult = SendEMail.SimpleSendHtmlEmail(record.Email, Request["EmailSubject"], formatEMailTxt(body)); //SendEMail em = new SendEMail() if (emailResult == null) { TempData["emailMsg"] = " Notification Email sent to " + record.Email + "."; //record.AdminOnlyNotes+="\nEmail sent on "+DateTime.Now.FmtDateTime(); } else { TempData["emailMsg"] = " Notification Email failed to send to " + record.Email + ".<!--[" + emailResult + "]-->"; // //record.AdminOnlyNotes+="\nEmail send failed on "+DateTime.Now.FmtDateTime(); } }
public ActionResult TestEmail() { var prizeTypeID = 3; var tb = TextBlockCache.Get("WinningEmail", FileSystem.ReadTextFile("~/SiteCustom/email.html"), "Claim your prize"); var description = ""; if (prizeTypeID == 3) // $100 Restaurant Voucher { description = "You found a $100 restaurant voucher - possibly the most delicious thing ever to grow in paddock soil. Please reply with your postal address so we can get your prize out to you. "; } else if (prizeTypeID == 4) // Limited Edition Cider Glasses { description = "Wild Side glasses don’t grow on trees. They’re found underground. And with the help of the farm dog, you dug one up. If you think it looks good now, wait until you pour cider into it - it’ll still look good. All you have to do is reply to this email and let us know what address to send it to. "; } else if (prizeTypeID == 5) // Wild Side Bottle Opener { description = "You just found a bottle opener in the Paddock of Prizes. Of course, you did have the help of master digger, sheep enthusiast, and current world fetch champion, the farm dog. Please reply to with your postal address so we can get your prize out to you."; } SendEMail.SimpleSendHTMLEmail("*****@*****.**", tb.Title, tb.BodyTextHtml.Replace("[firstname]", "André").Replace("[description]", description)); return(Content("OK")); }
public string RessetPasswordById(int id) { bool _sendSucess = false; string _msg = "", _newPassword = "", _newPasswordHash = ""; bool _isBodyHtml = true; string _subject, _textBody; Colaborador _colaborador = new Colaborador(); _colaborador = GetColaboradorById(id); SendEMail _sendMail = new SendEMail(); _newPassword = PasswordFunctions.GetNovaSenhaAcesso(""); _newPasswordHash = PasswordFunctions.CriptografaSenha(_newPassword); using (SqlConnection connection = new SqlConnection(strConnSql)) { connection.Open(); SqlCommand command = connection.CreateCommand(); SqlTransaction transaction; // Start a local transaction. transaction = connection.BeginTransaction("RessetSenhaColaborador"); command.Connection = connection; command.Transaction = transaction; try { // Atualizando a senha na tabela PESSOA: command.CommandText = "" + "UPDATE dbo.AD_Pessoa " + "SET PasswordHash = @PasswordHash " + "WHERE PessoaId = @id"; command.Parameters.AddWithValue("PasswordHash", _newPasswordHash); command.Parameters.AddWithValue("id", _colaborador.PessoaId); int i = command.ExecuteNonQuery(); transaction.Commit(); if (i > 0) { _subject = "Site FBTC - Troca de Senha - A sua nova senha de acesso chegou!"; _textBody = "<html><body> " + $"<p>Olá {_colaborador.Nome}!</p>" + "<p>Esta mensagem foi gerada pelo sistema Troca de Senha do Site FBTC.</p>" + "<p>Conforme solicitação através do site, a sua senha de acesso a sua conta no site fbtc.org.br foi reiniciada.</br></br>" + "Para você logar-se, por favor, informe o seu e-mail e a senha abaixo:</br></br></br>" + $" <b>{_newPassword}</b></br></br></br>" + "Por favor, para seu segurança, troque-a no seu próximo acesso.</br></br></br>" + "<a href='http://administrativo.fbtc.org.br' target='_blank'>http://administrativo.fbtc.org.br - Acessar sua Conta</a></br>" + "</p>" + "<p><i>2018 - FBTC Federação Brasileira de Terapias Cognitivas - Direitos reservados.</i></p> " + "<p>Este é um e-mail automático da FBTC, por favor não o responda.</p> " + "</body></html> "; _sendSucess = _sendMail.SendMessage(_colaborador.EMail, _subject, _isBodyHtml, _textBody); _msg = _sendSucess == true ? $"A nova senha foi enviada para o e-mail: { _colaborador.EMail }." : "Houve uma falha no envio da sua senha"; } else { _msg = "Atualização NÃO Realizada com sucesso"; _sendSucess = false; } } catch (Exception ex) { if (ex.Message.IndexOf("Mail") < 0) { try { transaction.Rollback(); } catch (Exception ex2) { throw new Exception($"Rollback Exception Type:{ex2.GetType()}. Erro:{ex2.Message}"); } } if (ex.Message.IndexOf("System.Net.Mail.SmtpException") > 0) { return("ATENÇÃO: Não foi possível enviar o e-mail com a nova senha agora. Por favor, tente novamente mais tarde."); } else { throw new Exception($"Commit Exception Type:{ex.GetType()}. Erro:{ex.Message}"); } } finally { connection.Close(); } } return(_msg); }
public void Init() { int blogid = Crypto.DecryptID(Web.Request["id"]); var blogSql = new Sql("select * from blog where blogid=", blogid, " and ispublished=1"); var rec = blogSql.GetHashtable(); BlogTitle = rec["Title"] + ""; BlogBody = rec["BodyText"] + ""; BlogDate = rec["DateAdded"] + ""; Sql mainlist = new Sql("select top 25 * from blogcomment where blogid=", blogid, " and ispublished=1 order by dateadded desc"); blogCommentList = mainlist.GetDataTable(); Url = Web.Server.UrlEncode(Web.ResolveUrlFull("~") + "blogdetail.aspx?page=" + Web.Request["page"] + "&id=" + Web.Request["id"]); bool autopublish = false; if (Web.Request["go"] != null) { int id = (Web.Session["CurrentUserID"] + "").ToInt(-1); if (id > 0) { autopublish = true; } var sql = new Sql(@"insert into blogcomment(title,bodytext ,[Company] ,[FirstName] ,[LastName] ,[Email],CommentByPersonID, blogid, dateadded, ispublished) values(" ); sql.Add("", (Web.Request["title"] + "").SqlizeText(), ",", (Web.Request["body"] + "").SqlizeText(), ","); sql.Add("", (Web.Request["company"] + "").SqlizeText(), ",", (Web.Request["firstname"] + "").SqlizeText(), ",", (Web.Request["lastname"] + "").SqlizeText(), ",", (Web.Request["email"] + "").SqlizeText(), ","); sql.Add("", (id + "").SqlizeNumber(), ",", blogid.SqlizeNumber(), ", getdate(),", autopublish.SqlizeBool(), ");select @@identity;"); decimal savedNewID = (sql).FetchDecimalOrZero(); //send email //Response.Write("ok"); string adminurl = Web.ResolveUrlFull("~/admin/") + "BlogCommentAdmin/EditEnc?encID=" + Crypto.EncryptID(savedNewID.ToInt()); //string EmailToAddress = Util.GetSetting("BlogEmailToAddress"); string EmailToAddress = Util.GetSetting("EmailToAddress"); //fromemail = "*****@*****.**"; //EmailToAddress = "*****@*****.**"; string msg = "" + "Site Admin,\n" + "\n" + " A new comment has been posted to your blog."+ "\n" + " Link to admin: "+ adminurl + "" + "\n"; if (!autopublish) { msg += " Note that you will to review the data and publish it if it has appropriate content."+ "\n"; } else { msg += " This was auto-published, as it was created by a logged in user."+ "\n"; } SendEMail.SimpleSendEmail(EmailToAddress, Util.GetSiteName() + " : New Blog Comment", msg); //reload page string url = Web.Request.RawUrl.ToString(); //Response.Redirect(url + (url.Contains("&post") ? "" : "&post=1")); } }
public ActionResult PatientForgotPassword(ForgetPasswordModel forgetPatient) { if (ModelState.IsValid) { using (db) { //check user existance var count = db.patientlogins.Count(u => u.EmailID == forgetPatient.EmailId); if (count == 0) { //ModelState.AddModelError("", "Entered Email does not exist."); @TempData["ErrorMessage"] = "Entered Email does not exist."; } else { generatepassword genPass = new generatepassword(); var TempPassword = genPass.generate_password(); //generate password token var crypto = new SimpleCrypto.PBKDF2(); var token = crypto.Compute(TempPassword); var newUser = db.patientlogins.Where(a => a.EmailID == forgetPatient.EmailId).FirstOrDefault(); if (newUser != null) { newUser.PasswordVerificationToken = token; newUser.PasswordVerificationTokenExpirationDate = System.DateTime.Now.AddHours(48); } db.SaveChanges(); //create url with above token var resetLink = "<a href='" + Url.Action("ResetPasswordPatient", "Account", new { unp = forgetPatient.EmailId, rtp = token }, "http") + "'>Reset Password</a>"; //var resetLink = Url.Action("ResetPassword", "Account", new { un = email, rt = token }, "http"); //get user emailid var emailid = (from i in db.patientlogins where i.EmailID == forgetPatient.EmailId select i.EmailID).FirstOrDefault(); //send mail string subject = "Password Reset Token"; string body = "<b>You have requested to change the password by Forgot Password option, Please find the Password Reset Token in this mail, You can click on the link or copy and paste the link in you browser</b><br/>" + resetLink; //edit it try { SendEMail sendemail = new SendEMail(); sendemail.Send_EMail(emailid, subject, body); // ViewBag.StatusMessage = "An email has been sent to the email address you registered with. Follow the instruction in this email to complete your password reset."; @TempData["Message"] = "An email has been sent to the email address you registered with. Follow the instruction in this email to complete your password reset."; } catch (Exception ex) { // ViewBag.StatusMessage = "Error occured while sending email." + ex.Message; @TempData["ErrorMessage"] = "Error occured while sending email." + ex.Message; } ViewBag.Status = 1; return(View()); } } } return(View(forgetPatient)); }
public ActionResult ResetPasswordPatient(ResetPasswordConfirmModel model) { model.EmailId = Session["EmailId"].ToString(); model.Token = Session["Token"].ToString(); if (ModelState.IsValid) { //TODO: Check the un and rt matching and then perform following //get userid of received username var EmailId = (from i in db.patientlogins where i.EmailID == model.EmailId select i.EmailID).FirstOrDefault(); //check userid and token matches bool any = (from j in db.patientlogins where (j.EmailID == model.EmailId) && (j.PasswordVerificationToken == model.Token) //&& (j.PasswordVerificationTokenExpirationDate < DateTime.Now) select j).Any(); if (any == true) { var UpdateUser = db.patientlogins.Where(a => a.EmailID == EmailId).FirstOrDefault(); //Setting password expiry date if (UpdateUser.PasswordVerificationTokenExpirationDate > System.DateTime.Now) { if (UpdateUser != null) { var crypto = new SimpleCrypto.PBKDF2(); var encrypPass = crypto.Compute(model.NewPassword); UpdateUser.Password = encrypPass; UpdateUser.ConfirmPassword = encrypPass; UpdateUser.PasswordSalt = crypto.Salt; } db.SaveChanges(); //reset password //send email string subject = "New Patient Password"; string body = "<b>Your password has been changed as per our record, Please login with your new password</b><br/>";//edit it try { SendEMail sendemail = new SendEMail(); sendemail.Send_EMail(EmailId, subject, body); ViewBag.StatusMessage = "Patient Password has been reset now and An email has been sent to the email address you registered with for confirmation."; } catch (Exception ex) { ViewBag.StatusMessage = "Error occured while sending email to Patient." + ex.Message; } ViewBag.Status = 1; return(View()); } else { ModelState.AddModelError("", "Patient Reset Password Token is expired, Use Forgot password link from login screen to regenerate your tocken"); } } else { if (model.Token == null) { ModelState.AddModelError("", "Patient- No Valid Token found, Use Forgot password link from login screen to regenerate your token"); } else { ModelState.AddModelError("", "Patient- Input Token number is not correct or expired"); } } } return(View(model)); }
public ActionResult RegisterUser(UserRegisterViewModel registerVM) { ModelState.Clear(); // Cleare Model state if (ModelState.IsValid) { //var cUser = db.UserLogins.FirstOrDefault(x => x.UserName == registerVM.Userlogins.UserName); var cUserEmail = db.UserLogins.FirstOrDefault(x => x.EmailID == registerVM.Userlogins.EmailID); var cEmpId = db.UserLogins.FirstOrDefault(X => X.EmployeeId == registerVM.Userlogins.EmployeeId); //if (ReferenceEquals(cUser, null)) //{ if (ReferenceEquals(cUserEmail, null)) { if (ReferenceEquals(cEmpId, null)) { using (var dbContextTransaction = db.Database.BeginTransaction()) { try { //Take the password for email string password = registerVM.Userlogins.Password; //Insert data in Userlogins Table userRepository.InsertUserLogins(registerVM.Userlogins, registerVM); userRepository.Save(); //Insert data in Login_Role Table var newUserRole = db.UserLoginRoles.Create(); userRepository.InsertUserLoginRoles(newUserRole, registerVM); userRepository.Save(); // Insert data in Login_Speciality Table if (registerVM.SpecialityID != 0) { var newUserspeciality = db.UserLoginSpecialitys.Create(); userRepository.UserLoginSpecialitys(newUserspeciality, registerVM); userRepository.Save(); } dbContextTransaction.Commit(); //ViewBag.StatusMessage = " User Name with " + registerVM.Userlogins.UserName + " having Email Id " + registerVM.Userlogins.EmailID + " is created successfully"; //ViewBag.Status = 1; @TempData["SuccessMessage"] = " User Name with " + registerVM.Userlogins.FirstName + " " + registerVM.Userlogins.LastName + " having Email Id " + registerVM.Userlogins.EmailID + " is created successfully"; //var callbackUrl = Url.Action("ConfirmEmail", "Account",new { userId = user.Id, code = code },protocol: Request.Url.Scheme); //get user emailid var emailid = registerVM.Userlogins.EmailID; //send mail string subject = "doxedox Registration"; string body = "Dear " + registerVM.Userlogins.FirstName + " " + registerVM.Userlogins.LastName + "<br/> <br/>" + System.Environment.NewLine + System.Environment.NewLine + "You have been successfully registered at doxedox , Your login credentials are given below<br/><br/>" + "Your Id" + " : " + registerVM.Userlogins.LoginId + "<br/><br/>Password" + " : " + password + "<br/><br/><br/>Thank You" + "<br/>Admin" + "<br/>doxedox"; //edit it try { SendEMail sendemail = new SendEMail(); sendemail.Send_EMail(emailid, subject, body); @TempData["SuccessMessage"] = "User has been created Successfully. Email sent to " + registerVM.Userlogins.EmailID + ""; } catch (Exception ex) { // ViewBag.StatusMessage = "User has been created successfully but Error occurred while sending email. Error:" + ex.Message; @TempData["Message"] = "User has been created successfully but Error occurred while sending email. Error:" + ex.Message; } } catch (DbEntityValidationException) { dbContextTransaction.Rollback(); } } } else { @TempData["Message"] = "Employee ID Already Exist"; } } else { @TempData["Message"] = "Email ID Already Exist"; } // } //else //{ // @TempData["Message"] = "User Name Already Exist"; //} } // ViewBag.ExistStatus = 1; return(RedirectToAction("RegisterUser")); }
public ActionResult Create(DocRegisterViewModel docRegVM) { ModelState.Clear(); if (ModelState.IsValid) { var cUserEmail = db.UserLogins.FirstOrDefault(x => x.EmailID == docRegVM.Userlogins.EmailID); if (ReferenceEquals(cUserEmail, null)) { using (var dbContextTransaction = db.Database.BeginTransaction()) { try { docRegVM.RoleId = 4; generatepassword genpass = new generatepassword(); var TempPassword = genpass.generate_password(); //Take the password for email string password = TempPassword.ToString(); docRegVM.Userlogins.Password = password; //Insert data in Userlogins Table docregistor.InsertDoctor(docRegVM.Userlogins, docRegVM); docregistor.Save(); //Insert data in Login_Role Table var newUserRole = db.UserLoginRoles.Create(); docregistor.InsertDoctorRoles(newUserRole, docRegVM); docregistor.Save(); //if (registerVM.SpecialityID!=0) //{ //Insert data in Login_Speciality Table var newUserspeciality = db.UserLoginSpecialitys.Create(); docregistor.DocLoginSpecialitys(newUserspeciality, docRegVM); docregistor.Save(); // } dbContextTransaction.Commit(); // ViewBag.StatusMessage = " User Name with " + docRegVM.Userlogins.UserName + " having Email Id " + docRegVM.Userlogins.EmailID + " is created successfully"; // ViewBag.Status = 1; @TempData["SuccessMessage"] = " User Name with " + docRegVM.Userlogins.FirstName + " " + docRegVM.Userlogins.LastName + " having Email Id " + docRegVM.Userlogins.EmailID + " is created successfully"; //var callbackUrl = Url.Action("ConfirmEmail", "Account",new { userId = user.Id, code = code },protocol: Request.Url.Scheme); //get user emailid var emailid = docRegVM.Userlogins.EmailID; //send mail string subject = "MyCityMyDoctor Registration"; string body = "Dear " + docRegVM.Userlogins.FirstName + " " + docRegVM.Userlogins.LastName + "<br/> <br/>" + System.Environment.NewLine + System.Environment.NewLine + "You have been successfully registered at MyCityMyDoctor , Your login credentials are given below<br/><br/>" + "<br/><br/>Password" + " : " + password + "<br/><br/><br/>Thank You" + "<br/>Admin" + "<br/>Edox"; //edit it try { SendEMail sendemail = new SendEMail(); sendemail.Send_EMail(emailid, subject, body); @TempData["SuccessMessage"] = "User has been created Successfully. Email sent to " + docRegVM.Userlogins.EmailID + ""; } catch (Exception ex) { //ViewBag.StatusMessage = "User has been created successfully but Error occurred while sending email. Error:" + ex.Message; @TempData["Message"] = "User has been created successfully but Error occurred while sending email. Error:" + ex.Message; } } catch (DbEntityValidationException) { dbContextTransaction.Rollback(); } } } else { @TempData["Message"] = "Email ID Already Exist"; } } return(RedirectToAction("Create")); }
protected void WriteResults() { string isOK; // Savvy Console JSON CommandStatus.success = true; if (mode == "GenModels") { Web.Write("<b>Generating Savvy Active Record Classes</b><br /><br />"); ActiveRecordGenerator.Run(); Web.Write("<br>Done."); CommandStatus.message = "Models updated successfully"; } else if (mode == "AddDbFields") { Web.Write("<b>Creating any missing fields in Database from Savvy Active Record Classes</b><br /><br />"); ActiveRecordDatabaseGenerator.CreateAnyMissingFields(); Web.Write("<br>Done."); CommandStatus.message = "Database updated successfully"; } else if (mode == "MinifyJsCss") { Web.Write("<b>Minifying JS and CSS files</b><br /><br />"); MinifyJS(); MinifyCSS(); Web.Write("<br>Done. (Note: The script will only minify immediate children files)"); CommandStatus.message = "Minified JS and CSS files created successfully"; } else if (mode == "GenDatabaseScripts") { Web.Write("<b>Generating Database Create Statements from Savvy Active Record Classes</b><br /><br />"); Web.Write(Fmt.Text(ActiveRecordDatabaseGenerator.GetSqlStatements())); Web.Write("<br>Done."); } else if (mode == "ImportFromLive") { isOK = OKToImport("LVE"); if (isOK == "OK") { Web.Write("<b>Importing all data from Live and replacing local data</b><br /><br />"); //ActiveRecordDatabaseGenerator.ImportDataFrom(Util.GetSetting("LinkedServerDatabaseLVE", "throw")); ActiveRecordDatabaseGenerator.ImportDataFrom("LVE"); } else { Web.Write(isOK); } } else if (mode == "ImportFromStaging") { isOK = OKToImport("STG"); if (isOK == "OK") { Web.Write("<b>Importing all data from Staging and replacing local data</b><br /><br />"); ActiveRecordDatabaseGenerator.ImportDataFrom("STG"); Web.Write("<br>Done."); } else { Web.Write(isOK); } } else if (mode == "LegacyMigration") { Web.Write("<b>Migrating all Old Data</b><br /><br />"); //LegacyDataMigration.GenerateDataMigrationScripts("RinnaiWebsite", true); Web.Write("<br>Done."); } else if (mode == "ExportToStaging") { Web.Write("<b>Copying all local data up to Staging and replacing existing staging data</b><br /><br />"); ActiveRecordDatabaseGenerator.ExportDataTo("STG"); Web.Write("<br>Done."); } else if (mode == "ViewCache") { Web.Write("<b>Displaying all objects in ASP.NET Web Cache</b><br /><br />"); Web.Write(Fmt.Text(Logging.DumpCache())); Web.Write("<br>Done."); } else if (mode == "ClearCache") { Web.Write("<b>Clearing all objects in ASP.NET Web Cache</b><br /><br />"); Web.CacheClearAll(); Web.Write("<br>Done."); CommandStatus.message = "Cache cleared successfully"; } else if (mode == "UpdateDLLs") { Web.Write("<b>Updating DLLs</b><br /><br />"); UpdateDLLs(); Web.Write("<br>Done."); Web.Write("<br>"); Web.Write("<br><br><a href='?mode=AddDbFields'>Add fields to database</a>"); Web.Write("<br><br><a href='?mode=RollbackDLLs'>Rollback</a>"); Web.Write("<br><br><a href='" + Web.Root + "'>Check homepage</a>"); } else if (mode == "RollbackDLLs") { Web.Write("<b>Rolling back DLLs to backup</b><br /><br />"); RollbackDLLs(); Web.Write("<br>Done."); Web.Write("<br><br><a href='" + Web.Root + "'>Check homepage</a>"); } else if (mode == "FixError") { Web.Write("<b>Applying a Fix</b><br /><br />"); Beweb.Logging.FixError(Request["message"], Request["title"], Request["lineThatDied"]); Web.Write("<br>Done."); } else if (currentClass == "all") { Assert.RunAllTests(); Web.Write("<br>Done."); } else if (currentClass != null) { Assert.RunTests(currentClass); Web.Write("<br>Done."); } else if (mode == "CreateTable") { if (Util.ServerIsDev) { var tableName = Request["tableName"].UpperCaseFirstLetter(); var ar = new ActiveRecord(tableName, tableName + "ID"); var sql = ar.GetSqlForCreate(); sql.Execute(); CommandStatus.message = "Created table " + tableName; } else { CommandStatus.success = false; CommandStatus.message = "Only allowed on dev."; } } else if (mode == "DropTable") { if (Util.ServerIsDev) { var tableName = Request["tableName"].UpperCaseFirstLetter(); new Sql("DROP TABLE " + tableName).Execute(); CommandStatus.message = "Dropped table " + tableName; } else { CommandStatus.success = false; CommandStatus.message = "Only allowed on dev."; } } else if (mode == "ListTables") { var sql = new Sql().AddRawSqlString("SELECT t.name as [Table Name] FROM sys.tables AS t INNER JOIN sys.schemas AS s ON t.[schema_id] = s.[schema_id] ORDER BY t.name"); CommandStatus.message = "Done"; CommandStatus.data = Logging.DumpTableToHtml(sql.GetDataTable()); } else if (mode == "Sql") { var query = Request["query"]; if (query.IsNotBlank()) { if (query.ToLower().DoesntContain("select")) { try { int affectedRows = new Sql().AddRawSqlString(query).Execute(); CommandStatus.message = "Affected rows: " + affectedRows; } catch (Exception ex) { CommandStatus.success = false; CommandStatus.message = ex.Message; } } else { var sql = new Sql().AddRawSqlString(query); CommandStatus.message = query; CommandStatus.data = Logging.DumpTableToHtml(sql.GetDataTable()); } } else { CommandStatus.success = false; CommandStatus.message = "Missing parameter"; } } else if (mode == "ListTables") { var sql = new Sql().AddRawSqlString("SELECT t.name as [Table Name] FROM sys.tables AS t INNER JOIN sys.schemas AS s ON t.[schema_id] = s.[schema_id] ORDER BY t.name"); CommandStatus.message = "Done"; CommandStatus.data = Logging.DumpTableToHtml(sql.GetDataTable()); } else if (mode == "SendEmail") { var email = Request["email"]; var subject = Request["subject"]; var message = Request["message"]; if (email.IsNotBlank() && subject.IsNotBlank() && message.IsNotBlank()) { try { SendEMail.SimpleSendHTMLEmail(email, subject, message); CommandStatus.message = "Email sent to " + email; } catch (Exception ex) { CommandStatus.success = false; CommandStatus.message = ex.Message; } } else { CommandStatus.success = false; CommandStatus.message = "Missing parameters"; } } else if (mode == "WhoAmI") { if (Security.IsLoggedIn) { CommandStatus.message = "You are logged in as " + UserSession.Person.FullName; } else { CommandStatus.message = "You are not logged in"; CommandStatus.success = false; } } else if (mode == "gotoServerStage") { var serverStage = Request["serverStage"]; CommandStatus.data = Util.GetSetting("WebsiteBaseUrl" + serverStage); CommandStatus.message = "Going to " + serverStage + " url " + CommandStatus.data; } else if (mode == "ServerIs") { CommandStatus.message = "Server is: " + Util.ServerIs(); } else if (mode == "UploadFile") { try { var file = Request.Files[0]; if (file.ContentLength > 0) { var fullPath = Server.MapPath(Path.Combine("~/attachments/", Path.GetFileName(file.FileName))); int count = 1; string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath); string extension = Path.GetExtension(fullPath); string path = Path.GetDirectoryName(fullPath); string newFullPath = fullPath; while (File.Exists(newFullPath)) { string tempFileName = string.Format("{0}({1})", fileNameOnly, count++); newFullPath = Path.Combine(path, tempFileName + extension); } file.SaveAs(newFullPath); CommandStatus.message = "The file was uploaded successfully. <a href='" + Web.Attachments + Path.GetFileName(newFullPath) + "' target='_blank'>" + Path.GetFileName(newFullPath) + "</a>"; } else { throw new Exception("No file selected"); } } catch (Exception ex) { CommandStatus.success = false; CommandStatus.message = ex.Message.Replace("\\", "\\\\"); } } else if (mode == "UploadURL") { var url = Request["url"]; if (url.IsNotBlank()) { try { var filename = url.RightFrom("/"); if (!url.Replace("http://", "").Replace("https://", "").Contains("/") || !filename.Contains(".")) { throw new Exception("The URL doesn't point to any file"); } var newFilename = FileSystem.GetUniqueAttachmentFilename(filename); using (var client = new WebClient()) { client.DownloadFile(url, Server.MapPath(Path.Combine("~/attachments/", newFilename))); } CommandStatus.message = "The file was uploaded successfully. <a href='" + Web.Attachments + newFilename + "' target='_blank'>" + newFilename + "</a>"; } catch (Exception ex) { CommandStatus.success = false; CommandStatus.message = ex.Message; } } else { CommandStatus.success = false; CommandStatus.message = "Missing parameter"; } } else if (mode == "EncodeKeystoneID") { CommandStatus.message = "Encoded ID: " + Crypto.EncryptID(Request["id"].ToInt(0)); } else if (mode == "EncodeKeystoneIDClassic") { CommandStatus.message = "Encoded ID: " + Crypto.EncryptIDClassic(Request["id"].ToInt(0)); } else if (mode == "Encrypt") { CommandStatus.message = "Encrypted: " + Crypto.Encrypt(Request["enc"]); } else if (mode == "Decrypt") { CommandStatus.message = "Decrypted: " + Crypto.Decrypt(Request["decr"]); } else if (mode == "DecodeKeystoneID") { try { var id = Crypto.DecryptID(Request["encid"]); if (id == -1) { throw new Exception(); } CommandStatus.message = "Decoded ID: " + id; } catch { CommandStatus.success = false; CommandStatus.message = "Invalid ID"; } } else if (mode == "DecodeKeystoneIDClassic") { try { var id = Crypto.DecryptIDClassic(Request["encid"]); if (id == -1) { throw new Exception(); } CommandStatus.message = "Decoded ID: " + id; } catch { CommandStatus.success = false; CommandStatus.message = "Invalid ID"; } } else if (mode == "LockSite") { try { ConfigurationManager.AppSettings["LockSiteHomepage" + Util.ServerIs()] = "true"; ConfigurationManager.RefreshSection("appSettings"); //edit the actual web config SetLockSiteHomepageAppSettingsValue(true); //clear the cookie so if it works the lockscreen will appear on next page load / refresh var httpCookie = Response.Cookies["pwlock"]; if (httpCookie != null) { httpCookie.Expires = DateTime.Now.AddDays(-1); } CommandStatus.message = "Site locked. [PWD:" + Util.GetSetting("LockSitePassword") + "] Double check your app settings before your next deploy"; } catch (Exception) { CommandStatus.success = false; CommandStatus.message = "Failed to lock site"; } } else if (mode == "UnlockSite") { try { //update app settings in memory. ConfigurationManager.AppSettings["LockSiteHomepage" + Util.ServerIs()] = "false"; ConfigurationManager.RefreshSection("appSettings"); //edit the actual web config SetLockSiteHomepageAppSettingsValue(false); //var replaceText = fileContent.ExtractTextBetween(@"<add key=""LockSiteHomepage"+Util.ServerIs()+@""" value=""", @"""/>"); //clear the cookie so if it fails the lockscreen will appear on next page load / refresh var httpCookie = Response.Cookies["pwlock"]; if (httpCookie != null) { httpCookie.Expires = DateTime.Now.AddDays(-1); } CommandStatus.message = "Site unlocked. Double check your app settings before your next deploy."; } catch (Exception) { CommandStatus.success = false; CommandStatus.message = "Failed to unlock site"; } } }