public async Task <CommandHandlerResult> HandleAsync(CreateRequestServiceCommand command) { var model = command.Model; var profile = await _profileDbContext.Profiles.SingleOrDefaultAsync(q => q.ProfileId == model.RequesterId); if (profile == null) { return(CommandHandlerResult.Error("Couldn't find the Profile")); } var requestService = new RequestService { RequesterId = profile.ProfileId, Title = model.Title, Description = model.Description, ServiceTypeId = model.ServiceTypeId }; await _profileDbContext.RequestServices.AddAsync(requestService); return(CommandHandlerResult.OkDelayed(this, _ => new { RequesterId = requestService.RequesterId.ToString(), requestService.RequestServiceId, requestService.Title, requestService.Description, requestService.Completed, requestService.ServiceTypeId, ServiceTypeName = requestService.ServiceType?.Name ?? "", CreatedWhen = requestService.CreatedWhen.ToString() })); }
public async Task <CommandHandlerResult> HandleAsync(UpdateProfileCommand command) { var model = command.Model; var profile = await _profileDbContext.Profiles.SingleOrDefaultAsync(q => q.ProfileId == model.ProfileId); if (profile == null) { return(CommandHandlerResult.Error("Couldn't find the Profile")); } profile.FirstName = model.FirstName; profile.LastName = model.LastName; if (!string.IsNullOrEmpty(model.PhotoThumbUrl)) { profile.PhotoThumbUrl = model.PhotoThumbUrl; } _profileDbContext.Profiles.Update(profile); return(CommandHandlerResult.OkDelayed(this, _ => new { ProfileId = profile.ProfileId.ToString(), profile.FirstName, profile.LastName, PhotoThumbUrl = profile.PhotoThumbUrl ?? "" })); }
public void ProcessCommand_PollOpen_PollClosed() { //Arrange BotCommand command = new BotCommandBuilder().WithUser(_ADMINUSER).WithMessage("!poll !option 1 !option 2 !option 3").Build(); BotCommand command2 = new BotCommandBuilder().WithUser(_ADMINUSER).WithMessage("!poll").Build(); var poll = new Mock <IPoll>(); poll.Setup(x => x.EndPoll()).Returns("End Poll"); var pollFacotry = new Mock <IPollFactory>(); pollFacotry.Setup(x => x.CreatePoll(new string[] { "option 1", "option 2", "option 3" })).Returns(poll.Object); var pollCommandHandler = new PollCommandHandler(pollFacotry.Object); //Act CommandHandlerResult result = pollCommandHandler.ProcessCommand(command, _channel).Result; result = pollCommandHandler.ProcessCommand(command2, _channel).Result; //Assert Assert.AreEqual(ResultType.HandledWithMessage, result.ResultType); Assert.AreEqual($"End Poll", result.Message); Assert.AreEqual("#channel", result.Channel); }
public CommandHandlerResult Handle(UpdateProfileCommand command) { var profile = command.Profile; var patching = command.IsPatch; var existing = _db.Profiles.SingleOrDefault(p => p.UserId == profile.UserId); if (existing == null) { return(CommandHandlerResult.Error("no profile found")); } if (!patching) { existing.BirthDate = profile.BirthDate; existing.FirstName = profile.FirstName; existing.Gender = profile.Gender; existing.LastName = profile.LastName; existing.Email = profile.Email; if (profile.Skype != null) { existing.Skype = profile.Skype; } if (profile.Mobile != null) { existing.Mobile = profile.Mobile; } return(CommandHandlerResult.Ok); } else { return(PatchProfile(existing, profile)); } }
public void ProcessCommand_UserCastsVote_VoteIsCast() { //Arrange BotCommand command = new BotCommandBuilder().WithUser(_ADMINUSER).WithMessage("!poll !option 1 !option 2 !option 3").Build(); BotCommand command2 = new BotCommandBuilder().WithUser("user").WithMessage("!vote 2").Build(); var poll = new Mock <IPoll>(); poll.Setup(x => x.CastVote("user", 2)).Returns(1); var pollFacotry = new Mock <IPollFactory>(); pollFacotry.Setup(x => x.CreatePoll(new string[] { "option 1", "option 2", "option 3" })).Returns(poll.Object); var pollCommandHandler = new PollCommandHandler(pollFacotry.Object); //Act CommandHandlerResult result = pollCommandHandler.ProcessCommand(command, _channel).Result; result = pollCommandHandler.ProcessCommand(command2, _channel).Result; //Assert poll.Verify(x => x.CastVote("user", 2), Times.Once()); Assert.AreEqual(ResultType.Handled, result.ResultType); Assert.AreEqual(null, result.Message); Assert.AreEqual(null, result.Channel); }
//logic for actually monitoring channel. private void ControlLoop() { while (!exit) { string currentTextLine = _inputStream.ReadLine(); /* IRC commands come in one of these formats: * :NICK!USER@HOST COMMAND ARGS ... :DATA\r\n * :SERVER COMAND ARGS ... :DATA\r\n */ //Display received irc message Console.WriteLine(currentTextLine); //if (currentTextLine[0] != ':') continue; //Send pong reply to any ping messages if (currentTextLine.StartsWith("PING ")) { _outputStream.Write(currentTextLine.Replace("PING", "PONG") + "\r\n"); _outputStream.Flush(); } else if (currentTextLine[0] != ':') { continue; } else if (BotCommand.isPotentialCommand(currentTextLine)) { BotCommand command = new BotCommand(currentTextLine); TwitchChannel channel = _channels.Find(c => '#' + c.Name == command.Channel); foreach (ICommandHandler handler in _commandHandlers) { CommandHandlerResult result = handler.ProcessCommand(command, channel).Result; bool breakLoop = false; switch (result.ResultType) { case ResultType.Handled: breakLoop = true; break; case ResultType.HandledWithMessage: SendPrivmsg(result.Channel, result.Message); breakLoop = true; break; default: break; } if (breakLoop) { break; } } } } }
public void ProcessCommand_8_NoQuestionAsked() { //Arrange var command = new BotCommandBuilder().WithMessage("!8 ").Build(); //Act CommandHandlerResult result = _commandHandler.ProcessCommand(command, _channel).Result; //Assert Assert.IsNotNull(result.Message); Assert.AreEqual(ResultType.HandledWithMessage, result.ResultType); }
public CommandHandlerResult Handle(AddSubscriptionCommand command) { var existing = _db.Users.SingleOrDefault(u => u.Id == command.UserId); if (existing == null) { return(CommandHandlerResult.Error($"User {command.UserId} not found")); } existing.Subscriptions.Add(command.Subscription); return(CommandHandlerResult.Ok); }
public void ProcessCommand_Roll_ValidInputNegativeModifier() { //Arrange var command = new BotCommandBuilder().WithMessage("!roll 2d6-2").Build(); //Act CommandHandlerResult result = _commandHandler.ProcessCommand(command, _channel).Result; //Assert Assert.GreaterOrEqual(Int32.Parse(result.Message), 0); Assert.LessOrEqual(Int32.Parse(result.Message), 10); }
public void ProcessCommand_Roll_ValidInputNoModifier() { //Arrange var command = new BotCommandBuilder().WithMessage("!roll 1d4").Build(); //Act CommandHandlerResult result = _commandHandler.ProcessCommand(command, _channel).Result; //Assert Assert.AreEqual(ResultType.HandledWithMessage, result.ResultType); Assert.GreaterOrEqual(Int32.Parse(result.Message), 1); Assert.LessOrEqual(Int32.Parse(result.Message), 4); }
private async Task <CommandHandlerResult> SaveDataToBlobs(byte[] imgData, string fileName) { try { await SaveDataToBlob(imgData, fileName, "avatar-output"); await SaveDataToBlob(imgData, fileName, "avatar-input"); return(CommandHandlerResult.Ok); } catch (Exception ex) { return(CommandHandlerResult.Error($"Error {ex.GetType().Name} - {ex.Message}")); } }
public CommandHandlerResult Handle(UpdateIssueCommand command) { var issue = command.Issue; var dbIssue = _db.Issues.FirstOrDefault(x => x.Id == issue.Id); if (dbIssue == null) { return(CommandHandlerResult.Error("Invalid Issue")); } dbIssue.Solved = issue.Solved; return(CommandHandlerResult.Ok); }
/// <summary> /// MediatR Handle implementation /// </summary> /// <param name="command"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <CommandHandlerResult <TID> > Handle(TCommand command, CancellationToken cancellationToken = default) { CommandHandlerResult <TID> result = new CommandHandlerResult <TID>(command); try { if (result.ValidationResult.IsValid) { result.Id = await ExecuteCommand(command, cancellationToken); } } catch (Exception) { throw; } return(result); }
public async Task <CommandHandlerResult> HandleAsync(SignInCommand command) { var model = command.Model; var user = await _profileDbContext.Users.Include(q => q.Profile) .SingleOrDefaultAsync(q => q.UserName.ToLower() == model.UserName.Trim().ToLower()); if (user == null) { return(CommandHandlerResult.Error("Invalid Username or Password")); } var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false); if (result.Succeeded) { var claims = await _userManager.GetClaimsAsync(user); var roles = JsonConvert.SerializeObject(user.UserRoles.Select(r => new { r.RoleId, Role = r.Role?.Name ?? "User" }), Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver() }); return(CommandHandlerResult.OkDelayed(this, _ => new TokenResponse { AccessToken = _tokenProvider.GenerateJwtToken(claims), RefreshToken = _tokenProvider.GenerateRefreshToken(), ExpiresIn = 3600 * 24, TokenType = "Bearer", })); } if (result.IsLockedOut) { return(CommandHandlerResult.Error("This Account is locked")); } if (result.IsNotAllowed) { return(CommandHandlerResult.Error("This Account is not allowed")); } return(CommandHandlerResult.Error("Invalid Username or Password")); }
public void ProcessCommand_UnauthorizedUserCreatesPoll_ResultTypeIsHandled() { //Arrange BotCommand command = new BotCommandBuilder().WithUser("bob").WithMessage("!poll !option 1 !option 2 !option 3").Build(); var poll = new Mock <IPoll>(); var pollFacotry = new Mock <IPollFactory>(); var pollCommandHandler = new PollCommandHandler(pollFacotry.Object); //Act CommandHandlerResult result = pollCommandHandler.ProcessCommand(command, _channel).Result; //Assert Assert.AreEqual(ResultType.Handled, result.ResultType); Assert.AreEqual(null, result.Message); Assert.AreEqual(null, result.Channel); }
public CommandHandlerResult Handle(CreateProfileAndUserCommand command) { _command = command; var existing = _db.Users.Any(x => x.UserName == command.User.UserName); if (existing) { return(CommandHandlerResult.Error($"Invalid username ({command.User.UserName})")); } _db.Users.Add(command.User); return(CommandHandlerResult.OkDelayed(this, x => new { UserId = _command.User.Id, ProfileId = _command.Profile.Id })); }
private void PrintErrorsAndWarnings(CommandHandlerResult result) { if (result.Errors.Count > 0) { Console.WriteLine("Evaluation produced errors:"); } foreach (var message in result.Errors) { Console.WriteLine(message); } if (result.Warnings.Count > 0) { Console.WriteLine("Evaluation produced warnings:"); } foreach (var message in result.Warnings) { Console.WriteLine(message); } }
public CommandHandlerResult Handle(SetPaymentDataCommand command) { var existing = _db.Profiles.Include(p => p.Payment). SingleOrDefault(p => p.UserId == command.UserId); if (existing == null) { return(CommandHandlerResult.NotFound("Profile not found")); } var payment = existing.Payment; if (payment == null) { return(AddNewPayment(existing, command.Data)); } return(UpdatePayment(existing, command.Data)); }
public void ProcessCommand_NoOpenPoll_NewPollCreated() { //Arrange var command = new BotCommandBuilder().WithUser(_ADMINUSER).WithMessage("!poll !option 1 !option 2 !option 3").Build(); var poll = new Mock <IPoll>(); poll.Setup(x => x.PrintPoll()).Returns("Print Poll"); var pollFacotry = new Mock <IPollFactory>(); pollFacotry.Setup(x => x.CreatePoll(new string[] { "option 1", "option 2", "option 3" })).Returns(poll.Object); var pollCommandHandler = new PollCommandHandler(pollFacotry.Object); //Act CommandHandlerResult result = pollCommandHandler.ProcessCommand(command, _channel).Result; //Assert Assert.AreEqual(ResultType.HandledWithMessage, result.ResultType); Assert.AreEqual($"Poll started! use !vote <number> to case your vote. Print Poll", result.Message); Assert.AreEqual("#channel", result.Channel); }
public async Task <CommandHandlerResult> HandleAsync(SignUpCommand command) { var model = command.Model; var userName = model.Email.ToUpper().Substring(0, model.Email.ToLower().IndexOf('@')); var user = new User { UserName = model.Email, Email = model.Email, Profile = new Profile { CompanyName = model.CompanyName ?? userName, Website = model.Website, FirstName = model.FirstName, LastName = model.LastName, Email = model.Email.ToLower() }, }; user.Profile.CreatedBy = user; var createUserResult = await _userManager.CreateAsync(user, model.Password); if (!createUserResult.Succeeded) { return(CommandHandlerResult.Error(createUserResult.Errors?.FirstOrDefault()?.Description)); } var addClaimsResult = await _userManager.AddClaimsAsync(user, new Claim[] { new Claim(JwtClaimTypes.Id, user.Id.ToString()), new Claim(JwtClaimTypes.Subject, user.Id.ToString()), new Claim(JwtClaimTypes.Email, user.Email), new Claim(JwtClaimTypes.Name, user.Profile?.FullName), new Claim(JwtClaimTypes.Role, model.RoleName) }); if (!addClaimsResult.Succeeded) { return(CommandHandlerResult.Error(addClaimsResult.Errors?.FirstOrDefault()?.Description)); } string roleName = model.RoleName.ToLower(); bool roleExists = await _roleManager.RoleExistsAsync(roleName); if (!roleExists) { var createRoleResult = await _roleManager.CreateAsync(new Role(roleName)); if (!createRoleResult.Succeeded) { return(CommandHandlerResult.Error(createRoleResult.Errors?.FirstOrDefault()?.Description)); } } var addToRoleResult = await _userManager.AddToRoleAsync(user, roleName); if (!addToRoleResult.Succeeded) { return(CommandHandlerResult.Error(addToRoleResult.Errors?.FirstOrDefault()?.Description)); } string token = await _userManager.GenerateEmailConfirmationTokenAsync(user); string encodedToken = HttpUtility.UrlEncode(token); string emailConfirmationLink = $"{_configuration["EmailSettings:EmailConfirmationUrl"]}?userid={user.Id.ToString()}&token={encodedToken}"; return(CommandHandlerResult.OkDelayed(this, _ => new { UserId = user.Id.ToString(), Link = emailConfirmationLink })); }