示例#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;
        }