예제 #1
0
        public Task <Result <Guid> > SendAdminMessage(CreateMessageModel model)
        => Result <Guid> .TryAsync(async() =>
        {
            var message = new Message
            {
                Id       = Guid.NewGuid(), Title = model.Title, CreationDate = DateTime.Now,
                Body     = model.Body, FromUserId = generalDataService.User.Id,
                ToUserId = model.ToUser != null ? model.ToUser.Value : Guid.Empty,
                Priority = (byte)model.Priority, IsRead = false
            };
            _repository.Add(message);
            await _repository.CommitAsync();

            var toUser = (await _membershipServiceApi.SystemUserApiService.Get(
                              new MembershipService.ApiClient.Models.BaseModel {
                Id = model.ToUser
            })).Data;
            if (toUser == null)
            {
                return(Result <Guid> .Failed(Error.WithData(1000, new [] { "User not found" })));
            }

//                _coreSmtpClient.Send(toUser.Email,
//                    $"Dear  {toUser.Firstname} {toUser.Lastname} ,\n  you have a new message , please take a time to check your inbox in the system. \n Best Regards",
//                    "You have a new Message ");

//                await _smsHttpClient.Send(toUser.Email,
//                    $"Dear  {toUser.Firstname} {toUser.Lastname} ,\n  you have a new message , please take a time to check your inbox in the system. \n Best Regards");

            return(Result <Guid> .Successful(message.Id));
        });
예제 #2
0
        public ActionResult CreateMessage(string phone)
        {
            var model = new CreateMessageModel();

            model.Phones = phone;
            return(View(model));
        }
예제 #3
0
        public IActionResult CreateMessage(CreateMessageModel model)
        {
            if (ModelState.IsValid)
            {
                var email = new Message
                {
                    EmailSender   = User.Identity.Name,
                    EmailReceiver = model.EmailReceiver,
                    Text          = model.Text,
                    AttachedFile  = model.File
                };

                var rsaEncryption    = new RSAEncryption(email.EmailReceiver);
                var digitalSignature = new DigitalSignature(email.EmailSender);

                var encryptedMessage = _messageEncryptionService.EncryptData(email, rsaEncryption, digitalSignature);

                if (email.AttachedFile != null)
                {
                    _fileEncryptionService.EncryptFile(email.AttachedFile, encryptedMessage, rsaEncryption, digitalSignature);
                }

                return(RedirectToAction(nameof(MessageSentSuccessfully)));
            }

            return(View());
        }
예제 #4
0
        public async Task CreateMessage_UsingUserID_Works()
        {
            var options = new DbContextOptionsBuilder <DatabaseContext>()
                          .UseInMemoryDatabase(nameof(CreateMessage_UsingUserID_Works))
                          .Options;

            await using (var dbContext = new DatabaseContext(options))
            {
                dbContext.Users.Add(new User {
                    Username = "******", Email = "[email protected]", Password = "******"
                });

                dbContext.SaveChanges();
            }

            await using (var dbContext = new DatabaseContext(options))
            {
                var service = CreateTimelineService(dbContext);
                var model   = new CreateMessageModel
                {
                    Content = "123"
                };

                await service.CreateMessage(model, 1);
            }

            await using (var dbContext = new DatabaseContext(options))
            {
                var messages = dbContext.Messages.Where(message => message.AuthorID == 1).ToList();

                Assert.Single(messages);
            }
        }
예제 #5
0
        public async Task <IActionResult> Create([Bind("Message,RecipientId")] CreateMessageModel model)
        {
            var sender = _context.Users.FirstOrDefaultAsync(user => user.Id == _userManager.GetUserId(User));

            model.UsersHasMessages = new UsersHasMessages {
                Sender = await sender
            };
            //model.Message = await sender;

            //model.Message.SenderId = model.Message.Sender.Id;

            model.Message.DateSent = DateTime.Now;
            if (ModelState.IsValid)
            {
                _context.Add(model.Message);
                await _context.SaveChangesAsync();

                //Data for UsersHasMessages table
                model.UsersHasMessages.Messages       = model.Message;
                model.UsersHasMessages.MessagesId     = model.Message.Id;
                model.UsersHasMessages.RecipientId    = model.RecipientId;
                model.UsersHasMessages.IsAdminMessage = 0;
                model.UsersHasMessages.IsDeleted      = 0;
                model.UsersHasMessages.AlreadyRead    = 0;

                _context.Add(model.UsersHasMessages);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(model));
        }
