public void ShouldGenerateRandomFourCharacterNumericCodes() { const int sampleSize = 10; var sampleCodes = new List <string>(); for (var i = 0; i < sampleSize; i++) { // Arrange. var generator = new RandomCodeGenerator(); // Act. var code = generator.GenerateNumeric(); // Assert. Assert.IsFalse(string.IsNullOrWhiteSpace(code)); Assert.AreEqual(4, code.Length); Assert.IsTrue(code.All(c => RandomCodeGenerator.Numerics.Contains(c))); CollectionAssert.DoesNotContain(sampleCodes, code); sampleCodes.Add(code); } Assert.AreEqual(sampleSize, sampleCodes.Count); }
public async Task <Unit> Handle(SendAuthorizationCodeCommand request, CancellationToken cancellationToken) { var account = await _repository.GetAccountByEmail(request.Email, cancellationToken) ?? throw new NotFoundException("There is no account registered by that email", new { request.Email }); var authorizationCode = RandomCodeGenerator.GenerateRandomCode(30, false); account.Codes.Add(new AccountAuthorizationCode { Account = account, Active = true, Code = BC.HashPassword(authorizationCode), Generated = DateTime.Now } ); await _emailManager.SendAuthorizationCode( request.Email, account.Username, authorizationCode, _context.GetUserAgentAsString(), _context.GetRequestIpAsString(), cancellationToken ); _repository.Update(account); return(Unit.Value); }
public void RandomCodeGenerator_GenerateCode_ReturnsSomething() { var result1 = RandomCodeGenerator.GenerateCode(10, CharacterSet.Numbers); Assert.False(String.IsNullOrEmpty(result1)); Assert.Equal(result1.ToNumeric(), result1); Assert.Equal(10, result1.Length); }
public void CreateLockerComboSixLength() { var length = 6; var randomCodeGenerator = new RandomCodeGenerator(length); var lockerCombo = randomCodeGenerator.CreateLockerCombo(); Assert.Equal(length, lockerCombo.Length); }
public void ShouldGenerateCodeOfFirstCharacterInSetWhenUsingRandomNumberGeneratorTestImplementation() { //Arrange var generator = new RandomCodeGenerator(new RandomNumberGeneratorTestClass()); //Act var code = generator.GenerateAlphaNumeric(4); //Assert Assert.AreEqual("4444", code); }
public GenerateOtpResult GenerateOtp(GenerateOtpInput input) { var expireDateTime = DateTime.Now.AddSeconds(Settings.ExpirationInSeconds); var password = RandomCodeGenerator.GenerateRandomCode(Settings.Length, Settings.PermittedLetters); var otpJsonObj = CreateOtpJsonObject(input, password, expireDateTime); var serializedOtpJsonObj = SerializeOtpJsonObject(otpJsonObj); var encryptedOtpJsonObj = EncryptOtpJsonObject(serializedOtpJsonObj); return(new GenerateOtpResult(encryptedOtpJsonObj, expireDateTime)); }
private void GenerateCodes(object parameter) { try { // Construct cache for code uniqueness check var existingCodes = GetExistingCodes(); BaseInfo coupon = null; using (var context = new CMSActionContext()) { // Do not touch parent for all codes context.TouchParent = false; context.LogEvents = false; var logMessage = GetString("com.couponcode.generated"); // Create generator var generator = new RandomCodeGenerator(new CodeUniquenessChecker(existingCodes), pattern, prefix); for (var i = 0; i < count; i++) { // Get new code var code = generator.GenerateCode(); var couponConfig = GetCouponConfig(code); coupon = Discount.CreateCoupon(couponConfig); // Log that coupon was created AddLog(string.Format(logMessage, HTMLHelper.HTMLEncode(code))); } } // Touch parent (one for all) coupon?.Generalized.TouchParent(); // Log information that coupons were generated var logData = new EventLogData(EventTypeEnum.Information, "Discounts", "GENERATECOUPONCODES") { EventDescription = $"{count} coupon codes for discount '{Discount.DiscountDisplayName}' successfully generated.", UserID = CurrentUser.UserID, UserName = CurrentUser.UserName, SiteID = SiteContext.CurrentSiteID }; Service.Resolve <IEventLogService>().LogEvent(logData); } catch (Exception ex) { CurrentError = GetString("com.couponcode.generateerror"); Service.Resolve <IEventLogService>().LogException("Discounts", "GENERATECOUPONCODES", ex); } }
public string GenerateRefreshToken(Guid id, DateTime creationDate) { var token = RandomCodeGenerator.GenerateRandomCode(128); _store.Insert(new RefreshTokenDto { Token = token, AccountIdentity = id, CreationDate = creationDate }); return(token); }
private void GenerateCodes(object parameter) { try { // Construct cache for code uniqueness check var existingCodes = GetExistingCodes(); BaseInfo coupon = null; using (CMSActionContext context = new CMSActionContext()) { // Do not touch parent for all codes context.TouchParent = false; context.LogEvents = false; // Create generator var generator = new RandomCodeGenerator(pattern, prefix); // Use cache for checking code uniqueness generator.CodeChecker = code => !existingCodes.Contains(code); for (int i = 0; i < count; i++) { // Get new code string code = generator.GenerateCode(); coupon = Discount.CreateCoupon(code, numberOfUses); // Log that coupon was created AddLog(string.Format(GetString("com.couponcode.generated"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(code)))); } } // Touch parent (one for all) if (coupon != null) { coupon.Generalized.TouchParent(); } // Log information that coupons were generated EventLogProvider.LogEvent(EventType.INFORMATION, "Discounts", "GENERATECOUPONCODES", string.Format("{0} coupon codes for discount '{1}' successfully generated.", count, Discount.DiscountDisplayName), userId: CurrentUser.UserID, userName: CurrentUser.UserName, siteId: SiteContext.CurrentSiteID ); } catch (Exception ex) { CurrentError = GetString("com.couponcode.generateerror"); EventLogProvider.LogException("Discounts", "GENERATECOUPONCODES", ex); } }
public void RandomCodeGenerator_Should_Generate_Unique_Codes() { IRandomCodeGenerator r = new RandomCodeGenerator(); HashSet <string> codes = new HashSet <string>(); for (int i = 0; i < 1000; i++) { var code = r.Next(); AddCodeOrThrowException(codes, code); Thread.Sleep(1); } Assert.NotEmpty(codes); }
public void It_Should_Return_A_SecretCodeWithALengthOfFour_When_CodeLengthInConfigIsFour() { //arrange var config = new MastermindConfig { [DataConstants.CodeLength] = 4, [DataConstants.NumberOfColours] = 6, [DataConstants.NumberOfTurns] = 8 }; var randomCodeGenerator = new RandomCodeGenerator(config); //act var secretCode = randomCodeGenerator.GenerateSecretCode(); //assert Assert.Equal(4, secretCode.Count); }
public void RandomCodeGenerator_Length_10_Should_Generate_Unique_Codes_With_Length_10() { IRandomCodeGenerator r = new RandomCodeGenerator(10); HashSet <string> codes = new HashSet <string>(); for (int i = 0; i < 1000; i++) { var code = r.Next(); AddCodeOrThrowException(codes, code); Thread.Sleep(1); } foreach (var c in codes) { Assert.Equal(c.Length, 10); } }
public void It_Should_Return_A_SecretCodeOfColouredPegsWithFlagsFiveOrLess_When_NumberOfColoursInConfigIsSix() { //arrange var config = new MastermindConfig { [DataConstants.CodeLength] = 4, [DataConstants.NumberOfColours] = 6, [DataConstants.NumberOfTurns] = 8 }; var randomCodeGenerator = new RandomCodeGenerator(config); //act var secretCode = randomCodeGenerator.GenerateSecretCode(); //assert foreach (var peg in secretCode) { Assert.True(Enum.IsDefined(typeof(Peg), peg) && (int)peg < config[DataConstants.NumberOfColours]); } }
public async Task <Account> Handle(CreateAccountCommand request, CancellationToken cancellationToken) { if (await _repository.GetAccountByUsername(request.Account.Username, cancellationToken) != null) { throw new EntityCreationException("The username is already registered"); } if (await _repository.GetAccountByEmail(request.Account.Email, cancellationToken) != null) { throw new EntityCreationException("The email is already registered"); } request.Account.Hash = BC.HashPassword(request.Password); request.Account.Active = false; var authorizationCode = RandomCodeGenerator.GenerateRandomCode(30, false); request.Account.Codes = new List <AccountAuthorizationCode> { new AccountAuthorizationCode { Account = request.Account, Active = true, Code = BC.HashPassword(authorizationCode), Generated = DateTime.Now } }; await _emailManager.SendInvitation( request.Account.Email, request.Account.Username, request.Account.Role.ToString(), authorizationCode, cancellationToken ); _repository.Insert(request.Account); return(request.Account); }
public virtual void GeneratePasswordResetCode() { PasswordResetCode = RandomCodeGenerator.Generate(32); }
public virtual void GenerateEmailConfirmationCode() { EmailConfirmationCode = RandomCodeGenerator.Generate(16); }
private void GenerateCodes(object parameter) { try { // Construct cache for code uniqueness check var existingCodes = GetExistingCodes(); BaseInfo coupon = null; using (CMSActionContext context = new CMSActionContext()) { // Do not touch parent for all codes context.TouchParent = false; context.LogEvents = false; // Create generator var generator = new RandomCodeGenerator(pattern, prefix); // Use cache for checking code uniqueness generator.CodeChecker = code => !existingCodes.Contains(code); for (int i = 0; i < count; i++) { // Get new code string code = generator.GenerateCode(); coupon = Discount.CreateCoupon(code, numberOfUses); // Log that coupon was created AddLog(string.Format(GetString("com.couponcode.generated"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(code)))); } } // Touch parent (one for all) if (coupon != null) { coupon.Generalized.TouchParent(); } // Log information that coupons were generated EventLogProvider.LogEvent(EventType.INFORMATION, "Discounts", "GENERATECOUPONCODES", string.Format("{0} coupon codes for discount '{1}' successfully generated.", count, Discount.DiscountDisplayName), userId: CurrentUser.UserID, userName: CurrentUser.UserName, siteId: SiteContext.CurrentSiteID ); } catch (Exception ex) { CurrentError = GetString("com.couponcode.generateerror"); EventLogProvider.LogException("Discounts", "GENERATECOUPONCODES", ex); } }