public void ReturnSuccessMessage_WhenPassedValidParameters() { // Arrange var sessionMock = new Mock <IUserSession>(); var userServiceMock = new Mock <IUserService>(); var user = new User() { Id = 1 }; userServiceMock .Setup(c => c.RegisterUser(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .Returns(user); var sut = new RegisterCommand(sessionMock.Object, userServiceMock.Object); var parameters = new string[4] { "username", "pass", "pass", "email" }; // Act var result = sut.Execute(parameters); // Assert StringAssert.Contains(result, "registered succesfully"); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (!_applicationConfiguration.AllowUserRegistration()) { return(RedirectToAction("Login")); } if (ModelState.IsValid) { var(adminAppUser, result) = await _registerCommand.Execute(model, _userManager); if (result.Succeeded) { _editUserRoleCommand.Execute(new EditUserRoleModel { UserId = adminAppUser.Id, RoleId = Role.SuperAdmin.Value.ToString() }); await _signInManager.SignInAsync(adminAppUser, isPersistent : false); if (ZeroOdsInstanceRegistrations()) { return(RedirectToAction("RegisterOdsInstance", "OdsInstances")); } return(RedirectToAction("Index", "Home")); } AddErrors(result); } return(View(model)); }
public async Task ShouldRegisterUserWithRequirePasswordChangeAsFalse() { var guidString = Guid.NewGuid().ToString("N"); var newUser = new RegisterViewModel { Email = $"test{guidString}@test.com", Password = "******", ConfirmPassword = "******" }; var manager = SetupApplicationUserManager(); var command = new RegisterCommand(); var(adminAppUser, _) = await command.Execute(newUser, manager); using (var database = AdminAppIdentityDbContext.Create()) { var addedUser = database.Users.Single(x => x.Id == adminAppUser.Id); addedUser.UserName.ShouldBe($"test{guidString}@test.com"); addedUser.Email.ShouldBe($"test{guidString}@test.com"); addedUser.RequirePasswordChange.ShouldBe(false); } }
public async Task ShouldRegisterUserWithRequirePasswordChangeAsFalse() { var guidString = Guid.NewGuid().ToString("N"); var newUser = new RegisterViewModel { Email = $"test{guidString}@test.com", Password = "******", ConfirmPassword = "******" }; await ScopedAsync <UserManager <AdminAppUser> >(async manager => { var command = new RegisterCommand(); var(adminAppUser, identityResult) = await command.Execute(newUser, manager); string.Join(Environment.NewLine, identityResult.Errors.Select(x => x.Description)).ShouldBe(""); identityResult.Succeeded.ShouldBeTrue(); Scoped <AdminAppIdentityDbContext>(database => { var addedUser = database.Users.Single(x => x.Id == adminAppUser.Id); addedUser.UserName.ShouldBe($"test{guidString}@test.com"); addedUser.Email.ShouldBe($"test{guidString}@test.com"); addedUser.RequirePasswordChange.ShouldBe(false); }); }); }
public void AccountRegister_Execute_ReturnsSuccessMessage() { _accountService.Setup(s => s.RegisterUser(It.IsAny <RegisterUserDto>())) .ReturnsAsync(new UserDto()); var command = new RegisterCommand(_console, LoggerMock.GetLogger <RegisterCommand>().Object, _accountService.Object) { Email = "*****@*****.**" }; var resultMessage = command.Execute(); Assert.StartsWith("User [email protected] has been registered", resultMessage); }
public void EngineRegister_Execute_ReturnsSuccessMessage() { _engineService.Setup(s => s.RegisterEngine(It.IsAny <RegisterCatapultEngineDto>())) .ReturnsAsync(new CatapultEngineDto()); var command = new RegisterCommand(_console, LoggerMock.GetLogger <RegisterCommand>().Object, _engineService.Object) { Name = "Engine02" }; var resultMessage = command.Execute(); Assert.StartsWith("Engine has been registered:", resultMessage); }
public void ThrowArgumentException_WhenPassedInvalidParametersCount() { // Arrange var sessionMock = new Mock <IUserSession>(); var userServiceMock = new Mock <IUserService>(); var sut = new RegisterCommand(sessionMock.Object, userServiceMock.Object); var parameters = new string[3] { "username", "pass", "pass" }; // Act && Assert Assert.ThrowsException <ArgumentException>(() => sut.Execute(parameters)); }
public void ProviderRegister_Execute_ReturnsNoFileMessage() { var testFile = Path.Combine(AppContext.BaseDirectory, "providerTest.yaml"); if (File.Exists(testFile)) { File.Delete(testFile); } var command = new RegisterCommand(_providerService.Object, _console, LoggerMock.GetLogger <RegisterCommand>().Object) { MetadataFile = testFile }; var message = command.Execute(); Assert.Equal($"Could not find \"{testFile}\".", message); }
public void ProviderRegister_Execute_ReturnsNotParsedMessage() { var testFile = Path.Combine(AppContext.BaseDirectory, "providerTest.yaml"); if (File.Exists(testFile)) { File.Delete(testFile); } File.WriteAllText(testFile, ""); var command = new RegisterCommand(_providerService.Object, _console, LoggerMock.GetLogger <RegisterCommand>().Object) { MetadataFile = testFile }; var message = command.Execute(); Assert.Equal("Task provider metadata could not be parsed from the file content.", message); }
private void Register_Click(object sender, RoutedEventArgs e) { if (RegisterCommand != null) { ErrorMessage = string.Empty; string password = pbPassword.Password; string confirmPassword = pbConfirmPassword.Password; if (password != confirmPassword) { ResourceDictionary oldDict = (from d in Application.Current.Resources.MergedDictionaries where d.Source != null && d.Source.OriginalString.StartsWith("Resources/Lang.") select d).First(); ErrorMessage = oldDict["Errors_PasswordMissmatch"].ToString(); return; } RegisterCommand.Execute(password); } }
public void ThrowInvalidOperationException_WhenThereIsLoggedInUser() { // Arrange var sessionMock = new Mock <IUserSession>(); var currentUser = new User() { UserType = UserType.Admin }; sessionMock.Setup(s => s.CurrentUser).Returns(currentUser); var userServiceMock = new Mock <IUserService>(); var sut = new RegisterCommand(sessionMock.Object, userServiceMock.Object); var parameters = new string[4] { "username", "pass", "pass", "email" }; // Act && Assert Assert.ThrowsException <InvalidOperationException>(() => sut.Execute(parameters)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (!_applicationConfiguration.AllowUserRegistration()) { return(RedirectToAction("Login")); } if (ModelState.IsValid) { var(adminAppUser, result) = await _registerCommand.Execute(model, UserManager); if (result.Succeeded) { _editUserRoleCommand.Execute(new EditUserRoleModel { UserId = adminAppUser.Id, RoleId = Role.SuperAdmin.Value.ToString() }); await SignInManager.SignInAsync(adminAppUser, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Identity", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); if (ZeroOdsInstanceRegistrations()) { return(RedirectToAction("RegisterOdsInstance", "OdsInstances")); } return(RedirectToAction("Index", "Home")); } AddErrors(result); } return(View(model)); }
public void ProviderRegister_Execute_ReturnsSuccessMessage() { var testFile = Path.Combine(AppContext.BaseDirectory, "providerTest.yaml"); if (File.Exists(testFile)) { File.Delete(testFile); } var testContent = new NewTaskProviderDto { Name = "AProvider01", Type = TaskProviderType.HostingProvider, Author = "Frandi", Version = "1.0" }; var stringContent = YamlSerialize(testContent); File.WriteAllText(testFile, stringContent); _providerService.Setup(s => s.AddProvider(It.IsAny <NewTaskProviderDto>())).ReturnsAsync((NewTaskProviderDto dto) => new TaskProviderDto { Id = 1, Name = dto.Name, Type = dto.Type, Author = dto.Author, Version = dto.Version }); var command = new RegisterCommand(_providerService.Object, _console, LoggerMock.GetLogger <RegisterCommand>().Object) { MetadataFile = testFile }; var message = command.Execute(); Assert.Equal("Task provider AProvider01 (v1.0) by Frandi has been registered successfully.", message); }
public void RegisterWithEmail(WebRequestData args, Action <CommandResult> Callback) { if (args is RegisterRequestData registerArgs) { CommandArgs commandArgs = new RegisterCommandArgs { Callback = Callback, RegisterUsername = registerArgs.RegisterUsername, RegisterEmail = registerArgs.RegisterEmail, RegisterPassword = registerArgs.RegisterPassword }; RegisterCommand command = CommandFactory .Instance .CreateCommand <RegisterCommand>(commandArgs); command.Execute(); } else { // Make more verbose exceptions throw new ArgumentException("Incorrect args data type;"); } }
// Chooses specific command to execute depending on the input given. public string Dispatch(string input) { string[] inputArgs = input.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); string commandName = input.Length != 0 ? inputArgs[0].ToLower() : string.Empty; inputArgs = inputArgs.Skip(1).ToArray(); string output = string.Empty; switch (commandName) { case "register": RegisterCommand register = new RegisterCommand() { UserValidator = new UserValidator() }; output = register.Execute(inputArgs); break; case "login": LoginCommand login = new LoginCommand(); output = login.Execute(inputArgs); break; case "logout": LogoutCommand logout = new LogoutCommand(); output = logout.Execute(inputArgs); break; case "exit": ExitCommand exit = new ExitCommand(); output = exit.Execute(inputArgs); break; case "add": AddAccountCommand add = new AddAccountCommand() { CheckingAccountValidator = new CheckingAccountValidator(), SavingAccountValidator = new SavingAccountValidator() }; output = add.Execute(inputArgs); break; case "deposit": DepositCommand deposit = new DepositCommand(); output = deposit.Execute(inputArgs); break; case "withdraw": WithdrawCommand withdraw = new WithdrawCommand(); output = withdraw.Execute(inputArgs); break; // List Accounts case "listaccounts": ListAccountsCommand list = new ListAccountsCommand(); output = list.Execute(inputArgs); break; // Deduct Fee case "deductfee": DeductFeeCommand deduct = new DeductFeeCommand(); output = deduct.Execute(inputArgs); break; // Add Interest case "addinterest": AddInterestCommand addInterest = new AddInterestCommand(); output = addInterest.Execute(inputArgs); break; default: throw new ArgumentException($"Command \"{commandName}\" not supported!"); } return(output); }
static void Main(string[] args) { var db = new CommandRunner("dvds"); var q = new RegisterCommand(db); q.Email = "*****@*****.**"; q.Password = "******"; q.Confirmation = "password"; q.First = "Nick"; q.Last = "Shoup"; var result = q.Execute(); Console.WriteLine(result.Message, result.NewUserId, result.Status); var qAuth = new AuthenticateCommand(db); qAuth.ProviderKey = "*****@*****.**"; qAuth.ProviderValue = "password"; var authResult = qAuth.Execute(); Console.WriteLine(authResult.Message, authResult.UserID); var query = new RawSalesByDate(db); query.Year = 2007; var sales = query.Execute(); foreach (var sale in sales) { //Console.WriteLine(sale.Title); } var films = db.Execute <Film>("select * from film"); foreach (var film in films) { // Console.WriteLine(film.Title); } var filmsDynamic = db.ExecuteDynamic("select * from film"); foreach (var film in filmsDynamic) { // Console.WriteLine(film.title); } //var cmd = db.BuildCommand("insert into actor(first_name, last_name, last_update) values (@0, @1, @2)", "Nick", "Shoup", DateTime.Now); //var resulsts = db.Transact(cmd); //foreach (var result in resulsts) //{ // Console.WriteLine(result); //} var actorQuery = new ActorQuery(db); actorQuery.ActorId = 3; var actors = actorQuery.Execute(); Console.WriteLine(actors.Fullname); foreach (var film in actors.Films) { // Console.WriteLine(film.Title) ; } var actor1 = new Actor() { First = "Woody", Last = "Harrelson" }; var actor2 = new Actor() { First = "Joe", Last = "Biff" }; var actor3 = new Actor() { First = "Jolene", Last = "Silidkdk" }; var qCommand = new Commands.Actors.AddBatchOfActors(db); qCommand.Actors = new Actor[] { actor1, actor2, actor3 }; qCommand.Execute(); Console.Read(); }
public string DispatchCommand(string[] commandParameters) { string commandName = commandParameters[0]; commandParameters = commandParameters.Skip(1).ToArray(); string result = string.Empty; SavingService savingService = new SavingService(); CheckingService checkingService = new CheckingService(); UserService userService = new UserService(); switch (commandName) { case "Exit": ExitCommand exit = new ExitCommand(); result = exit.Execute(); break; case "Deposit": DepositCommand deposit = new DepositCommand(savingService); result = deposit.Execute(commandParameters); break; case "Withdraw": WithdrawCommand withdeow = new WithdrawCommand(savingService); result = withdeow.Execute(commandParameters); break; case "AddInterest": AddInterestCommand addInterest = new AddInterestCommand(savingService); result = addInterest.Execute(commandParameters); break; case "DeductFee": DeductCommand deduct = new DeductCommand(checkingService); result = deduct.Execute(commandParameters); break; case "Register": RegisterCommand register = new RegisterCommand(userService); result = register.Execute(commandParameters); break; case "Login": LoginCommand login = new LoginCommand(); result = login.Execute(commandParameters); break; case "Logout": Logout logout = new Logout(); result = logout.Execute(); break; case "AddSavingAccount": AddSavingAccountCommand addAccount = new AddSavingAccountCommand(savingService); result = addAccount.Execute(commandParameters); break; case "ListAccounts": ListAccounts listAccounts = new ListAccounts(savingService, checkingService); result = listAccounts.Execute(); break; } return(result); }
public static int Main(string[] args) { CommandLine.Initialize(); var options = new CommandLineParser(args); options.AddOptions(null, OPTIONS_GENERAL); options.AddOptions("help", OPTIONS_HELP); options.AddOptions("version", OPTIONS_VERSION); options.AddOptions("convert", OPTIONS_CONVERT); options.AddOptions("list", OPTIONS_LIST); options.AddOptions("register", OPTIONS_REGISTER); // save the error state bool invalidArguments = !options.Parse("convert"); // get the Quiet option first, before we emit anything Quiet = options.GetOptionSwitch("quiet"); if (Quiet) { Console.SetOut(new StreamWriter(Stream.Null)); Console.SetError(Console.Out); } NoLog = options.GetOptionSwitch("nolog"); if (!NoLog) { Process running_proc = Process.GetCurrentProcess(); Process[] mbinc_procs = Process.GetProcessesByName(running_proc.ProcessName); // If we only have one instance of MBINCompiler running create the usual log. // If a process starts and there is already a running MBINCompiler process, then // add the PID to the log file name so that there is no issue with two processes // attempting to write to the same log file. if (mbinc_procs.Length == 1) { Logger.Open(Path.ChangeExtension(Utils.GetExecutablePath(), ".log")); } else { Logger.Open(Path.ChangeExtension(Utils.GetExecutablePath(), $".{running_proc.Id}.log")); } Logger.EnableTraceLogging = true; Logger.LogMessage("VERSION", $"MBINCompiler v{Version.GetVersionStringCompact()}"); Logger.LogMessage("ARGS", $"\"{string.Join("\" \"", args)}\"\n"); using (var indent = new Logger.IndentScope()) { Logger.LogMessage("If you encounter any errors, please submit a bug report and include this log file.\n" + "Please check that there isn't already a similar issue open before creating a new one.\n" + "https://github.com/monkeyman192/MBINCompiler/issues\n"); } } // now we can emit an error if we need to if (invalidArguments) { return(CommandLine.ShowInvalidCommandLineArg(options)); } // initialize remaining global options DebugMode = options.GetOptionSwitch("debug"); // execute the appropriate mode try { switch (options.Verb) { case "help": return(HelpCommand.Execute(options)); case "version": return(VersionCommand.Execute(options)); case "list": return(ListCommand.Execute(options)); case "register": return(RegisterCommand.Execute(options)); default: return(ConvertCommand.Execute(options)); } } catch (System.Exception e) { return(CommandLine.ShowException(e)); } }