예제 #6
0
        public async Task <MessageModel> CreateMessageAsync(CreateMessageModel createMessageModel)
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (createMessageModel is null)
            {
                throw new ArgumentNullException(nameof(createMessageModel));
            }

            var message = new Message
            {
                AuthorId    = createMessageModel.AuthorId,
                Body        = createMessageModel.Body,
                ChatroomId  = createMessageModel.ChatroomId,
                TimeSentUtc = createMessageModel.TimeSentUtc,
            };
            await _unitOfWork.GetRepository <IMessageRepository>().AddAsync(message);

            _ = await _unitOfWork.CompleteAsync();

            return(Mappers.ToMessageModel(message));
        }
예제 #7
0
        public ActionResult CreateMessage(CreateMessageModel model)
        {
            model.Date         = DateTime.Now;
            model.SrcUserLogin = User.Identity.Name;

            var userlist = new SelectList(_db.Users, "Login", "Login");

            ViewBag.List = userlist;

            int userIdSrc, userIdDst;

            if (ModelState.IsValid)
            {
                // определение id пользователя отправителя сообщения
                var user = _db.Users
                           .FirstOrDefault(u => u.Login == model.SrcUserLogin);

                if (user == null)
                {
                    return(HttpNotFound());
                }
                userIdSrc = user.Id;

                // определение id пользователя получателя сообщения
                user = _db.Users
                       .FirstOrDefault(u => u.Login == model.DstUserLogin);
                if (user == null)
                {
                    return(HttpNotFound());
                }
                userIdDst = user.Id;

                // поиск чата с заданным отправителем и получателем
                var c = _db.Chats
                        .FirstOrDefault(u => u.UserIdSrc == userIdSrc && u.UserIdDst == userIdDst);

                // если такого чата нет - создаем его
                if (c == null)
                {
                    c = new Chat {
                        UserIdSrc = userIdSrc, UserIdDst = userIdDst
                    };
                    _db.Chats.Add(c);
                    _db.SaveChanges();
                }

                // создаем сообщение в своем чате
                var m = new Message {
                    Content = model.Content, Date = model.Date, Chat = c
                };
                _db.Messages.Add(m);
                _db.SaveChanges();

                string message = Resources.Resource.MessageSent;
                ModelState.AddModelError("", message);
            }
            return(View(model));
        }
        public async Task <JsonResult> CreateMessage(CreateMessageModel message, string tenantUid)
        {
            var token  = Request.Cookies["token"].Value;
            var origin = TenantHelper.GetCurrentTenantUrl(_contentService, tenantUid);

            var response = await _ticketService.CreateMessage(tenantUid, token, origin, message.TicketId, message.EmailAddress, message.MessageText, message.Attachment);

            return(Json(response));
        }
예제 #9
0
        public IActionResult CreateAdmin()
        {
            var recipient = GetRecipientUser(Request.Query["recipientId"]);
            var model     = new CreateMessageModel {
                RecipientId = Request.Query["recipientId"], Recipient = recipient
            };

            return(View(model));
        }
예제 #10
0
        public async Task CreateMessage(CreateMessageModel model, string username)
        {
            var user = await _userService.GetUserFromUsername(username);

            if (user == null)
            {
                throw new UnknownUserException($"Unknown user with username: {username}");
            }

            await CreateMessage(model, user.ID);
        }
예제 #11
0
        public async Task CreateMessage(CreateMessageModel model, int userID)
        {
            var user = await _databaseContext.Users.SingleOrDefaultAsync(row => row.ID == userID);

            if (user == null)
            {
                throw new UnknownUserException($"Unknown user with ID: {userID}.");
            }

            await CreateMessage(model, user);
        }
예제 #12
0
        public async Task <Message> CreateMessage(CreateMessageModel model)
        {
            var request = new CreateRequest
            {
                Text = model.Text
            };

            var message = await _messageClient.CreateAsync(request);

            return(ToModel(message));
        }
예제 #13
0
        public async Task <IActionResult> AddMessageToUser(string username, CreateMessageModel model)
        {
            try
            {
                await _timelineService.CreateMessage(model, username);
            }
            catch (UnknownUserException e)
            {
                return(BadRequest(new ErrorResponse(e)));
            }

            return(NoContent());
        }
