Exemplo n.º 1
0
        public bool Create(MessageAddRequest data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("Parameter data is required");
            }
            string storedProc = "[dbo].[Messages_Insert]";

            int  empId        = 0;
            bool isSuccessful = false;

            _dataProvider.ExecuteNonQuery(storedProc
                                          , delegate(SqlParameterCollection paramCollection)
            {
                paramCollection.AddWithValue("@ConversationId", data.ConversationId);
                paramCollection.AddWithValue("@UserId", data.UserId);
                paramCollection.AddWithValue("@Text", data.Text);
                paramCollection.AddWithValue("@ReadStatus", data.ReadStatus = false);

                SqlParameter idParameter = new SqlParameter("@Id", System.Data.SqlDbType.Int);
                idParameter.Direction    = System.Data.ParameterDirection.Output;

                paramCollection.Add(idParameter);
            }, returnParameters : delegate(SqlParameterCollection param)
            {
                Int32.TryParse(param["@Id"].Value.ToString(), out empId);
            });

            if (empId != 0)
            {
                isSuccessful = true;
            }

            return(isSuccessful);
        }
Exemplo n.º 2
0
 private static void MapMessageAddRequest(MessageAddRequest model, SqlParameterCollection col, int senderId)
 {
     col.AddWithValue("@Message", model.MessageText);
     col.AddWithValue("@Subject", model.Subject);
     col.AddWithValue("@RecipientId", model.RecipientId);
     col.AddWithValue("@SenderId", senderId);
     col.AddWithValue("@DateSent", model.DateSent);
     col.AddWithValue("@DateRead", model.DateRead);
 }
Exemplo n.º 3
0
        public Conversation Create(List <int> userIds, int createdBy, string message)
        {
            if (userIds == null)
            {
                throw new ArgumentNullException("Parameter data is required");
            }
            string storedProc = "[dbo].[Conversations_Insert]";

            int          empId           = 0;
            Conversation newConversation = null;
            bool         isSuccessful    = false;

            _dataProvider.ExecuteNonQuery(storedProc
                                          , delegate(SqlParameterCollection paramCollection)
            {
                paramCollection.AddWithValue("@CreatedBy", createdBy);

                SqlParameter p = new SqlParameter("@UserIds", System.Data.SqlDbType.Structured);

                if (userIds != null && userIds.Any())
                {
                    p.Value = new Sabio.Data.IntIdTable(userIds);
                }

                paramCollection.Add(p);

                SqlParameter idParameter = new SqlParameter("@Id", System.Data.SqlDbType.Int);
                idParameter.Direction    = System.Data.ParameterDirection.Output;

                paramCollection.Add(idParameter);
            }, returnParameters : delegate(SqlParameterCollection param)
            {
                Int32.TryParse(param["@Id"].Value.ToString(), out empId);
            });

            if (empId != 0)
            {
                newConversation = GetConversation(empId);

                MessageAddRequest messageModel = new MessageAddRequest()
                {
                    ConversationId = newConversation.Id,
                    UserId         = createdBy,
                    Text           = message
                };

                isSuccessful = Create(messageModel);
            }

            if (!isSuccessful)
            {
                newConversation = null;
            }

            return(newConversation);
        }
Exemplo n.º 4
0
        public async Task <MessageAddResponse> AddMessage(MessageAddRequest request)
        {
            var client = EventHubClient.CreateFromConnectionString(MessageHubConnectionString);
            var json   = JsonConvert.SerializeObject(request);
            var data   = new EventData(Encoding.UTF8.GetBytes(json));
            await client.SendAsync(data);

            return(new MessageAddResponse
            {
                Timestamp = DateTimeOffset.Now
            });
        }
