Esempio n. 1
0
 public void RandomStringGeneratorTest()
 {
     var rsg = new RandomStringGenerator();
     foreach (var s in Enumerable.Range(1, 30))
     {
         Console.WriteLine(rsg.Generate(s % 10 + 1));
     }
 }
Esempio n. 2
0
        public ActionResult Create()
        {
            var randomStringGenerator = new RandomStringGenerator();
            var objectKey = string.Format("uploads/{0}/${{filename}}", randomStringGenerator.GenerateString(16));
            var bucket = "foo-bucket";

            var maxFileSize = 512 * 1024 * 1024;
            var objectConfiguration = new AmazonS3ObjectConfiguration(objectKey, AmazonS3CannedAcl.Private, maxFileSize);
            var uploadConfiguration = new AmazonS3UploadConfiguration(_credentials, bucket, objectConfiguration);

            return View(uploadConfiguration);
        }
Esempio n. 3
0
        public string CreateNewSession()
        {
            var stringGenerator = new RandomStringGenerator();
            string newSessionUrl;

            //Generate unique session url
            var isNotUniqueSessionUrl = true;
            do
            {
                newSessionUrl = stringGenerator.RandomString(SessionIdLength);
                var session = _sessionRepository.GetByUniqueUrl(newSessionUrl);
                isNotUniqueSessionUrl = session != null;
            } while (isNotUniqueSessionUrl);

            var newSession = new Session {UniqueUrl = newSessionUrl, Created = DateTime.Now};
            _sessionRepository.Save(newSession);

            return newSessionUrl;
        }
        public void TestGetNextStringWithHistory()
        {
            var indexStrs = GetStringHistory();

            Console.WriteLine("{0} historical items found.", indexStrs.Count);

            var needed    = 10000;
            var attempts  = 0;
            var generated = 0;
            var gen       = new RandomStringGenerator();

            while (generated < needed)
            {
                attempts++;

                var id = gen.NextIndex();
                if (indexStrs.ContainsKey(id))
                {
                    continue;
                }
                indexStrs[id] = gen.StringOfIndex(id);
                generated++;
            }

            Console.WriteLine("generated {0} ids, attempted {1} times", generated, attempts);

            var file_name = "id_logs.txt";

            if (File.Exists(file_name))
            {
                File.Delete(file_name);
            }

            var data = new StringBuilder();

            foreach (var key in indexStrs.Keys)
            {
                data.AppendFormat("{0}:{1}", key, indexStrs[key]);
                data.AppendLine();
            }
            File.WriteAllText(file_name, data.ToString());
        }
        public async Task SaveLinkInLowerCase()
        {
            var link       = RandomStringGenerator.GenerateRandomLatin(30);
            var publicLink = new PublicLink
            {
                ShopId   = Guid.NewGuid(),
                Link     = link.ToUpperInvariant(),
                IsActive = true,
            };

            var result = await publicLinkRepository.WriteOrUpdateAsync(publicLink);

            var dbPublicLinkUpper = await publicLinkRepository.ReadByPublicLinkAsync(link.ToUpperInvariant());

            var dbPublicLinkLower = await publicLinkRepository.ReadByPublicLinkAsync(link);

            result.Should().BeTrue();
            dbPublicLinkUpper.Link.Should().BeEquivalentTo(link);
            dbPublicLinkLower.Should().BeEquivalentTo(dbPublicLinkUpper);
        }
Esempio n. 6
0
 //
 // GET: /Account/Login
 public ActionResult Login(string returnUrl)
 {
     if (IsLogged())
     {
         return(RedirectToLocal(""));
     }
     if (ModelState.IsValid)
     {
         RandomStringGenerator random = new RandomStringGenerator();
         random.UseSpecialCharacters   = false;
         random.UseUpperCaseCharacters = false;
         random.UseLowerCaseCharacters = false;
         ViewBag.key           = random.Generate(16);
         Session["keylogin"]   = ViewBag.key;
         ViewBag.isNhapCaptcha = false;
         ViewBag.linkCaptcha   = "";
         ViewBag.ReturnUrl     = returnUrl;
     }
     return(View());
 }
