Ejemplo n.º 1
0
        /// <summary>
        /// Removing chat from Database and remove user bindings with that chat
        /// </summary>
        /// <param name="chatModel"><see cref="ChatReceiveModel"/></param>
        public void Delete(ChatReceiveModel chatModel)
        {
            using (DatabaseContext context = new DatabaseContext())
            {
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        if (!chatModel.Id.HasValue)
                        {
                            throw new Exception("Ошибка передачи данных, свойство Id модели не было установлено");
                        }

                        Chat cht = context.Chats.FirstOrDefault(c => c.Id == chatModel.Id.Value);
                        if (cht == null)
                        {
                            throw new Exception("Чата с таким идентификатором нет в БД");
                        }

                        //remove binded users
                        _userChatBinder.RemoveUsersFromChat(chatModel.ChatUsers, context);

                        context.Chats.Remove(cht);
                        context.SaveChanges();

                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 2
0
 public ChatResponseModel GetChat(ChatReceiveModel model)
 {
     try
     {
         return(_chatLogic.GetChat(model));
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return(null);
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Getting chat and binded users with that chat using chat Id
        /// </summary>
        /// <param name="model"><see cref="ChatReceiveModel"/></param>
        /// <returns><see cref="ChatResponseModel"/></returns>
        public ChatResponseModel GetChat(ChatReceiveModel model)
        {
            using (var context = new DatabaseContext())
            {
                var chat = context.Chats.FirstOrDefault(c => c.Id == model.Id);
                if (chat == null)
                {
                    throw new Exception("Чат не найден в БД");
                }

                return(new ChatResponseModel()
                {
                    Id = chat.Id,
                    CreatorId = chat.CreatorId,
                    ChatName = chat.ChatName,
                    CountUsers = chat.CountUsers,
                    ChatUsers = GetChatUsers(chat.Id)
                });
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Syncronization deleting chats
        /// </summary>
        /// <param name="chatReceiveModel"></param>
        public void SynchronizeDeletingChat(ChatReceiveModel chatReceiveModel)
        {
            var chatUsers = _connectedClients.Where(connClient => connClient.Id != chatReceiveModel.CreatorId && chatReceiveModel.ChatUsers.FirstOrDefault(cu => cu.UserId == connClient.Id) != null);

            Parallel.ForEach(chatUsers, (cu) =>
            {
                _logger.Info($"Sync deleting chat {chatReceiveModel.Id} for user {cu.Id} from user {chatReceiveModel.CreatorId}");
                var responseJson = _jsonStringSerializer.Serialize(new OperationResultInfo()
                {
                    ErrorInfo       = string.Empty,
                    OperationResult = OperationsResults.Successfully,
                    JsonData        = _jsonStringSerializer.Serialize(new ChatResponseModel()
                    {
                        Id = chatReceiveModel.Id.Value
                    }),
                    ToListener = ListenerType.ChatListDeleteListener
                });

                cu.SendMessage(_encoder.Encryption(responseJson));
                //cu.SendMessage(responseJson);
            });
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creating a new chat in Database and binding users with that chat
        /// </summary>
        /// <param name="chatModel"><see cref="ChatReceiveModel"/></param>
        /// <returns><see cref="ChatResponseModel"/></returns>
        public ChatResponseModel Create(ChatReceiveModel chatModel)
        {
            //TODO : review
            using (DatabaseContext context = new DatabaseContext())
            {
                if (string.IsNullOrEmpty(chatModel.ChatName) && chatModel.ChatUsers.Count() > 2)
                {
                    throw new Exception("Ошибка создания чата. Чат в котором больше 2ух людей должен иметь название");
                }

                context.Chats.Add(new Chat()
                {
                    ChatName       = chatModel.ChatName,
                    CreatorId      = chatModel.CreatorId,
                    DateOfCreation = chatModel.DateOfCreation,
                    IsPrivate      = chatModel.ChatUsers.Count() == 2 ? true : false,
                    CountUsers     = chatModel.ChatUsers.Count()
                });
                context.SaveChanges();

                //getting a added chat
                var addedChat = context.Chats.FirstOrDefault(c => c.CreatorId == chatModel.CreatorId && c.DateOfCreation.Equals(chatModel.DateOfCreation));

                //binding received users id with new chat id
                chatModel.ChatUsers.ForEach(cu => cu.ChatId = addedChat.Id);

                //binding users with chat
                _userChatBinder.AddUsersToChat(chatModel.ChatUsers, context);

                return(new ChatResponseModel()
                {
                    Id = addedChat.Id,
                    CreatorId = addedChat.CreatorId,
                    ChatName = addedChat.ChatName,
                    CountUsers = addedChat.CountUsers,
                    ChatUsers = GetChatUsers(addedChat.Id)
                });
            }
        }
Ejemplo n.º 6
0
 public OperationResultInfo ChatDelete(ChatReceiveModel chatModel)
 {
     try
     {
         _chatLogic.Delete(chatModel);
         return(new OperationResultInfo()
         {
             ErrorInfo = string.Empty,
             ToListener = ListenerType.ChatListListener,
             OperationResult = OperationsResults.Successfully
         });
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return(new OperationResultInfo()
         {
             ErrorInfo = ex.Message,
             ToListener = ListenerType.ChatListDeleteListener,
             OperationResult = OperationsResults.Unsuccessfully
         });
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Updating chat in database, rebinding users
        /// </summary>
        /// <param name="chatModel"><see cref="ChatReceiveModel"/></param>
        public ChatResponseModel Update(ChatReceiveModel chatModel)
        {
            using (DatabaseContext context = new DatabaseContext())
            {
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        if (!chatModel.Id.HasValue)
                        {
                            throw new Exception("Ошибка передачи данных, свойство Id модели не было установлено");
                        }

                        Chat cht = context.Chats.FirstOrDefault(c => c.Id == chatModel.Id.Value);

                        if (cht == null)
                        {
                            throw new Exception("Чата с таким идентификатором нет в БД");
                        }

                        if (cht.CountUsers > 2)
                        {
                            cht.ChatName = chatModel.ChatName ?? cht.ChatName;
                            context.SaveChanges();
                        }

                        if (chatModel.ChatUsers != null)
                        {
                            if (cht.CountUsers == 2 && chatModel.ChatUsers.Count() > 2)
                            {
                                return(Create(chatModel));
                            }
                            else
                            {
                                cht.CountUsers = chatModel.ChatUsers.Count();
                                cht.IsPrivate  = chatModel.ChatUsers.Count() == 2 ? true : false;
                                context.SaveChanges();

                                var chatUsersFromDb = context.RelationChatUsers.Where(rcu => rcu.ChatId == cht.Id).ToList();

                                var addBindings = chatModel.ChatUsers
                                                  .Where(cu => chatUsersFromDb.FirstOrDefault(rcu => rcu.UserId == cu.UserId) == null)
                                                  .ToList();

                                //adding users that isn't contains in database
                                _userChatBinder.AddUsersToChat(addBindings, context);
                                context.SaveChanges();

                                //removing users that isn't contains in chatModel
                                var removeBindings = chatUsersFromDb
                                                     .Where(rcu => chatModel.ChatUsers.FirstOrDefault(cu => cu.UserId == rcu.UserId) == null)
                                                     .Select(rcu => new ChatUserReceiveModel()
                                {
                                    UserId = rcu.UserId,
                                    ChatId = rcu.ChatId
                                })
                                                     .ToList();

                                _userChatBinder.RemoveUsersFromChat(removeBindings, context);
                                context.SaveChanges();
                            }
                        }

                        transaction.Commit();

                        //getting its updated chat from database
                        var updatedChat = context.Chats.FirstOrDefault(c => c.Id == chatModel.Id.Value);

                        return(new ChatResponseModel()
                        {
                            Id = updatedChat.Id,
                            CreatorId = updatedChat.CreatorId,
                            ChatName = updatedChat.ChatName,
                            CountUsers = updatedChat.CountUsers,
                            ChatUsers = GetChatUsers(updatedChat.Id)
                        });
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }