public void IsValidTests() { // Arrange var attribute = new EmailAddressAttribute(); // Act & Assert Assert.IsTrue(attribute.IsValid(null)); // Optional values are always valid Assert.IsTrue(attribute.IsValid("*****@*****.**")); Assert.IsTrue(attribute.IsValid("*****@*****.**")); Assert.IsFalse(attribute.IsValid("joe")); Assert.IsFalse(attribute.IsValid("joe@")); Assert.IsFalse(attribute.IsValid("joe@contoso")); }
static void Main(string[] args) { Console.WriteLine("Path to the file: "); string path = Console.ReadLine(); Console.WriteLine("Sender Email Address: "); string senderEmail = Console.ReadLine(); var foo = new EmailAddressAttribute(); while (!foo.IsValid(senderEmail)) { Console.WriteLine("Incorrect email. Try again.\nSender Email Address: "); senderEmail = Console.ReadLine(); } Console.WriteLine("Sender Password: "******"Receiver Email Address: "); string receiverEmail = Console.ReadLine(); var foo1 = new EmailAddressAttribute(); while (!foo1.IsValid(receiverEmail)) { Console.WriteLine("Incorrect email. Try again.\nReceiver Email Address: "); receiverEmail = Console.ReadLine(); } List <Person> people = new List <Person>(); try { StreamReader reader = new StreamReader(File.OpenRead(path)); while (!reader.EndOfStream) { string line = reader.ReadLine(); if (!String.IsNullOrWhiteSpace(line)) { string[] values = line.Split(';'); if (values.Length >= 5 && values[0] != "First Name") { Person person = new Person(values[0], values[1], values[2], values[3], int.Parse(values[4])); people.Add(person); } } } } catch (Exception exc) { Console.WriteLine("Unable to open the file with this pathname.\nError: " + exc); } List <string> countries = new List <string>(); foreach (Person person in people) { if (!countries.Contains(person.Country)) { countries.Add(person.Country); } } List <Sample> samples = new List <Sample>(); foreach (string country in countries) { List <Person> group = new List <Person>(); List <int> scores = new List <int>(); Sample sample = new Sample(); foreach (Person person in people) { if (person.Country == country) { group.Add(person); } } foreach (Person participant in group) { scores.Add(participant.Score); } sample.Country = country; sample.FindAverage(scores); sample.FindMedian(scores); sample.FindMax(scores); sample.FindMaxPerson(group); sample.FindMin(scores); sample.FindMinPerson(group); sample.FindRecordCount(scores); samples.Add(sample); } List <Sample> sortedSamples = samples.OrderByDescending(o => o.Average).ToList(); string directoryName = Path.GetDirectoryName(path); string newPath = directoryName + @"\ReportByCountry.csv"; try { using (File.Create(newPath)); using (StreamWriter writer = new StreamWriter(newPath)) using (CsvWriter csvWriter = new CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture)) { csvWriter.Configuration.Delimiter = ";"; csvWriter.Configuration.HasHeaderRecord = true; csvWriter.Configuration.AutoMap <Sample>(); csvWriter.WriteHeader <Sample>(); csvWriter.NextRecord(); csvWriter.WriteRecords(sortedSamples); writer.Flush(); } } catch (Exception exc) { Console.WriteLine("Error pathname or incorrect writing data in the new file.\nError: " + exc); } try { SmtpClient client = new SmtpClient("smtp.gmail.com", 587); MailMessage mail = new MailMessage(); mail.From = new MailAddress(senderEmail); mail.To.Add(receiverEmail); mail.Subject = "Email with attachment"; mail.Attachments.Add(new Attachment(newPath)); client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(senderEmail, senderPassword); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.EnableSsl = true; client.Send(mail); } catch (Exception exc) { Console.WriteLine("Unable to send email.\nError: " + exc); } }
internal URegisterResponse UserRegisterAction(URegisterData data) { UDataTable result; EmailAddressAttribute validate = new EmailAddressAttribute(); if (validate.IsValid(data.Email)) { string pass = LoginHelper.HashGen(data.Password); if (data.Password == data.ConfirmedPassword) { using (var db = new UserContext()) { result = db.Users.FirstOrDefault(u => u.Email == data.Email); } if (result != null) { return(new URegisterResponse { Status = false, StatusMessage = "This Username is already in use(1)" }); } result = new UDataTable { Username = data.Username, Email = data.Email, LastIp = data.LoginIp, LastLogin = data.LoginDateTime, ProfileImageUrl = data.ProfileImageUrl, Level = Role.User, Password = LoginHelper.HashGen(data.Password) }; using (var todo = new UserContext()) { todo.Users.Add(result); todo.SaveChanges(); } return(new URegisterResponse { Status = true }); } return(new URegisterResponse { Status = false, StatusMessage = "Passwords did not Match" }); } else { string pass = LoginHelper.HashGen(data.Password); if (data.Password == data.ConfirmedPassword) { using (var db = new UserContext()) { result = db.Users.FirstOrDefault(u => u.Username == data.Username); } if (result != null) { return(new URegisterResponse { Status = false, StatusMessage = "This Username is already in use(2)" }); } result = new UDataTable { Username = data.Username, Email = data.Email, LastIp = data.LoginIp, LastLogin = data.LoginDateTime, ProfileImageUrl = data.ProfileImageUrl, Level = Role.User, Password = LoginHelper.HashGen(data.Password) }; using (var todo = new UserContext()) { todo.Users.Add(result); todo.SaveChanges(); } return(new URegisterResponse { Status = true }); } return(new URegisterResponse { Status = false, StatusMessage = "Passwords did not Match" }); } }
private bool IsValidEmail(string email) { var emailAttribute = new EmailAddressAttribute(); return(emailAttribute.IsValid(email)); }
//Email validation public bool IsValidEmail(String email) { EmailAddressAttribute emailObj = new EmailAddressAttribute(); return(emailObj.IsValid(email)); }
public bool IsEmailValid(string emailaddress) { return(checkmail.IsValid(emailaddress)); }
/// <summary> /// Provides a common email validator, ensure max length is 250, is all lowercase, and use validator. /// </summary> public static CommonValidator <string?> Email = CommonValidator.Create <string?>(cv => cv.String(250).Override(v => v.Value !.ToLowerInvariant()).Must(v => _emailValidator.IsValid(v.Value)));
private void adduser_btn(object sender, RoutedEventArgs e) { try { var user = new ABusers(); if (firstname_txt.Text == "" || lastname_txt.Text == "" || password_txt.Text == "" || email_txt.Text == "" || phone_txt.Text == "" || company_txt.Text == "" || combobox.Text == "" || imagetext.Text == "") { MessageBox.Show("Some information are missing ,please fill the form completely", "Information Message"); } if (firstname_txt.Text.Any(c => char.IsNumber(c))) { MessageBox.Show("Please enter your firstname in letters,numbers ae not allowed ", "Adminstrator Message"); firstname_txt.Focus(); } if (lastname_txt.Text.Any(c => char.IsNumber(c))) { MessageBox.Show("Please enter your lastname in letters,numbers ae not allowed ", "Adminstrator Message"); firstname_txt.Focus(); } if (password_txt.Text.Length < 8) { MessageBox.Show("Password is at least 8 characters ", "Adminstrator Message"); password_txt.Focus(); } if (phone_txt.Text.Any(c => char.IsLetter(c)) && phone_txt.Text.Length < 11) { MessageBox.Show("Phone is only numeric digits and must be at least 11 number ", "Adminstrator Message"); password_txt.Focus(); } var email = new EmailAddressAttribute(); bool check = email.IsValid(email_txt.Text); if (!check) { MessageBox.Show("Not the desired format of email ,please enter your email as the format shown beside email textbox", "Adminstrator Message"); } else { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:62135/"); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); user.FirstName = firstname_txt.Text; user.LastName = lastname_txt.Text; user.Username = username_txt.Text; byte[] data = UTF8Encoding.UTF8.GetBytes(password_txt.Text); user.Pass = Convert.ToBase64String(data).ToString(); user.Email = email_txt.Text; user.Phone = phone_txt.Text; user.Company = company_txt.Text; user.Type_user = combobox.Text; user.Picture = getImageArraybyte(bm); var response = client.PostAsJsonAsync("api/journal", user).Result; if (response.IsSuccessStatusCode) { MessageBox.Show("New User has been added Sucessfully"); clearTexts(); retrieveData(); } else { MessageBox.Show(response.StatusCode + " With Message " + response.ReasonPhrase); } } } catch (Exception ex) { MessageBox.Show("Username is already exist"); } }
public static bool CheckEmailFormat(string email) { var attr = new EmailAddressAttribute(); return(attr.IsValid(email)); }
internal ULoginResp UserLoginAction(ULoginData data) { UserDatas result; var validate = new EmailAddressAttribute(); if (validate.IsValid(data.Credential)) { var pass = LoginHelper.HashGen(data.Password); using (var db = new UserContext()) { result = db.Users.FirstOrDefault(u => u.Email == data.Credential && u.Password == pass); } if (result == null) { return(new ULoginResp { Status = false, StatusMsg = "The Email or Password is Incorrect" }); } using (var todo = new UserContext()) { result.LastIp = data.LoginIp; result.LastLogin = data.LoginDateTime; todo.Entry(result).State = EntityState.Modified; todo.SaveChanges(); } return(new ULoginResp { Status = true, StatusMsg = "Registration Successfull! " + "Redirectind to login page in 5 seconds." }); } else { var pass = LoginHelper.HashGen(data.Password); using (var db = new UserContext()) { result = db.Users.FirstOrDefault(u => u.Username == data.Credential && u.Password == pass); } if (result == null) { return(new ULoginResp { Status = false, StatusMsg = "The Username or Password is Incorrect" }); } using (var todo = new UserContext()) { result.LastIp = data.LoginIp; result.LastLogin = data.LoginDateTime; todo.Entry(result).State = EntityState.Modified; todo.SaveChanges(); } return(new ULoginResp { Status = true, StatusMsg = "Registration Successful! " + "Redirecting to login page in 5 seconds." }); } }
public ICredential GetCredential(string credentialString) { if (string.IsNullOrEmpty(credentialString) || credentialString.IndexOf(';') <= 0) { return(null); } var type = string.Empty; var name = string.Empty; var user = string.Empty; var password = string.Empty; var token = string.Empty; var accountId = string.Empty; var validTo = DateTime.MinValue; var regex = new Regex(@";"); var items = regex.Split(credentialString); foreach (var item in items) { if (string.IsNullOrEmpty(item) || item.IndexOf('=') <= 0) { continue; } var itemName = item.Substring(0, item.IndexOf('=')).Trim(); var itemValue = item.Substring(item.IndexOf('=') + 1).Trim(); if (string.Compare(itemName, "Type", StringComparison.InvariantCultureIgnoreCase) == 0) { type = itemValue; } if (string.Compare(itemName, "Name", StringComparison.InvariantCultureIgnoreCase) == 0) { name = itemValue; } if (string.Compare(itemName, "user", StringComparison.InvariantCultureIgnoreCase) == 0) { user = itemValue; } if (string.Compare(itemName, "Password", StringComparison.InvariantCultureIgnoreCase) == 0) { password = itemValue; } if (string.Compare(itemName, "Token", StringComparison.InvariantCultureIgnoreCase) == 0) { token = itemValue; } if (string.Compare(itemName, "AccountId", StringComparison.InvariantCultureIgnoreCase) == 0) { accountId = itemValue; } if (string.Compare(itemName, "ValidTo", StringComparison.InvariantCultureIgnoreCase) == 0) { var success = long.TryParse(itemValue, out var value); if (success) { validTo = DateTime.FromBinary(value); } } } if (string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(password)) { if (string.Compare(type, "CustomUser", StringComparison.CurrentCultureIgnoreCase) == 0) { var emailAddress = new EmailAddressAttribute(); var isvalid = emailAddress.IsValid(user); type = isvalid ? Authentication.AuthenticationType.User.ToString() : Authentication.AuthenticationType.Client.ToString(); } else { type = Authentication.AuthenticationType.Studio.ToString(); } name = user; } if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(name)) { var credential = new Credential { Type = (Authentication.AuthenticationType)Enum.Parse(typeof(Authentication.AuthenticationType), type, true), Name = name, Password = password, Token = token, AccountId = accountId, ValidTo = validTo }; if (!string.IsNullOrEmpty(token) && credential.ValidTo == DateTime.MinValue) { credential.ValidTo = GetTokenValidTo(token); } return(credential); } return(null); }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { var result = new List <ValidationResult>(); // Required fields if (string.IsNullOrWhiteSpace(UpdateUser)) { result.Add(GetRequiredError(nameof(UpdateUser))); } if (!UpdateDate.HasValue) { result.Add(GetRequiredError(nameof(UpdateDate))); } // Card No if (string.IsNullOrWhiteSpace(CardNo) ^ string.IsNullOrWhiteSpace(SubscriptTypeCode)) { result.Add(new ValidationResult("Incomplete card information (missing CardNo or SubscriptTypeCode).")); } else if (!IsValidCardFormat()) { result.Add(new ValidationResult("Invalid Personal card information.")); } // FirstName if (string.IsNullOrWhiteSpace(FirstName)) { result.Add(GetRequiredError(nameof(FirstName))); } else if (FirstName.Length > Constants.MaxLength.FirstName) { result.Add(GetTooLongError(nameof(FirstName), Constants.MaxLength.FirstName)); } // LastName if (!string.IsNullOrWhiteSpace(LastName) && LastName.Length > Constants.MaxLength.LastName) { result.Add(GetTooLongError(nameof(LastName), Constants.MaxLength.LastName)); } bool?isActive; // ExpireDate if (ExpiryDate.HasValue && ExpiryDate.Value < DateTime.Today) { result.Add(new ValidationResult("ExpiryDate is before today")); } if (!IsValidTrueFalseDigit(Status, out isActive)) { result.Add(GetInvalidTrueFalseDigitFormat(nameof(Status))); } // System Code if (SystemCode.GetCleanString().Length > Constants.MaxLength.SystemCode) { result.Add(GetTooLongError(nameof(SystemCode), Constants.MaxLength.SystemCode)); } // Remark if (Remark.GetCleanString().Length > Constants.MaxLength.RemarkDoNotCall) { result.Add(GetTooLongError(nameof(SystemCode), Constants.MaxLength.RemarkDoNotCall)); } bool validBlockInfo = true; bool?isBlockSalesEmail = null; bool?isBlockSalesSms = null; bool?isBlockSalesTelephone = null; bool?isBlockInfoEmail = null; bool?isBlockInfoSms = null; bool?isBlockInfoTelephone = null; // Sales if (SalesBlockInfo == null) { validBlockInfo = false; result.Add(GetRequiredError(nameof(SalesBlockInfo))); } else { if (!IsValidTrueFalseDigit(SalesBlockInfo.BlockEmail, out isBlockSalesEmail)) { validBlockInfo = false; result.Add(GetInvalidTrueFalseDigitFormat(nameof(SalesBlockInfo.BlockEmail))); } if (!IsValidTrueFalseDigit(SalesBlockInfo.BlockSMS, out isBlockSalesSms)) { validBlockInfo = false; result.Add(GetInvalidTrueFalseDigitFormat(nameof(SalesBlockInfo.BlockSMS))); } if (!IsValidTrueFalseDigit(SalesBlockInfo.BlockTelephone, out isBlockSalesTelephone)) { validBlockInfo = false; result.Add(GetInvalidTrueFalseDigitFormat(nameof(SalesBlockInfo.BlockTelephone))); } else { var productList = SalesBlockInfo.BlockProducts; if (productList != null && productList.Count > 0) { List <string> duplicatedItems = productList.GroupBy(x => x.ProductCode.GetCleanString()).Where(group => group.Count() > 1).Select(x => x.Key).ToList(); if (duplicatedItems != null && duplicatedItems.Count > 0) { result.Add(new ValidationResult($"Duplicated product code: {string.Join(",", duplicatedItems)}")); } else { foreach (var product in productList) { ValidateProductListItem(result, product); } } } } } // Information if (InformationBlockInfo == null) { validBlockInfo = false; result.Add(GetRequiredError(nameof(InformationBlockInfo))); } else { if (!IsValidTrueFalseDigit(InformationBlockInfo.BlockEmail, out isBlockInfoEmail)) { validBlockInfo = false; result.Add(GetInvalidTrueFalseDigitFormat(nameof(InformationBlockInfo.BlockEmail))); } if (!IsValidTrueFalseDigit(InformationBlockInfo.BlockSMS, out isBlockInfoSms)) { validBlockInfo = false; result.Add(GetInvalidTrueFalseDigitFormat(nameof(InformationBlockInfo.BlockSMS))); } if (!IsValidTrueFalseDigit(InformationBlockInfo.BlockTelephone, out isBlockInfoTelephone)) { validBlockInfo = false; result.Add(GetInvalidTrueFalseDigitFormat(nameof(InformationBlockInfo.BlockTelephone))); } else { var productList = InformationBlockInfo.BlockProducts; if (productList != null && productList.Count > 0) { List <string> duplicatedItems = productList.GroupBy(x => x.ProductCode.GetCleanString()).Where(group => group.Count() > 1).Select(x => x.Key).ToList(); if (duplicatedItems != null && duplicatedItems.Count > 0) { result.Add(new ValidationResult($"Duplicated product code: {string.Join(",", duplicatedItems)}")); } else { foreach (var product in productList) { ValidateProductListItem(result, product); } } } } } if (validBlockInfo) // every block sales/information item is valid { //Telephone List if (isBlockSalesTelephone.Value || isBlockInfoTelephone.Value || isBlockSalesSms.Value || isBlockInfoSms.Value) { if (TelephoneList.Count == 0) { result.Add(GetRequiredError(nameof(TelephoneList))); } else { List <string> duplicatedItems = TelephoneList.GroupBy(x => x.PhoneNo.GetCleanString()).Where(group => group.Count() > 1).Select(x => x.Key).ToList(); if (duplicatedItems != null && duplicatedItems.Count > 0) { result.Add(new ValidationResult($"Duplicated Telephone: {string.Join(",", duplicatedItems)}")); } else { foreach (var phone in TelephoneList) { string phoneNo = phone.PhoneNo; bool hasPhoneNo = !string.IsNullOrWhiteSpace(phoneNo); if (hasPhoneNo) { // validate format string cleanPhoneNo = phoneNo.GetCleanString(); int phoneNoLength = cleanPhoneNo.Length; int maxPhoneLength = Constants.MaxLength.DoNotCallPhoneNo; int minPhoneLength = Constants.MinLenght.PhoneNo; if (phoneNoLength < minPhoneLength || phoneNoLength > maxPhoneLength || cleanPhoneNo.Any(c => !char.IsDigit(c))) { result.Add(new ValidationResult($"Telephone ต้องระบุเป็นตัวเลข {minPhoneLength}-{maxPhoneLength} หลักเท่านั้น")); break; } } else { result.Add(new ValidationResult("มี Telephone เป็นค่าว่าง")); break; } bool? isActivePhone; string status = phone.IsActive; if (string.IsNullOrWhiteSpace(status) || !IsValidYesNoString(status, out isActivePhone)) { result.Add(GetInvalidTrueFalseDigitFormat("PhoneNoStatus")); } } } } } //Email List if (isBlockInfoEmail.Value || isBlockSalesEmail.Value) { if (EmailList.Count == 0) { result.Add(GetRequiredError(nameof(EmailList))); } else { List <string> duplicatedItems = EmailList.GroupBy(x => x.Email.GetCleanString()).Where(group => group.Count() > 1).Select(x => x.Key).ToList(); if (duplicatedItems != null && duplicatedItems.Count > 0) { result.Add(new ValidationResult($"Duplicated Email: {string.Join(",", duplicatedItems)}")); } else { foreach (var item in EmailList) { var email = item.Email; bool hasEmail = !string.IsNullOrWhiteSpace(email); if (hasEmail) { // validate format string cleanEmail = email.GetCleanString(); var emailChecker = new EmailAddressAttribute(); bool isValid = emailChecker.IsValid(cleanEmail); if (!isValid) { result.Add(new ValidationResult("รูปแบบ email ไม่ถูกต้อง")); break; } else if (email.Length > Constants.MaxLength.Email) { result.Add(new ValidationResult($"ความยาว Email ต้องไม่เกิน {Constants.MaxLength.Email} ตัวอักษร")); break; } } else { result.Add(new ValidationResult("มี Email เป็นค่าว่าง")); break; } bool? isActiveEmail; string status = item.IsActive; if (string.IsNullOrWhiteSpace(status) || !IsValidYesNoString(status, out isActiveEmail)) { result.Add(GetInvalidTrueFalseDigitFormat("EmailStatus")); } } } } } } return(result); }
public ActionResult Account(ProfileValidation model) { var domain = DB.CompanyDomainName.Single(x => x.Id == model.EmailDomain).Name; var newLogin = $"{model.Mailname}@{domain}"; var ea = new EmailAddressAttribute(); if (!ea.IsValid(newLogin)) { ModelState.AddModelError("Mailname", "Неверный формат email"); } if (!ModelState.IsValid) { var appointmentList = DB.AccountAppointment.Where(x => x.GlobalEnabled) .Select(x => new OptionElement { Text = x.Name, Value = x.Id.ToString() }) .ToList(); // добавили кастомную должность, если есть var userOptionAppointment = DB.AccountAppointment.SingleOrDefault(x => x.Id == CurrentUser.AppointmentId && !x.GlobalEnabled); if (userOptionAppointment != null) { appointmentList.Add(new OptionElement { Value = userOptionAppointment.Id.ToString(), Text = userOptionAppointment.Name }); } ViewBag.AppointmentList = appointmentList; ViewBag.DomainList = DB.CompanyDomainName .Where(x => x.CompanyId == CurrentUser.CompanyId) .ToList() .Select(x => new OptionElement { Text = '@' + x.Name, Value = x.Id.ToString() }) .ToList(); return(View(model)); } var accountSave = DB.Account.Single(x => x.Id == CurrentUser.Id); var changeLogin = accountSave.Login != newLogin; accountSave.Name = $"{model.LastName} {model.FirstName} {model.OtherName}"; accountSave.LastName = model.LastName; accountSave.FirstName = model.FirstName; accountSave.OtherName = model.OtherName; accountSave.Login = newLogin; accountSave.Phone = model.PhoneNumber; accountSave.AppointmentId = model.AppointmentId; DB.SaveChanges(); if (changeLogin) { CurrentUser = accountSave; FormsAuthentication.SetAuthCookie(CurrentUser.Login, true); } SuccessMessage("Ваш профиль сохранен"); return(RedirectToAction("Index", "Profile")); }
public override bool IsValid(object value) { return(_validator.IsValid(value)); }
public IHttpActionResult ResetPasswordConfirmation(ResetPasswordConfirmationViewModel user) { var isEmail = new EmailAddressAttribute(); var isExists = new User(); var isValidInput = false; var result = false; bool isValid = string.IsNullOrEmpty(user.Email) ? false : (isEmail.IsValid(user.Email) ? true : (user.Email.ValidatePhoneNumber(true) ? true : false)); if (!isValid) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid Email Address or Mobile Number.,")); } isExists = isEmail.IsValid(user.Email) ? _serviceFactory.CreateUserService.IsUserExist(user.Email) : _serviceFactory.CreateUserService.IsMobileUser(user.Email); if (isExists == null) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "User Not Exists.,")); } if (isEmail.IsValid(user.Email)) { if ((isExists.OTP == user.OTP) && isExists.Email.ToUpper() == user.Email.ToUpper()) { isValidInput = true; } } if (user.Email.ValidatePhoneNumber(true)) { if ((isExists.OTP == user.OTP) && isExists.MobileNo == user.Email) { isValidInput = true; } } if (isExists.OTP != user.OTP) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid OTP.,")); } if (user.Password != user.ConfirmPassword) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Password and confirm password does not match.,")); } isExists.OTP = user.OTP; isExists.IsOTP = true; isExists.UpdatedOn = DateTime.Now; isExists.Password = Utilities.Encrypt(user.Password); if (isValidInput) { result = _serviceFactory.CreateUserService.InsertOrUpdate(isExists) > 0 ? true : false; if (result == false) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Unable to reset your password.,")); } } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Unable to reset your password.,")); } return(Ok(result)); }
public async Task <IActionResult> OnPostContact(ContactVM model) { string messageBack = "Dear Customer, thank you for reaching out! Our team will contact you shortly!"; if (!ModelState.IsValid) { string messages = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)); //if (messages.ToLower().Contains("recaptcha")) //{ // ModelState.Clear(); // //ModelState.AddModelError("", "Are you a human?"); // //messageBack = "ERROR: Are you a robot?"; // //return new JsonResult(new { messageBack = messageBack }); //} } ; var contact = Mapper.Map <ContactVM, Contact>(model); //check email if (model.Email != null) { var foo = new EmailAddressAttribute(); if (!foo.IsValid(model.Email)) { messageBack = "ERROR: Email is not valid!"; return(new JsonResult(new { messageBack = messageBack })); } } else { messageBack = "ERROR: Email is not valid!"; return(new JsonResult(new { messageBack = messageBack })); } //Search for SPAM bool containsAny = false; string[] spam = _config.GetSection("ContactInfoSettintgs")["SpamInclude"].Trim().Split('|'); foreach (string value in spam) { if (model.Message.ToLower().Trim().Contains(value.Trim().ToLower())) { containsAny = true; break; } } if (containsAny) { messageBack = "ERROR: Let's play fair, we are blocking spam messages! Please ensure you enter work related informaiton!"; return(new JsonResult(new { messageBack = messageBack })); } // Insert new contact and send email if (contact.Name != null && contact.Name.Length > 0) { var addContact = new Data.Core.Domain.Contact() { Name = contact.Name, Phone = contact.Phone, Email = contact.Email, Message = contact.Message, AgreeTerms = contact.AgreeTerms, Sent = false, Status = "NEW", DateUpdated = DateTime.UtcNow, UpdatedBy = contact.Name, DateCreated = DateTime.UtcNow, CreatedBy = contact.Name }; try { _unitOfWork.Contacts.Add(addContact); _unitOfWork.Complete(); } catch (Exception ex) { } //if (!model.AgreeTerms) //{ // string body = this.createEmailBody_Contact(contact); // await _sendemail.SendEmailAsync("", "from Contact page", body); //} //StatusMessage = "Dear Customer, thank you for reaching out! Our team will contact you shortly!"; } return(new JsonResult(new { messageBack = messageBack })); }
public virtual UserAccount CreateAccount(string tenant, string username, string password, string email) { Tracing.Information(String.Format("[UserAccountService.CreateAccount] called: {0}, {1}, {2}", tenant, username, email)); if (SecuritySettings.Instance.EmailIsUsername) { username = email; } if (!SecuritySettings.Instance.MultiTenant) { tenant = SecuritySettings.Instance.DefaultTenant; } if (String.IsNullOrWhiteSpace(tenant)) { throw new ArgumentException("tenant"); } if (String.IsNullOrWhiteSpace(username)) { throw new ArgumentException("username"); } if (String.IsNullOrWhiteSpace(password)) { throw new ArgumentException("password"); } if (String.IsNullOrWhiteSpace(email)) { throw new ArgumentException("email"); } ValidatePassword(tenant, username, password); EmailAddressAttribute validator = new EmailAddressAttribute(); if (!validator.IsValid(email)) { Tracing.Verbose(String.Format("[UserAccountService.CreateAccount] Email validation failed: {0}, {1}, {2}", tenant, username, email)); throw new ValidationException("Email is invalid."); } if (EmailExists(tenant, email)) { Tracing.Verbose(String.Format("[UserAccountService.CreateAccount] Email already exists: {0}, {1}, {2}", tenant, username, email)); throw new ValidationException("Email already in use."); } if (UsernameExists(tenant, username)) { Tracing.Verbose(String.Format("[UserAccountService.CreateAccount] Username already exists: {0}, {1}", tenant, username)); throw new ValidationException("Username already in use."); } using (var tx = new TransactionScope()) { var account = new UserAccount(tenant, username, password, email); this.userRepository.Add(account); this.userRepository.SaveChanges(); if (this.notificationService != null) { if (SecuritySettings.Instance.RequireAccountVerification) { this.notificationService.SendAccountCreate(account); } else { this.notificationService.SendAccountVerified(account); } } tx.Complete(); return(account); } }
static public bool isValidEmail(string email) { var addr = new EmailAddressAttribute(); return(addr.IsValid(email)); }
public virtual bool ChangeEmailRequest(string tenant, string username, string newEmail) { Tracing.Information(String.Format("[UserAccountService.ChangeEmailRequest] called: {0}, {1}, {2}", tenant, username, newEmail)); if (!SecuritySettings.Instance.MultiTenant) { tenant = SecuritySettings.Instance.DefaultTenant; } if (String.IsNullOrWhiteSpace(tenant)) { return(false); } if (String.IsNullOrWhiteSpace(username)) { return(false); } if (String.IsNullOrWhiteSpace(newEmail)) { return(false); } EmailAddressAttribute validator = new EmailAddressAttribute(); if (!validator.IsValid(newEmail)) { Tracing.Verbose(String.Format("[UserAccountService.ChangeEmailRequest] email validation failed: {0}, {1}, {2}", tenant, username, newEmail)); throw new ValidationException("Email is invalid."); } var account = this.GetByUsername(tenant, username); if (account == null) { return(false); } Tracing.Verbose(String.Format("[UserAccountService.ChangeEmailRequest] account located: {0}, {1}", account.Tenant, account.Username)); if (EmailExists(tenant, newEmail)) { Tracing.Verbose(String.Format("[UserAccountService.ChangeEmailRequest] Email already exists: {0}, {1}, new email: {2}", tenant, username, newEmail)); throw new ValidationException("Email already in use."); } var result = account.ChangeEmailRequest(newEmail); Tracing.Verbose(String.Format("[UserAccountService.ChangeEmailRequest] change request outcome: {0}, {1}, {2}", account.Tenant, account.Username, result ? "Successful" : "Failed")); if (result) { using (var tx = new TransactionScope()) { this.userRepository.SaveChanges(); if (this.notificationService != null) { this.notificationService.SendChangeEmailRequestNotice(account, newEmail); } tx.Complete(); } } return(result); }
public static async Task <TSEmail> SendEmail(TSEmail ParTSEmail, string ParIPAddress, string ParMachineID, List <string> CallTrace) { var attr = new EmailAddressAttribute(); if (!attr.IsValid(ParTSEmail.To)) { ParTSEmail.Result = "Error:Email format is not valid!"; return(ParTSEmail); } if (ParTSEmail.To.ToLower().Equals("*****@*****.**")) { ParTSEmail.Result = "Error:Can't sent any email to demo user!"; return(ParTSEmail); } bool MustSaveEmailedCode = false; EmailOperationsEnum tmp_Operation = (EmailOperationsEnum)ParTSEmail.OperationCode; string tmp_Code = string.Empty; switch (tmp_Operation) { case EmailOperationsEnum.Registration: tmp_Code = GlobalFunctions.GetSalt(); if (CmdSendEmailAsync(ParTSEmail.To.Trim(), "Registration", "Hello,\n\nYour code is " + tmp_Code + "\nThank you for registration.\n\nBest Regards,\nSite Administration", AddThisCaller(CallTrace, MethodBase.GetCurrentMethod())).Result) { ParTSEmail.Result = "OK"; MustSaveEmailedCode = true; } else { ParTSEmail.Result = "Error"; MustSaveEmailedCode = false; } break; case EmailOperationsEnum.EmailChange: tmp_Code = GlobalFunctions.GetSalt(); if (CmdSendEmailAsync(ParTSEmail.To.Trim(), "Email change", "Hello,\n\nYour code is " + tmp_Code + "\n\nBest Regards,\nSite Administration", AddThisCaller(CallTrace, MethodBase.GetCurrentMethod())).Result) { ParTSEmail.Result = "OK"; MustSaveEmailedCode = true; } else { ParTSEmail.Result = "Error"; MustSaveEmailedCode = false; } break; case EmailOperationsEnum.PasswordChange: tmp_Code = GlobalFunctions.GetSalt(); if (CmdSendEmailAsync(ParTSEmail.To.Trim(), "Password change", "Hello,\n\nYour code is " + tmp_Code + "\n\nBest Regards,\nSite Administration", AddThisCaller(CallTrace, MethodBase.GetCurrentMethod())).Result) { ParTSEmail.Result = "OK"; MustSaveEmailedCode = true; } else { ParTSEmail.Result = "Error"; MustSaveEmailedCode = false; } break; case EmailOperationsEnum.PasswordRecovery: MustSaveEmailedCode = false; if (CmdSendEmailAsync(ParTSEmail.To.Trim(), "Password Recovery", "Hello,\n\nYour new password is " + ParMachineID + "\n\nPlease change password after login.\n\nBest Regards,\nSite Administration", AddThisCaller(CallTrace, MethodBase.GetCurrentMethod())).Result) { ParTSEmail.Result = "OK"; } else { ParTSEmail.Result = "Error"; } break; case EmailOperationsEnum.TodoReminder: MustSaveEmailedCode = false; if (CmdSendEmailAsync(ParTSEmail.To.Trim(), "Todo Reminder", "Hello,\n\nYour requested todo remind is here.\n\n" + ParMachineID + "\n\nBest Regards,\nSite Administration", AddThisCaller(CallTrace, MethodBase.GetCurrentMethod())).Result) { ParTSEmail.Result = "OK"; } else { ParTSEmail.Result = "Error"; } break; default: break; } if (MustSaveEmailedCode) { CosmosEmailedCode tsEmailedCode = new CosmosEmailedCode { Email = ParTSEmail.To.Trim(), Code = tmp_Code, IPAddress = ParIPAddress, OperationType = ParTSEmail.OperationCode, MachineID = ParMachineID, }; await CmdSaveEmailedCode(tsEmailedCode, AddThisCaller(CallTrace, MethodBase.GetCurrentMethod())); } return(ParTSEmail); }
/// <summary> /// Tries to convert the given value to the given format /// </summary> /// <param name="dataType">The data type of the given value</param> /// <param name="value">The value to type check</param> /// <returns>True of successful, otherwise throws exception</returns> private bool TryDataConversion(DataDescriptor descriptor, object data) { // Gaurd against null reference if (data == null) { throw new NullReferenceException(); } var value = data.ToString(); switch (descriptor.DataType) { case "bool": Convert <bool>(value); break; case "date-time": Convert <DateTimeOffset>(value); break; case "double": Convert <double>(value); break; case "email": Convert <string>(value); var emailValidator = new EmailAddressAttribute(); return(emailValidator.IsValid(value)); case "int32": Convert <int>(value); break; case "int64": Convert <long>(value); break; case "guid": Convert <Guid>(value); break; case "phone": Convert <string>(value); var phoneValidator = new PhoneAttribute(); return(phoneValidator.IsValid(value)); case "string": Convert <string>(value); if (!string.IsNullOrEmpty(descriptor.Pattern)) { var regexValidator = new RegularExpressionAttribute(descriptor.Pattern); return(regexValidator.IsValid(value)); } break; case "time-span": Convert <TimeSpan>(value); break; default: // Log error throw new NotImplementedException(string.Format("The format: {0} with value: {1} has no corresponding cast", descriptor.DataType, value)); } return(true); }
public static Boolean validarMail(string mail) { var foo = new EmailAddressAttribute(); return(foo.IsValid(mail)); }
static void Main(string[] args) { bool flag = true; //toggled by every do while once user input matches expectations long temp; //used for TryParse output to have a place to go, data never retrieved or used only written Person tempPerson = new Person(); Console.Write("\nPlease enter the person's first name: "); tempPerson.fName = Console.ReadLine(); Console.Write("\nPlease enter the person's middle name: "); tempPerson.mName = Console.ReadLine(); Console.Write("\nPlease enter the person's last name: "); tempPerson.lName = Console.ReadLine(); Console.Write("\nPlease enter the person's street address: "); tempPerson.streetOne = Console.ReadLine(); Console.Write("\nPlease enter the person's secondary address info ex. Apt #: "); tempPerson.streetTwo = Console.ReadLine(); Console.Write("\nPlease enter the person's city:"); tempPerson.city = Console.ReadLine(); do { Console.Write("\nPlease enter the person's state code:"); tempPerson.stateCode = Console.ReadLine().ToUpper(); if (tempPerson.stateCode.Length == 2) { flag = false; } } while (flag); do { Console.Write("\nPlease enter the person's zip code:"); tempPerson.zipCode = Console.ReadLine(); if (tempPerson.zipCode.Length == 5 && Int64.TryParse(tempPerson.zipCode, out temp)) { flag = true; } } while (!flag); do { Console.Write("\nPlease enter the person's phone number (10 digit no format:"); tempPerson.phoneNum = Console.ReadLine(); if (tempPerson.phoneNum.Length == 10 && Int64.TryParse(tempPerson.phoneNum, out temp)) { flag = false; } } while (flag); do { Console.Write("\nPlease enter the person's email address:"); tempPerson.emailAddress = Console.ReadLine(); //Logic for if this is an email address I'll figure it out later var foo = new EmailAddressAttribute(); //got this idea from stackOverflow https://stackoverflow.com/questions/1365407/c-sharp-code-to-validate-email-address flag = foo.IsValid(tempPerson.emailAddress); } while (!flag); System.Console.Clear(); Console.Write("\n\nThe Person object contains the following data..."); Console.Write($"\n Name: {tempPerson.fName} {tempPerson.mName} {tempPerson.lName}"); Console.Write($"\n Address: {tempPerson.streetOne} {tempPerson.streetTwo} , {tempPerson.city} {tempPerson.stateCode} , {tempPerson.zipCode}"); Console.Write($"\n Phone Number: {tempPerson.phoneNum}"); Console.Write($"\n EMail: {tempPerson.emailAddress}"); BasicTools.pause(); }
public bool IsValid(string value) { return(_emailAddressAttribute.IsValid(value)); }
private void BtnRegister_Click(object sender, RoutedEventArgs e) { User NewUser = new User(); Runner NewRunner = new Runner(); if (PasswdBox.Password == "" || PasswdBox.Password == " " || ConfirmPasswdBox.Password == "" || ConfirmPasswdBox.Password == " " || TxtFirstName.Text == "" || TxtFirstName.Text == " " || TxtLastName.Text == "" || TxtLastName.Text == " " || BirthOfDatePick.SelectedDate == null) { MessageBox.Show("Заполнены не все поля!"); return; } NewUser.RoleId = "R"; NewUser.FirstName = TxtFirstName.Text; NewUser.LastName = TxtLastName.Text; NewRunner.Gender = CmbGender.SelectedValue.ToString(); NewRunner.CountryCode = CmbCountry.SelectedValue.ToString(); #region Проверка Email. EmailAddressAttribute emailCheck = new EmailAddressAttribute(); if (!emailCheck.IsValid(TxtEmail.Text)) { MessageBox.Show("Введен некорректный Email"); return; } #endregion NewUser.Email = TxtEmail.Text; NewRunner.Email = TxtEmail.Text; #region Проверка пароля. if (PasswdBox.Password.Length < 6) { MessageBox.Show("Пароль должен содержать не менее 6 символов"); return; } if (ConfirmPasswdBox.Password != PasswdBox.Password) { MessageBox.Show("Пароли не совпадают"); return; } Regex reg = new Regex(@"[a-z]"); if (!reg.IsMatch(PasswdBox.Password)) { MessageBox.Show("Пароль должен содержать как минимум 1 прописную букву"); return; } reg = new Regex(@"[0-9]"); if (!reg.IsMatch(PasswdBox.Password)) { MessageBox.Show("Пароль должен содержать как минимум 1 цифру"); return; } reg = new Regex(@"[!@#$%^]"); if (!reg.IsMatch(PasswdBox.Password)) { MessageBox.Show("Пароль должен содержать как минимум один из следующих символов\n !@#$%^"); return; } #endregion NewUser.Password = PasswdBox.Password; #region Подсчет возраста. int yearOld = DateTime.Now.Year - Convert.ToInt32(BirthOfDatePick.SelectedDate.Value.Year); if (DateTime.Now.DayOfYear < BirthOfDatePick.SelectedDate.Value.DayOfYear) { yearOld--; if (yearOld < 10) { MessageBox.Show("Вы не можете зарегистрироваться, так как вам меньше 10 лет"); return; } } #endregion NewRunner.DateOfBirth = Convert.ToDateTime(BirthOfDatePick.SelectedDate); #region Сохранение изображения. if (LblFileName.Content != "") { try { Byte[] ImgData = null; FileStream stream = new FileStream(LblFileName.Content.ToString(), FileMode.Open, FileAccess.Read); StreamReader read = new StreamReader(stream); ImgData = new byte[stream.Length - 1]; stream.Read(ImgData, 0, (int)stream.Length - 1); NewUser.Image = ImgData; } catch (Exception ex) { MessageBox.Show(ex.Message); } } #endregion using (var DataBase = new MarathonDBEntities1()) { DataBase.User.Add(NewUser); DataBase.Runner.Add(NewRunner); DataBase.SaveChanges(); } #region Сохранение данных в LocalStorage. LocalStorage.UserClass.Email = TxtEmail.Text; LocalStorage.UserClass.FirstName = TxtFirstName.Text; LocalStorage.UserClass.LastName = TxtLastName.Text; LocalStorage.UserClass.RunnerId = NewRunner.RunnerId.ToString(); #endregion new WinRegForTheMarathon().Show(); Close(); }
internal ULoginResponse UserLoginAction(ULoginData data) { UDataTable result; var validate = new EmailAddressAttribute(); if (validate.IsValid(data.Username)) { var pass = LoginHelper.HashGen(data.Password); using (var db = new UserContext()) { result = db.Users.FirstOrDefault(u => u.Email == data.Email && u.Password == pass); } if (result == null) { return(new ULoginResponse { Status = false, StatusMessage = "The Username or Password is Incorrect(1)" }); } using (var todo = new UserContext()) { result.LastIp = data.LoginIp; result.LastLogin = data.LoginDateTime; todo.Entry(result).State = EntityState.Modified; todo.SaveChanges(); } return(new ULoginResponse { Status = true }); } else { var pass = LoginHelper.HashGen(data.Password); using (var db = new UserContext()) { result = db.Users.FirstOrDefault(u => u.Username == data.Username && u.Password == pass); } if (result == null) { return(new ULoginResponse { Status = false, StatusMessage = "The Username or Password is Incorrect(2)" }); } using (var todo = new UserContext()) { result.LastIp = data.LoginIp; result.LastLogin = data.LoginDateTime; todo.Entry(result).State = EntityState.Modified; todo.SaveChanges(); } return(new ULoginResponse { Status = true }); } }
Boolean IsEmailValid(String mail) { var ema = new EmailAddressAttribute(); return(ema.IsValid(mail)); }
public static bool IsValid(string email) { return(_attribute.IsValid(email)); }
public bool HandleMessage(IMessage message, IServerPeer peer) { var serverPeer = peer as PhotonServerPeer; var operation = new RegisterOperation(serverPeer.protocol, message); if (!operation.IsValid) { peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, operation.GetErrorMessage(), (int)ReturnCode.OperationInvalid)); return(true); } if (operation.Login.Length < 6 || operation.Password.Length < 6) { peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, "Login and password can't be less than 6 symbols.", (int)ReturnCode.OperationInvalid)); return(true); } else if (operation.Login.Length > 16 || operation.Password.Length > 16) { peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, "Login and password can't be more than 16 symbols.", (int)ReturnCode.OperationInvalid)); return(true); } var checkMail = new EmailAddressAttribute(); if (!checkMail.IsValid(operation.Email)) { peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, "Email address incorrect.", (int)ReturnCode.OperationInvalid)); return(true); } var characterData = MessageSerializerService.DeserializeObjectOfType <RegisterCharacterData>( operation.CharacterRegisterData); characterData.CharacterType = 1; // delete this if we add more types if (characterData.CharacterName.Length < 6) { peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, "Name of your character can't be less than 6 symbols.", (int)ReturnCode.OperationInvalid)); return(true); } else if (characterData.CharacterName.Length > 16) { peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, "Name of your can't be more than 16 symbols.", (int)ReturnCode.OperationInvalid)); return(true); } else if (characterData.Sex != "Male" && characterData.Sex != "Female") { return(true); } else if (characterData.CharacterType != 1) // add more types { return(true); } else if (characterData.Class != "Warrior" && characterData.Class != "Rogue" && characterData.Class != "Mage") { return(true); } else if (characterData.SubClass != "Warlock" && characterData.SubClass != "Cleric") { return(true); } try { using (var session = NHibernateHelper.OpenSession()) { using (var transaction = session.BeginTransaction()) { var accounts = session.QueryOver <AccountModel>().Where(a => a.Login == operation.Login).List(); var accountsByEmail = session.QueryOver <AccountModel>().Where(a => a.Email == operation.Email).List(); var characters = session.QueryOver <CharacterModel>().Where(c => c.Name == characterData.CharacterName).List(); if (accounts.Count > 0) { transaction.Commit(); peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, "Login already taken.", (int)ReturnCode.AlreadyExist)); return(true); } else if (accountsByEmail.Count > 0) { transaction.Commit(); peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, "Email already taken.", (int)ReturnCode.AlreadyExist)); return(true); } else if (characters.Count > 0) { transaction.Commit(); peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, "Name already taken.", (int)ReturnCode.AlreadyExist)); return(true); } string salt = Guid.NewGuid().ToString().Replace("-", ""); AccountModel newAccount = new AccountModel() { Login = operation.Login, Password = BitConverter.ToString(SHA512.Create().ComputeHash( Encoding.UTF8.GetBytes(salt + operation.Password))).Replace("-", ""), Salt = salt, Email = operation.Email, AdminLevel = 0, BanLevel = 0, Created = DateTime.Now, Updated = DateTime.Now }; session.Save(newAccount); transaction.Commit(); Log.DebugFormat("Create new Account. Login - {0}.", operation.Login); } using (var transaction = session.BeginTransaction()) { var accounts = session.QueryOver <AccountModel>().Where(a => a.Login == operation.Login).SingleOrDefault(); CharacterModel newCharacter = new CharacterModel() { AccountId = accounts, Name = characterData.CharacterName, Sex = characterData.Sex, CharacterType = characterData.CharacterType, Class = characterData.Class, SubClass = characterData.SubClass, Level = 1, Exp = 0, Strength = 1, Intellect = 1, RangLevel = 0, Gold = 10000, Donate = 0, SkillPoint = 1000, StatPoint = 0, InventorySize = 32, GuildId = 0, Created = DateTime.Now, Updated = DateTime.Now }; session.Save(newCharacter); transaction.Commit(); Log.DebugFormat("Create new Character. Name - {0}.", characterData.CharacterName); } peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, "Register success.", (int)ReturnCode.OK)); } return(true); } catch (Exception ex) { Log.ErrorFormat("Error register handler: {0}", ex); peer.SendMessage(new Response(Code, SubCode, new Dictionary <byte, object>() { { (byte)MessageParameterCode.SubCodeParameterCode, SubCode }, { (byte)MessageParameterCode.PeerIdParameterCode, message.Parameters[(byte)MessageParameterCode.PeerIdParameterCode] }, }, ex.ToString(), (int)ReturnCode.OperationDenied)); return(true); } }
private bool IsValidEmail(string target) { var emailValidator = new EmailAddressAttribute(); return(emailValidator.IsValid(target)); }
public IEnumerable GetErrors(string propertyName) { var list = new List <string>(); if (propertyName.Equals(nameof(FirstName))) { if (string.IsNullOrEmpty(FirstName) || string.IsNullOrWhiteSpace(FirstName)) { list.Add("Please, enter a valid name"); } } if (propertyName.Equals(nameof(LastName))) { if (string.IsNullOrWhiteSpace(LastName) || string.IsNullOrWhiteSpace(LastName)) { list.Add("Please, enter a valid name"); } } if (propertyName.Equals(nameof(Nationality))) { if (string.IsNullOrEmpty(Nationality)) { list.Add("Please, enter your nationality"); } } if (propertyName.Equals("Email")) { var validEmail = new EmailAddressAttribute(); if (!validEmail.IsValid(Email) || string.IsNullOrEmpty(Email)) { list.Add("Please, enter a valid email"); } } if (propertyName.Equals("Password")) { if (string.IsNullOrEmpty(Password)) { list.Add("Please, enter a password"); } if (!string.IsNullOrEmpty(Password) && !Regex.IsMatch(Password, "^.*(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*$")) { list.Add("Password must contain at least 1 Upper/lower case letter and a digit."); } if (Password != null && Password.Length < 10) { list.Add("Password must at least have 10 characters."); } } if (propertyName.Equals("PasswordRepeat")) { if (PasswordRepeat != Password) { list.Add("Passwords do not match."); } } if (propertyName.Equals(nameof(BirthDate))) { var currentDate = DateTime.Now; if (BirthDate.Date > currentDate.Date) { list.Add("Obviously, you cannot be born in the future"); return(list); } if (BirthDate.Date.AddYears(12) > currentDate.Date) { list.Add("You must be 12 years or older"); } if (BirthDate.Date == DateTime.Now.Date) { list.Add("You must be 12 years or older"); } } return(list); }