Esempio n. 7
0
        public AuthKey GenerateAuthKey(string email, string password)
        {
            Account account = _accountRepository.GetAccountByEmail(email);

            if (account == null)
            {
                return(null);
            }

            string  hash    = SHAHasher.ComputeSha256Hash(RandomStringGenerator.CreateString(256));
            AuthKey authKey = new AuthKey()
            {
                AccountId = account.AccountId,
                Key       = hash
            };

            _appDbContext.AuthKeys.Add(authKey);
            _appDbContext.SaveChanges();
            return(authKey);
        }
        public AuthKey GenerateAuthKey(string email, string password)
        {
            User user = _userRepository.GetUserByEmail(email);

            if (user == null)
            {
                return(null);
            }

            string  hash    = SHAHasher.ComputeSha256Hash(RandomStringGenerator.CreateString(256));
            AuthKey authKey = new AuthKey()
            {
                UserId = user.Id,
                Key    = hash
            };

            _appDbContext.AuthKeys.Add(authKey);
            _appDbContext.SaveChanges();
            return(authKey);
        }
        public async Task <IActionResult> Register(Customer customer)
        {
            if (ModelState.IsValid)
            {
                var allCustomers = await _database.Customers.ToListAsync();

                if (allCustomers.Any(c => c.Email == customer.Email))
                {
                    TempData["emailexists"] = "Sorry a customer with this email address exists";

                    return(View(customer));
                }
                else
                {
                    //var generator = new Random();
                    //var number = generator.Next(0, 100000000).ToString();

                    var stringGenerator = new RandomStringGenerator();
                    var memberid        = stringGenerator.RandomString(8);

                    var _customer = new Customer()
                    {
                        FirstName       = customer.FirstName,
                        LastName        = customer.LastName,
                        Email           = customer.Email,
                        MobileNumber    = customer.MobileNumber,
                        Password        = BCrypt.Net.BCrypt.HashPassword(customer.Password),
                        ConfrimPassword = BCrypt.Net.BCrypt.HashPassword(customer.ConfrimPassword),
                        MemberId        = memberid
                    };

                    await _database.Customers.AddAsync(_customer);

                    await _database.SaveChangesAsync();

                    return(RedirectToAction("Signin", "Customer"));
                }
            }

            return(RedirectToAction("Signin", "Customer"));
        }
Esempio n. 10
0
        public override string Execute()
        {
            string result = string.Empty;

            if (!Engine.UserIsLogged)
            {
                result = string.Format(ErrorMessages.ActionDenied);

                return(result);
            }

            if (this.arguments.Length != 2)
            {
                result = ErrorMessages.InvalidArgumentsCount;

                return(result);
            }

            decimal balance = decimal.Parse(arguments[0]);
            double  rate    = double.Parse(arguments[1]);

            string accountNumber = string.Empty;

            do
            {
                accountNumber = RandomStringGenerator.GenerateString(10);
            }while (
                db.SavingAccounts.Any(sa => sa.AccountNumber == accountNumber)
                ||
                db.CheckingAccounts.Any(ca => ca.AccountNumber == accountNumber)
                );

            var account = new SavingAccount(accountNumber, balance, Engine.CurrentUserId, rate);

            db.SavingAccounts.Add(account);
            db.SaveChanges();

            result = string.Format(SuccessMessages.AccountAdded, accountNumber);

            return(result);
        }
Esempio n. 11
0
        public async Task <(Admin Admin, string Login)> AddAsync(CreateAdmin command)
        {
            var login     = RandomStringGenerator.GenerateUnique();
            var loginHash = _hashManager.CalculateDataHash(_hashManager.CalculateDataHash(login).ToString());

            if (await _context.Admins.ExistsInDatabaseAsync(command.Nick, loginHash) == true)
            {
                throw new CorruptedOperationException("Admin already exists.");
            }

            _hashManager.CalculatePasswordHash(command.Password, out var passwordHash, out var salt);
            var restoreKey = PasswordGenerator.GenerateRandomPassword();

            var admin = new Admin(command.Nick, loginHash, salt, passwordHash, restoreKey);

            await _context.Admins.AddAsync(admin);

            await _context.SaveChangesAsync();

            return(admin, login);
        }
 public static PayRequest GeneratePayRequest(CheckRequest checkRequest)
 {
     return(new PayRequest()
     {
         SD = checkRequest.SD,
         AP = checkRequest.AP,
         OP = checkRequest.OP,
         DATE = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"),
         SESSION = checkRequest.SESSION,
         NUMBER = checkRequest.NUMBER,
         ACCOUNT = checkRequest.ACCOUNT,
         AMOUNT = checkRequest.AMOUNT,
         AMOUNT_ALL = checkRequest.AMOUNT_ALL,
         PAY_TOOL = checkRequest.PAY_TOOL,
         TERM_ID = checkRequest.TERM_ID,
         COMMENT = "TEST 9876543210",
         RRN = RandomStringGenerator.GenerateNumericString(32, Rng),
         ACCEPT_KEYS = TestConfigurations.ManagerConfiguration.PublicKeySerial,
         NO_ROUTE = "1",
     });
 }
