Example #1
0
        public async Task Add_InvalidMeetingMinute_Returns_BadRequest()
        {
            //Arrange
            MeetingMinuteInputDto x = null;

            //Act
            var result = await meetingMinutesController.CreateMeetingMinute(Guid.NewGuid(), x);

            //Assert
            Assert.IsType <BadRequestResult>(result.Result);
        }
Example #2
0
        public async Task <IActionResult> OnPostUploadMeetingMinuteAsync(CancellationToken cancellationToken, [FromForm] RequiredFileDto FileUploaded)
        {
            if (!ModelState.IsValid)
            {
                //need to manually add this due to a bug in the model binding process for .net core
                //see issue here https://github.com/JeremySkinner/FluentValidation/issues/1029
                ModelState.AddModelError("FileUploaded.FileToUpload",
                                         ModelState.Keys.Where(k => k == "FileToUpload").Select(k => ModelState[k].Errors[0].ErrorMessage).First());

                //set the pagemodel property to be the values submitted by the user
                //not doing this will cause all model state errors to be lost
                this.FileUploaded = FileUploaded;
                return(Partial("_UploadMeetingMinutePartial", this));
            }

            var baseAPIUrl = $"api/boardmeetings/{Id}";

            try
            {
                //call the api with a GET request
                //ensure to set the httpcompletion mode to response headers read
                //this allows the response to be read as soon as content starts arriving instead of having to wait
                //until the entire response is read
                //with this option, we can read the response content into a stream and deserialize it
                var response = await(await _apiClient.WithAuthorization()).GetAsync(baseAPIUrl,
                                                                                    HttpCompletionOption.ResponseHeadersRead, cancellationToken);

                //return the same page with an error message if the user is trying to call the API too many times
                if (response.StatusCode == HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(Partial("_UploadMeetingMinutePartial", this));
                }

                //ensure success status code else throw an exception
                response.EnsureSuccessStatusCode();

                //read the response content into a stream
                var streamContent = await response.Content.ReadAsStreamAsync();

                //deserialize the stream into an object (see StreamExtensions on how this is done)
                boardMeeting = streamContent.ReadAndDeserializeFromJson <BoardMeetingViewDto>();
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(Partial("_UploadMeetingMinutePartial", this));
            }

            //GetFileTypeExtension returns a tuple that is deconstructed into separate variables
            var(FileType, FileExtension) = _fileValidate.GetFileTypeExtension(FileUploaded.FileToUpload);

            try
            {
                //if meeting minute id is null, it does not exist so do a post request
                if (boardMeeting.MeetingMinuteId == null)
                {
                    baseAPIUrl = $"api/boardmeetings/{Id}/meetingminutes";

                    //generate the file name instead of letting the user provide one
                    FileName = $"MeetingMinute_{DateTime.Now.ToString("MM-dd-yyyy_HH-mm-ss")}{FileExtension}";

                    //set the MeetingMinute filename here as otherwise it will be null
                    //this property is generated by the server and not provided by the user
                    var meetingToCreate = new MeetingMinuteInputDto {
                        FileName = this.FileName
                    };

                    //get the response with authorization as the API endpoint requires an authenticated user
                    var response = await(await _apiClient.WithAuthorization()).PostAsJsonAsync <MeetingMinuteInputDto>(baseAPIUrl,
                                                                                                                       meetingToCreate, cancellationToken);

                    //return the same page with an error message if the user is trying to call the API too many times
                    if (response.StatusCode == HttpStatusCode.TooManyRequests)
                    {
                        TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                        return(Partial("_UploadMeetingMinutePartial", this));
                    }

                    //ensure success status code else throw an exception
                    response.EnsureSuccessStatusCode();
                }
                else
                {
                    //meeting minute already exists so just need to upload the new file
                    //no need to update anything as we will re-use the existing file name
                    FileName = boardMeeting.FileName;
                }
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(Partial("_UploadMeetingMinutePartial", this));
            }


            //MeetingMinute was created/updated successfully so can upload file to blob storage
            var blobFileToUpload = _azureBlob.GetAzureBlobFileReference(FileName, AzureBlobFolder);

            //set the content type of the blob file so that downloads suggest correct file type to save as
            blobFileToUpload.Properties.ContentType = FileType;

            //upload the file to Azure
            await _azureBlob.UploadAzureBlobFileAsync(FileUploaded.FileToUpload, blobFileToUpload);

            //if successful, return the partial view which will have the IsValid value set to true by default
            //this is because ajax is used to post the form rather than a submit button
            return(Partial("_UploadMeetingMinutePartial", this));
        }
        public async Task <ActionResult <MeetingMinuteViewDto> > CreateMeetingMinute([FromRoute] Guid boardMeetingId, [FromBody] MeetingMinuteInputDto meetingMinuteInputDto)
        {
            if (meetingMinuteInputDto == null)
            {
                return(BadRequest());
            }

            var boardMeeting = await _boardMeetingRepository.GetBoardMeetingAsync(boardMeetingId);

            if (boardMeeting == null)
            {
                return(NotFound());
            }

            if (boardMeeting.MeetingNotes != null)
            {
                return(StatusCode(409, new { Error = "A meeting minute already exists for this board meeting" }));
            }

            //model state validation is not required due to the [ApiController] attribute automatically returning UnprocessableEntity (see startup.cs)
            //when model binding fails

            //fetch the user id from the JWT via HttpContext. Then get the user from the repository. This is to ensure that an authorized user
            //is calling the API with a valid user id
            var user = await _userRepository.GetUserAsync(User.GetUserId());

            if (user == null)
            {
                return(BadRequest(new { Error = "The user was not found in the system. Please try again with an authorized and valid user." }));
            }

            var meetingMinuteToAdd = _mapper.Map <MeetingMinute>(meetingMinuteInputDto); //map EventInputDto to Event

            meetingMinuteToAdd.UserId = user.Id;                                         //set the user id as otherwise navigation property will be null
            await _meetingMinuteRepository.AddMeetingMinute(boardMeetingId, meetingMinuteToAdd);

            if (!await _meetingMinuteRepository.SaveChangesAsync())
            {
                throw new Exception($"Error saving Event {meetingMinuteToAdd.Id} to the database");
            }

            var meetingMinuteToReturn = _mapper.Map <MeetingMinuteViewDto>(meetingMinuteToAdd);

            return(CreatedAtRoute("GetMeetingMinute", new { boardMeetingId = boardMeetingId, id = meetingMinuteToAdd.Id }, meetingMinuteToReturn));
        }