public override IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { if (string.IsNullOrEmpty(this.Type)) { yield return(new ValidationResult("Required", new[] { "Type" })); } else if (!PersonContact.AllowedTypes.Contains(this.Type.ToLower())) { yield return(new ValidationResult("Must be one of: " + string.Join(", ", PersonContact.AllowedTypes), new[] { "Type" })); } ContactInfoSubType subtypes = PersonContact.GetSubTypes(this.Type); if (subtypes.SubTypes.Length == 0 && !string.IsNullOrEmpty(this.Subtype)) { yield return(new ValidationResult("SubType can't be specified for type '" + this.Type + "'", new[] { "SubType" })); } else if (subtypes.SubTypes.Length > 0 && !subtypes.SubTypes.Contains(this.Subtype)) { yield return(new ValidationResult("SubType must be one of: " + string.Join(", ", subtypes.SubTypes), new[] { "SubType" })); } string dummy; if (string.IsNullOrEmpty(this.Value)) { yield return(new ValidationResult("Required", new[] { "Value" })); } else if (!PersonContact.TryParse(this.Type, this.Subtype, this.Value, true, out dummy)) { yield return(new ValidationResult(string.Format("'{0}' is not in valid form", this.Value), new[] { "Value" })); } }
public override bool Validate() { errors.Clear(); //if (this.Person == null && this.PersonReference.EntityKey == null) //{ // errors.Add(new RuleViolation(this.Id, "Person", "", "Required")); //} if (string.IsNullOrEmpty(this.Type)) { errors.Add(new RuleViolation(this.Id, "Type", "", "Required")); } else if (!PersonContact.AllowedTypes.Contains(this.Type.ToLower())) { errors.Add(new RuleViolation(this.Id, "Type", this.Type, "Must be one of: " + string.Join(", ", PersonContact.AllowedTypes))); } ContactInfoSubType subtypes = PersonContact.GetSubTypes(this.Type); if (subtypes.SubTypes.Length == 0 && !string.IsNullOrEmpty(this.Subtype)) { errors.Add(new RuleViolation(this.Id, "SubType", this.Subtype, "SubType can't be specified for type '" + this.Type + "'")); } else if (subtypes.SubTypes.Length > 0 && !subtypes.SubTypes.Contains(this.Subtype)) { errors.Add(new RuleViolation(this.Id, "SubType", this.Subtype, "SubType must be one of: " + string.Join(", ", subtypes.SubTypes))); } if (string.IsNullOrEmpty(this.Value)) { errors.Add(new RuleViolation(this.Id, "Value", "", "Required")); } string dummy; if (!PersonContact.TryParse(this.Type, this.Subtype, this.Value, true, out dummy)) { errors.Add(new RuleViolation(this.Id, "Value", this.Value, string.Format("'{0}' is not in valid form", this.Value))); } return(errors.Count == 0); }
public PersonContact() : base() { this.Type = PersonContact.AllowedTypes[0]; this.Subtype = PersonContact.GetSubTypes(this.Type).SubTypes.FirstOrDefault() ?? ""; }
private Member NewEsarTrainee_Internal(FormCollection fields) { Member m = new Member(); TryUpdateModel(m, new[] { "FirstName", "LastName", "MiddleName", "BirthDate", "SheriffApp", "Gender" }); this.db.Members.Add(m); SarUnit esar = (from u in this.db.Units where u.DisplayName == "ESAR" select u).First(); UnitStatus status = (from s in this.db.UnitStatusTypes where s.Unit.Id == esar.Id && s.StatusName == "trainee" select s).First(); if (!string.IsNullOrEmpty(fields["Street"])) { PersonAddress address = new PersonAddress { Person = m, Type = PersonAddressType.Mailing }; TryUpdateModel(address, new[] { "Street", "City", "State" }); GeographyServices.RefineAddressWithGeography(address); if (address.Quality < 8) { try { ModelState.SetModelValue("Zip", new ValueProviderResult(fields["Zip"], fields["Zip"], CultureInfo.CurrentUICulture)); // This is supposed to be UpdateModel, not TryUpdate UpdateModel(address, new[] { "Zip" }); } catch (Exception) { ModelState.AddModelError("Zip", "Can't locate address. ZIP is required"); } } this.db.PersonAddress.Add(address); } foreach (string contact in new[] { "Home", "Work", "Cell" }) { if (string.IsNullOrEmpty(fields[contact + "Phone"])) { continue; } ModelState.SetModelValue(contact + "Phone", new ValueProviderResult(fields[contact + "Phone"], fields[contact + "Phone"], CultureInfo.CurrentUICulture)); PersonContact pc = new PersonContact { Person = m, Type = "phone", Subtype = contact.ToLower(), Value = fields[contact + "Phone"] }; this.db.PersonContact.Add(pc); } if (!string.IsNullOrEmpty(fields["HamCall"])) { ModelState.SetModelValue("HamCall", new ValueProviderResult(fields["HamCall"], fields["HamCall"], CultureInfo.CurrentUICulture)); PersonContact pc = new PersonContact { Person = m, Type = "hamcall", Value = fields["HamCall"] }; this.db.PersonContact.Add(pc); } if (!string.IsNullOrEmpty(fields["Email"])) { ModelState.SetModelValue("Email", new ValueProviderResult(fields["Email"], fields["Email"], CultureInfo.CurrentUICulture)); PersonContact pc = new PersonContact { Person = m, Type = "email", Value = fields["Email"] }; this.db.PersonContact.Add(pc); } if (!string.IsNullOrEmpty(fields["Email2"])) { ModelState.SetModelValue("Email2", new ValueProviderResult(fields["Email2"], fields["Email2"], CultureInfo.CurrentUICulture)); PersonContact pc = new PersonContact { Person = m, Type = "email", Value = fields["Email2"] }; this.db.PersonContact.Add(pc); } DateTime courseDate = new DateTime(1900, 1, 1); ModelState.SetModelValue("CourseDate", new ValueProviderResult(fields["CourseDate"], fields["CourseDate"], CultureInfo.CurrentUICulture)); if (string.IsNullOrEmpty(fields["CourseDate"])) { ModelState.AddModelError("CourseDate", "Required"); return null; } else if (!DateTime.TryParse(fields["CourseDate"], out courseDate)) { ModelState.AddModelError("CourseDate", "Unknown format. Try yyyy-mm-dd"); return null; } courseDate = courseDate.Date; UnitMembership um = new UnitMembership { Person = m, Status = status, Unit = esar, Activated = courseDate }; this.db.UnitMemberships.Add(um); TrainingCourse courseA = (from tc in this.db.TrainingCourses where tc.DisplayName == "Course A" select tc).First(); DateTime nextDate = courseDate.AddDays(1); Training t = (from trn in this.db.Trainings where trn.StartTime >= courseDate && trn.StartTime < nextDate && trn.Title == "Course A" select trn).FirstOrDefault(); if (t == null) { t = new Training(); t.OfferedCourses.Add(courseA); t.StartTime = courseDate.AddHours(19); t.StopTime = courseDate.AddHours(21); t.County = "King"; t.Title = "Course A"; t.Location = "Eastside Fire Headquarters"; this.db.Trainings.Add(t); } TrainingRoster tr = new TrainingRoster { Person = m, TimeIn = courseDate.AddHours(18), TimeOut = courseDate.AddHours(22) }; this.db.TrainingRosters.Add(tr); t.Roster.Add(tr); TrainingAward ta = new TrainingAward(); ta.Completed = courseDate.AddHours(21); if ((courseA.ValidMonths ?? 0) > 0) { ta.Expiry = ta.Completed.AddMonths(courseA.ValidMonths.Value); } ta.Course = courseA; ta.Member = m; this.db.TrainingAward.Add(ta); tr.TrainingAwards.Add(ta); return m; }
public DataActionResult SubmitContact(/*[ModelBinder(typeof(JsonDataContractBinder<MemberContactView>))] */MemberContactView view) { if (!Permissions.IsAdmin && !Permissions.IsSelf(view.MemberId) && !Permissions.IsMembershipForPerson(view.MemberId)) return GetLoginError(); List<SubmitError> errors = new List<SubmitError>(); PersonContact model = (from c in this.db.PersonContact.Include("Person") where c.Id == view.Id select c).FirstOrDefault(); if (model == null) { model = new PersonContact(); model.Priority = 0; if ((from c in this.db.PersonContact where c.Person.Id == view.MemberId && c.Type == view.Type select c.Id).Count() > 0) { model.Priority = 1; } this.db.PersonContact.Add(model); } try { if (model.Type != view.Type) model.Type = view.Type; if (model.Subtype != view.SubType) model.Subtype = view.SubType; if (model.Value != view.Value) model.Value = view.Value; if (model.Person == null || model.Person.Id != view.MemberId) model.Person = (from m in this.db.Members where m.Id == view.MemberId select m).FirstOrDefault(); this.db.SaveChanges(); view.Id = model.Id; view.Priority = model.Priority; } catch (DbEntityValidationException ex) { foreach (var entry in ex.EntityValidationErrors.Where(f => !f.IsValid)) { foreach (var err in entry.ValidationErrors) { errors.Add(new SubmitError { Error = err.ErrorMessage, Property = err.PropertyName, Id = new[] { ((IModelObject)entry.Entry.Entity).Id } }); } } } return Data(new SubmitResult<MemberContactView> { Errors = errors.ToArray(), Result = (errors.Count > 0) ? (MemberContactView)null : view }); }
public string Signup(AccountSignup data) { if (string.IsNullOrWhiteSpace(data.Firstname)) return "First name is required"; if (string.IsNullOrWhiteSpace(data.Lastname)) return "Last name is required"; if (data.BirthDate > DateTime.Today.AddYears(-14)) return "Applicants must be 14 years or older"; if (data.BirthDate < DateTime.Today.AddYears(-120)) return "Invalid birthdate"; if (!(new[] { "m", "f", null }.Contains(data.Gender))) return "Invalid gender"; if (data.Units.Length == 0) return "Must select at least one unit"; return AddNewMember(data, () => { Member newMember = new Member { FirstName = data.Firstname, MiddleName = data.Middlename, LastName = data.Lastname, BirthDate = data.BirthDate, Gender = (data.Gender == "m") ? Gender.Male : (data.Gender == "f") ? Gender.Female : Gender.Unknown, Status = MemberStatus.Applicant, Username = data.Username }; db.Members.Add(newMember); PersonContact email = new PersonContact { Person = newMember, Type = "email", Value = data.Email, Priority = 0 }; db.PersonContact.Add(email); foreach (Guid unitId in data.Units) { UnitsController.RegisterApplication(db, unitId, newMember); } if (!System.Web.Security.Roles.RoleExists(APPLICANT_ROLE)) { System.Web.Security.Roles.CreateRole(APPLICANT_ROLE); } System.Web.Security.Roles.AddUserToRole(data.Username, APPLICANT_ROLE); return newMember; }, "new-account-verification.html"); }
/// <summary> /// Internal method to create the user /// </summary> /// <param name="user">Membershipuser created in the controller</param> /// <param name="context">Instance of Db Context</param> /// <param name="log">Instance of the logManager</param> /// <returns>true if the user creation succeeds, false otherwise. Deletes the created user on failure</returns> internal bool CreateUser(MembershipUser user, KcsarContext context, ILog log) { try { user.IsApproved = false; System.Web.Security.Membership.UpdateUser(user); System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(this.Username, false, 5); Thread.CurrentPrincipal = new System.Web.Security.RolePrincipal(new System.Web.Security.FormsIdentity(ticket)); Member newMember = new Member { FirstName = this.Firstname, LastName = this.Lastname, Status = MemberStatus.Applicant, Username = this.Email }; context.Members.Add(newMember); var email = new PersonContact { Person = newMember, Type = "email", Value = this.Email, Priority = 0 }; context.PersonContact.Add(email); if (this.Units != null) { foreach (Guid unitId in this.Units) { UnitsController.RegisterApplication(context, unitId, newMember); } } var profile = ProfileBase.Create(this.Username) as KcsarUserProfile; if (profile != null) { profile.FirstName = this.Firstname; profile.LastName = this.Lastname; profile.LinkKey = newMember.Id.ToString(); profile.Save(); } if (!System.Web.Security.Roles.RoleExists(APPLICANT_ROLE)) { System.Web.Security.Roles.CreateRole(APPLICANT_ROLE); } System.Web.Security.Roles.AddUserToRole(this.Username, APPLICANT_ROLE); context.SaveChanges(); } catch(Exception ex) { log.Error(ex.ToString()); var existingUser = Membership.GetUser(this.Username); if (existingUser != null) { Membership.DeleteUser(existingUser.UserName); } return false; } return true; }
public string Signup(AccountSignup data) { if (string.IsNullOrWhiteSpace(data.Firstname)) return "First name is required"; if (string.IsNullOrWhiteSpace(data.Lastname)) return "Last name is required"; if (string.IsNullOrWhiteSpace(data.Email)) return "Email is required"; if (!Regex.IsMatch(data.Email, @"^\S+@\S+\.\S+$")) return "Unrecognized email address"; if (data.BirthDate > DateTime.Today.AddYears(-14)) return "Applicants must be 14 years or older"; if (data.BirthDate < DateTime.Today.AddYears(-120)) return "Invalid birthdate"; if (!(new[] { "m", "f", null }.Contains(data.Gender))) return "Invalid gender"; if (data.Units.Length == 0) return "Must select at least one unit"; if (string.IsNullOrWhiteSpace(data.Username)) return "Username is required"; if (data.Username.Length < 3) return "Username must be 3 or more characters"; if (data.Username.Length > 200) return "Username must be less than 200 characters"; if (!Regex.IsMatch(data.Username, @"^[a-zA-Z0-9\.\-_]+$")) return "Username can only contain numbers, letters, and the characters '.', '-', and '_'"; if (membership.GetUser(data.Username, false) != null) return "Username is already taken"; if (string.IsNullOrWhiteSpace(data.Password)) return "Password is required"; if (data.Password.Length < 6) return "Password must be at least 6 characters"; if (data.Password.Length > 64) return "Password must be less than 64 characters"; MembershipCreateStatus status; var user = membership.CreateUser(data.Username, data.Password, data.Email, null, null, false, null, out status); if (status != MembershipCreateStatus.Success) return "Could not create user"; try { System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(data.Username, false, 5); Thread.CurrentPrincipal = new System.Web.Security.RolePrincipal(new System.Web.Security.FormsIdentity(ticket)); Member newMember = new Member { FirstName = data.Firstname, MiddleName = data.Middlename, LastName = data.Lastname, BirthDate = data.BirthDate, Gender = (data.Gender == "m") ? Gender.Male : (data.Gender == "f") ? Gender.Female : Gender.Unknown, Status = MemberStatus.Applicant, Username = data.Username }; db.Members.Add(newMember); PersonContact email = new PersonContact { Person = newMember, Type = "email", Value = data.Email, Priority = 0 }; db.PersonContact.Add(email); foreach (Guid unitId in data.Units) { UnitsController.RegisterApplication(db, unitId, newMember); } SarMembership.KcsarUserProfile profile = ProfileBase.Create(data.Username) as SarMembership.KcsarUserProfile; if (profile != null) { profile.FirstName = data.Firstname; profile.LastName = data.Lastname; profile.LinkKey = newMember.Id.ToString(); profile.Save(); } if (!System.Web.Security.Roles.RoleExists(APPLICANT_ROLE)) { System.Web.Security.Roles.CreateRole(APPLICANT_ROLE); } System.Web.Security.Roles.AddUserToRole(data.Username, APPLICANT_ROLE); string mailSubject = string.Format("{0} account verification", ConfigurationManager.AppSettings["dbNameShort"] ?? "KCSARA"); string mailTemplate = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates", "Email", "new-account-verification.html")); string mailBody = mailTemplate .Replace("%Username%", data.Username) .Replace("%VerifyLink%", new Uri(this.Request.RequestUri, Url.Route("Default", new { httproute = "", controller = "Account", action = "Verify", id = data.Username })).AbsoluteUri + "?key=" + user.ProviderUserKey.ToString()) .Replace("%WebsiteContact%", "*****@*****.**"); db.SaveChanges(); EmailService.SendMail(data.Email, mailSubject, mailBody); } catch (Exception ex) { log.Error(ex.ToString()); membership.DeleteUser(data.Username, true); return "An error occured while creating your user account"; } return "OK"; }