Esempio n. 13
0
        public virtual ActionResult Logo()
        {
            var randomStringGenerator = new RandomStringGenerator();
            var objectKey             = string.Format("uploads/{0}/${{filename}}", randomStringGenerator.GenerateString(16));
            var bucket = "wnuh";

            var maxFileSize         = 512 * 1024 * 1024;
            var objectConfiguration = new AmazonS3ObjectConfiguration(objectKey, AmazonS3CannedAcl.Private, maxFileSize);

            var credentials = new AmazonCredentials(
                ConfigurationManager.AppSettings.Get("amazon.access_key_id"),
                ConfigurationManager.AppSettings.Get("amazon.secret_access_key"));

            var uploadConfiguration = new AmazonS3UploadConfiguration(credentials, bucket, objectConfiguration);

            var viewModel = new OrganizationVm {
                Configuration = uploadConfiguration
            };

            return(PartialView(viewModel));
        }
Esempio n. 14
0
 private CheckRequest prepareCheckRequest(GateCheckRequest request)
 {
     return(new CheckRequest()
     {
         SD = m_Configuration.SD,
         AP = m_Configuration.AP,
         OP = m_Configuration.OP,
         DATE = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"),
         SESSION = RandomStringGenerator.GenerateAlphaNumericString(20, m_Rng),
         NUMBER = request.Number,
         ACCOUNT = request.Number != null ? string.Empty : request.Account,
         AMOUNT = request.Amount.HasValue ? printDouble(request.Amount.Value) : printDouble(FAKE_AMOUNT),
         AMOUNT_ALL = request.Amount.HasValue ? printDouble(request.Amount.Value) : printDouble(FAKE_AMOUNT),
         REQ_TYPE = request.Amount == null ? "1" : "0",
         PAY_TOOL = ((int)m_Configuration.PAY_TOOL).ToString(),
         TERM_ID = m_Configuration.TERM_ID,
         COMMENT = "",
         ACCEPT_KEYS = null, // will be filled right before sending
         NO_ROUTE = m_Configuration.NO_ROUTE ? "1" : "0",
     });
 }
Esempio n. 15
0
        private UserEntity SetupFormsAuthTicket(string userName, bool persistanceFlag)
        {
            var userEntity = _userRepository.GetUserObjByUserName(userName);
            var userId     = userEntity.UserID;
            var token      = RandomStringGenerator.RandomString(8);

            _userRepository.SetOneTimeToken(userId, token);
            var userData = string.Format("{0}:{1}", userId.ToString(CultureInfo.InvariantCulture),
                                         token);
            var authTicket = new FormsAuthenticationTicket(1,                           //version
                                                           userName,                    // user name
                                                           DateTime.Now,                //creation
                                                           DateTime.Now.AddMinutes(30), //Expiration
                                                           persistanceFlag,             //Persistent
                                                           userData);

            var encTicket = FormsAuthentication.Encrypt(authTicket);

            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
            return(userEntity);
        }