예제 #14
0
        public ActionResult CreateMessage(CreateMessageModel model)
        {
            var eventLogs = "";

            // Start transaction
            var transaction = db.Database.BeginTransaction();

            try
            {
                if (ModelState.IsValid)
                {
                    var arrPhones = model.Phones.Split(',');
                    foreach (var phone in arrPhones)
                    {
                        var message = new Message();
                        message.date    = DateTime.Now;
                        message.phone   = phone;
                        message.title   = model.Title;
                        message.message = model.Message;
                        message.status  = (int)Message.Status.UNREAD;
                        db.Messages.Add(message);
                    }
                    db.SaveChanges();
                    transaction.Commit();

                    return(RedirectToAction("ListMessages"));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.ToString());

                // Rollback transaction
                if (transaction != null)
                {
                    transaction.Rollback();
                }

                // Update event logs
                eventLogs += "MessageController - CreateMessage: " + ex.Message;
            }
            finally
            {
                if (!string.IsNullOrWhiteSpace(eventLogs))
                {
                    EventWriter.WriteEventLog(eventLogs);
                }
            }
            return(View(model));
        }
 public ActionResult Create(CreateMessageModel message)
 {
     using (ITransaction transaction = _session.BeginTransaction())
     {
         DataManager dataManager = new DataManager(_session);
         Profile     sendProfile = dataManager.ProfileRepository.GetProfileByUserName(User.Identity.Name);
         Profile     getProfile  = dataManager.ProfileRepository.GetProfileByFullName(message.Friend);
         sendProfile.SendMessage(getProfile, message.Text);
         _session.Save(sendProfile);
         _session.Save(getProfile);
         transaction.Commit();
     }
     return(RedirectToAction("TheMessages"));
 }
예제 #16
0
        private async Task CreateMessage(CreateMessageModel model, User user)
        {
            _databaseContext.Messages.Add(new Message
            {
                AuthorID    = user.ID,
                Text        = model.Content.Trim(),
                PublishDate = DateTimeOffset.Now,
                IsFlagged   = false
            });

            await _databaseContext.SaveChangesAsync();

            _logger.LogInformation($"Created message for user: {user.Username}.");
        }
예제 #17
0
        private static void CreateMessage(Ticket ticket)
        {
            Console.Write("Enter your message:");
            string content = Console.ReadLine();

            Console.WriteLine("Choose state");
            Console.WriteLine("Draft");
            Console.WriteLine("Posted");
            Console.Write("Enter state:");
            string state = Console.ReadLine();

            Console.Write("Enter file path(optional): ");
            if (ticket.Title == null)
            {
                Console.WriteLine("Invalid Ticket title!");
            }
            else
            {
                try
                {
                    string path     = Console.ReadLine();
                    byte[] file     = File.ReadAllBytes(path);
                    string fileName = Path.GetFileName(path);

                    var message = new CreateMessageModel
                    {
                        State          = state,
                        UserId         = _identity.UserId,
                        Content        = content,
                        PublishingDate = DateTime.Now,
                        FileContent    = file,
                        FileName       = fileName,
                        TicketId       = ticket.Id
                    };
                    _messageService.Create(message);
                }
                catch
                {
                    var message = new CreateMessageModel
                    {
                        State          = state,
                        UserId         = _identity.UserId,
                        Content        = content,
                        PublishingDate = DateTime.Now,
                        TicketId       = ticket.Id,
                    };
                    _messageService.Create(message);
                }
            }
        }
예제 #18
0
        public IActionResult Create()
        {
            // Jeigu vartotojas bando rasyti zinute sau
            if (Request.Query["recipientId"].Equals(this.User.FindFirstValue(ClaimTypes.NameIdentifier)))
            {
                return(RedirectToAction("Index", "Home"));
            }


            var recipient = GetRecipientUser(Request.Query["recipientId"]);
            var model     = new CreateMessageModel {
                RecipientId = Request.Query["recipientId"], Recipient = recipient, Message = new Messages()
            };

            model.Message.Subject = Request.Query["subject"];
            return(View(model));
        }
