public async Task <bool> ChangePassword(ChangePasswordDto input) { bool IsCaptchaValid = (ReCaptchaClass.Validate(input.CaptchaResponse) == "true" ? true : false); if (!IsCaptchaValid) { throw new UserFriendlyException("تیک من ربات نیستم را کلیک کنید."); } if (AbpSession.UserId == null) { throw new UserFriendlyException("شماره هنوز وارد سیستم نشده اید."); } long userId = AbpSession.UserId.Value; var user = await UserManager.GetUserByIdAsync(userId); var passwordCombination = passwordHasher.VerifyHashedPassword(user, user.Password, input.CurrentPassword); if (passwordCombination != PasswordVerificationResult.Success) { throw new UserFriendlyException("کلمه عبور ثبت شده برای شما با کلمه عبور وارد شده مطابقت ندارد."); } if (!new Regex(PasswordRegex).IsMatch(input.NewPassword)) { throw new UserFriendlyException("کاراکترهای مجاز برای رمز عبور: حروف انگلیسی بزرگ و کوچک، اعداد و @#.$&* میباشند. طول رمز عبور باید حداقل 6 باشد"); } user.Password = passwordHasher.HashPassword(user, input.NewPassword); user.IsPasswordReset = false; CurrentUnitOfWork.SaveChanges(); return(true); }
public async Task <IHttpActionResult> Register(UserInscModel userInsc) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (userInsc.response == null) { return(BadRequest("Captcha invalide !!")); } string EncodedResponse = userInsc.response; bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "True" ? true : false); if (!IsCaptchaValid) { return(BadRequest("Captcha invalide !!")); } User user = _UserService.getByEmailOrUsername(userInsc.Email, userInsc.UserName); if (user != null) { return(BadRequest("Email Adresse /Username existe already !!")); } _UserService.AddUser(userInsc); return(Ok()); }
public ActionResult Register(user user) { if (!checkUser(user.Email)) { try { if (ModelState.IsValid) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "True" ? true:false); if (IsCaptchaValid) { using (var db = new ecm.Models.ecmEntities2()) { var crypto = new SimpleCrypto.PBKDF2(); var encrypPass = crypto.Compute(user.Password); var newUser = db.users.Create(); newUser.Email = user.Email; newUser.Password = encrypPass; newUser.PasswordSalt = crypto.Salt; newUser.FirstName = user.FirstName; newUser.LastName = user.LastName; newUser.UserType = user.UserType; db.users.Add(newUser); db.SaveChanges(); Session["username"] = user.Email; Session["userType"] = user.UserType; //FormsAuthentication.SetAuthCookie(user.Email, false); return(RedirectToAction("dashboard", "User")); } } else { TempData["recaptcha"] = "Please verify that you're not a robot"; } } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } } else { TempData["error"] = "This email already exists!"; } return(View("Authentication")); }
protected void CreateUser_Click(object sender, EventArgs e) { string response = Request.Form["g-Recaptcha-Response"]; bool isValid; if (ReCaptchaClass.Validate(response) == "true") { isValid = true; } else { isValid = false; } if (isValid) { var manager = new UserManager(); var user = new ApplicationUser() { UserName = UserName.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { if (isVenueOwner.Checked) { manager.SetPhoneNumber(user.Id, ""); } string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnect"].ConnectionString; OleDbConnection c = new OleDbConnection(connectionString); c.Open(); OleDbCommand cmd = c.CreateCommand(); cmd.CommandType = CommandType.Text; // Create query if (isVenueOwner.Checked) { cmd.CommandText = "INSERT INTO users VALUES ('" + UserName.Text + "', 1, '" + "" + "', '" + "" + "')"; } else { cmd.CommandText = "INSERT INTO users VALUES ('" + UserName.Text + "', 0, '" + "" + "', '" + "" + "')"; } //execute query OleDbDataReader reader = cmd.ExecuteReader(); c.Close(); manager.SetEmail(user.Id, UserName.Text); Response.Redirect("~/Account/Login"); } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } } else { ErrorMessage.Text = "ReCaptcha Failed"; } }
public async Task <IActionResult> ChangePW([Bind("UserName,CurrentPassword,NewPassword,ConfirmPassword")] User userObject) { //Validating ReCaptcha string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "true" ? true : false); String displayName = ""; if (IsCaptchaValid) { if (userObject.confirmNewPwEqualsConfirmPw()) { using (var context = new PrincipalContext(ContextType.Domain)) { try { var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userObject.UserName); if (user == null) { throw new Exception("Username does not Exist, Please enter a valid Username"); } user.ChangePassword(userObject.CurrentPassword, userObject.NewPassword); displayName = user.Name; user.Save(); } catch (PasswordException e) { TempData["Exception"] = e.Message.Remove(e.Message.Length - 36); return(RedirectToAction("Index")); } catch (PrincipalOperationException e) { TempData["Exception"] = e.Message.Remove(e.Message.Length - 36); return(RedirectToAction("Index")); } catch (Exception e) { TempData["Exception"] = e.Message; return(RedirectToAction("Index")); } } } } else { TempData["Exception"] = "Invalid ReCaptcha Response - Please ensure the I'm not a robot check box is ticked"; return(RedirectToAction("Index")); } TempData["Pass"] = "******" + displayName; return(RedirectToAction("Index")); }
public string CaptchaValidate(String EncodedResponse) { try { return(ReCaptchaClass.Validate(EncodedResponse)); } catch (Exception e) { Console.Write(e.Message); } return(""); }
[ValidateAntiForgeryToken] //Para prevenir ataques CSRF public ActionResult RegistrarUsuario([Bind(Include = "Nombre, Apellido, Email, Contrasenia")] Usuario usuario) { var encodedResponse = Request.Form["g-Recaptcha-Response"]; bool isCaptchaValid = ReCaptchaClass.Validate(encodedResponse); System.Diagnostics.Debug.Write("Registracion - Captcha: ", isCaptchaValid.ToString()); if (!isCaptchaValid) { TempData["Error"] = "El captcha es inválido"; } else { if (ModelState.IsValid) { String nombre = usuario.Nombre; String apellido = usuario.Apellido; String email = usuario.Email; String contrasenia = usuario.Contrasenia; String contrasenia2 = Request["Contrasenia2"]; //Chequeo en la salida los datos que se recibieron System.Diagnostics.Debug.WriteLine("Datos recibidos del formulario: " + nombre + " " + apellido + " " + email + " " + contrasenia + " " + contrasenia2); Usuario user = _usuarioService.registrarUsuario(new Usuario(usuario.Nombre, usuario.Apellido, usuario.Email, usuario.Contrasenia), contrasenia2); string mensajeError = ""; if (user != null) { Session["usuarioSesionEmail"] = user.Email; Session["usuarioSesionNombre"] = user.Nombre; Session["usuarioSesionApellido"] = user.Apellido; Session["usuarioSesionId"] = user.IdUsuario; return(RedirectToAction("Index", "Usuario")); /*redirije al Home*/ } else { //Informar de alguna forma que no se pudo registrar el usuario mensajeError = _usuarioService.mostrarMensajeDeError(); TempData["Error"] = mensajeError; } } else { TempData["Error"] = null; } } return(View("Registracion", usuario)); }
public async Task <ResetPassOutput> ResetPass(ResetPassInput model) { bool IsCaptchaValid = (ReCaptchaClass.Validate(model.CaptchaResponse) == "true" ? true : false); if (!IsCaptchaValid) { return(new ResetPassOutput { CaptchaInvalid = true }); } try { var randomService = new RandomService(); var user = await UserManager.FindByEmailAsync(model.Email); var code = await UserManager.GeneratePasswordResetTokenAsync(user); user.IsPasswordReset = true; CurrentUnitOfWork.SaveChanges(); var password = $"{randomService.RandomPassword()}"; var resetRes = await UserManager.ResetPasswordAsync(user, code, password); if (!resetRes.Succeeded) { throw new UserFriendlyException("خطایی در تغییر رمز عبور اتفاق افتاده است."); } BackgroundJobClient.Enqueue <AccountAppService>(instance => instance.SendResetPassEmailAsync(user, password)); eventBus.Trigger(new PasswordResetEventData { UserId = user.Id, NewPassword = password }); return(new ResetPassOutput { Success = true }); } catch (Exception ex) { Logger.Error("Error in reset password", ex); return(new ResetPassOutput { Success = true }); } }
public async Task <RegisterOutput> Register(RegisterInput input) { bool isCaptchaValid = (ReCaptchaClass.Validate(input.CaptchaResponse) == "true" ? true : false); if (!isCaptchaValid) { throw new UserFriendlyException("تیک من ربات نیستم را کلیک نمایید."); } var userExists = userRepo.GetAll().Any(ff => ff.NormalizedEmailAddress == input.EmailAddress.ToUpper()); if (userExists) { throw new UserFriendlyException("آدرس ایمیل وارد شده تکراری است."); } var user = await _userRegistrationManager.RegisterAsync( input.Name, input.Surname, input.EmailAddress, input.EmailAddress, input.Password, input.KodeMelli, input.PhoneNumber, false ); user.SetNewEmailConfirmationCode(); BackgroundJobClient.Enqueue <AccountAppService>(instance => instance.SendConfirmEmailAsync(user)); var verifyCode = RandomService.GetNDigitsRandomNumber(4).ToString(); user.MobileVerificationCode = verifyCode; user.MobileVerificationCodeTime = DateTime.Now; user.IsPhoneNumberConfirmed = false; await UserManager.UpdateAsync(user); var message = $@"مالکینو کد تایید شما: {verifyCode} "; BackgroundJobClient.Enqueue <AccountAppService>(instance => instance.SendSms(message, user.PhoneNumber)); return(new RegisterOutput { RegisterResult = true }); }
private void ClickME() { //Session[sessionNames.userName_StudentOstad] = ""; //test students and profs for exams var testMode = false; var profdTests = new string[] { "1", "12", "13", "136", "1539", "4023", "4257", "5008", "5010", "5051" }; var studentsTests = new string[] { "99001", "99002", "99003", "99004", "99005", "99006" }; if (testMode && profdTests.Contains(txtUserName.Value)) { string name = Rbusiness.getTeacherName_Fostad(int.Parse(txtUserName.Value)); Session[sessionNames.userID_StudentOstad] = txtUserName.Value; Session[sessionNames.userName_StudentOstad] = name; Session["Password"] = txtPassword.Value; Session["IsOstad"] = true; Session["UserType_lms"] = 2; Response.Redirect("~/CommonUI/TeacherIntro.aspx"); } if (testMode && studentsTests.Contains(txtUserName.Value)) { Session[sessionNames.userID_StudentOstad] = txtUserName.Value; Session["Password"] = txtPassword.Value; Session["LogStatus"] = "1-1"; Session["UserType_lms"] = 3; Response.Redirect("~/CommonUI/IntroPage.aspx"); } Session[sessionNames.userName_StudentOstad] = ""; if (int.Parse(Session["Counter"].ToString()) < 2) { LoginMangement(txtUserName.Value.changePersianNumberToLatinNumber(), txtPassword.Value.changePersianNumberToLatinNumber()); } else { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "true" ? true : false); if (IsCaptchaValid) { LoginMangement(txtUserName.Value.changePersianNumberToLatinNumber(), txtPassword.Value.changePersianNumberToLatinNumber()); Session["Counter"] = 0; } } }
protected void Btnvalida_Click(object sender, EventArgs e) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "true" ? true : false); if (IsCaptchaValid) { //Valid Request LblEsito.Text = "validazione ok"; } else { LblEsito.Text = "errore validazione"; } //if (!checkRecaptcha(request.ReCaptcha, "6LfD8GAUAAAAAJFXoMzqt3FHHRwpsypGBJKtLxwi")) //{ //} }
protected void Unnamed_Click(object sender, EventArgs e) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = Convert.ToBoolean((ReCaptchaClass.Validate(EncodedResponse))); if (IsCaptchaValid) { if (CheckControls() == true) { string Name = Nametb.Text; string Subject = Subjecttb.Text; string Body = Bodytb.Text; string ModBody = Name + "," + Environment.NewLine + Body; email.SendQCEmail(Subject, ModBody); } } Nametb.Text = ""; Subjecttb.Text = ""; Bodytb.Text = ""; }
public ActionResult Create([Bind(Include = "Id,Title,Content,UserId,UserName")] Comment comment) { comment.UserId = User.Identity.GetUserId(); comment.UserName = User.Identity.GetUserName(); ModelState.Clear(); TryValidateModel(comment); if (ModelState.IsValid) { string EncodedResponse = Request.Form["g-recaptcha-response"]; bool isCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "true" ? true : false); if (isCaptchaValid) { db.Comments.Add(comment); db.SaveChanges(); return(RedirectToAction("Index")); } else { TempData["recaptcha"] = "Please verify you are not a robot"; } } return(View(comment)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "True" ? true : false); if (IsCaptchaValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // 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, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } else { TempData["recaptcha"] = "Please verify that you are not a robot"; } } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult LogOn(LogOnModel model, string returnUrl) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "True" ? true : false); int FailedLogonAttempts = 0; HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["FailedLogonAttempts"]; if (cookie != null) { int.TryParse(cookie.Value, out FailedLogonAttempts); } if (ModelState.IsValid && (FailedLogonAttempts < 2 || IsCaptchaValid)) { using (ccEntities context = new ccEntities()) { //get membership user with the same username var membershipUser = context.MembershipUsers .Include(f => f.User) .SingleOrDefault(f => f.LoweredUserName == model.UserName); //validate password if the user exists if (membershipUser == null) { var u = context.Users.SingleOrDefault(f => f.UserName == model.UserName); if (u != null) { var mu = context.MembershipUsers.SingleOrDefault(f => f.Id == u.Id); log.Debug(string.Format("LogOn failed: membershipUser is null, user not null. The user's username is {0}, the username of membershipUser with same id is {1}", u.UserName, mu.LoweredUserName)); } else { log.Debug(string.Format("LogOn failed: user wasn't found. The entered username is {0}", model.UserName)); } ModelState.AddModelError("", "The user name or password provided is incorrect."); FailedLogonAttempts++; if (cookie != null) { cookie.Value = FailedLogonAttempts.ToString(); this.ControllerContext.HttpContext.Response.Cookies.Add(cookie); } } else if (membershipUser != null && membershipUser.ValidatePassword(model.Password)) { //get the last agreement id var lastAgreement = context.UserAgreements.OrderByDescending(f => f.Date).FirstOrDefault(); //user is required to sing the agreement if it exists an he had not already sing it var agreementRequired = lastAgreement != null && !membershipUser.User.UserAgreementAudits.Any(f => f.UserAgreementId == lastAgreement.Id); if (membershipUser.User.Disabled) { ModelState.AddModelError("", "This ID has been disabled due to inactivity. If you wish to have this ID re-enabled, please contact your local administrator or your Claims Conference Program Assistant."); } else if (membershipUser.ExpirationDate > DateTime.Now) { return(this.RedirectToAction(f => f.AccountExpired(membershipUser.User.UniqueId))); } else if (agreementRequired) { return(this.RedirectToAction(f => f.UserAgreement(membershipUser.User.UniqueId))); } else { //set authentication cookie var user = membershipUser.User; membershipUser.FailedPasswordAttemptCount = 0; membershipUser.LastLoginDate = DateTime.Now; context.SaveChanges(); FailedLogonAttempts++; if (cookie != null) { cookie.Value = FailedLogonAttempts.ToString(); cookie.Expires = DateTime.Now.AddDays(-1); this.ControllerContext.HttpContext.Response.Cookies.Add(cookie); } FormsAuthentication.RedirectFromLoginPage(user.UserName, true); //redirect from login if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return(Redirect(returnUrl)); } else { return(Redirect("~/")); } } } else { //if user inserted incorrect password less then 5 times and he is not disabled if (membershipUser.FailedPasswordAttemptCount < 4 && !membershipUser.User.Disabled) { membershipUser.FailedPasswordAttemptCount++; ModelState.AddModelError("", "The user name or password provided is incorrect."); FailedLogonAttempts++; if (cookie != null) { cookie.Value = FailedLogonAttempts.ToString(); this.ControllerContext.HttpContext.Response.Cookies.Add(cookie); } } //user inserted incorrect password on his 5th time, or he is already disabled else { membershipUser.User.Disabled = true; ModelState.AddModelError("", "You have exceeded the number of failed login attempts allowed and your account has been locked. Please contact your Program Assistant or Program Officer for assistance."); } context.SaveChanges(); } } } else if (!IsCaptchaValid) { ModelState.AddModelError("", "Please complete captcha verification to login."); } ViewBag.FailedLogonAttempts = FailedLogonAttempts; // If we got this far, something failed, redisplay form return(View(model)); }
protected void CreateUser_Click(object sender, EventArgs e) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "true" ? true : false); }
public JsonResult IsValidRecapcha(string response) => Json(ReCaptchaClass.Validate(response) == "True" ? true : false);
public ActionResult Reg(regModel backModel) { if (ModelState.IsValid) { string PrivateKey = Settings.SecretKey; string EncodedResponse = Request["g-Recaptcha-Response"]; bool IsCaptchaValid = (ReCaptchaClass.Validate(PrivateKey, EncodedResponse).ToLower() == "true" ? true : false); bool IsEmailValid = _repository.CheckCustomerMail(backModel.Email); if (IsCaptchaValid) { if (!IsEmailValid) { char[] _pass = backModel.Pass.Password.ToCharArray(); Cripto password = new Cripto(_pass); string NewSalt = password.Salt; string NewHash = password.Hash; UsersModel User = new UsersModel() { Id = Guid.NewGuid(), FIO = backModel.UserName, Phone = backModel.Phone, EMail = backModel.Email, Address = backModel.Address, Organization = backModel.Organization, Salt = NewSalt, Hash = NewHash, Disabled = true }; if (_repository.createCustomer(User)) { #region Оповещение string Massege = String.Empty; Mailer Letter = new Mailer() { Theme = "Регистрация на сайте " + Settings.BaseURL }; Massege = "<p>Здравствуйте, " + User.FIO + "</p>"; Massege += "<p>Благодарим Вас за регистрацию на сайте " + Settings.SiteTitle + ". Для подтверждения регистрация и активации вашего аккаунта, пожалуйста, перейдите по ссылке.</p>"; Massege += "<p>Если ваша почтовая программа не поддерживает прямые переходы, Вы можете скопировать данную ссылку в адресную строку браузера.</p>"; Massege += "<p><a href=\"https://" + Settings.BaseURL + "/User/ConfirmMail/" + User.Id + "/\">https://" + Settings.BaseURL + "/User/ConfirmMail/" + User.Id + "/</a></p>"; Massege += "<p>Если Вы не проходили регистрацию на сайте " + Settings.BaseURL + " и получили это письмо случайно, пожалуйста, удалите его.</p>"; Massege += "<p>С уважением,<br />Администрация сайта " + Settings.BaseURL + "</p>"; Massege += "<hr><i><span style=\"font-size:12px\">Это сообщение отпралено роботом, на него не надо отвечать</i></span>"; Letter.MailTo = User.EMail; Letter.Text = Massege; string ErrorText = Letter.SendMail(); #endregion return(RedirectToAction("RegCompleted", "user")); } else { ModelState.AddModelError("", "Ошибка при регистрации пользователя. Обратитесь в службу тех. поддержки."); } } else { //userMassege.info = "Не пройдена проверка \"Я не робот\"."; ModelState.AddModelError("", "пользователь с таким E-Mail уже зарегистрирован. Воспользуйтесь сервисом востановления пароля."); } } else { //userMassege.info = "Не пройдена проверка \"Я не робот\"."; ModelState.AddModelError("", "Не пройдена проверка \"Я не робот\"."); } } else { ModelState.AddModelError("", "Произошла ошибка, попробуйте снова."); } return(View(model)); }
public void ProcessForm([FromBody] Dictionary <string, object> contactFormRequest) { // Pre-work: help the dictionary with the values uses case-insensitive key AccessLevel contactFormRequest = new Dictionary <string, object>(contactFormRequest, StringComparer.OrdinalIgnoreCase); // test exception to see how the js-side behaves on errors // throw new Exception(); // 0. Pre-Check - validate recaptcha if used if (Content.Recaptcha ?? false) { var recap = contactFormRequest["Recaptcha"]; if (!(recap is string) || String.IsNullOrEmpty(recap as string)) { throw new Exception("recaptcha is empty"); } // do server-validation // based on http://stackoverflow.com/questions/27764692/validating-recaptcha-2-no-captcha-recaptcha-in-asp-nets-server-side var ok = ReCaptchaClass.Validate(recap as string, App.Settings.RecaptchaSecretKey); if (!ok) { throw new Exception("bad recaptcha '" + ok + "'"); } } // after saving, remove recaptcha fields from the data-package, // because we don't want them in the e-mails removeKeys(contactFormRequest, new string[] { "g-recaptcha-response", "useRecaptcha", "Recaptcha", "submit" }); // get configuration for this Form // it is either customized at Content-level, or we should use the default in the App.Settings // the content-type is stored as the StaticName - but for the simple API we need the "nice name" var config = (Content.Presentation.SubmitType as IEnumerable <dynamic>).FirstOrDefault() ?? (App.Settings.SubmitType as IEnumerable <dynamic>).First(); var type = Data.Cache.GetContentType(config.ContentType); // 1. add IP / host, and save all fields // if you add fields to your content-type, just make sure they are // in the request with the correct name, they will be added automatically contactFormRequest.Add("Timestamp", DateTime.Now); contactFormRequest.Add("SenderIP", System.Web.HttpContext.Current.Request.UserHostAddress); contactFormRequest.Add("ModuleId", Dnn.Module.ModuleID); // add raw-data, in case the content-type has a "RawData" field contactFormRequest.Add("RawData", JsonConvert.SerializeObject(contactFormRequest)); // add Title (if non given), in case the Content-Type would benefit of an automatic title var addTitle = !contactFormRequest.ContainsKey("Title"); if (addTitle) { contactFormRequest.Add("Title", "Form " + DateTime.Now.ToString("s")); } App.Data.Create(type.Name, contactFormRequest); // 2. assemble all settings to send the mail // background: some settings are made in this module, // but if they are missing we use fallback settings // which are taken from the App.Settings var settings = new { MailFrom = !String.IsNullOrEmpty(Content.MailFrom) ? Content.MailFrom : App.Settings.OwnerMail, OwnerMail = !String.IsNullOrEmpty(Content.OwnerMail) ? Content.OwnerMail : App.Settings.OwnerMail }; // Pre 3: Improve keys / values for nicer presentation in the mail // after saving, remove raw-data and the generated title // because we don't want them in the e-mails removeKeys(contactFormRequest, new string[] { "RawData", addTitle ? "Title" : "some-fake-key" }); // rewrite the keys to be a nicer format, based on the configuration string mailLabelRewrites = (!String.IsNullOrEmpty(config.MailLabels) ? config.MailLabels : App.Settings.SubmitType[0].MailLabels) ?? ""; var valuesWithMailLabels = RewriteKeys(contactFormRequest, mailLabelRewrites); // 3. Send Mail to owner // uses the DNN command: http://www.dnnsoftware.com/dnn-api/html/886d0ac8-45e8-6472-455a-a7adced60ada.htm var custMail = contactFormRequest.ContainsKey("SenderMail") ? contactFormRequest["SenderMail"].ToString() : ""; if (Content.OwnerSend != null && Content.OwnerSend) { var ownerMailEngine = TemplateInstance(config.OwnerMailTemplate); var ownerBody = ownerMailEngine.Message(valuesWithMailLabels, this).ToString(); var ownerSubj = ownerMailEngine.Subject(valuesWithMailLabels, this); Mail.SendMail(settings.MailFrom, settings.OwnerMail, Content.OwnerMailCC, "", custMail, MailPriority.Normal, ownerSubj, MailFormat.Html, System.Text.Encoding.UTF8, ownerBody, new string[0], "", "", "", "", false); } // 4. Send Mail to customer if (Content.CustomerSend != null && Content.CustomerSend && !String.IsNullOrEmpty(custMail)) { var customerMailEngine = TemplateInstance(config.CustomerMailTemplate); var customerBody = customerMailEngine.Message(valuesWithMailLabels, this).ToString(); var customerSubj = customerMailEngine.Subject(valuesWithMailLabels, this); Mail.SendMail(settings.MailFrom, custMail, Content.CustomerMailCC, "", settings.OwnerMail, MailPriority.Normal, customerSubj, MailFormat.Html, System.Text.Encoding.UTF8, customerBody, new string[0], "", "", "", "", false); } }