Exemplo n.º 5
0
        public async Task SendMessage(string messageText, int recipientId, string recipientName)
        {
            int userId = _authService.GetCurrentUserId();
            //Create MessageAddRequest
            MessageAddRequest message = new MessageAddRequest();

            message.RecipientId = recipientId;
            message.MessageText = messageText;
            message.DateSent    = DateTime.Now;

            //DB Call
            int createdMessageId = _service.Add(message, userId);

            //Create message to send
            Message     createdMessage = new Message();
            UserProfile recipient      = new UserProfile();

            recipient.UserId = recipientId;
            UserProfile sender = new UserProfile();

            sender.UserId              = userId;
            createdMessage.Recipient   = recipient;
            createdMessage.Sender      = sender;
            createdMessage.MessageText = messageText;
            createdMessage.DateSent    = DateTime.Now;
            Random rnd = new Random();

            createdMessage.Id = rnd.Next(500000);

            // TODO Try/catch sql exception

            //Get current chatroom and send
            NotificationAddRequest notification = new NotificationAddRequest();

            notification.UserId             = recipientId;
            notification.NotificationTypeId = 2;
            notification.NotificationText   = $"New message from {recipientName}";
            Notification notification1 = new Notification();

            notification1.NotificationText   = $"New message from {recipientName}";
            notification1.UserId             = recipientId;
            notification1.NotificationTypeId = 2;
            notification1.DateCreated        = new DateTime();

            _notificationService.Add(notification);
            string chatRoomId = await _chatHubService.GetCurrentUserRoom(userId);

            await Clients.Group(chatRoomId).SendAsync("AddMessage", createdMessage);

            await _notificationHubContext.Clients.User(recipientId.ToString()).SendAsync("ReceiveNotification", notification1);
        }
Exemplo n.º 6
0
        public async Task SendMessage(int recipient, string text, List <string> files)
        {
            int userId = _auth.GetCurrentUserId();

            try
            {
                List <string> urls = null;

                if (files != null)
                {
                    List <string> uploadResponses = _filesService.UploadMultipleV2(files);
                    if (urls == null)
                    {
                        urls = new List <string>();
                    }
                    uploadResponses.ForEach(url => urls.Add(url));
                }

                MessageAddRequest message = new MessageAddRequest();
                message.Recipient = recipient;
                message.Text      = text;
                Message newMessage = _chatService.AddMessage(userId, message, urls);
                if (newMessage == null)
                {
                    await Clients.Users($"{userId}", $"{recipient}").SendAsync("ReceiveMessage", null);
                }
                else
                {
                    newMessage.FileData = new List <string>();
                    newMessage.FileData = files;
                    if (newMessage.SenderInfo != null)
                    {
                        await Clients.User($"{recipient}").SendAsync("ReceiveSingleContact", newMessage.SenderInfo);

                        await Clients.Users($"{userId}", $"{recipient}").SendAsync("ReceiveMessage", newMessage, 3);
                    }
                    else
                    {
                        await Clients.Users($"{userId}", $"{recipient}").SendAsync("ReceiveMessage", newMessage, 1);
                    }
                }
            }
            catch (Exception ex)
            {
                await Clients.User($"{userId}").SendAsync("ReceiveMessage", null, null, ex);
            }
        }
Exemplo n.º 7
0
        public void SendMessage(MessageAddRequest message, string groupName)
        {
            bool        isSuccessful = false;
            UserProfile sender       = null;

            isSuccessful = _service.Create(message);
            sender       = _userProfileService.GetUser(message.UserId);

            if (isSuccessful)
            {
                Clients.Group(groupName).addChatMessageToGroup(message, groupName);
                if (sender != null)
                {
                    Clients.Group(groupName).sendNotificationToGroup(message, sender);
                }
            }
        }
Exemplo n.º 8
0
        public int Add(MessageAddRequest model, int senderId)
        {
            int    id       = 0;
            string procName = "[dbo].[Messages_Insert]";

            _data.ExecuteNonQuery(procName,
                                  inputParamMapper : delegate(SqlParameterCollection col)
            {
                MapMessageAddRequest(model, col, senderId);
                SqlParameter idOut = new SqlParameter("@Id", SqlDbType.Int);
                idOut.Direction    = ParameterDirection.Output;
                col.Add(idOut);
            },
                                  returnParameters : delegate(SqlParameterCollection returnCollection)
            {
                object oId = returnCollection["@Id"].Value;
                int.TryParse(oId.ToString(), out id);
            });
            return(id);
        }
Exemplo n.º 9
0
        public ActionResult <ItemResponse <int> > Add(MessageAddRequest model)
        {
            ObjectResult result = null;

            try
            {
                int userId = _authService.GetCurrentUserId();
                int id     = _service.Add(model, userId);
                ItemResponse <int> response = new ItemResponse <int> {
                    Item = id
                };
                result = Created201(response);
            }
            catch (Exception ex)
            {
                base.Logger.LogError(ex.ToString());
                ErrorResponse response = new ErrorResponse($"Server Error: {ex.Message}");
                result = StatusCode(500, response);
            }
            return(result);
        }