예제 #19
0
        public override async Task <int> AddAsync(CreateMessageModel message, CancellationToken cancellationToken = default)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(0);
            }

            var exist = await ExistAsync(message.Key, cancellationToken);

            if (exist)
            {
                throw new Exception($"The configuration key for the {_source.Environment} environment and {_source.NameSpace} NameSpace already exists");
            }

            var dateTime    = DateTime.Now;
            var dateUtcTime = DateTime.UtcNow;

            object[] sqlParams =
            {
                new MySqlParameter("@Key",         message.Key),
                new MySqlParameter("@Value",       message.Value),
                new MySqlParameter("@Environment", _source.Environment),
                new MySqlParameter("@Description", message.Description),
                new MySqlParameter("@NameSpace",   _source.NameSpace),
                new MySqlParameter("@CreateTime",  dateTime),
                new MySqlParameter("@UpdateTime",  dateTime),
                new MySqlParameter("@UtcTime",     dateUtcTime)
            };

            var sql = $@"INSERT INTO {GetTableName()} (`Key`,`Value`,`Environment`,`Description`,`NameSpace`,`CreateTime`,`UpdateTime`,`UtcTime`) 
VALUES (@Key,@Value,@Environment,@Description,@NameSpace,@CreateTime,@UpdateTime,@UtcTime);";

            using var connection = new MySqlConnection(_source.DbConnection);
            var executeRows = connection.ExecuteNonQuery(sql, sqlParams);

            if (executeRows <= 0)
            {
                return(executeRows);
            }

            var events = new ConcurrentQueue <Event>();

            events.Enqueue(new Event(EventType.Add, message.Key, message.Value));
            InvokeEvent(events);
            return(await Task.FromResult(executeRows));
        }
예제 #20
0
        public async Task <ActionResult> Create(CreateThemeViewModel model)
        {
            var themeId = await ThemeService.CreateThemeAsync(model.SubjectId, User.GetId(), model.Title);

            var message = new CreateMessageModel
            {
                ThemeId       = themeId,
                AuthorId      = User.GetId(),
                Content       = model.Content,
                AttachedFiles =
                    Mapper.Map <ICollection <HttpPostedFileBase>, ICollection <UploadFileModel> >(model.AttachedFiles)
            };

            await MessageService.CreateMessageAsync(message);

            return(RedirectToAction("Theme", new { themeId }));
        }
예제 #21
0
        public void CreateMessageTest_ShouldCreateAndReturnMessage()
        {
            var testContent = new CreateMessageModel
            {
                Message = "new test content"
            };
            var controller = GetControllerInstance();
            var result     = controller.CreateMessage(testContent) as CreatedAtActionResult;

            Assert.IsNotNull(result);
            Assert.AreEqual(StatusCodes.Status201Created, result.StatusCode);

            var message = result.Value as Message;

            Assert.IsNotNull(message);
            Assert.AreEqual(testContent.Message, message.Content);
        }
예제 #22
0
        public async Task AddAsync(CreateMessageModel dto, HttpContext context, CancellationToken cancellationToken)
        {
            try
            {
                dto ??= new CreateMessageModel();
                await _configurationStorage.AddAsync(dto, cancellationToken);

                var apiResult = new ApiResult();
                await context.Response.WriteAsync(apiResult.ToJson(), Encoding.UTF8, cancellationToken);
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                var apiResult = new ApiResult(500, e.Message);
                await context.Response.WriteAsync(apiResult.ToJson(), Encoding.UTF8, cancellationToken);
            }
        }
예제 #23
0
        public async Task Create_Message_SendMessage()
        {
            // Arrange
            var messagesController = this.CreateMessagesController(true);

            var userRecipient = new ApplicationUser()
            {
                Email    = "*****@*****.**",
                UserName = "******"
            };

            mockadvert_siteContext.Users.Add(userRecipient);
            mockadvert_siteContext.SaveChanges();

            var msg = new Messages()
            {
                Subject = "Helo",
                Text    = "Sup"
            };


            var userHasMsgs = new UsersHasMessages()
            {
                IsDeleted   = 0,
                MessagesId  = msg.Id,
                RecipientId = userRecipient.Id,
                Sender      = fakeUser,
                Messages    = msg
            };
            var model = new CreateMessageModel()
            {
                Message          = msg,
                RecipientId      = userRecipient.Id,
                UsersHasMessages = userHasMsgs
            };

            // Act
            var result = await messagesController.Create(model);

            var redirResult = (RedirectToActionResult)result;

            // Assert
            Assert.IsType <RedirectToActionResult>(result);
            Assert.Equal(nameof(messagesController.Index), redirResult.ActionName);
        }
