예제 #1
0
        public object CreateContext(string otherUserName)
        {
            var otherUser = entities.Users.FirstOrDefault(u => u.UserName == otherUserName);
            if (otherUser.UserName == Context.User.Identity.Name)
            {
                throw new HttpException("Can't create a context with yourself.");
            }

            var chatContext = new ChatContext()
            {
                InitiatorId = Context.User.Identity.GetUserId(),
                OtherUser = otherUser,
                LastInteraction = DateTime.Now
            };

            entities.ChatContexts.Add(chatContext);
            entities.SaveChanges();

            var viewModel = new
            {
                Id = chatContext.Id,
                OtherUser = new UserProfileBasicViewModel(otherUser)
                {
                    UserId = otherUser.Id
                }
            };

            SendNewContextToConnectedClients(chatContext);
            return Serialize(viewModel);
        }
예제 #2
0
        private void SendMessageToConnectedClients(ChatContext chatContext, object messageViewModel)
        {
            var otherUserConnections = GetOtherUser(chatContext)
                .SignalRConnections.Select(c => c.ConnectionId);

            foreach (var connectionId in otherUserConnections)
            {
                Clients.Client(connectionId).newMessage(messageViewModel);
            }
        }
예제 #3
0
        private void SendNewContextToConnectedClients(ChatContext context)
        {
            var otherUser = GetOtherUser(context);
            var currentUser = GetCurrentUser();

            var viewModel = new
            {
                Id = context.Id,
                OtherUser = new UserProfileBasicViewModel(currentUser)
                {
                    UserId = otherUser.Id
                }
            };

            var otherUserConnections = otherUser.SignalRConnections.Select(c => c.ConnectionId);

            foreach (var connectionId in otherUserConnections)
            {
                Clients.Client(connectionId).newContext(viewModel);
            }
        }
예제 #4
0
        private ApplicationUser GetOtherUser(ChatContext context)
        {
            if (context.Initiator == null)
            {
                context.Initiator = entities.Users
                    .FirstOrDefault(u => u.Id == context.InitiatorId);
            }

            var otherUser = context.Initiator
                    .Id != Context.User.Identity.GetUserId() ?
                        context.Initiator : context.OtherUser;

            return otherUser;
        }