public async Task <IActionResult> AddImage(AddImageViewModel addImageViewModel) { if (!ModelState.IsValid) { return(View()); } // create an ImageForCreation instance var imageForCreation = new ImageForCreation() { Title = addImageViewModel.Title }; // take the first (only) file in the Files list var imageFile = addImageViewModel.Files.First(); if (imageFile.Length > 0) { using (var fileStream = imageFile.OpenReadStream()) using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); imageForCreation.Bytes = ms.ToArray(); } } // serialize it var serializedImageForCreation = JsonSerializer.Serialize(imageForCreation); var httpClient = _httpClientFactory.CreateClient("APIClient"); var request = new HttpRequestMessage( HttpMethod.Post, $"/api/images"); request.Content = new StringContent( serializedImageForCreation, System.Text.Encoding.Unicode, "application/json"); var response = await httpClient.SendAsync( request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); response.EnsureSuccessStatusCode(); return(RedirectToAction("Index")); }
public async Task <IActionResult> AddImage(AddImageViewModel addImageViewModel) { if (!ModelState.IsValid) { return(View()); } // create an ImageForCreation instance var imageForCreation = new ImageForCreation() { Title = addImageViewModel.Title }; // take the first (only) file in the Files list var imageFile = addImageViewModel.Files.First(); if (imageFile.Length > 0) { using (var fileStream = imageFile.OpenReadStream()) using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); imageForCreation.Bytes = ms.ToArray(); } } // serialize it var serializedImageForCreation = JsonConvert.SerializeObject(imageForCreation); // call the API var httpClient = await _imageGalleryHttpClient.GetClientAsync(); var response = await httpClient.PostAsync( $"api/images", new StringContent(serializedImageForCreation, System.Text.Encoding.Unicode, "application/json")) .ConfigureAwait(false); if (response.IsSuccessStatusCode) { return(RedirectToAction("Index")); } else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized || response.StatusCode == System.Net.HttpStatusCode.Forbidden) { return(Redirect("/Authorization/AccessDenied")); } throw new Exception($"A problem happened while calling the API: {response.ReasonPhrase}"); }
private async Task <StringContent> CreateUploadImageContent(string title, string imageFilePath) { output.WriteLine($"Current Directory: {Directory.GetCurrentDirectory()}"); var uploadData = new ImageForCreation { Title = title, Bytes = null, }; if (imageFilePath != null) { uploadData.Bytes = await File.ReadAllBytesAsync(imageFilePath); } var serializedImageForCreation = JsonConvert.SerializeObject(uploadData); return(new StringContent(serializedImageForCreation, Encoding.Unicode, JsonContentType)); }
public IActionResult PostImage([FromBody] ImageForCreation imageForCreation) { if (imageForCreation == null) { return(BadRequest()); } if (!ModelState.IsValid) { // return 422 - Unprocessable Entity when validation fails return(new UnprocessableEntityObjectResult(ModelState)); } // Automapper maps only the Title in our configuration var imageEntity = Mapper.Map <Entities.Image>(imageForCreation); // Create an image from the passed-in bytes (Base64), and // set the filename on the image // get this environment's web root path (the path // from which static content, like an image, is served) var webRootPath = _env.WebRootPath; // create the filename string fileName = Guid.NewGuid().ToString() + ".jpg"; // the full file path var filePath = Path.Combine($"{webRootPath}/images/{fileName}"); // write bytes and auto-close stream System.IO.File.WriteAllBytes(filePath, imageForCreation.Bytes); // fill out the filename imageEntity.FileName = fileName; _repo.AddImage(imageEntity); if (!_repo.Save()) { throw new Exception($"Adding an image failed on save."); } var imageToReturn = Mapper.Map <Model.Image>(imageEntity); return(CreatedAtRoute("GetImage", new { id = imageToReturn.Id }, imageToReturn)); }
public async Task <IActionResult> AddImage(AddImageViewModel addImageViewModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // create an ImageForCreation instance var imageForCreation = new ImageForCreation { Title = addImageViewModel.Title, Category = addImageViewModel.Category, }; // take the first (only) file in the Files list var imageFile = addImageViewModel.File; if (imageFile.Length > 0) { using (var fileStream = imageFile.OpenReadStream()) using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); imageForCreation.Bytes = ms.ToArray(); } } // serialize it var serializedImageForCreation = JsonConvert.SerializeObject(imageForCreation); // call the API var httpClient = await _imageGalleryHttpClient.GetClient(); var response = await httpClient.PostAsync( InternalImagesRoute, new StringContent(serializedImageForCreation, Encoding.Unicode, "application/json")) .ConfigureAwait(false); if (response.IsSuccessStatusCode) { return(Ok()); } throw new Exception($"A problem happened while calling the API: {response.ReasonPhrase}"); }
public IActionResult CreateImage([FromBody] ImageForCreation imageForCreation) { // Automapper maps only the Title in our configuration var imageEntity = _mapper.Map <Entities.Image>(imageForCreation); var userId = User.Claims.FirstOrDefault(i => i.Type == "sub")?.Value; imageEntity.OwnerId = userId; // Create an image from the passed-in bytes (Base64), and // set the filename on the image // get this environment's web root path (the path // from which static content, like an image, is served) var webRootPath = _hostingEnvironment.WebRootPath; // create the filename string fileName = Guid.NewGuid().ToString() + ".jpg"; // the full file path var filePath = Path.Combine($"{webRootPath}/images/{fileName}"); // write bytes and auto-close stream System.IO.File.WriteAllBytes(filePath, imageForCreation.Bytes); // fill out the filename imageEntity.FileName = fileName; // ownerId should be set - can't save image in starter solution, will // be fixed during the course //imageEntity.OwnerId = ...; // add and save. _galleryRepository.AddImage(imageEntity); _galleryRepository.Save(); var imageToReturn = _mapper.Map <Image>(imageEntity); return(CreatedAtRoute("GetImage", new { id = imageToReturn.Id }, imageToReturn)); }
public async Task <IActionResult> AddImage(AddImageViewModel addImageViewModel) { if (ModelState.IsValid == false) { return(View()); } // create an ImageForCreation instance var imageForCreation = new ImageForCreation { Title = addImageViewModel.Title, }; // take the first (only) file in the Files list var imageFile = addImageViewModel.Files.First(); if (imageFile.Length > 0) { using (var fileStrem = imageFile.OpenReadStream()) using (var ms = new MemoryStream()) { await fileStrem.CopyToAsync(ms); imageForCreation.Bytes = ms.ToArray(); } } // serialize it var serializedImageForCreation = JsonConvert.SerializeObject(imageForCreation); // call the API var httpClient = imageGalleryHttpClient.GetClient(); var content = new StringContent(serializedImageForCreation, Encoding.Unicode, ApplicationJsonMediaType); var response = await httpClient.PostAsync("api/images", content); if (response.IsSuccessStatusCode) { return(RedirectToAction("Index")); } throw new Exception($"A problem happend while calling the API: {response.ReasonPhrase}"); }
public IActionResult CreateImage([FromBody] ImageForCreation imageForCreation) { if (imageForCreation == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(new UnprocessableEntityObjectResult(ModelState)); } var imageEntity = Mapper.Map <Entities.Image>(imageForCreation); var webRootPath = _hostingEnvironment.WebRootPath; string fileName = Guid.NewGuid().ToString() + ".jpg"; var filePath = Path.Combine($"{webRootPath}/images/{fileName}"); System.IO.File.WriteAllBytes(filePath, imageForCreation.Bytes); imageEntity.FileName = fileName; var ownerId = User.Claims.FirstOrDefault(c => c.Type == "sub").Value; imageEntity.OwnerId = ownerId; _galleryRepository.AddImage(imageEntity); if (!_galleryRepository.Save()) { throw new Exception($"Adding an image failed on save."); } var imageToReturn = Mapper.Map <Image>(imageEntity); return(CreatedAtRoute("GetImage", new { id = imageToReturn.Id }, imageToReturn)); }
public IActionResult CreateImage([FromBody] ImageForCreation imageForCreation) { // Automapper maps only the Title in our configuration var imageEntity = _mapper.Map <Entities.Image>(imageForCreation); // Create an image from the passed-in bytes (Base64), and // set the filename on the image // get this environment's web root path (the path // from which static content, like an image, is served) var webRootPath = _hostingEnvironment.WebRootPath; // create the filename string fileName = Guid.NewGuid().ToString() + ".jpg"; // the full file path var filePath = Path.Combine($"{webRootPath}/images/{fileName}"); // write bytes and auto-close stream System.IO.File.WriteAllBytes(filePath, imageForCreation.Bytes); // fill out the filename imageEntity.FileName = fileName; //seems like we could create a custom controller class and hang this value off of it for all to use... var ownerId = User.Claims.FirstOrDefault(c => c.Type == "sub")?.Value; //a good reason to have DTOs separate from ViewModels...ownerId couldn't be spoofed imageEntity.OwnerId = ownerId; // add and save. _galleryRepository.AddImage(imageEntity); _galleryRepository.Save(); var imageToReturn = _mapper.Map <Image>(imageEntity); return(CreatedAtRoute("GetImage", new { id = imageToReturn.Id }, imageToReturn)); }
public async Task PostImageGalleryApi(TokenResponse token, ImageForCreation image, CancellationToken cancellation) { _httpClient.SetBearerToken(token.AccessToken); var serializedImageForCreation = JsonConvert.SerializeObject(image); await _httpClient.PostAsync( $"/api/images", new StringContent(serializedImageForCreation, System.Text.Encoding.Unicode, "application/json"), cancellation) .ContinueWith(r => { if (!r.Result.IsSuccessStatusCode) { Log.Error("{@Status} ImageGalleryCommand Post Error {@Image}", r.Result.StatusCode.ToString(), image.ToString()); } else { Log.Information("{@Status} ImageGalleryCommand Post Complete {@Image}", r.Result.StatusCode, image.ToString()); } }, cancellation); }
public async Task <IActionResult> AddImage(AddImageViewModel addImageViewModel) { if (!ModelState.IsValid) { return(View()); } // create an ImageForCreation instance var imageForCreation = new ImageForCreation() { Title = addImageViewModel.Title }; // take the first (only) file in the Files list var imageFile = addImageViewModel.Files.First(); if (imageFile.Length > 0) { using (var fileStream = imageFile.OpenReadStream()) using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); imageForCreation.Bytes = ms.ToArray(); } } // serialize it var serializedImageForCreation = JsonConvert.SerializeObject(imageForCreation); // call the API var httpClient = await _imageGalleryHttpClient.GetClient(); var response = await httpClient.PostAsync( $"api/images", new StringContent(serializedImageForCreation, System.Text.Encoding.Unicode, "application/json")) .ConfigureAwait(false); return(HandleApiResponse(response, () => RedirectToAction("Index"))); }
public IEnumerable <ImageForCreation> GetImages() { List <ImageForCreation> imageForCreations = new List <ImageForCreation>(); string appPath = Directory.GetCurrentDirectory(); string photoPath = @"../../../../../data/photos"; var filePath = Path.GetFullPath(Path.Combine(appPath, photoPath)); var images = new List <string> { "7444320646_fbc51d1c60_z.jpg", "7451503978_ce570a5471_z.jpg", "9982986024_0d2a4f9b20_z.jpg", "12553248663_e1abd372d1_z.jpg", "12845283103_8385e5a19d_z.jpg", "25340114767_6ee4be93f6_z.jpg" }; var imageList = images.Select(i => Path.Combine(filePath, i)); foreach (var fileName in imageList) { var imageForCreation = new ImageForCreation { Category = "Test Category", Title = "Test" }; using (var fileStream = new FileStream(fileName, FileMode.Open)) using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); imageForCreation.Bytes = ms.ToArray(); } imageForCreations.Add(imageForCreation); } return(imageForCreations); }
public async Task <IEnumerable <ImageForCreation> > GetImagesAsync(int maxImagesCount = 0) { var photoSearchOptions = new PhotoSearchOptions() { MachineTags = "machine_tags => nychalloffame:", Extras = PhotoSearchExtras.All, }; List <ImageForCreation> imageForCreations = new List <ImageForCreation>(); var photos = await _searchService.SearchPhotosAsync(photoSearchOptions); var list = maxImagesCount == 0 ? photos : photos.Take(maxImagesCount); foreach (var photo in list) { var image = new ImageForCreation { Title = photo.Title, Category = "Test", }; var photoUrl = photo.Medium640Url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(photoUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream inputStream = response.GetResponseStream()) { using (var ms = new MemoryStream()) { inputStream.CopyTo(ms); image.Bytes = ms.ToArray(); } } imageForCreations.Add(image); } return(imageForCreations); }
/// <summary> /// Image Gallery API - Post Message /// </summary> /// <param name="client"></param> /// <param name="image"></param> /// <param name="apiUri"></param> /// <param name="waitForPostComplete"></param> /// <returns></returns> private static async Task <HttpResponseMessage> GoPostImageGalleryApi(HttpClient client, ImageForCreation image, string apiUri, bool waitForPostComplete) { Log.Information("ImageGalleryAPI Post {@Image}", image.ToString()); // TODO - Add Errors to be Handled var serializedImageForCreation = JsonConvert.SerializeObject(image); var response = await client.PostAsync( $"{apiUri}/api/images", new StringContent(serializedImageForCreation, System.Text.Encoding.Unicode, "application/json")) .ConfigureAwait(waitForPostComplete); // TODO - Log Transaction Time/Sucess Message if (waitForPostComplete) { Log.Information("{@Status} Post Complete {@Image}", response.StatusCode, image.ToString()); } return(response); }
/// <summary> /// Image Gallery API - Post Message /// </summary> /// <param name="client"></param> /// <param name="policy"></param> /// <param name="image"></param> /// <param name="apiUri"></param> /// <param name="waitForPostComplete"></param> /// <param name="cancellation"></param> /// <returns></returns> private static async Task PostImageGalleryApi(HttpClient client, RetryPolicy policy, ImageForCreation image, string apiUri, bool waitForPostComplete, CancellationToken cancellation) { Log.Verbose("ImageGalleryAPI Post {@Image}| {FileSize}", image.ToString(), image.Bytes.Length); try { var serializedImageForCreation = JsonConvert.SerializeObject(image); // TODO - Log Transaction Time/Sucess Message await policy.ExecuteAsync(async token => await client.PostAsync( $"{apiUri}/api/images", new StringContent(serializedImageForCreation, System.Text.Encoding.Unicode, "application/json"), cancellation) .ConfigureAwait(waitForPostComplete), cancellation).ContinueWith(r => { if (!r.Result.IsSuccessStatusCode) { Log.Error("{@Status} ImageGalleryAPI Post Error {@Image}", r.Result.StatusCode.ToString(), image.ToString()); } else { Log.Information("{@Status} ImageGalleryAPI Post Complete {@Image}", r.Result.StatusCode, image.ToString()); } r.Result.Dispose(); }, cancellation); } catch (JsonSerializationException ex) { Log.Error(ex, "ImageGalleryAPI Post JSON Exception: {ex}", ex.InnerException?.Message ?? ex.Message); } catch (HttpRequestException ex) { Log.Error(ex, "ImageGalleryAPI Post HTTP Exception: {ex}", ex.InnerException?.Message ?? ex.Message); } catch (Exception ex) { Log.Error(ex, "ImageGalleryAPI Post General Exception: {ex}", ex.InnerException?.Message ?? ex.Message); } }
public void InsertImage(ImageForCreation value) { throw new NotImplementedException(); }