public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId, false); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId, false); if (recipient == null) { return(BadRequest("Could not find user")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { // We will get the complete sender information and store it // in memory so that AutoMapper can do some magic and automatically // harvest any information from the memory once we do mapping var sender = await _repo.GetUser(userId, true); // The first thing that we want to do is to check the user that is // attempting to update their profile matches the token that the // service is receiving. On the AuthController at line #77, we are // setting the ClaimTypes.NameIdentifier equal to the user identifier if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; // We are getting the recipient information from our repo but // after that, we don't include that information as part of the // return data. But, with AutoMapper's magic, since the recipient // information is already in memory, it maps it automatically // when we call var messageToReturn = _mapper.Map<MessageToReturnDto>(message); var recipient = await _repo.GetUser(messageForCreationDto.RecipientId, false); if (recipient == null) { return(BadRequest("Could not find user.")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { // After we added the message to our repository, we don't need to map this // back into a DTO so that we can return it. What we are using for our // MessageForCreationDto is good enough for our purposes to send back to // our user. That is why in the AutoMapperProfiles, we are using the // .ReverseMap() method to chain the mapping of the Message to MessageForCreationDto // and MessageForCreationDto to Message // Recipient information is coming from var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); // even if we don't explicitly assigned it to the 'message' field // since AutoMapper magically got it from the memory. // We are placing this code nside the if statement so that we can get // the correct message id when returned var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save."); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { /* * The sender is the logged in user * We load the User data into memory here because AutoMapper will see this object in memory * and automatically map the properties like KnownAs and PhotoUrl to the MessageToReturnDto. * Without doing this, these properties on the Dto returned will be null. */ var sender = await _repo.GetUser(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; // NOTE: Because we are loading recipient User in memory here, AutoMapper knows about this and will also attempt to map any properties that match // to the MessageToReturnDto - we get recipientKnownAs and RecipientPhotoUrl automatically for this reason. var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } // map request dto into our message entity var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); // not async - not querying or doing anything with the db at this time if (await _repo.SaveAll()) { /* * return the dto after the information is saved to the database in order to populate the Id for the created Resource correctly * Otherwise, you will see a random long negative number there. */ // you need to map the message model back to a dto to return to the client so you don't return password info, etc. in th response // you might want to create a separate response dto for this, but the one we have suffices for this example var messageToReturn = _mapper.Map <MessageToReturnDto>(message); // "GetMessage" is the Name assigned to the method above return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add <Message>(message); var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var userFormRepo = await _repo.GetUser(currentUserId); var messageToReturn = _mapper.Map <MessageForCreationDto>(message); messageToReturn.SenderKnownAs = userFormRepo.KnownAs; if (userFormRepo.Photos != null || userFormRepo.Photos.Count > 0) { IEnumerator <Photo> iterator = userFormRepo.Photos.GetEnumerator(); while (iterator.MoveNext()) { if (iterator.Current.IsMain == true) { messageToReturn.SenderPhotoUrl = iterator.Current.Url; break; } } } if (await _repo.SaveAll()) { return(Ok(messageToReturn)); } return(BadRequest("Failed to send message")); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId); // if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) return Unauthorized(); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // if (messageForCreationDto.RecipientId == userId) // { // return BadRequest("You cannot send a message to your self"); // } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Couldn't find the member")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); /* * The CreatedAtRoute method is intended to return a URI * to the newly created resource when you invoke a POST * method to store some new object. * So if you POST an order item for instance, * you might return a route like 'api/order/11' * (11 being the id of the order obviously) */ return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } else { throw new Exception("Couldn't send message"); } }
public async Task <IActionResult> CreateMessage(int userId, [FromBody] MessageForCreationDto messageForCreationDto) { // check if the user is the current user if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // set the sender id messageForCreationDto.SenderId = userId; // get the sender information // so that we can return the sender information // along with the message var sender = _repo.GetUser(messageForCreationDto.SenderId); // get the recipient and check if exists in our database var recipient = _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could find the user")); } // map var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); // map the return message var messageToReturn = _mapper.Map <MessageToReturnDto>(message); if (await _repo.SaveAll()) { // because we're creating resource we // CreateaAtRoute method return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
// in this request we need to send the body public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // [Route("api/users/{userId}/[controller]")] userId is passed from route // store who sent the message so it's the id of the logged in user messageForCreationDto.SenderId = userId; // messageForCreationDto.RecipientId is being fetched from the POST request body var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } // this means we are casting the Dto data into message class then storing all data // in the var message var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { // we do reverse map to only get the required 4 paramaters //to get to call method GetMessage // this is the response // { // "senderId": 5, // "recipientId": 11, // "messageSent": "2020-09-08T17:54:09.3906257+03:00", // "content": "get off " // } var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { // if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) // return Unauthorized(); // added next line and then this line I commented out // to be able to put "sender" info in memory for auto-mapper to // then be able to access. var sender = await _repo.GetUser(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); // var messageToReturn = _mapper.Map<MessageForCreationDto>(message); // replaced the DTO because the new one // includes sender's photo and KnownAs // then moved it to inside of the if stmt below // so that the correct id is being returned from the server if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { //make sure that user in token matches user id that was passed in the router var sender = await _repo.GetUser(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //userid is id of logged in user, will be retieved from router messageForCreationDto.SenderId = userId; //recipient id will be sent with the body of http post var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find a recipient of the message")); } //map dto to message object, which is a database table var message = Mapper.Map <Message>(messageForCreationDto); _repo.Add(message); //note: this is not async method, so no wait //map message object back to dto to return limitted data //note: since sender and recipient were pulled from a database in variables, //automapper will map knownAs and photoUrls of both to messageToReturn dto if (await _repo.SaveAll()) //save to a database { //note that after saving to a database, message object will get generated id automatically //and will be mapped to MessageToReturnDto var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { id = message.id }, messageToReturn)); } throw new System.Exception("Creatng the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { //We are fetching this sender info becasue we want the senderPhotoUrl. // It is getting set with the help of AutoMaaper where the values of URL and knownAs is getting set automatically var sender = await _repo.GetUser(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); //Added by saurabh --start-- // We can use this method of just fetching back the photo and assigning it to messageToReturn // But we do not do that since AUto Mapper as a special magic which automatically sets matching parmaters // from other objects. in Our case recipentPhotoUrl, recipientKnowAs, SenderPhotoUrl, SenderKnownAs. //var photo = await _repo.GetPhoto(userId); if (recipient == null) { return(BadRequest("Could not find user")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); //Added by saurabh //messageToReturn.SenderPhotoUrl = photo.Url; return(CreatedAtRoute("GetMessage", new { userId = userId, id = message.Id }, messageToReturn)); } throw new System.Exception("Creating the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId); // checks the token for currently logged in user if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } //Map dto into our message class var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { //this line maps the message back to messageforcreationdto as it is supposed to be return. //we use reverseMap() in the AutoMapperProfiles class to do this. var messageToReturn = _mapper.Map <MessageToReturnDto>(message); //-----reason to use CreatedatRoute here------------- //The correct response from an API for a successful post is to include the location //in the header of where we can locate the newly created resource. //In this case we return a 201 CreatedAtRoute with the location of the newly created resource. return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); //return messageToReturn; } throw new Exception("Creating message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { //get the user that's sending the message var sender = await _repo.GetUser(userId, false); //check if logged in user is authorized if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //set the user ID messageForCreationDto.SenderId = userId; //get the user that the message is been sent to var recipient = await _repo.GetUser(messageForCreationDto.RecipientId, false); //confirm the user exist if (recipient == null) { return(BadRequest("Could not find user")); } //map the collected data frm the client to the MESSAGE object var message = _mapper.Map <Message>(messageForCreationDto); //add to memory _repo.Add(message); //save all changes to database if (await _repo.SaveAll()) { //remap the returning message from the saved message var messageToReturn = _mapper.Map <MessageToReturnDto>(message); //create a repose with the saved message details return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (userId != currentUserId) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); var messageToReturn = _mapper.Map <MessageForCreationDto>(message); if (await _repo.SaveAll()) { return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } return(BadRequest("Message was not created.")); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId); //authorized check.. if (sender.id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //setting parameter messagefor creatindto to a user id messageForCreationDto.SenderId = userId; //taking recipient from the repo var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); //if recipent exist.. if (recipient == null) { return(BadRequest("Could not find user")); } //maping our message for creation data into our message class or message//<Message> is destination and we pass in messageforcreationdto var message = _mapper.Map <Message>(messageForCreationDto); //need maping because i want to map my messageForCreationDto to a message entity //after maping i add this message to repo (database) //dont need to async because add is not async metod it is just sync bit of code //because we are not querying and we are not doing anything with our databse at this time _repo.Add(message); //saving it to the datapase if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { // getting the sender data for automapper to map the sender Id and photo in // message to return var sender = await _repo.GetUser(userId, false); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // setting the sender ID in DTO messageForCreationDto.SenderId = userId; // checking if recipient exists, also needed for auto mapper to map // recipient info in messageToReturn var recipient = await _repo.GetUser(messageForCreationDto.RecipientId, false); if (recipient == null) { return(BadRequest("Could not find User")); } // mapping to required database requirements var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { // using reverse mapper to map the message to required returning values var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } throw new Exception("Message Failed to Save"); }
public async Task <IActionResult> CreateMessage(int userId, [FromBody] MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } var message = _mapper.Map <Message>(messageForCreationDto); // sau khi mapper, lúc này user sender bị null do trước đó không được gọi lên _repo.Add(message); // sau khi thêm message trên vào database // 2 user trong message được tự động cập nhật: // vì nhờ có 2 hàm: // var sender = await _repo.GetUser(userId); // var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); var messageToReturn = _mapper.Map <MessageToReturnDto>(message); if (await _repo.SaveAll()) { return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var user = await _repo.GetUser(userId); if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user.")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); // var messageToReturn = _mapper.Map<MessageForCreationDto>(message); // var messageToReturn = _mapper.Map<MessageToReturnDto>(message); // My approach: beyond GetUser it was redundant; AutoMapper would have done all // var user = await _repo.GetUser(userId); // var userPhoto = await _repo.GetMainPhotoForUser(userId); // messageToReturn.SenderKnownAs = user.KnownAs; // messageToReturn.SenderPhotoUrl = userPhoto.Url; if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save."); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _datingRepository.GetUser(userId); messageForCreationDto.SenderId = userId; var reciever = await _datingRepository.GetUser(messageForCreationDto.RecieverId); if (reciever == null) { return(BadRequest("Could not found user")); } var message = _mapper.Map <Message>(messageForCreationDto); _datingRepository.Add(message); if (await _datingRepository.SaveAll()) { //var messagesFromRepo = await _datingRepository.GetMessageThread(userId, messageForCreationDto.RecieverId); //message = messagesFromRepo.FirstOrDefault(m => m.SenderId == userId && m.RecieverId == messageForCreationDto.RecieverId); var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId = userId, id = message.Id }, messageToReturn)); } throw new Exception("Creating message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; //creating to check if the recipient exists. Still we get this information back in the MessageToReturn thanks to auto mapping "magic". /*By getting this info from repo, we have the recipient's details * //Because auto mapper by convention is going to attempt to map any properties that it can * //And because we have this recipient information inside the memory * //Automapper is automatically mapping this information into our MessagesToReturn.*/ var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); var Mainphoto = await _repo.GetMainPhoto(userId); if (recipient == null) { return(BadRequest("Could not find user")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { var msg = _mapper.Map <MessageForCreationDto>(message); if (Mainphoto != null) { msg.senderPhotoUrl = Mainphoto.Url; } return(CreatedAtRoute("Getmessage", new { id = message.Id }, msg)); } throw new System.Exception("Creating new message failed"); }
public async Task <IActionResult> CreateMessage(int userId, [FromBody] MessageForCreationDto messageForCreationDto) { // Getting the sender data so AutoMapper can do it's magic // Check the big next comment for details var sender = await _repo.GetUser(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetUser(messageForCreationDto.RecipientId); // Auto Mapper auto map data from memory to object if it cans. For instance, in this function it's mapping the data in recipient // to the messageToReturn automatically without us asking it for that. It just sees that we have that info in memory, so why not // map it? Now see the example in ep 169 to see that we needed at this point to get the photo of the sender to display in chat // and to do so, we will just get the sender info like we are getting the recipient info and AutoMapper will do its magice! if (recipient == null) { return(BadRequest("Couldn't find user")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); }
public async Task <IActionResult> CreateMessage(int userId, [FromBody] MessageForCreationDto messageForCreationDto) { // Get the sender beucae we ned autoMapper to map the sender info later. var sender = await _repo.GetUser(userId, false); // Compare that the id the user wants to update matches the id that was passed in the token. if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // Set the sender id to be the authorized user. messageForCreationDto.SenderId = userId; // Check if the user this user is trying to send this message to exists var recipient = await _repo.GetUser(messageForCreationDto.RecipientId, false); if (recipient == null) { return(BadRequest("Could not find user")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { // Convert the message back into a DTO. Need to do this inside the if statement so that we get the ID after the message has been craeted. var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } throw new Exception("Creating the message failed on save"); // return BadRequest("Could not save message"); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repository.GetUser(userId); // check if the user that is logged in is attempting to update his profile via HttpPut(id) if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repository.GetUser(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } var message = _mapper.Map <Message>(messageForCreationDto); _repository.Add(message); // persist to the db if (await _repository.SaveAll()) { // automapper will map the properties from the recipient and sender entity into the // MessageToReturnDto automatically even though they are not implictlly indicated to // be mapped var messageToReturn = _mapper.Map <MessageToReturnDto>(message); return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn)); } throw new AutoMapperConfigurationException("Creating the message failed on save"); }
public async Task <IActionResult> PostMessages(Guid userUniqueId, MessageForCreationDto message) { var senderId = await _repo.GetUser(userUniqueId); var claim = User.FindFirst(ClaimTypes.NameIdentifier).Value; if (userUniqueId.ToString() != claim) { return(Unauthorized("Invalid user Access")); } message.SenderUniqueId = userUniqueId; var sender = await _repo.GetUser(message.SenderUniqueId); var recipent = await _repo.GetUser(message.RecipientUniqueId); if (recipent == null) { return(BadRequest("Could not find User")); } message.SenderId = sender.Id; message.RecipientId = recipent.Id; var messagepost = _mapper.Map <Messages>(message); _repo.Add(messagepost); if (await _repo.SaveAll()) { var returnMessage = _mapper.Map <MessageToReturnDTO>(messagepost); return(CreatedAtRoute("GetMessage", new{ UniqueId = message.UniqueId }, returnMessage)); } return(BadRequest("Unable to send message")); }