Exemplo n.º 1
0
        public Message Send(string text, Guid userid, Guid chatid, IEnumerable <string> fileNames = null, IEnumerable <byte[]> files = null,
                            bool selfDestruction = false, string destructionTime = null)
        {
            if (text.IsEmpty())
            {
                var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content      = new StringContent("Введите текст сообщения"),
                    ReasonPhrase = "Message text is empty"
                };
                throw new HttpResponseException(resp);
            }
            if (userid == null || !_usersRepository.UserExists(userid))
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent($"Пользователь с ID = {userid} не найден"),
                    ReasonPhrase = "User ID Not Found"
                };
                throw new HttpResponseException(resp);
            }
            if (chatid == null || !_chatsRepository.ChatExists(chatid))
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent($"Чат с ID = {chatid} не найден"),
                    ReasonPhrase = "Chat ID Not Found"
                };
                throw new HttpResponseException(resp);
            }
            if (!_usersRepository.GetUserChats(userid).Any(c => c.Id == chatid))
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent($"Среди доступных чатов пользователя нет чата с id {chatid}"),
                    ReasonPhrase = "Chat ID Not Found"
                };
                throw new HttpResponseException(resp);
            }
            files = files ?? new List <byte[]>();
            var msg = new Message()
            {
                Text = text
            };

            msg.Id                  = Guid.NewGuid();
            msg.Date                = DateTime.Now;
            msg.SelfDestruction     = selfDestruction;
            msg.SelfDestructionDate = destructionTime == null ? DateTime.MaxValue : Convert.ToDateTime(destructionTime);

            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    using (var command = connection.CreateCommand())
                    {
                        command.Transaction = transaction;
                        command.CommandText = "INSERT INTO Messages (MessageId, Text, Date, " +
                                              "SelfDestruction, SelfDestructionDate, SenderId, ChatId) " +
                                              "VALUES (@msg, @text, @date, @sd, @sddate, @sender, @chat)";

                        command.Parameters.AddWithValue("@msg", msg.Id);
                        command.Parameters.AddWithValue("@text", msg.Text);
                        command.Parameters.AddWithValue("@date", msg.Date);
                        command.Parameters.AddWithValue("@sd", msg.SelfDestruction);
                        command.Parameters.AddWithValue("@sddate", msg.SelfDestructionDate);
                        command.Parameters.AddWithValue("@sender", userid);
                        command.Parameters.AddWithValue("@chat", chatid);

                        command.ExecuteNonQuery();
                    }
                    for (int i = 0; i < files.Count(); i++)//foreach (var f in files)
                    {
                        using (var command = connection.CreateCommand())
                        {
                            command.Transaction = transaction;
                            command.CommandText = "INSERT INTO Attachs (AttachId, FileName, FileData, UserId, MessageId)" +
                                                  " VALUES (@attachid, @filename, @filedata, @userid, @messageid)";

                            command.Parameters.AddWithValue("@attachid", Guid.NewGuid());
                            command.Parameters.AddWithValue("@filename", fileNames.ElementAt(i));
                            command.Parameters.AddWithValue("@filedata", files.ElementAt(i));
                            command.Parameters.AddWithValue("@userid", userid);
                            command.Parameters.AddWithValue("@messageid", msg.Id);

                            command.ExecuteNonQuery();
                        }
                    }
                    transaction.Commit();
                    msg.Sender  = _usersRepository.Get(userid);
                    msg.Attachs = GetMessageAttachs(msg.Id);
                    return(msg);
                }
            }
        }