예제 #24
0
        public async Task <IActionResult> AddMessage(CreateMessageModel model)
        {
            try
            {
                await _timelineService.CreateMessage(model, User.GetUserID());
            }
            catch (UnknownUserException e)
            {
                return(BadRequest(new ErrorResponse(e)));
            }

            ViewData["messages"] = new List <string>
            {
                "Your message was recorded"
            };

            return(RedirectToAction(nameof(Timeline)));
        }
예제 #25
0
        public async Task CreateMessage_UsingUsername_Throws_WhenUserDoesNotExist()
        {
            var options = new DbContextOptionsBuilder <DatabaseContext>()
                          .UseInMemoryDatabase(nameof(CreateMessage_UsingUsername_Throws_WhenUserDoesNotExist))
                          .Options;

            await using (var dbContext = new DatabaseContext(options))
            {
                var service = CreateTimelineService(dbContext);
                var model   = new CreateMessageModel
                {
                    Content = "123"
                };

                await Assert.ThrowsAsync <UnknownUserException>(async() => {
                    await service.CreateMessage(model, "a");
                });
            }
        }
예제 #26
0
        public async Task <Guid> CreateMessageAsync(CreateMessageModel model)
        {
            var message = Mapper.Map <CreateMessageModel, Message>(model);

            message.Id           = Guid.NewGuid();
            message.CreationDate = DateTime.Now;

            foreach (var attachedFile in model.AttachedFiles)
            {
                attachedFile.UploaderId = model.AuthorId;
            }

            Context.Messages.Add(message);
            await Context.SaveChangesAsync();

            await FileService.SaveMessageFilesAsync(message.Id, model.AttachedFiles);

            return(message.Id);
        }
예제 #27
0
        public async Task CreateAdmin_AdminMessage_SendAdminMessageToUsers()
        {
            // Arrange
            var messagesController = this.CreateMessagesController(true);
            var user = new ApplicationUser()
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };
            var user2 = new ApplicationUser()
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };

            mockadvert_siteContext.Users.Add(user2);
            mockadvert_siteContext.Users.Add(user);
            mockadvert_siteContext.SaveChanges();
            CreateMessageModel model = new CreateMessageModel()
            {
                RecipientId = this.fakeUser.Id,
                Message     = new Messages()
                {
                    Subject = "test",
                    Text    = "This is a test message"
                }
            };
            // Act
            var result = await messagesController.CreateAdmin(model);

            var messageCount = mockadvert_siteContext.UsersHasMessages.Where(x => x.IsAdminMessage == 1 && x.SenderId.Equals(this.fakeUser.Id)).Count();
            var userCount    = mockadvert_siteContext.Users.Count();

            // Assert
            Assert.IsType <RedirectToActionResult>(result);
            Assert.Equal(userCount, messageCount);
        }
예제 #28
0
        public int Create(CreateMessageModel model)
        {
            DATA.StateMessage messageState = (DATA.StateMessage)Enum.Parse(typeof(DATA.StateMessage), model.State);
            if (!Enum.IsDefined(typeof(DATA.StateMessage), messageState))
            {
                throw new ServiceException("Invalid message state.");
            }

            var message = new DATA.Message
            {
                UserId         = model.UserId,
                Content        = model.Content,
                PublishingDate = model.PublishingDate,
                State          = messageState,
                TicketId       = model.TicketId
            };

            _context.Add(message);

            if (!string.IsNullOrEmpty(model.FileName))
            {
                DATA.File file = new DATA.File
                {
                    Name      = model.FileName,
                    Content   = model.FileContent,
                    MessageId = message.Id
                };

                _context.Files.Add(file);
            }

            _context.Add(message);

            _context.SaveChanges();

            return(message.Id);
        }
예제 #29
0
        public IActionResult Create(int id, string state, ViewTicketViewModel viewModel)
        {
            Ticket ticket = _ticketService.GetByTicketId(id);

            int currnetUserId = _userService.GetByUsername(User.Identity.Name).Id;

            if (User.IsInRole("Client") && currnetUserId != ticket.SubmitterId)
            {
                return(NotFound());
            }

            var model = new CreateMessageModel
            {
                TicketId       = id,
                UserId         = currnetUserId,
                PublishingDate = DateTime.UtcNow,
                Content        = viewModel.MessageContent,
                State          = state
            };

            _messageService.Create(model);

            return(RedirectToAction($"{nameof(TicketController.View)}", "Ticket", new { id }));
        }
예제 #30
0
 public Task <Result <Guid> > Add(CreateMessageModel model)
 => _messageBiz.Add(model);