public async Task ShouldReturnBadRequestResult_ForInvalidApiVersionAndIncludeHateoas_AsXml(string invalidApiVersion) { await Task.Run(async() => { using (var testAppConfiguration = new AppConfigurationMock(@"{ ""LatestApiVersion"": 1 }")) { // ARRANGE var headerValidationInstance = new HeaderValidation(null, testAppConfiguration.Instance); var httpContextMock = new DefaultHttpContext(); httpContextMock.Request.Headers.Add("Content-Type", "application/xml"); httpContextMock.Request.Headers.Add("ApiVersion", invalidApiVersion); httpContextMock.Request.Headers.Add("IncludeHateoas", invalidApiVersion); // The Response.Body stream in DefaultHttpContext is Stream.Null, which is a stream that ignores all reads/writes. // We need to set the Stream ourself. httpContextMock.Response.Body = new MemoryStream(); // ACT await headerValidationInstance.Invoke(httpContextMock); // ASSERT // After having written to the stream, we have to set the pointer to the beginning of the stream, or the stream is null httpContextMock.Response.Body.Seek(0, SeekOrigin.Begin); // Only now the stream can be read! var reader = new StreamReader(httpContextMock.Response.Body); string responseBody = reader.ReadToEnd(); var actualResponse = responseBody.MinifyXml().PrettifyXml(); var expectedResponse = @" <headers> <value>The header 'IncludeHateoas' can only take a value of '0' (false) or '1' (true)!</value> <value>The header 'api-version' can only take an integer value of greater than or equal to '1'. The latest supported version is 1</value> </headers> ".MinifyXml().PrettifyXml(); Assert.AreEqual(actualResponse, expectedResponse); Assert.AreEqual(httpContextMock.Response.StatusCode, 400); } }); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage httpRequestMessage, ILogger log) { log.LogInformation($"ImageConverterFunction :HTTP trigger function processed request at : { DateTime.Now}"); //Binding file content from httpRequestMessage var fileContent = httpRequestMessage.Content; string jsonContent = fileContent.ReadAsStringAsync().Result; //Get headers from httpRequestMessage var headers = httpRequestMessage.Headers; var jsonToReturn = string.Empty; string errormessage = string.Empty; HeaderModel headerModel = new HeaderModel(); try { //Validating headers from httprequestMessage if (HeaderValidation.ValidateHeader(headers, ref errormessage)) { headerModel.FileExtension = headers.GetValues(Constants.FILE_EXTENSION).First(); headerModel.FileType = headers.GetValues(Constants.FILE_TYPE).First(); log.LogInformation($"HeaderValidation success for File extension and FileType"); } else { //Header values has empty or null return badrequest response log.LogInformation($"HeaderValidation Failure for File extension and FileType :{errormessage}"); return(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent($"{errormessage}") }); } #region ImageToThumbnail //Converting Image file to Thumbnail image if (headerModel.FileExtension == Constants.PNG || headerModel.FileExtension == Constants.JPEG) { try { //Validating Image specific headers if (HeaderValidation.ValidateImageHeader(headers, ref errormessage)) { headerModel.ThumnailImageHeight = headers.GetValues(Constants.THUMBNAIL_HEIGHT).First(); headerModel.ThumnailImageWidth = headers.GetValues(Constants.THUMBNAIL_WIDTH).First(); headerModel.InlineImageHeight = headers.GetValues(Constants.INLINE_HEIGHT).First(); headerModel.InlineImageWidth = headers.GetValues(Constants.INLINE_WIDTH).First(); log.LogError($"HeaderValidation Success for Image to thumbnail conversion"); } else { //Header values has empty or null return badrequest response log.LogInformation($"HeaderValidation Failure in Image to thumbnail conversion: {errormessage}"); return(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent($"{ errormessage }", Encoding.UTF8, Constants.JSON) }); } //Convert file content to memorystream var memoryStream = new MemoryStream(Convert.FromBase64String(jsonContent)); var imageObj = new { thumbnail = ConvertToThumbnail(memoryStream, Convert.ToInt32(headerModel.ThumnailImageHeight), Convert.ToInt32(headerModel.ThumnailImageWidth), log), inline = ConvertToThumbnail(memoryStream, Convert.ToInt32(headerModel.InlineImageHeight), Convert.ToInt32(headerModel.InlineImageWidth), log) }; jsonToReturn = JsonConvert.SerializeObject(imageObj); } catch (Exception ex) { log.LogError($"Exception occurred in Image file conversion to thumbnail, Error : {ex.Message},Details:{ex.InnerException}"); return(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ex.Message, Encoding.UTF8, Constants.JSON) }); } } #endregion #region PDFToThumbnail //Converting Pdf first page to Thumbnail image if (headerModel.FileExtension == Constants.PDF) { try { //To include license Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("Aspose.Pdf.lic"); log.LogInformation("Aspose SetLicense Success"); ImageFormat format = GetImageFormat(headerModel.FileType, log); PdfConverter pdfConverter = new PdfConverter(); //Validating pdf file specific headers if (HeaderValidation.ValidatePdfFileHeader(headers, ref errormessage)) { headerModel.Height = headers.GetValues(Constants.HEIGHT).First(); headerModel.Width = headers.GetValues(Constants.WIDTH).First(); log.LogInformation($"HeaderValidation Success for PDF to thumbnail conversion"); } else { //Header values has empty or null return badrequest response log.LogError($"HeaderValidation Failure for PDF to thumbnail conversion : {errormessage}"); return(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent($"{errormessage}", Encoding.UTF8, Constants.JSON) }); } var streamContent = httpRequestMessage.Content.ReadAsStreamAsync(); pdfConverter.BindPdf(streamContent.Result); //To convert first page of PDF pdfConverter.StartPage = 1; pdfConverter.EndPage = 1; pdfConverter.Resolution = new Aspose.Pdf.Devices.Resolution(100); pdfConverter.DoConvert(); MemoryStream imageStream = new MemoryStream(); while (pdfConverter.HasNextImage()) { // Save the image in the given image Format pdfConverter.GetNextImage(imageStream, format); // Set the stream position to the beginning of the stream imageStream.Position = 0; } var imageObj = new { content = ConvertToThumbnail(imageStream, Convert.ToInt32(headerModel.Width), Convert.ToInt32(headerModel.Height), log), contentType = "image/" + headerModel.FileType }; jsonToReturn = JsonConvert.SerializeObject(imageObj); pdfConverter.Close(); imageStream.Close(); } catch (Exception ex) { log.LogError($"Exception occurred in pdf file conversion to thumbnail,Error : {ex.Message},Details:{ex.InnerException}"); return(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ex.Message, Encoding.UTF8, Constants.JSON) }); } } #endregion log.LogInformation("ImageConverterFunction successfully processed."); return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(jsonToReturn, Encoding.UTF8, Constants.JSON) }); } catch (Exception ex) { log.LogError($"Exception occurred in ImageConverterFunction,Error: { ex.Message},Details: { ex.InnerException}"); return(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ex.Message, Encoding.UTF8, Constants.JSON) }); } }