Exemplo n.º 10
0
        public async Task SendMessage(MessageAddRequest msgAdd)
        {
            int userId = _authService.GetCurrentUserId();

            msgAdd.ConversationId = msgAdd.ConversationId;
            msgAdd.Body           = msgAdd.Body;
            msgAdd.RecepientId    = msgAdd.RecepientId;
            msgAdd.UserId         = userId;

            int msgId = _messageService.Create(msgAdd, userId);

            Message msgInfo = new Message();

            msgInfo = _messageService.Get(msgId);

            MessageRecepientAddRequest msgRecAdd = new MessageRecepientAddRequest();

            msgRecAdd.ConversationId = msgAdd.ConversationId;
            msgRecAdd.MessageId      = msgId;
            msgRecAdd.TargetUserId   = msgAdd.RecepientId;
            msgRecAdd.Read           = false;

            _messageService.SendMsgToRecepient(msgRecAdd);

            if (Users.ContainsKey(msgAdd.RecepientId))
            {
                foreach (string connectionID in Users[msgAdd.RecepientId])
                {
                    await Clients.Client(connectionID).SendAsync("ReceiveMessageNoti", msgInfo);

                    await Clients.Client(connectionID).SendAsync("ReceiveMessage", msgInfo);
                }

                //await Clients.Clients(connectIds).SendAsync("ReceiveMessageNoti", msgInfo);
                //await Clients.Clients(connectIds).SendAsync("ReceiveMessage", msgInfo);
            }

            await Clients.Caller.SendAsync("ReceiveMessage", msgInfo);
        }
Exemplo n.º 11
0
        public int Create(MessageAddRequest req, int userId)
        {
            int id = 0;

            _dataProvider.ExecuteNonQuery("dbo.UserMessages_Insert", (parameters) =>
            {
                SqlParameter param  = new SqlParameter();
                param.ParameterName = "@Id";
                param.SqlDbType     = SqlDbType.Int;
                param.Direction     = ParameterDirection.Output;
                parameters.Add(param);

                parameters.AddWithValue("@ConversationId", req.ConversationId);
                parameters.AddWithValue("@Body", req.Body);
                parameters.AddWithValue("@UserId", userId);
            },
                                          (returnParams) =>
            {
                Int32.TryParse(returnParams["@Id"].Value.ToString(), out id);
            }
                                          );

            return(id);
        }
Exemplo n.º 12
0
        public Message AddMessage(int currUser, MessageAddRequest message, List <string> urls)
        {
            string   procName  = "[dbo].[Chat_Insert]";
            int      messageId = 0;
            DateTime dateSent  = DateTime.MinValue;
            Contact  contact   = null;
            string   urlJSON   = "";

            if (urls != null)
            {
                foreach (string url in urls)
                {
                    if (urlJSON != "")
                    {
                        urlJSON += $", {url}";
                    }
                    else
                    {
                        urlJSON += url;
                    }
                }
            }


            _data.ExecuteCmd(procName, paramCol =>
            {
                paramCol.AddWithValue("@sender", currUser);
                paramCol.AddWithValue("@recipient", message.Recipient);
                paramCol.AddWithValue("@message", message.Text);
                paramCol.AddWithValue("@urls", urlJSON);

                SqlParameter messageIdOut = new SqlParameter("@messageId", SqlDbType.Int)
                {
                    Direction = ParameterDirection.Output
                };

                SqlParameter dateSentOut = new SqlParameter("@dateSent", SqlDbType.DateTime)
                {
                    Direction = ParameterDirection.Output
                };

                paramCol.Add(messageIdOut);
                paramCol.Add(dateSentOut);
            }, (reader, set) =>
            {
                contact = ContactsService.HydrateContact(reader);
            }, returnParams =>
            {
                Object oid = returnParams["@messageId"].Value;
                Object ots = returnParams["@dateSent"].Value;
                Int32.TryParse(oid.ToString(), out messageId);
                DateTime.TryParse(ots.ToString(), out dateSent);
            });

            Message      formattedMessage = new Message();
            Interlocutor sender           = new Interlocutor();

            sender.Id = currUser;
            formattedMessage.Sender = sender;
            Interlocutor recipient = new Interlocutor();

            recipient.Id = message.Recipient;
            formattedMessage.Recipient  = recipient;
            formattedMessage.Text       = message.Text;
            formattedMessage.Urls       = urlJSON;
            formattedMessage.Id         = messageId;
            formattedMessage.DateSent   = dateSent;
            formattedMessage.SenderInfo = contact;
            return(formattedMessage);
        }