public async void CreateMessageWithMessageNotCreated() { // Arrange var message = new MessageViewModel { Conversation = 0, Content = "content", ReceiverId = "id" }; var expectedErrorMessage = "MessageNotCreated"; _identityService.GetUserByUsername(Arg.Any <string>()).ReturnsForAnyArgs(new User { Id = "id", UserName = "******" }); _identityService.GetUserById(Arg.Any <string>()).ReturnsForAnyArgs(new User { Id = "idd", UserName = "******" }); _convRepository.CreateConversation(Arg.Any <Conversation>()).ReturnsForAnyArgs(1); _repository.CreateMessage(Arg.Any <Message>()).ReturnsForAnyArgs(false); MessageService service = new MessageService(_repository, _convRepository, _identityService, _notifService); // Act var result = await service.CreateMessage(message, "username"); // Assert Assert.False(result.Succeeded); Assert.Equal(expectedErrorMessage, result.Messages[0]); }
public void SaveMessage(IMessageEntry message) { using (var transaction = uow.BeginTransaction()) { messageRepository.CreateMessage(message); } }
public async Task CreateNewMessage() { var message = _chat.CreateNewMessage(ActiveMessage); await _messageRepository.CreateMessage(message); ActiveMessage = string.Empty; }
public async Task <int> SendMessage(Message message, User activeUser) { IEnumerable <int> recipientIds = new List <int>(); message.SenderUserId = activeUser.Id; using (var trans = TransactionScopeFactory.Create()) { if (!await MessageRepo.UserIsChannelMember(message.ChannelId, activeUser.Id)) { throw new CritterException($"Could not send that message, recipient does not exist!", $"Invalid channel provided - channel: {message.ChannelId}, sender: {message.SenderUserId}", System.Net.HttpStatusCode.BadRequest); } recipientIds = await MessageRepo.GetAllChannelMemberIds(message.ChannelId); message.Id = await MessageRepo.CreateMessage(message, recipientIds.Where(id => id != activeUser.Id), activeUser.Id); trans.Complete(); } await Task.WhenAll( recipientIds.Select(async userId => await(SignalRHubContext?.Clients?.Group(NotificationHub.GetUserGroupIdentifier(userId)) ?.ReceiveNotification( new NewMessageAlert(new MessageDetails() { Message = message, SenderUsername = activeUser.Username }, message.ChannelId) ) ?? Task.CompletedTask) ) );; return(message.Id); }
public async Task <MessageDto> CreateMessage(MessageDto messageCreateDto) { messageCreateDto.DateTimeSent = DateTime.Now; MessageDto newMessage = await _messageRepository.CreateMessage(messageCreateDto); return(newMessage); }
public async Task <HttpResponseMessage> Post(ClientMessageRequest request) { Response <string> responseResult = new Response <string>(); try { var id = Guid.NewGuid(); var user = await Utils.GetUserIdAsync(User); if (user == null) { throw new ArgumentNullException("no found any user"); } using (_messageRepository) { var res = await _messageRepository.CreateMessage( new MessageRequest { ClientId = request.ClientId, Messsage = request.Messsage, MesssageType = request.MesssageType, NickName = request.NickName, User = user }); } //using (_unitOfWork) //{ // var dt=DateTime.UtcNow; // List<object> parameters = new List<object>(); // var query = "exec [dbo].[createMessage] @message,@user,@clientid,@messageType,@nickName,@replay "; // parameters.Add(new SqlParameter("@message", request.Messsage)); // parameters.Add(new SqlParameter("@user", user)); // parameters.Add(new SqlParameter("@clientid", request.ClientId)); // parameters.Add(new SqlParameter("@messageType", request.MesssageType)); // parameters.Add(new SqlParameter("@nickName", request.NickName)); // parameters.Add(new SqlParameter("@replay", true)); // var resultSp = await _unitOfWork.Database.SqlQuery<object>(query, parameters.ToArray()).FirstOrDefaultAsync(); //} responseResult.Message = "add to queue"; responseResult.Result = "";// resultSp.ToString(); } catch (Exception eee) { responseResult.IsError = true; responseResult.Message = eee.Message; } var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent <ResponseBase>(responseResult, new JsonMediaTypeFormatter(), new MediaTypeWithQualityHeaderValue("application/json")) }; return(response); }
public ResponseViewModel SendMessage(MessageInputModel message) { message.SenderId = _userService.GetCurrentLoggedOnUserAsync().Result.Id; var results = _messageRepository .CreateMessage(_mapper.Map <MessageInputModel, Message>(message)); return(Ok(_mapper.Map <Message, MessageViewModel>(results))); }
public Guid SendMessage(IUser user, string messageText) { if ((MessageSendingPermission(user)) && (_userRepository.GetUser(user.UserId) != null)) { IMessage newMessage = _messageRepository.CreateMessage(user, messageText); return(newMessage.MessageId); } throw new UnauthorizedAccessException( "This user is not able to send the message to the chat!" ); }
public void CreateNewMessage(Message messageToSave, string pinId) { _messageRepository.CreateMessage(messageToSave); var pin = _pinRepository.ReadPin(pinId); if (pin != null) { pin.Messages.Add(messageToSave.Id); _pinRepository.UpdatePin(pin); } else { throw new Exception("No pin"); } }
public async Task <JsonResult> SendMessage(string ToUserName, string msg) { try { var user = await _user.UserManager.FindByIdAsync(User.Identity.GetUserId()); _message.CreateMessage(user.Id, ToUserName, msg); _hubContext.SendMessage(ToUserName, String.Format("Пользователь {0} отправил вам сообщение!", user.UserName)); return(Json(new SuccessResponce("Сообщение успешно отправлено!"))); } catch (Exception Ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new ErrorResponce(Ex.ToString()))); } }
public async Task <IActionResult> SendMessage(MessageViewModel messageVM) { try { var userId = (this.User.Identity as ClaimsIdentity).FindFirst(ClaimTypes.NameIdentifier).Value; messageVM.SenderId = userId; messageVM.When = DateTime.Now; messageVM.SenderName = User.Identity.Name.Split('@')[0].ToCamelCase(); var vc = new System.ComponentModel.DataAnnotations.ValidationContext(messageVM); var results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(messageVM, vc, results); await messageRepo.CreateMessage(mapper.Map <Message>(messageVM)); return(Ok(messageVM)); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(Ok(messageVM)); }
public async Task <IActionResult> CreateMessage(MessageDto messageDto) { if (await _userRepository.GetUserId(messageDto.SenderUsername) != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var IsReceiverExists = await _userRepository.UserExistsByUsername(messageDto.ReceiverUsername); if (!IsReceiverExists) { return(BadRequest("User could not found")); } var IsBlocked = await _userRepository.IsBlocked(messageDto.SenderUsername, messageDto.ReceiverUsername); if (IsBlocked) { return(BadRequest("You cant send messages because this user blocked you")); } var message = new Message { SenderId = await _userRepository.GetUserId(messageDto.SenderUsername), ReceiverId = await _userRepository.GetUserId(messageDto.ReceiverUsername), Content = messageDto.Content, Date = messageDto.Date, IsRead = false }; if (await _messageRepo.CreateMessage(message)) { return(CreatedAtRoute("GetMessage", new { id = message.MessageId }, messageDto)); } _logger.LogError("Failed to send message"); return(BadRequest("Failed to send message")); }
public MessageDTO CreateMessage(MessageCreateDTO newMessage, int senderID) { var user = _userMockRepository.GetUserByID(senderID); if (user == null) { throw new NotFoundException("User with passed ID is not found..."); } Message entity = mapper.Map <Message>(newMessage); entity.SenderID = senderID; if (_messageRepository.CheckDidIBlockUser(senderID, entity.ReceiverID)) { throw new BlockingException("You have blocked this user and you can not send him message."); } if (!_messageRepository.CheckDoIFollowUser(senderID, entity.ReceiverID)) { throw new BlockingException("You are not following this user and you can not send him message."); } try { entity.IsSent = true; var message = _messageRepository.CreateMessage(entity); _messageRepository.SaveChanges(); return(mapper.Map <MessageDTO>(message)); } catch (Exception ex) { throw new ErrorOccurException(ex.Message); } }
public async Task <Message> CreateMessage(Message message, CancellationToken cancellationToken) => await _messageRepository.CreateMessage(message, cancellationToken);
private void CreateMessage(Message message) { _messageRepository.CreateMessage(message); }
/// <summary> /// Permet de créer un message en base de données /// </summary> /// <param name="msg"></param> /// <returns>MyResponse</returns> public async Task <MyResponse> CreateMessage(MessageViewModel msg, string username) { if (msg != null && !String.IsNullOrWhiteSpace(username) && !String.IsNullOrWhiteSpace(msg.Content) && !String.IsNullOrWhiteSpace(msg.ReceiverId)) { // On récupère l'utilisateur courant via son nom d'utilisateur dans le token var user = await _identityService.GetUserByUsername(username); // On pense également à récupérer l'utilisateur à qui l'on veut envoyer le message pour être sûr qu'il existe var receiver = await _identityService.GetUserById(msg.ReceiverId); if (user != null && receiver != null) { // On vérifie si une conversation n'existe pas déjà avec les deux utilisateurs pour éviter de créer des doublons var conv = _convRepository.GetConversationByUsers(user.Id, receiver.Id); if (conv != null && msg.Conversation == 0) { msg.Conversation = conv.Id; } // Si la conversation est égale à 0 c'est qu'on doit en créer une nouvelle if (msg.Conversation == 0) { Conversation newConv = new Conversation { FirstUser = user.Id, SecondUser = receiver.Id, LastMessageDate = DateTime.Now }; var createdConvId = await _convRepository.CreateConversation(newConv); // On vérifie si la conversation a bien été créée if (createdConvId != 0) { Message newMsg = new Message { Conversation = createdConvId, Content = msg.Content, Date = DateTime.Now, Sender = user.Id }; if (await _repository.CreateMessage(newMsg)) { // Si le message a bien été créé, on envoie une notification au destinataire Notification notif = new Notification { Context = Notification.Type.Message, ContextId = createdConvId, Content = $"<strong>{user.UserName}</strong> vous a envoyé un message !", UserId = receiver.Id, Date = DateTime.Now }; await _notifService.CreateNotification(notif); // On ajoute l'id de la conversation dans la réponse pour pouvoir y rediriger l'utilisateur var response = new MyResponse { Succeeded = true }; response.Result = createdConvId; return(response); } var creationError = new MyResponse { Succeeded = false }; creationError.Messages.Add("MessageNotCreated"); return(creationError); } var error = new MyResponse { Succeeded = false }; error.Messages.Add("ConversationNotCreated"); return(error); } // Sinon, c'est que la conversation existe déjà else { // On vérifie que la conversation existe bien et que l'envoyeur et le receveur du message y sont bien renseignés var existingConv = _convRepository.GetConversationByIdAndUsers(msg.Conversation, user.Id, msg.ReceiverId); // Si la conv existe, on continue if (existingConv != null) { Message newMsg = new Message { Conversation = msg.Conversation, Content = msg.Content, Date = DateTime.Now, Sender = user.Id }; if (await _repository.CreateMessage(newMsg)) { // On met à jour la date du dernier message de la conversation pour la faire remonter en haut await _convRepository.UpdateConversationDate(msg.Conversation); // Si le message a bien été créé, on envoie une notification au destinataire Notification notif = new Notification { Context = Notification.Type.Message, ContextId = existingConv.Id, Content = $"<strong>{user.UserName}</strong> vous a envoyé un message !", UserId = receiver.Id, Date = DateTime.Now }; await _notifService.CreateNotification(notif); var response = new MyResponse { Succeeded = true }; response.Result = existingConv.Id; return(response); } var creationError = new MyResponse { Succeeded = false }; creationError.Messages.Add("MessageNotCreated"); return(creationError); } var error = new MyResponse { Succeeded = false }; error.Messages.Add("ConversationNotFound"); return(error); } } } return(new MyResponse { Succeeded = false }); }
public InfoScreenMutation( IAdminRepository admins, ILunchplanRepository lunchplans, IMealRepository meals, IMessageRepository messages ) { Name = "Mutation"; FieldAsync <BooleanGraphType>( "createAdmin", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <AdminInputType> > { Name = "admin" } ), resolve: async ctx => { var input = ctx.GetArgument <Dictionary <string, object> >("admin"); var admin = new DAL.Entity.Admin { Username = (string)input["username"] }; admin.SetPassword((string)input["password"]); return(await admins.CreateAdmin(admin)); } ); FieldAsync <BooleanGraphType>( "updateAdmin", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <AdminInputType> > { Name = "admin" } ), resolve: async ctx => { var input = ctx.GetArgument <Dictionary <string, object> >("admin"); var admin = new DAL.Entity.Admin { Username = (string)input["username"] }; admin.SetPassword((string)input["password"]); return(await admins.UpdateAdmin(admin)); } ); FieldAsync <BooleanGraphType>( "deleteAdmin", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <StringGraphType> > { Name = "admin" } ), resolve: async ctx => { if (ctx.HasArgument("admin")) { return(await admins.DeleteAdmin(ctx.GetArgument <string>("admin"))); } return(false); }); FieldAsync <BooleanGraphType>( "saveLunchplan", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <LunchplanInputType> > { Name = "lunchplan" } ), resolve: async ctx => { var arg = ctx.GetArgument <Dictionary <string, object> >("lunchplan"); var week = (int)arg["week"]; var mp = (Dictionary <string, object>)arg["mealplan"]; var mealplan = new Dictionary <Weekday, int>(); foreach (var(key, val) in mp) { mealplan[Enum.Parse <Weekday>(key, true)] = (int)val; } var lunchplan = new Lunchplan { WeekNumber = week, Mealplan = mealplan }; return(await lunchplans.SaveLunchplan(lunchplan)); } ); FieldAsync <BooleanGraphType>( "createMeal", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <MealInputType> > { Name = "meal" } ), resolve: async ctx => { var meal = ctx.GetArgument <Meal>("meal"); return(await meals.CreateMeal(meal)); } ); FieldAsync <BooleanGraphType>( "createMessage", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <MessageInputType> > { Name = "message" } ), resolve: async ctx => { var message = ctx.GetArgument <Message>("message"); message.Date = DateTime.Now; message.CreatedBy = ctx.UserContext.As <InfoScreenUserContext>().AdminId; return(await messages.CreateMessage(message)); } ); }
public void PostMessage(string userName, string text, IDateTimeHelper dateTime) { var user = _userService.GetUser(userName); _messageRepository.CreateMessage(user, text, dateTime); }