public void InnerFieldsDictionary() { var validationService = new ValidationService(); var target = new Outer() { Licenses2 = new Dictionary<string,DriversLicense> { { "first", new DriversLicense() { Number = "TX" } } } }; try { Validator.ValidateObject(target, Factories.BuildValidationContext(target), true); Assert.Fail("Should have thrown an Exception."); } catch (ValidationException ex) { var results = (ex.ValidationResult as IEnumerable<ValidationResult>).Flatten(result => result as IEnumerable<ValidationResult>, leafNodesOnly: true); Assert.IsTrue((from entry in results from member in entry.MemberNames select member + ": " + entry.ErrorMessage).SequenceEqual(new[] { "Licenses2[0].Value.Number: Licenses2 Number Invalid", "Licenses2[0].Value.State: Licenses2 State Required", })); } }
protected void Button1_Click(object sender, EventArgs e) { int userID = int.Parse(txt_userID.Text); string fName = txt_fname.Text; string Lname = txt_lname.Text; string country = txt_country.Text; string gender = rbl_gender.Text; string email = txt_email.Text; int creditCard = int.Parse(txt_creditcard.Text); string password = txt_password.Text; string password2 = txt_password2.Text; string sage = ddl_years.SelectedValue; int Age = int.Parse(sage); Service reg = new Service(); ValidationService vs = new ValidationService(); if (password == password2) { string msg = vs.CheckUserIDRegister(userID); if (msg == "Available") { reg.Register(userID, fName, Lname, Age, country, gender, email, creditCard, password); Response.Redirect("Default.aspx"); } else { Response.Write("UserID Already Taken"); } } else { Response.Write("Error - passwords do no match"); } }
public void InnerFields() { var validationService = new ValidationService(); var target = new Outer() { Licenses = new [] { new DriversLicense() { Number = "TX" }, new DriversLicense() { State = "TX" } } }; try { Validator.ValidateObject(target, Factories.BuildValidationContext(target), true); Assert.Fail("Should have thrown an Exception."); } catch (ValidationException ex) { var results = (ex.ValidationResult as IEnumerable <ValidationResult>).Flatten(result => result as IEnumerable <ValidationResult>, leafNodesOnly: true); Assert.IsTrue((from entry in results from member in entry.MemberNames select member + ": " + entry.ErrorMessage).SequenceEqual(new[] { "Licenses[0].Number: Licenses Number Invalid", "Licenses[0].State: Licenses State Required", "Licenses[1].Number: Licenses Number Required", })); } }
public HttpResponseMessage AppliedHistory(string sortByKey, bool isAscending, int pageIndex, int pageSize) { if (ValidationService.AuthorizeToken(GetToken(), "get:/api/organization/appliedhistory?sortByKey=&isAscending=&pageIndex=&pageSize=") == false) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } User organization = ValidationService.FindUserWithToken(GetToken()); List <object> source = new List <object>(); foreach (var information in ((OrganizationProfile)organization.UserProfiles[organization.Name + "OrganizationProfile"]).ApplyOrganizerInformation) { User organizer = (User)myService.FindOneById(information.OrganizerId); if (information.hasHandled == false) { source.Add(new AppliedToMeHistoryModel { organizerId = information.OrganizerId, organizerName = information.OrganizerName, time = information.Time, comment = information.Comment, avatar = ((OrganizerProfile)organizer.UserProfiles[organizer.Name + "OrganizerProfile"]).Avatar }); } } List <object> result = myService.SortAndPaging(source, sortByKey, isAscending, pageIndex, pageSize); StringWriter tw = new StringWriter(); JsonSerializer jsonSerializer = new JsonSerializer(); jsonSerializer.Serialize(tw, result, result.GetType()); string json = tw.ToString(); return(new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); }
public void ShouldReturnTransactionsBetweenTheGivenDateRange() { var dbQueryResult = new List <Transaction>(); var dataContextConfig = new Mock <DataContext>(); var mappingConfigs = new IMappingConfiguration[] { new TransactionToGetAllTransactionsResponseModelMappingConfiguration() }; var mappingService = new MappingService(mappingConfigs); var validationService = new ValidationService(); var transactionsQueryable = _transactions.AsQueryable(); var transactionsDbSetMockConfig = new Mock <DbSet <Transaction> >(); transactionsDbSetMockConfig.As <IQueryable <Transaction> >().Setup(mockSetup => mockSetup.Provider).Returns(new CustomizedQueryProvider(transactionsQueryable.Provider, new Action <string, Expression, EnumerableQuery <Transaction> >((methodName, expression, result) => { dbQueryResult = result.ToList(); }))); transactionsDbSetMockConfig.As <IQueryable <Transaction> >().Setup(mockSetup => mockSetup.Expression).Returns(transactionsQueryable.Expression); transactionsDbSetMockConfig.As <IQueryable <Transaction> >().Setup(mockSetup => mockSetup.ElementType).Returns(transactionsQueryable.ElementType); transactionsDbSetMockConfig.As <IQueryable <Transaction> >().Setup(mockSetup => mockSetup.GetEnumerator()).Returns(() => transactionsQueryable.GetEnumerator()); var dbContextOptions = new DbContextOptionsBuilder <DataContext>() .UseInMemoryDatabase(databaseName: "Test") .Options; var dataContextMockConfig = new Mock <DataContext>(dbContextOptions); dataContextMockConfig.SetupGet(mockSetup => mockSetup.Transactions).Returns(() => transactionsDbSetMockConfig.Object); var transactionManager = new TransactionManager(dataContextMockConfig.Object, validationService, mappingService); var begin = new DateTime(2021, 5, 9); var end = new DateTime(2021, 5, 11); transactionManager.GetAllTransactionsByDateRange(begin, end); Assert.IsTrue(dbQueryResult.All(transaction => transaction.TransactionDate >= begin && transaction.TransactionDate <= end)); }
private bool CheckInputParameters() { if (String.IsNullOrEmpty(Email) || String.IsNullOrEmpty(Password)) { new CustomMessageDialog( AppMessages.RequiredFields_Title, AppMessages.RequiredFieldsLogin, App.AppInformation, MessageDialogButtons.Ok).ShowDialog(); return(false); } if (!ValidationService.IsValidEmail(Email)) { new CustomMessageDialog( AppMessages.LoginFailed_Title, AppMessages.MalformedEmail, App.AppInformation, MessageDialogButtons.Ok).ShowDialog(); return(false); } return(true); }
public void ValidationService_Failed() { //Mock _mockValManager.Setup(m => m.GetValidatorsResult(It.IsAny <RepoModel.User>())) .Returns(Task.FromResult(new List <Func <Result> > { () => new Result(), () => new Result { ErrorCode = ErrorCode.NoAuthorized, StatusCode = StatusCode.Failed, StatusDetail = "Test Validation Service" } }.AsEnumerable())); //Arrange var service = new ValidationService(); //Act var result = service.ProcessValidation(_mockValManager.Object, _userRepo).Result; //Assert Assert.IsInstanceOfType(result, typeof(Result)); Assert.IsTrue(((Result)result).StatusCode == StatusCode.Failed); Assert.IsTrue(((Result)result).ErrorCode == ErrorCode.NoAuthorized); }
public void ValidateTemplateName() { ValidationService.Initialize(() => new List <string>() { "Main", "Settings", "SettingsStorage" }); // Add a template that can choose the name Assert.True(ValidationService.ValidateTemplateName("Map", true, true).IsValid); // Add a template that can choose the name and this name is already used Assert.False(ValidationService.ValidateTemplateName("Main", true, true).IsValid); // Add a template that can not choose the name Assert.True(ValidationService.ValidateTemplateName("UriScheme", false, true).IsValid); // Add a template that can not choose the name and this name is already used Assert.False(ValidationService.ValidateTemplateName("SettingsStorage", false, true).IsValid); // Add a template that can choose the name but we don't know if it is already used (Right click) Assert.True(ValidationService.ValidateTemplateName("Main", true, false).IsValid); }
public virtual Result <TReadDto> Create(TCreateDto dto, string createdBy) { var objectValidationErrors = ValidationService.ValidateObject(dto); if (objectValidationErrors.Any()) { return(Result.ValidationFailed <TReadDto>(objectValidationErrors)); } var bo = Mapper.Map <TEntity>(dto); Repository.Add(bo, createdBy); var result = UnitOfWork.Complete(); if (result.IsFailure) { switch (result.ErrorType) { case ErrorType.ValidationFailed: return(Result.ValidationFailed <TReadDto>(result.Errors)); default: throw new ArgumentException(); } } var readDto = Mapper.Map <TReadDto>(bo); if (HubContext != null) { HubContext.CreatedAsync(readDto).Wait(); } return(Result.Ok(readDto)); }
protected override async Task ValidateAndSave() { await Service.UpdatePatientFlagsAsync(PatientDetails); // Remove already invalidated states from modelState as rely // on changes made in UpdatePatientFlags ModelState.ClearValidationState("PatientDetails.Postcode"); ModelState.ClearValidationState("PatientDetails.NHSNumber"); ModelState.ClearValidationState("PatientDetails.OccupationOther"); if (PatientDetails.UkBorn != false) { ModelState.ClearValidationState("PatientDetails.YearOfUkEntry"); } PatientDetails.SetValidationContext(Notification); await FindAndSetPostcodeAsync(); ValidationService.TrySetFormattedDate(PatientDetails, "Patient", nameof(PatientDetails.Dob), FormattedDob); if (TryValidateModel(PatientDetails, "PatientDetails")) { await Service.UpdatePatientDetailsAsync(Notification, PatientDetails); } }
static void Main(string[] args) { try { Console.WriteLine("Please enter input as KeyWord1 KeyWord2 Range and input file path"); var input = Console.ReadLine(); var inputArray = input.Split(' '); ValidationService.ValidateNumberOfArgumentsProvided(inputArray); var processCommandService = new ProcessCommandsService(); var keyWordsOccurenceWithinRange = processCommandService.Process(inputArray[0], inputArray[1], inputArray[2], inputArray[3]); Console.WriteLine(keyWordsOccurenceWithinRange); Main(new string[0]); } catch (InputValidationException ex) { Console.WriteLine(ex.Message); Main(new string[0]); } catch (Exception) { Console.WriteLine("unknown error occured"); Main(new string[0]); } }
public HttpResponseMessage RefuseToJoin([FromBody] IdAndCommentModel model) { if (ValidationService.AuthorizeToken(GetToken(), "post:/api/organization/refusetojoin") == false) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } User organization = ValidationService.FindUserWithToken(GetToken()); User organizer = (User)myService.FindOneById(new Guid(model.id)); if (myService.OrganizationRefuseOrganizerApplication(organizer, organization, model.comment)) { //myService.MessageService.SendMessage("System", organizer.Id, "你加入组织的申请被拒绝", "你加入组织" + organization.Name + "的申请被拒绝了", null, null); //myService.MessageService.SendMessage("System", organization.Id, "你拒绝某人加入组织的申请", organizer.Name + "加入组织的申请被你拒绝了", null, null); return(new HttpResponseMessage(HttpStatusCode.OK)); } else { return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent("Service错误", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") } }; }
public HttpResponseMessage KickOut([FromBody] IdAndCommentModel model) { if (ValidationService.AuthorizeToken(GetToken(), "post:/api/organization/kickout") == false) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } User organization = ValidationService.FindUserWithToken(GetToken()); User organizer = (User)myService.FindOneById(new Guid(model.id)); if (myService.OrganizationKickOrganizerOut(organizer, organization, model.comment)) { //myService.MessageService.SendMessage("System", organizer.Id, "你被组织踢出", "你被组织" + organization.Name + "踢出了", null, null); //myService.MessageService.SendMessage("System", organization.Id, "你将某人踢出了组织", organizer.Name + "被踢出了组织", null, null); return(new HttpResponseMessage(HttpStatusCode.OK)); } else { return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent("Service错误", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") } }; }
public IActionResult OnPostValidateSocialContextDates([FromBody] DatesValidationModel validationData) { List <(string, object)> propertyValueTuples = new List <(string key, object property)>(); foreach (var keyValuePair in validationData.KeyValuePairs) { var formattedDate = new FormattedDate() { Day = keyValuePair["day"], Month = keyValuePair["month"], Year = keyValuePair["year"] }; if (formattedDate.TryConvertToDateTime(out var convertedDob)) { propertyValueTuples.Add((keyValuePair["key"], convertedDob)); } else { // As we know that the validation will have already run for each date separately, we don't need to // return any errors as they will already have been displayed. // It would be better if we didn't get to this point if we knew there was an invalid date. return(BadRequest("One or more of the provided dates does not have a valid format.")); } } return(ValidationService.GetMultiplePropertiesValidationResult <T>(propertyValueTuples)); }
private bool CheckInputParameters() { //Because lastname is not an obligatory parameter, if the lastname field is null or empty, //force it to be an empty string to avoid "ArgumentNullException" when call the createAccount method. if (string.IsNullOrWhiteSpace(LastName)) { LastName = string.Empty; } if (string.IsNullOrWhiteSpace(this.Email) || string.IsNullOrWhiteSpace(this.Password) || string.IsNullOrWhiteSpace(this.FirstName) || string.IsNullOrWhiteSpace(this.ConfirmPassword)) { Deployment.Current.Dispatcher.BeginInvoke(() => _loginPage.SetApplicationBar(true)); new CustomMessageDialog( AppMessages.CreateAccountFailed_Title, AppMessages.RequiredFieldsCreateAccount, App.AppInformation, MessageDialogButtons.Ok).ShowDialog(); return(false); } if (ValidationService.IsValidEmail(this.Email)) { return(true); } Deployment.Current.Dispatcher.BeginInvoke(() => _loginPage.SetApplicationBar(true)); new CustomMessageDialog( AppMessages.CreateAccountFailed_Title, AppMessages.AM_IncorrectEmailFormat, App.AppInformation, MessageDialogButtons.Ok).ShowDialog(); return(false); }
public async Task <IActionResult> CreateApproved( [FromForm] DatasetNomination nomination, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var validationResult = ValidationService.IsDatasetNominationValidForApproval(nomination); if (!validationResult.IsValid) { return(BadRequest(validationResult)); } nomination.NominationStatus = NominationStatus.Approved; var nominationId = await UserDataStorage.CreateDatasetNominationAsync(this.User, nomination, cancellationToken).ConfigureAwait(false); if (nominationId.HasValue) { return(this.Ok(nominationId)); } return(this.NotFound()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ServiceInjector.Add(services, Configuration); ValidationService.Add(services); services.AddSession(); services.AddHttpContextAccessor(); //sayfayi yenileyince yenilikleri algilamasi icin services.AddControllersWithViews() .AddRazorRuntimeCompilation(); services.AddControllersWithViews() .AddFluentValidation(); services.AddFormHelper(new FormHelperConfiguration { CheckTheFormFieldsMessage = "Check the form fields." //RedirectDelay->Yönlendirme iþlemlerinde beklenecek varsayýlan süre. //ToastrDefaultPosition->Bildirim / Uyarý mesajlarýnýn ekranda görüneceði pozisyon. }); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { ValidationService validationService = new ValidationService(); if (value != null) { Uri uri = new Uri(ConfigurationManager.AppSettings["webpage_apiurl"] + "/api/OkSetup/CheckSSN"); HttpClient client = new HttpClient(); client.BaseAddress = uri; HttpResponseMessage responseMessage = client.GetAsync(uri).Result; string responseBody = responseMessage.Content.ToString(); if (!responseMessage.IsSuccessStatusCode) { return(null); } bool valid = validationService.validateSSN_Advanced(value.ToString()); if (!valid) { return(new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName))); } } return(null); }
public HttpResponseMessage ApplyFromMeHistory(string sortByKey, bool isAscending, int pageIndex, int pageSize) { if (ValidationService.AuthorizeToken(GetToken(), "get:/api/volunteer/applyfrommehistory?sortByKey=&isAscending=&pageIndex=&pageSize=") == false) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } User volunteer = ValidationService.FindUserWithToken(GetToken()); List <object> source = new List <object>(); foreach (var information in ((VolunteerProfile)volunteer.UserProfiles[volunteer.Name + "VolunteerProfile"]).ApplyFriendFromMe) { User friend = (User)myService.FindOneById(information.VolunteerId); source.Add(new ApplyFromMeModel { id = information.VolunteerId, Name = information.Name, avatar = ((VolunteerProfile)friend.UserProfiles[friend.Name + "VolunteerProfile"]).Avatar, Comment = information.Comment, ApplyTime = information.ApplyTime, ActionTime = information.ActionTime, Status = information.Status }); } List <object> result = myService.SortAndPaging(source, sortByKey, isAscending, pageIndex, pageSize); StringWriter tw = new StringWriter(); JsonSerializer jsonSerializer = new JsonSerializer(); jsonSerializer.Serialize(tw, result, result.GetType()); string json = tw.ToString(); return(new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); }
public async Task <string> ForgotPassword(string email) { if (!ValidationService.IsEmailValid(email)) { throw new Exception("Email isn't valid."); } if (email == null) { throw new Exception("Please, fill the email field."); } User user = await _userManager.FindByEmailAsync(email); if (user == null || user.Deleted || !user.IsRegistered) { throw new Exception("User doesn't exist."); } string messageSubject = Constants.messageSubjectForUserSignUp; Random random = new Random(); string confirmationCode = (random.Next(1000, 9999)).ToString(); string result = await _senderService.SendEmail(email, messageSubject, confirmationCode); return(result); }
public HttpResponseMessage GetMyRank(string id, string sortByKey, bool isAscending) { if (ValidationService.AuthorizeToken(GetToken(), "get:/api/volunteer/myrank?id=&sortByKey=&isAscending=") == false) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } Guid myId = new Guid(id); if (sortByKey == "" || sortByKey == "point" || sortByKey == "activityCount" || sortByKey == "badgeCount") { int result = myService.FriendServiceInVolunteerService.GetMyRank(myId, sortByKey, isAscending); return(new HttpResponseMessage { Content = new StringContent(result.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } else { return(new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound, Content = new StringContent("sortByKey参数错误", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } }
public async Task UsernameExists_UserNameDoesExist_ReturnsTrue(string expectedUsername, int numAccounts, string namePrefix, int startingId, int idIncrementFactor) { // Arrange // Setting up each dependency of ValidationService as a Mock Mock <IUserProfileService> mockProfileService = new Mock <IUserProfileService>(); Mock <IUserAccountService> mockAccountService = new Mock <IUserAccountService>(); // Create a container for WebUserAccountModel instances List <WebUserAccountModel> userAccounts = new List <WebUserAccountModel>(); // Test helper to assist in instantiating a list of WebUserAccountModels var testHelper = new BusinessLayerTestHelper(); /* Parameters: * numAccounts: How many would you like to generate? * namePrefix: What would you like to be the common prefix before every attribute? * startingId: What number would you like id to start from? * idIncrementFactor: How many numbers would you like each subsequent id to skip by? */ userAccounts = testHelper.PopulateListOfAccountModels(numAccounts, namePrefix, startingId, idIncrementFactor); // This function reads as: If GetAllUserAccounts is called, then return a list of userAccounts mockAccountService.Setup(x => x.GetAllUserAccounts()).Returns(Task.FromResult(userAccounts)); // Finally, instantiate the actual class being tested and pass in the mock objects IValidationService validationService = new ValidationService(mockAccountService.Object, mockProfileService.Object); // Act // Call the function that is being tested var actualResult = await validationService.UsernameExists(expectedUsername); // Assert // This unit test will pass if it returns true Assert.IsTrue(actualResult); }
public async Task <IActionResult> UpdateCoreSettings(ulong guildId, [FromBody] GuildConfigUpdate model) { if (model == null) { return(BadRequest(new { error = "Not all fields are filled" })); } GuildConfig config = await _context.GuildConfigs.SingleOrDefaultAsync(x => x.GuildId == guildId); if (config == null) { return(NotFound()); } Dictionary <string, string> errors = ValidationService.ValidateGuildConfig(model, config); if (errors.Count > 0) { return(BadRequest(errors)); } await _context.SaveChangesAsync(); return(Ok()); }
public ContentResult OnPostValidateTestDataProperty([FromBody] InputValidationModel validationData) { return(ValidationService.GetPropertyValidationResult <TestData>(validationData.Key, validationData.Value, validationData.ShouldValidateFull)); }
public IActionResult OnPostValidateVisitor([FromBody] VisitorDetails visitorDetails) { Service.ClearTravelOrVisitorFields(visitorDetails); return(ValidationService.GetFullModelValidationResult(visitorDetails)); }
/// <summary> /// Gets the error message for the property with the given name. /// </summary> /// <param name="columnName">The name of the property whose error message to get</param> /// <param name="newValue">The new value for the row</param> /// <returns>The error message for the property. The default is an empty string ("").</returns> /// <remarks> /// Used when inline-editing, the values are updated on focus lost /// </remarks> public virtual string ValidateProperty(string columnName, object newValue) { return(ValidationService.ValidateProperty(columnName, newValue, this)); }
static void Main(string[] args) { var logs = new List<ILog>(); var timedLogs = new List<ITimedLog>(); timedLogs.Add(new XCRI.Validator.App.Logging.TimedLogToConsole()); var xmlResolver = new xr.XmlCachingResolver(new [] { new xr.NullXmlCacheLocation() }, logs, timedLogs); var source = new xr.UriSource(logs, xmlResolver); var validatorFactory = new cv.ValidatorFactory(logs, timedLogs, source); var validationModule = new ValidationModule(logs, timedLogs, validatorFactory); var interpreterFactory = new mi.InterpreterFactory(logs, timedLogs); var interpretationModule = new m.InterpretationModule(logs, timedLogs, interpreterFactory); var validationService = new ValidationService<Uri> ( System.Globalization.CultureInfo.CurrentUICulture, null, null, logs, timedLogs, source, xmlResolver ); var runner = new ValidateRunner ( timedLogs[0], validationService, validationModule, interpretationModule ); System.IO.FileInfo fileToValidate = null; System.IO.FileInfo validationModuleLocation = new FileInfo(@"xml-files\ValidationModules\XCRICAP12.xml"); System.IO.FileInfo interpretationModuleLocation = new FileInfo(@"xml-files\XmlExceptionInterpretation.xml"); AnalyseArguments ( args, ref fileToValidate, ref validationModuleLocation, ref interpretationModuleLocation ); runner.FileToValidate = fileToValidate; runner.ValidationModuleLocation = validationModuleLocation; runner.InterpretationModuleLocation = interpretationModuleLocation; runner.Run(); }
public ValidateBlockChainBenchmarkService(ILogger <ValidateBlockChainBenchmarkService> logger, ValidationService validationService) { _logger = logger; _validationService = validationService; }
public async Task <string> SignUp(UserModel userModel) { if (!ValidationService.IsUserModelValid(userModel)) { throw new Exception("User model is not valid."); } if (!ValidationService.IsEmailValid(userModel.Email)) { throw new Exception("Email isn't valid."); } if (!ValidationService.IsPasswordValid(userModel.Password)) { throw new Exception("Password must be at least 8 characters, contain at least 1 digital, 1 lower case letter, 1 upper case letter, " + "1 non-character (such as !,#,%,@, etc)"); } User user = await _userManager.FindByEmailAsync(userModel.Email); if (user != null) { if (user.IsRegistered && !user.Deleted) { if (!user.EmailConfirmed) { throw new Exception("Please, confirm your email."); } else { throw new Exception("User with current email already exists."); } } } if (!string.Equals(userModel.Password, userModel.ConfirmPassword)) { throw new Exception("Passwords mismatch."); } user = new User { Name = userModel.Name, UserName = userModel.Email, Email = userModel.Email, EmailConfirmed = false, PhoneNumber = userModel.PhoneNumber, CreateDate = DateTime.Now, IsRegistered = false, Deleted = false }; IdentityResult identityResult = await _userManager.CreateAsync(user, userModel.Password); if (identityResult.Errors.Any()) { return(identityResult.Errors.FirstOrDefault().Description); } string messageSubject = Constants.messageSubjectForUserSignUp; Random random = new Random(); string confirmationCode = (random.Next(1000, 9999)).ToString(); string result = await _senderService.SendEmail(userModel.Email, messageSubject, confirmationCode); return(result); }
private void CalculatePasswordStrength(string value) { this.PasswordStrength = ValidationService.CalculatePasswordStrength(value); }
public async Task editPublicUserProfileAsync_EditProfile_ProfileSuccessfullyEdited(int userId, string description, string job, string goals, int age, string gender, string ethnicity, string sexualOrientation, string height, string visibility, string status, string photo, string intrests, string hobbies) { IDataGateway dataGateway = new SQLServerGateway(); IConnectionStringData connectionString = new ConnectionStringData(); IPublicUserProfileRepo publicUserProfileRepo = new PublicUserProfileRepo(dataGateway, connectionString); IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString); IUserProfileRepository userProfileRepository = new UserProfileRepository(dataGateway, connectionString); IUserProfileService userProfileService = new UserProfileService(userProfileRepository); IUserAccountService userAccountService = new UserAccountService(userAccountRepository); IValidationService validationService = new ValidationService(userAccountService, userProfileService); IPublicUserProfileService publicUserProfileService = new PublicUserProfileService(publicUserProfileRepo, validationService); PublicUserProfileManager publicUserProfileManager = new PublicUserProfileManager(publicUserProfileService); PublicUserProfileModel model = new PublicUserProfileModel(); model.UserId = userId; try { await publicUserProfileManager.CeatePublicUserProfileAsync(model); model.Description = description; model.Jobs = job; model.Goals = goals; model.Age = age; model.Gender = gender; model.Ethnicity = ethnicity; model.SexualOrientation = sexualOrientation; model.Height = height; model.Visibility = visibility; model.Status = status; model.Intrests = intrests; model.Hobbies = hobbies; await publicUserProfileManager.EditPublicUserProfileAsync(model); PublicUserProfileModel profile = await publicUserProfileRepo.GetPublicProfilebyUserId(userId); if (profile == null) { Assert.IsTrue(false); } if (profile.Description == description && profile.Hobbies == hobbies && profile.Jobs == job && profile.Goals == goals && profile.Age == age && profile.Gender == gender && profile.Ethnicity == ethnicity && profile.SexualOrientation == sexualOrientation && profile.Height == height && profile.Visibility == visibility && profile.Intrests == intrests) { Assert.IsTrue(true); } else { Assert.IsTrue(false); } } catch { Assert.IsTrue(false); } }
public AccountController(ApplicationContext context, IMapper mapper, ValidationService validationService) { _context = context; _mapper = mapper; _validationService = validationService; }
private IValidationService CreateService() { var result = new ValidationService(); return result; }