Esempio n. 16
0
        public async Task RequestMemberEmailAddressUpdate(Guid memberId, string newEmailAddress)
        {
            Member member = await GetMember(memberId, memberId);

            if (member.EmailAddress.Equals(newEmailAddress, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (!MailUtils.ValidEmailAddress(newEmailAddress))
            {
                throw new OdkServiceException("Invalid email address format");
            }

            MemberEmailAddressUpdateToken existingToken = await _memberRepository.GetMemberEmailAddressUpdateToken(member.Id);

            if (existingToken != null)
            {
                await _memberRepository.DeleteEmailAddressUpdateToken(member.Id);
            }

            string activationToken = RandomStringGenerator.Generate(64);

            MemberEmailAddressUpdateToken token = new MemberEmailAddressUpdateToken(member.Id, newEmailAddress, activationToken);
            await _memberRepository.AddEmailAddressUpdateToken(token);

            Chapter chapter = await _chapterRepository.GetChapter(member.ChapterId);

            string url = _settings.ConfirmEmailAddressUpdateUrl.Interpolate(new Dictionary <string, string>
            {
                { "chapter.name", chapter.Name },
                { "token", HttpUtility.UrlEncode(activationToken) }
            });

            await _emailService.SendEmail(chapter, newEmailAddress, EmailType.EmailAddressUpdate, new Dictionary <string, string>
            {
                { "chapter.name", chapter.Name },
                { "url", url }
            });
        }
        public HttpResponseMessage PostCollaborator(Collaborators objCollaborators)
        {
            //TblCollaborator objTblCollaborator = ConvertToCollaboratorDataModel(objCollaborators);
            //_unitOfCollaborator.GetRepoInstance<TblCollaborator>().Insert(objTblCollaborator);
            //_unitOfCollaborator.SaveChanges();
            HttpResponseMessage objHTTPResponseMessage;

            _unitOfCollaborator = new GenericUnitOfWork();

            RandomStringGenerator objRandomStringGenerator = new RandomStringGenerator();

            objCollaborators.Token = objRandomStringGenerator.Generate(64);

            ObjectResult <string> objResult = _unitOfCollaborator.GetRepoInstance <TblCollaborator>().SPSave(objCollaborators.VaultID, objCollaborators.CollabeMail, objCollaborators.UserID, objCollaborators.CollabeID, objCollaborators.Token, objCollaborators.IPAddress);

            objHTTPResponseMessage = Request.CreateResponse(objResult.FirstOrDefault());
            if (objHTTPResponseMessage.StatusCode == HttpStatusCode.OK)
            {
                SendMail(objCollaborators);
            }
            return(objHTTPResponseMessage);
        }
Esempio n. 18
0
        public ActionResult Forgot(ForgotModel model)
        {
            if (ModelState.IsValid)
            {
                DbContext db = new DbContext("DefaultConnection");

                using (DiamondCircle_dbEntities dbs = new DiamondCircle_dbEntities())
                {
                    var user = dbs.UserDetails.Where(s => s.Email == model.Email).FirstOrDefault();
                    if (user == null)
                    {
                        TempData["Msg"] = "Your email address does not exist in our records. We are unable to reset your password.";
                        return(RedirectToAction("Message", "Home"));
                    }
                    else
                    {
                        string query    = String.Format("select UserName from UserProfile where UserId ='{0}'", user.UserId);
                        string username = db.Database.SqlQuery <string>(query, user.UserId).FirstOrDefault();

                        RandomStringGenerator newPass = new RandomStringGenerator();
                        string NewPassword            = newPass.Create(6).Trim();

                        var token = WebSecurity.GeneratePasswordResetToken(username);
                        WebSecurity.ResetPassword(token, NewPassword);

                        string body = "Dear " + username + ",\n\r Your new password is: \n\r  " +
                                      NewPassword + " \n\r \n\r  Regards,"
                                      + " \n\r \n\r  The Diamond Circle team";


                        SendEmail.Send("Diamond Circle", model.Email, "New Password", body);
                    }
                }

                TempData["Msg"] = "A new password has been sent to your email address.";
                return(RedirectToAction("Message", "Home"));
            }
            return(View(model));
        }
 public static CheckRequest GenerateCheckRequest()
 {
     return(new CheckRequest()
     {
         SD = "17031",
         AP = "17032",
         OP = "17034",
         DATE = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"),
         SESSION = RandomStringGenerator.GenerateAlphaNumericString(20, Rng),
         NUMBER = "9261112233",
         ACCOUNT = null,
         AMOUNT = "1234.56",
         AMOUNT_ALL = "1249.99",
         REQ_TYPE = "0",
         PAY_TOOL = "0",
         TERM_ID = null,
         //COMMENT = "TEST Кириллица TEST 0123456789", // CyberPlat not supports cyrillic even if I urlencode in cp1521
         COMMENT = "TEST 0123456789",
         ACCEPT_KEYS = TestConfigurations.ManagerConfiguration.PublicKeySerial,
         NO_ROUTE = "1",
     });
 }
Esempio n. 20
0
        public ActionResult ResetPassword(ResetPasswordModel model, string ticket)
        {
            if (string.IsNullOrEmpty(ticket))
            {
                return(RedirectToRoute("Default"));
            }

            if (ModelState.IsValid)
            {
                var randomCode     = RandomStringGenerator.RandomString();
                var encCode        = TripleDES.EncryptString(randomCode);
                var hashedPassword = PasswordHelper.GenerateHashedPassword(model.Password, randomCode);
                if (_userRepository.ResetPassword(model.EmailAddress, model.VerificationCode, hashedPassword, encCode))
                {
                    return(RedirectToRoute("AdminIndex"));
                }
                ModelState.AddModelError("__FORM", "unable to reset your password");
            }

            model.Title = SettingsRepository.BlogName;
            return(View(model));
        }
Esempio n. 21
0
        public void OnEvent(ref TNetMsg Msg)
        {
            byte kind = GSocket.GetBufToByte(ref Msg.Value);
            //Console.WriteLine("登入結果(kind):" + kind);
            byte sex     = 0;
            byte armType = 0;

            switch (kind)
            {
            case 1:
                // 登入成功
                var        gsid      = GSocket.GetBufToWord(ref Msg.Value);
                int        timeRange = GSocket.GetBufToInt(ref Msg.Value);
                sLoginType role      = new sLoginType(true);
                if (GSocket.GetBufToType <sLoginType>(ref Msg.Value, ref role))
                {
                    // 啟動效能監測工具
                    _monitorUnit.StartMonitor();
                    _monitorUnit.SetTag(role.Account);

                    Console.WriteLine($"{role.Account}發送 註冊禮包碼");
                    _socket.PushDWord(10);
                    _socket.PushString("sayhello2you");
                    _socket.SendMsg(1, 111);
                }
                break;

            case 3:
                // 創角帳號
                Thread.Sleep(2000);
                Console.WriteLine("創角帳號(kind):" + kind);
                var randomGenerator = new RandomStringGenerator();
                _socket.PushString(randomGenerator.RandomCreateCharacterName());
                _socket.PushByte(sex);
                _socket.PushByte(armType);
                _socket.SendMsg(1, 72);
                break;
            }
        }
Esempio n. 22
0
        public async Task RequestPasswordReset(string emailAddress)
        {
            if (!MailUtils.ValidEmailAddress(emailAddress))
            {
                throw new OdkServiceException("Invalid email address format");
            }

            Member member = await _memberRepository.FindMemberByEmailAddress(emailAddress);

            DateTime created = DateTime.UtcNow;
            DateTime expires = created.AddMinutes(_settings.PasswordResetTokenLifetimeMinutes);
            string   token   = RandomStringGenerator.Generate(64);

            try
            {
                _authorizationService.AssertMemberIsCurrent(member);
            }
            catch
            {
                return;
            }

            Chapter chapter = await _chapterRepository.GetChapter(member.ChapterId);

            await _memberRepository.AddPasswordResetRequest(member.Id, created, expires, token);

            string url = _settings.PasswordResetUrl.Interpolate(new Dictionary <string, string>
            {
                { "chapter.name", chapter.Name },
                { "token", HttpUtility.UrlEncode(token) }
            });

            await _emailService.SendEmail(chapter, member.EmailAddress, EmailType.PasswordReset, new Dictionary <string, string>
            {
                { "chapter.name", chapter.Name },
                { "url", url }
            });
        }
Esempio n. 23
0
        public async Task <string> Handle(GenerateResetTokenCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.GetByEmailAsync(request.Email);

            if (user == null)
            {
                throw new NotFoundException("User");
            }

            if (user.Role.IsAdminRole())
            {
                throw new ForbiddenException();
            }

            var resetToken = RandomStringGenerator.Generate(50);
            var userId     = Encoding.UTF8.GetBytes(user.Id.ToString());
            await _distributedCache.SetAsync(resetToken, userId, new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
            }, cancellationToken);

            return(resetToken);
        }
Esempio n. 24
0
        public ActionResult EmailSent()
        {
            String      emailAddress = Request["recoveryEmail"].ToString();
            String      tempPassword = RandomStringGenerator.GetRandomString();
            MailMessage msg          = new MailMessage();

            msg.To.Add(emailAddress);
            msg.From     = new MailAddress("*****@*****.**");
            msg.Subject  = "Password Recovery";
            msg.Body     = "Hello," + Environment.NewLine + "Password: "******"Good Bye";
            msg.Priority = MailPriority.Normal;

            SmtpClient client = new SmtpClient();

            client.Credentials           = new NetworkCredential("*****@*****.**", "sherazleo79");
            client.Host                  = "smtp.gmail.com";
            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
            client.EnableSsl             = true;
            client.UseDefaultCredentials = false;
            client.Port                  = 25;
            client.Send(msg);
            return(View());
        }
Esempio n. 25
0
        public void ShopInfoTest()
        {
            var shopName    = RandomStringGenerator.GenerateRandomCyrillic(50);
            var shopAddress = RandomStringGenerator.GenerateRandomCyrillic(60);

            var info = recordingInfoConverter.CreateInfo(new Shop
            {
                Name    = shopName,
                Address = shopAddress,
            },
                                                         new OnlineService[0],
                                                         new Product[0],
                                                         new Worker[0],
                                                         new ShopCalendarRange <WorkerScheduleRecord>
            {
                StartDate        = 10.January(2019),
                EndDate          = 9.February(2019),
                ShopCalendarDays = new ShopCalendarDay <WorkerScheduleRecord> [0],
            },
                                                         new ShopCalendarRange <ServiceCalendarRecord>
            {
                StartDate        = 10.January(2019),
                EndDate          = 9.February(2019),
                ShopCalendarDays = new ShopCalendarDay <ServiceCalendarRecord> [0],
            },
                                                         10.January(2019));

            info.Should().BeEquivalentTo(new RecordingInfoDto
            {
                Name     = shopName,
                Address  = shopAddress,
                Services = new ServiceDto[0],
                Workers  = new WorkerDto[0],
                Today    = 10.January(2019),
            });
        }
Esempio n. 26
0
        public Response <AccountDto> Save(AccountDto accountDto)
        {
            using (UnitOfWork unitOfWork = new UnitOfWork())
            {
                if (accountDto.CrudStatus == CrudStatus.CREATE)
                {
                    accountDto.Password = RandomStringGenerator.Generate(accountDto.UserName);
                }

                var response = unitOfWork.Accounts.Save(accountDto, AccountMappers.Instance.MapToAccountDto);

                if (response.HasErrors)
                {
                    return(response);
                }

                if (accountDto.CrudStatus == CrudStatus.CREATE)
                {
                    SendCreateAccountEmail(accountDto);
                }

                return(response);
            }
        }
        public async Task CreateMovie_WhenMovieImageUrlIsWhitespaces_ShouldThrow()
        {
            // Arrange
            var(domainFacade, _) = CreateDomainFacade();
            var invalidMovie = new Movie(title: RandomStringGenerator.GetRandomAciiString(50), imageUrl: "    ", genre: Genre.Action, year: 1900);

            try
            {
                // Act
                await domainFacade.CreateMovie(invalidMovie);

                Assert.Fail("We were expecting a InvalidMovieException exception to be thrown, but no exception was thrown");
            }
            catch (InvalidMovieException e)
            {
                // Assert
                StringAssert.Contains(e.Message, " valid ImageUrl and can not be Whitespaces");
                AssertEx.EnsureExceptionMessageDoesNotContains(e, "Title", "Genre", "Year");
            }
            finally
            {
                domainFacade.Dispose();
            }
        }
Esempio n. 28
0
        public void Execute_StressTest()
        {
            // Arrange
            var randomStringGenerator = new RandomStringGenerator();

            var substring = randomStringGenerator.Execute(1000);
            var sut       = new Kmp(substring);

            var max = 10;

            for (int i = 0; i < max; i++)
            {
                var mainString = randomStringGenerator.Execute(999000);
                mainString = $"{mainString.Substring(0, 500000)}{substring}{mainString.Substring(500000)}";

                var expectedResult = mainString.IndexOf(substring);

                // Act
                var result = sut.Execute(mainString);

                // Assert
                Assert.Equal(expectedResult, result);
            }
        }
        private RandomStringGenerator GetGeneratorImpl(IPatternScope scope)
        {
            if (generator == null)
            {
                var invoker = MakeFilterInvoker(scope);

                if (Pattern == null && stock == null)
                    throw new PatternUsageErrorException("You must specify how to generate random strings by setting either 'Pattern' or 'Stock' appropriately.");
                if (!String.IsNullOrEmpty(Pattern) && stock.HasValue)
                    throw new PatternUsageErrorException("You must specify how to generate random strings by setting either 'Pattern' or 'Stock' exclusively.");

                try
                {
                    if (stock.HasValue)
                    {
                        return generator = new RandomStockStringGenerator
                        {
                            Values = RandomStringStockInfo.FromStock(stock.Value).GetItems(),
                            Count = count,
                            Filter = invoker,
                            Seed = NullableSeed,
                        };
                    }

                    return generator = new RandomRegexLiteStringGenerator
                    {
                        RegularExpressionPattern = Pattern,
                        Count = count,
                        Filter = invoker,
                        Seed = NullableSeed,
                    };
                }
                catch (GenerationException exception)
                {
                    throw new PatternUsageErrorException(String.Format("The random strings generator was incorrectly initialized ({0}).", exception.Message), exception);
                }
            }

            return generator;
        }
 private string GenAuthCode()
 {
     RandomStringGenerator myrsg = new RandomStringGenerator();
     return myrsg.NextString(20);
 }
 public void Test()
 {
     string randString = new RandomStringGenerator().GetNext(10);
     Assert.AreEqual(10, randString.Length);
 }
Esempio n. 32
0
        public void AnswerToQuiz_FailsIfAnswerTooLong()
        {
            AnswerToQuizResponseModel answer = this.testContext.CommandsManager.AnswerToQuiz(this.caller, RandomStringGenerator.RandomString(1025));

            Assert.False(answer.Success);
        }
Esempio n. 33
0
 string RandomString()
 {
     return(RandomStringGenerator.Generate(10));
 }
Esempio n. 34
0
 private IGenerator GetRandomStrinGenerator()
 {
     return(_randomStringGenerator ?? (_randomStringGenerator = new RandomStringGenerator()));
 }
Esempio n. 35
0
 /// <summary>
 /// 
 /// </summary>
 static Utils()
 {
     rsg = new RandomStringGenerator(1, "ABCDEF0123456789");
     rsgPW = new RandomStringGenerator(1, "ABCDEFGHIJKLMNPRXTUVWXYZabcdefghijklmnpqrxtuvwxyz123456789#&$"); 
 }
        /**
     * Creates an instance of DefaultUniqueTicketIdGenerator with default values
     * including a {@link DefaultLongNumericGenerator} with a starting value of
     * 1.
     * 
     * @param suffix the value to append at the end of the unique id to ensure
     * uniqueness across JVMs.
     */
        public DefaultUniqueTicketIdGenerator(string suffix)
        {
            this.numericGenerator = new DefaultLongNumericGenerator(1);
            this.randomStringGenerator = new DefaultRandomStringGenerator();

            if (suffix != null)
            {
                this.suffix = "-" + suffix;
            }
            else
            {
                this.suffix = null;
            }
        }
        public static IEnumerable <TestCaseData> GenerateInvalidWorkOrders()
        {
            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 0),
            }, "workOrderNumber", "number should be >= 1 and <= 999999")
            {
                TestName = "Wrong order number"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ShopRequisites = new ShopRequisites {
                    Phone = "0123456789"
                },
            }, "shopPhone", "phone should be 11 digits string")
            {
                TestName = "Short phone"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ShopRequisites = new ShopRequisites {
                    Phone = "012345678901"
                },
            }, "shopPhone", "phone should be 11 digits string")
            {
                TestName = "Long phone"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ShopRequisites = new ShopRequisites {
                    Phone = "0123456789a"
                },
            }, "shopPhone", "phone should be 11 digits string")
            {
                TestName = "Phone with letter"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = new DateTime(2016, 6, 30),
            }, "receptionDate", "reception date should be more then 01.07.2016 and less then 2 days after now")
            {
                TestName = "Min reception date"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date.AddDays(3),
            }, "receptionDate", "reception date should be more then 01.07.2016 and less then 2 days after now")
            {
                TestName = "Max reception date"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddDays(-1),
            }, "completionDatePlanned", "completion date should be more then reception date and less then 1 year after reception date")
            {
                TestName = "Min completion date planned"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddYears(1).AddDays(1),
            }, "completionDatePlanned", "completion date should be more then reception date and less then 1 year after reception date")
            {
                TestName = "Max completion date planned"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
                CompletionDateFact = DateTime.UtcNow.Date.AddDays(-1),
            }, "completionDateFact", "completion date should be more then reception date and less then 1 year after reception date")
            {
                TestName = "Min completion date fact"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
                CompletionDateFact = DateTime.UtcNow.Date.AddYears(1).AddDays(1),
            }, "completionDateFact", "completion date should be more then reception date and less then 1 year after reception date")
            {
                TestName = "Max completion date fact"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
                WarrantyNumber = RandomStringGenerator.GenerateRandomLatin(21)
            }, "warrantyNumber", "warranty number length should be less then 20")
            {
                TestName = "Warranty number length"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
                CustomerValues = new CustomerValueList
                {
                    CustomerValueType = CustomerValueType.Vehicle,
                    CustomerValues = new BaseCustomerValue[] { new ApplianceCustomerValue() },
                },
            }, "customerValueType", "values should be of type Vehicle")
            {
                TestName = "Vehicle value type"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
                CustomerValues = new CustomerValueList
                {
                    CustomerValueType = CustomerValueType.Vehicle,
                    CustomerValues = new BaseCustomerValue[] { new VehicleCustomerValue {
                                                                   RegisterSign = "a"
                                                               } },
                },
            }, "vehicleValueRegisterSign", "register sign contains wrong characters")
            {
                TestName = "Vehicle value error"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
                CustomerValues = new CustomerValueList
                {
                    CustomerValueType = CustomerValueType.Appliances,
                    CustomerValues = new BaseCustomerValue[] { new OtherCustomerValue() },
                },
            }, "customerValueType", "values should be of type Appliance")
            {
                TestName = "Appliance value type"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
                CustomerValues = new CustomerValueList
                {
                    CustomerValueType = CustomerValueType.Appliances,
                    CustomerValues = new BaseCustomerValue[] { new ApplianceCustomerValue {
                                                                   Brand = RandomStringGenerator.GenerateRandomLatin(41)
                                                               } },
                },
            }, "applianceValueBrand", "brand should be less or equals to 40")
            {
                TestName = "Appliance value error"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
                CustomerValues = new CustomerValueList
                {
                    CustomerValueType = CustomerValueType.Other,
                    CustomerValues = new BaseCustomerValue[] { new VehicleCustomerValue() },
                },
            }, "customerValueType", "values should be of type Other")
            {
                TestName = "Other value type"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
                CustomerValues = new CustomerValueList
                {
                    CustomerValueType = CustomerValueType.Other,
                    CustomerValues = new BaseCustomerValue[] { new OtherCustomerValue {
                                                                   Description = RandomStringGenerator.GenerateRandomLatin(501)
                                                               } },
                },
            }, "otherValueDescription", "description should be less or equals to 500")
            {
                TestName = "Other value error"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
                AdditionalText = RandomStringGenerator.GenerateRandomLatin(2001)
            }, "additionalText", "additional text should be less or equals to 2000")
            {
                TestName = "Additional text length"
            });
        }
        public static IEnumerable <TestCaseData> GenerateValidWorkOrders()
        {
            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = new DateTime(2016, 7, 1, 0, 0, 0, DateTimeKind.Utc),
                CompletionDatePlanned = new DateTime(2016, 10, 1, 0, 0, 0, DateTimeKind.Utc),
            })
            {
                TestName = "Min reception date"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date.AddDays(2),
                CompletionDatePlanned = DateTime.UtcNow.Date.AddMonths(2),
            })
            {
                TestName = "Max reception date"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date,
            })
            {
                TestName = "Min completion date planned"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddYears(1),
            })
            {
                TestName = "Max completion date planned"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddMonths(2),
                CompletionDateFact = DateTime.UtcNow.Date,
            })
            {
                TestName = "Min completion date fact"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddMonths(2),
                CompletionDateFact = DateTime.UtcNow.Date.AddYears(1),
            })
            {
                TestName = "Max completion date fact"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddMonths(2),
                ShopRequisites = new ShopRequisites {
                    Phone = "79112223344"
                }
            })
            {
                TestName = "Shop phone"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddMonths(2),
                WarrantyNumber = "1234567890asdfghjkqw",
            })
            {
                TestName = "Warranty number"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddMonths(2),
                CustomerValues = new CustomerValueList
                {
                    CustomerValueType = CustomerValueType.Vehicle,
                    CustomerValues = new BaseCustomerValue[0],
                }
            })
            {
                TestName = "No customer values"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddMonths(2),
                CustomerValues = new CustomerValueList
                {
                    CustomerValueType = CustomerValueType.Vehicle,
                    CustomerValues = new BaseCustomerValue[]
                    {
                        new VehicleCustomerValue
                        {
                            Brand = RandomStringGenerator.GenerateRandomLatin(20),
                            Model = RandomStringGenerator.GenerateRandomLatin(50),
                            RegisterSign = "А123ВЕ198",
                            Year = DateTime.UtcNow.Year,
                            BodyNumber = RandomStringGenerator.GenerateRandomLatin(17).ToUpper(),
                            EngineNumber = RandomStringGenerator.GenerateRandomLatin(17).ToUpper(),
                            AdditionalInfo = RandomStringGenerator.GenerateRandomLatin(200),
                        },
                    }
                }
            })
            {
                TestName = "Vehicle"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddMonths(2),
                CustomerValues = new CustomerValueList
                {
                    CustomerValueType = CustomerValueType.Appliances,
                    CustomerValues = new BaseCustomerValue[]
                    {
                        new ApplianceCustomerValue()
                        {
                            Brand = RandomStringGenerator.GenerateRandomLatin(20),
                            Model = RandomStringGenerator.GenerateRandomLatin(50),
                            Number = RandomStringGenerator.GenerateRandomLatin(50),
                            Year = DateTime.UtcNow.Year,
                            AdditionalInfo = RandomStringGenerator.GenerateRandomLatin(200),
                        },
                    }
                }
            })
            {
                TestName = "Appliance"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddMonths(2),
                CustomerValues = new CustomerValueList
                {
                    CustomerValueType = CustomerValueType.Other,
                    CustomerValues = new BaseCustomerValue[]
                    {
                        new OtherCustomerValue()
                        {
                            Description = RandomStringGenerator.GenerateRandomLatin(200),
                            AdditionalInfo = RandomStringGenerator.GenerateRandomLatin(200),
                        },
                    }
                }
            })
            {
                TestName = "Other"
            });

            yield return(new TestCaseData(new WorkOrder
            {
                Number = new WorkOrderNumber("АА", 1),
                ReceptionDate = DateTime.UtcNow.Date,
                CompletionDatePlanned = DateTime.UtcNow.Date.AddMonths(2),
                AdditionalText = RandomStringGenerator.GenerateRandomLatin(2000),
            })
            {
                TestName = "Additional text"
            });
        }
        private string GenerateVerificationToken()
        {
            var generator = new RandomStringGenerator();

            var result = generator.GetString(Constants.VerificationTokenLength);

            return result;
        }