public async Task <IActionResult> PostMessage([FromBody] CreateMessageViewModel messageModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var currentUser = await _userManager.FindByNameAsync(User.FindFirstValue(ClaimTypes.NameIdentifier)); var conversation = await _context.Conversation.SingleOrDefaultAsync(c => c.ConversationId == messageModel.ConversationId); if (conversation == null) { return(NotFound()); } if (!conversation.Users.Contains(currentUser)) { return(Forbid()); } var message = new Message { Conversation = conversation, Content = messageModel.Content, Author = currentUser, }; _context.Message.Add(message); await _context.SaveChangesAsync(); return(CreatedAtAction("GetMessage", new { id = message.MessageId }, new GetViewModel(message))); }
public async Task <IActionResult> CreateMessage(int userId, CreateMessageViewModel messageModel) { User sender = await this.repo.GetUserAsync(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageModel.SenderId = userId; User recipient = await this.repo.GetUserAsync(messageModel.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } Message message = this.mapper.Map <Message>(messageModel); this.repo.Add(message); if (await this.repo.SaveAllAsync()) { MessageToReturnViewModel messageToReturn = this.mapper.Map <MessageToReturnViewModel>(message); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
public async Task <IActionResult> Create([FromBody] CreateMessageViewModel model) { var currentUser = await _userManager.GetUserAsync(HttpContext.User); var recipient = await _db.Users.FirstOrDefaultAsync(x => x.UserName == model.Recipient); if (recipient == null) { return(BadRequest(new { Message = $"Recipient {model.Recipient} not found." })); } model.RecipientId = recipient.Id; model.AuthorId = currentUser.Id; var id = Guid.NewGuid(); var message = _mapper.Map <Message>(model); await _db.Messages.AddAsync(message); await _db.SaveChangesAsync(); var msgFromDb = await _db.Messages.FirstOrDefaultAsync(x => x.Id == id); return(CreatedAtAction(nameof(Get), new { id }, model)); }
/// <summary> /// A helper method to generate the viewmodels that is used when creating a new message. /// </summary> /// <returns></returns> private CreateMessageViewModel generateCreateMessageModel() { using (var db = new ApplicationDbContext()) { List <RecieverViewModel> recieverList = new List <RecieverViewModel>(); List <ShortViewUserGroupViewModel> groupList = new List <ShortViewUserGroupViewModel>(); foreach (ApplicationUser au in db.Users.ToList()) { recieverList.Add(new RecieverViewModel { RecieverId = au.Id, UserName = au.UserName }); } foreach (UserGroup g in db.UserGroups) { groupList.Add(new ShortViewUserGroupViewModel { GroupId = g.GroupId, Name = g.Name }); } CreateMessageViewModel model = new CreateMessageViewModel { Recievers = new MultiSelectList(recieverList, "RecieverId", "UserName"), ReceiverGroups = new MultiSelectList(groupList, "GroupId", "Name"), Response = " ", SelectedRecieverId = new string[recieverList.Count()], SelectedGroupId = new int[groupList.Count()] }; return(model); } }
public ActionResult Create(CreateMessageViewModel viewModel) { var userId = User.Identity.GetUserId(); if (!ModelState.IsValid) { viewModel.Users = db.Users.ToList(); return(View()); } var Message = new Message { Id = viewModel.Id, Title = viewModel.Title, Text = viewModel.Text, DateTime = DateTime.Now }; var UserMessage = new UserMessage { MessageId = viewModel.Id, SenderId = userId, ReceiverId = viewModel.ReceiverId, IsRead = false }; // db.Messages.Add(Message); //db.UserMessages.Add(UserMessage); return(RedirectToAction("Index", "Messages")); }
public async Task <IActionResult> ChatAsync(string id) { string accessToken = await HttpContext.GetTokenAsync("access_token"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); string searchTalk = await client.GetStringAsync(Configuration["URLAPI"] + $"api/PrivateChat/GetTalk/{id}"); Talk talk = JsonConvert.DeserializeObject <Talk>(searchTalk); string searchMessages = await client.GetStringAsync(Configuration["URLAPI"] + $"api/PrivateChat/GetMessages/{talk.TalkId}"); IEnumerable <GetMessagesViewModel> messages = JsonConvert.DeserializeObject <IEnumerable <GetMessagesViewModel> >(searchMessages); string content = await client.GetStringAsync(Configuration["URLAPI"] + "api/account/getUserInfo"); AspNetUser user = JsonConvert.DeserializeObject <AspNetUser>(content); CreateMessageViewModel chat = new CreateMessageViewModel { Talk = talk, UserId = user.Id, DisplayMessages = messages, UserLikedId = id }; return(View(chat)); }
//[Authorize] public IActionResult Create() { var model = new CreateMessageViewModel() { }; return(View(model)); }
public ActionResult CreateMessage(int event_id) { CreateMessageViewModel model = new CreateMessageViewModel { EventId = event_id }; return(View(model)); }
public async Task <ActionResult> Create([Bind(Include = "Subject,Content,RecepientId")] CreateMessageViewModel model, List <HttpPostedFileBase> attachedFile) { if (ModelState.IsValid) { Message message = new Message(); message.Sender = await db.Users.FirstAsync(u => u.UserName.Equals(User.Identity.Name, StringComparison.InvariantCultureIgnoreCase)); message.Recepient = await db.Users.FirstAsync(u => u.Id.Equals(model.RecepientId, StringComparison.InvariantCultureIgnoreCase)); //ApplicationUserManager um = new ApplicationUserManager(new); message.Subject = model.Subject; message.Content = model.Content; message.Date = DateTime.Now; try { db.Messages.Add(message); await db.SaveChangesAsync(); } catch (DbEntityValidationException ex) { ex.LogException(); throw; } int filenumbers = attachedFile.Count(); if (filenumbers >= 1) { foreach (var uploadfile in attachedFile) { if (uploadfile != null) { byte[] buff = new byte[uploadfile.ContentLength]; int len = await uploadfile.InputStream.ReadAsync(buff, 0, uploadfile.ContentLength); DocFile df = new DocFile() { Description = "Message attachment", FileType = uploadfile.ContentType, FileName = uploadfile.FileName, Content = buff, Message = message }; db.DocFiles.Add(df); //await db.SaveChangesAsync(); } } } await db.SaveChangesAsync(); // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"); await UserManager.SendEmailAsync(message.Recepient.Id, "New Message From", string.Format(" Please login {0} to check your secure message box", Request.Url.Host)); return(RedirectToAction("Index", new { id = message.Recepient.Id })); } return(View(model)); }
// GET: Messages/Details/5 //public ActionResult Details(int? id) //{ // if (id == null) // { // return new HttpStatusCodeResult(HttpStatusCode.BadRequest); // } // Message message = db.Messages.Find(id); // if (message == null) // { // return HttpNotFound(); // } // return View(message); //} // GET: Messages/Create public ActionResult Create() { var viewModel = new CreateMessageViewModel { Users = db.Users.ToList() }; return(View(viewModel)); }
public IActionResult Create(int id) { var model = new CreateMessageViewModel { OfferId = id }; //this.ViewData["OfferId"] = id; return(View(model)); }
public ActionResult CreateMessage(CreateMessageViewModel createMessageViewModel) { //Validate, if users belongs to conversation if (ModelState.IsValid) { var message = _conversationService.CreateMessage(createMessageViewModel.ConversatonId, createMessageViewModel.Message, User.Identity.Id); return(PartialView("ConversationMessage", message)); } Response.StatusCode = (int)HttpStatusCode.BadRequest; return(PartialView(createMessageViewModel)); }
public ActionResult CreateMessage(CreateMessageViewModel model, int event_id) { if (ModelState.IsValid) { model.MessageText = RegularMessage(model.MessageText); var user = _userProfileService.GetUserByName(User.Identity.Name); model.ProdileId = user.ProfileId; var createMessageDto = _mapper.Map <CreateMessageViewModel, CreateMessageDTO>(model); _messageService.CreateMessage(createMessageDto); } return(RedirectToAction("Messages", "Message", new { event_id, page = 1 })); }
public void PostMessage_Forbidden() { var controller = GetController(); var c = new CreateMessageViewModel { ConversationId = 3, Content = "testtest" }; var res = controller.PostMessage(c).Result as ForbidResult; Assert.NotNull(res); }
public void PostMessage_Valid() { var controller = GetController(); var c = new CreateMessageViewModel { ConversationId = 2, Content = "testtest" }; var res = controller.PostMessage(c).Result as CreatedAtActionResult; Assert.NotNull(res); }
public ActionResult contactseller(CreateMessageViewModel model) { var listingQ = from l in db.Listings.Include("Owner") where l.ListingId == model.ListingId select l; var listing = listingQ.FirstOrDefault(); if (listing == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (ModelState.IsValid) { var userId = User.Identity.GetUserId(); Message message = new Message(); message.Detail = model.Detail; message.ListingId = model.ListingId; message.Phone = model.Phone; message.SenderEmail = model.SenderEmail; if (!String.IsNullOrEmpty(userId)) { message.SenderId = userId; } message.SenderName = model.SenderName; message.Subject = model.Subject; message.Type = "listing"; message.Created = DateTime.Now; message.Updated = DateTime.Now; db.Messages.Add(message); db.SaveChanges(); ViewBag.Message = "Message sent to seller successfully. Thank you for your message. "; var user = db.Users.Find(userId); if (user != null) { model.ListingId = listing.ListingId; model.Phone = user.ClassifiedsPhone; model.SenderEmail = user.Email; model.SenderName = user.Alias ?? user.FullName; } model.Subject = "About listing #" + listing.ListingId + " - " + listing.Title; //now send the email. //TMSendEmail.send(model.SenderEmail, model.SenderName, listing.Owner.Email, model.Subject, model.Detail, null); TMSendEmail.send(model.SenderEmail, "Zimpapers Classifieds", "*****@*****.**", model.Subject, "<strong>Phone : " + model.Phone + "<strong><br/><strong>Name: " + model.SenderName + "</strong><br/>" + model.Detail, null); } ViewBag.Listing = listing; return(View(model)); }
public IActionResult Create(CreateMessageViewModel model) { if (ModelState.IsValid) { var message = new Message() { Text = model.Text }; _context.Add(message); _context.SaveChanges(); } return(RedirectToAction(nameof(Index))); }
public ActionResult Create(CreateMessageViewModel model) { try { if (ModelState.IsValid) { if (model.MessageText != "" && model.MessageText != null) { _service.CreateMessage(model.MessageText, model.MemberUserName, model.ConversationId); //no ids in vm } } } catch { } return(RedirectToAction("Index", "Familys", new { userID = model.MemberUserName, famName = _service.GetFamilyNameById(model.FamilyId) }));// no ids in vm }
public async Task <IHttpActionResult> Create(CreateMessageViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var message = Mapper.Map <CreateMessageViewModel, CreateMessageModel>(model); message.AuthorId = User.GetId(); await MessageService.CreateMessageAsync(message); return(Ok(model.ThemeId)); }
public async Task <ActionResult> Create(CreateMessageViewModel model) { if (!ModelState.IsValid) { throw new NotImplementedException(); } var message = Mapper.Map <CreateMessageViewModel, CreateMessageModel>(model); message.AuthorId = User.GetId(); await MessageService.CreateMessageAsync(message); return(RedirectToAction("Theme", "Theme", new { themeId = model.ThemeId })); }
public async Task <ActionResult> Create(CreateMessageViewModel postVM) { if (ModelState.IsValid) { // Write to the DB! using (ApplicationDbContext db = new ApplicationDbContext()) { try { Message newMessage = new Message() { SenderID = User.Identity.GetUserId(), ReceiverID = postVM.ReceiverID, TransactionId = postVM.RelatedTransactionID, ParentMessageID = postVM.ParentMessageId, SentDate = DateTimeOffset.Now, ReceiverStatus = MessageStatus.Available, SenderStatus = MessageStatus.Available, Subject = WebUtility.HtmlEncode(postVM.Subject), Content = WebUtility.HtmlEncode(postVM.Content) }; db.Messages.Add(newMessage); await db.SaveChangesAsync(); TempData["Message"] = $"Message sent."; TempData["MessageConnotation"] = 1; // Positive feedback return(RedirectToAction("Index", "Messages", new { mailbox = "Sent" })); } catch (Exception e) { TempData["Message"] = $"Ooops! Something went wrong with the Database ({e.Message})."; TempData["MessageConnotation"] = -1; // Negative feedback return(RedirectToAction("Index", "Messages")); } } } else { // if Model is invalid I resend it to the user using (ApplicationDbContext db = new ApplicationDbContext()) { postVM.ParentMessage = await db.Messages.FindAsync(postVM.ParentMessageId); postVM.Receivers = await db.Users.Where(u => u.ProfileStatus == ApplicationUser.Status.Active).AsNoTracking().ToListAsync(); } } return(View(postVM)); }
// POST: Message/Create public ActionResult Create(CreateMessageViewModel model) { if (ModelState.IsValid) { List <ApplicationUser> recipientUsers = new List <ApplicationUser>(); List <UserGroup> recipientUserGroups = new List <UserGroup>(); using (var db = new ApplicationDbContext()) { var sender = db.Users.Find(User.Identity.GetUserId()); string responseMsg = "Message was sent to "; if (model.SelectedRecieverId != null) { recipientUsers = db.Users.Where(u => model.SelectedRecieverId.Contains(u.Id)).ToList(); } if (model.SelectedGroupId != null) { recipientUserGroups = db.UserGroups.Where(g => model.SelectedGroupId.Contains(g.GroupId)).ToList(); } foreach (var usr in recipientUsers) { responseMsg += usr.UserName + ", "; } foreach (var grp in recipientUserGroups) { responseMsg += grp.Name + ", "; } db.Messages.Add(new Message { Title = model.Title, Text = model.Text, Sender = sender, Timestamp = DateTime.Now, RecipientGroups = recipientUserGroups, RecipientUsers = recipientUsers }); db.SaveChanges(); responseMsg += " at " + DateTime.Now; var newMsgModel = generateCreateMessageModel(); newMsgModel.Response = responseMsg; return(View(newMsgModel)); } } // Something went wrong. return(View("Error")); }
public async Task <string> SaveAsync([FromBody] CreateMessageViewModel message) { NotificationDTO notification = new NotificationDTO { Body = message.Body, Recipients = message.Recipients != null?string.Join(';', message.Recipients) : string.Empty }; //var isSent = await notificationService.SendMessageToNotificationServiceAsync(notification); var mapperCreateMessageViewModelToMessageDTO = new MapperConfiguration(cfg => cfg.CreateMap <CreateMessageViewModel, MessageDTO>()).CreateMapper(); var messageDTO = mapperCreateMessageViewModelToMessageDTO.Map <CreateMessageViewModel, MessageDTO>(message); messageDTO.IsSent = false; return(await userService.SaveAsync(messageDTO)); }
public ActionResult CreateMessage(CreateMessageViewModel model) { if (ModelState.IsValid) { model.MessageText = RegularMessage(model.MessageText); model.UserId = User.Identity.GetUserId(); var createMessageDto = Mapper.Map <DTOCreateMessageViewModel>(model); if (!MessageService.CreateMessage(createMessageDto)) { return(HttpNotFound()); } return(RedirectToAction("ReadMessages", new { id = model.IdTheme, page = model.Page })); } return(HttpNotFound()); }
public async Task <IActionResult> Create(int id, CreateMessageViewModel model) { if (ModelState.IsValid) { try { var recipientId = this.offerService.GetOfferCreatorId(id); if (recipientId == null) { this.TempData[Constants.ValidationState.Error] = Constants.Message.InvalidOffer; return(this.RedirectToAction("Details", "Offer", new { id = id })); } var recipient = await this.userManager.FindByIdAsync(recipientId); model.RecipientId = recipient.Id; var dto = mapper.Map <CreateMessageViewModel, MessageDTO>(model); var sender = await this.userManager.GetUserAsync(HttpContext.User); dto.ReceiverId = recipientId; dto.SenderId = sender.Id; dto.OfferId = id; int messageId = await this.messageService.SendMessage(dto); var claim = new Claim("Message", messageId.ToString()); var setSender = await this.userManager.AddClaimAsync(sender, claim); var setReceiver = await this.userManager.AddClaimAsync(recipient, claim); this.TempData[Constants.ValidationState.Success] = Constants.Message.SuccessfulMessage; return(this.RedirectToAction("Details", "Offer", new { id = id })); } catch (Exception ex) { this.TempData[Constants.ValidationState.Error] = ex.Message; return(this.RedirectToAction("Details", "Offer", new { id = id })); } } foreach (var error in ModelState.Values.SelectMany(p => p.Errors)) { this.TempData[Constants.ValidationState.Error] += error.ErrorMessage + Environment.NewLine; } return(this.View()); }
public ActionResult Create(CreateMessageViewModel messageVm) { if (!this.messagesService.ReceiverExists(messageVm.ReceiverUsername)) { this.Danger($"Username with {messageVm.ReceiverUsername} does not exists!"); } else { if (this.ModelState.IsValid) { string senderUsername = HttpContext.User.Identity.Name; this.messagesService.Create(senderUsername, messageVm.ReceiverUsername, messageVm.Text); this.Success("Send successfully!", true); return(this.RedirectToAction("Inbox")); } } this.Danger("Something else went wrong!"); return(this.RedirectToAction("Create")); }
public ActionResult Create(CreateMessageViewModel model) { if (this.TryUpdateModel(model)) { // Get ID of current user var userId = dc.Users.Single(x => x.UserName.Equals(this.User.Identity.Name)).UserId; // Create new message dc.Messages.Add(new Message { Body = model.Body, DateCreated = DateTime.Now, Subject = model.Subject, UserId = userId }); dc.SaveChanges(); // Send message if (RuntimeOptions.Current.UseMailing) { var accountUri = new UriBuilder(this.Request.Url) { Path = this.Url.Action("Index", "Account"), Query = "", Fragment = "" }; var recipients = from u in dc.Users where u.UserId != userId && u.IsApproved && u.EmailMessages select u.Email; Mailer.SendMail(recipients, Properties.Resources.MessageCreateSubject, Properties.Resources.MessageCreateBody, model.Subject, // 0 this.User.Identity.Name, // 1 model.Body, // 2 accountUri); // 3 } return(this.RedirectToAction("Index")); } ViewBag.Title = "Nová zpráva"; ViewBag.CancelAction = "Index"; ViewBag.CancelController = "Messages"; return(View("~/Views/Shared/UniversalEditor.cshtml", model)); }
public ActionResult contactseller(int id) { var listing = db.Listings.Find(id); var userId = User.Identity.GetUserId(); var model = new CreateMessageViewModel(); if (listing == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var user = db.Users.Find(userId); if (user != null) { model.Phone = user.ClassifiedsPhone; model.SenderEmail = user.Email; model.SenderName = user.Alias ?? user.FullName; } ViewBag.Listing = listing; model.ListingId = listing.ListingId; model.Subject = "About listing #" + listing.ListingId + " - " + listing.Title; return(View(model)); }
public async Task <IActionResult> CreateMessageAsync(CreateMessageViewModel chat) { string accessToken = await HttpContext.GetTokenAsync("access_token"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); if (ModelState.IsValid) { StringContent httpContent = new StringContent(chat.NewMessage.ToJson(), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(Configuration["URLAPI"] + "api/PrivateChat/CreateMessage", httpContent); if (response.StatusCode != HttpStatusCode.OK) { return(BadRequest()); } return(RedirectToAction("Chat", "PrivateChat", new { id = chat.UserLikedId })); } return(RedirectToAction(nameof(IndexAsync))); }
public IActionResult CreateMessage(CreateMessageViewModel model) { if (ModelState.IsValid) { Message message = new Message() { IsRead = model.IsRead, Receiver = model.Receiver, Sender = User.Identity.Name, TimeSent = model.TimeSent, MessageItem = model.MessageItem, Subject = model.Subject, }; _repository.AddEntity(message); _repository.SaveAll(); ModelState.Clear(); ViewBag.Message = $"Message sent to {model.Receiver}"; } return(View()); }