Exemplo n.º 1
0
 public BoardMeetingsModel(ApiClient apiClient, IMapper mapper, IAzureSASTokenUrl azureSASTokenUrl,
                           IAzureBlob azureBlob, IFileValidate fileValidate, ILogger <BoardMeetingsModel> logger)
 {
     _apiClient        = apiClient;
     _mapper           = mapper;
     _azureSASTokenUrl = azureSASTokenUrl;
     _azureBlob        = azureBlob;
     _fileValidate     = fileValidate;
     _logger           = logger;
     //need to initialize an empty object because by default the property is null
     //within the view, when you try and access the objects underlying properties, razor will throw an error
     //because the property has not been initialized
     MeetingToCreateEdit = new BoardMeetingManipulationDto();
     FileUploaded        = new RequiredFileDto();
 }
Exemplo n.º 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));
        }