/// <summary> /// Creates a new image from the upload result /// </summary> /// <param name="uploadResult"></param> internal Image(ImageUploadResult uploadResult, int websiteId) { this._storageId = uploadResult.StorageId; this._source = uploadResult.Source; this._websiteId = websiteId; if (this._sizes == null) { this._sizes = new Dictionary<int, int>(); } // Only add the new size if it is different to any other size in there if (!this._sizes.ContainsKey(uploadResult.Width) || !this._sizes.ContainsValue(uploadResult.Height)) { this._sizes.Add(uploadResult.Width, uploadResult.Height); } }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto) { // Check if the user that passed the token is the actual user by the Id if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // Get the user from the inputted id var userFromRepo = await _repo.GetUser(userId); // Store the dto file data into a file var var file = photoForCreationDto.File; // Store the image upload response into a var var uploadResult = new ImageUploadResult(); // If there is actually data in the dto file prop if (file.Length > 0) { // Use a file stream reader using (var stream = file.OpenReadStream()) { // Set upload parameters for Cloudinary var uploadParams = new ImageUploadParams() { // Get file description data from Cloudinary for the file to be uploaded File = new FileDescription(file.Name, stream), // Transform the photo using specific parameters Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; // Upload the photo to cloudninary using the parameters above uploadResult = _cloudinary.Upload(uploadParams); } } // Set the photo creation dto url prop to the upload result uri photoForCreationDto.Url = uploadResult.Uri.ToString(); // Set the photo creation dto publicid prop to the upload publicid photoForCreationDto.PublicId = uploadResult.PublicId; // Map the photo for creation dto to the photo model var photo = _mapper.Map <Photo>(photoForCreationDto); // If the user has no photos that are set as main (no photos) if (!userFromRepo.Photos.Any(u => u.IsMain)) { // Set this photo to be the main photo photo.IsMain = true; } // Add the photo data to the post userFromRepo.Photos.Add(photo); // Attempt to save the upload if (await _repo.SaveAll()) { // Map the photo to the photo to return dto to modify the return data var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); // Return CreatedAtRoute using the GetPhoto route, user id and photo id prop, and the mapped photo to return return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn)); } // If the upload failed to save return(BadRequest("Could not add the photo.")); }
public async Task <string> UploadFile( Stream stream, string fileName, string fileType, int width, int height, string cropMode, string outputFormat) { Guard.WhenArgument( stream, GlobalConstants.StreamRequiredExceptionMessage).IsNull().Throw(); Guard.WhenArgument( fileName, GlobalConstants.FileNameRequiredExceptionMessage).IsNullOrWhiteSpace().Throw(); Guard.WhenArgument( fileType, GlobalConstants.FileTypeRequiredExceptionMessage).IsNullOrWhiteSpace().Throw(); Guard.WhenArgument( width, GlobalConstants.ImageWidthRequiredExceptionMessage).IsLessThanOrEqual(0).Throw(); Guard.WhenArgument( height, GlobalConstants.ImageHeightRequiredExceptionMessage).IsLessThanOrEqual(0).Throw(); if (!stream.CanRead) { throw new ArgumentException(GlobalConstants.StreamRequiredExceptionMessage); } if (width == 0) { width = DefaultWidth; } if (height == 0) { height = DefaultHeight; } if (string.IsNullOrWhiteSpace(cropMode)) { cropMode = DefaultCropMode; } if (string.IsNullOrWhiteSpace(outputFormat)) { outputFormat = DefaultOutputFormat; } var imageUploadParams = new ImageUploadParams { File = new FileDescription(fileName, stream), Transformation = new Transformation() .Width(width) .Height(height) .Crop(cropMode) .FetchFormat(outputFormat), PublicId = fileName }; ImageUploadResult result = null; try { result = await this.cloud.UploadAsync(imageUploadParams); } catch (Exception) { // Log stuff } return(result?.Uri?.AbsoluteUri); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto) { try { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.User.GetUser(userId, true); // Users can have only 2 photos if (userFromRepo.Photos.Count >= 2) { return(BadRequest("Vous ne pouvez télécharger que 2 photos.")); } var file = photoForCreationDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } if (uploadResult.Uri == null) { return(BadRequest("Impossible de communiquer avec votre compte en cloudinary!")); } photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreationDto); if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); _repo.User.UpdateUser(userFromRepo); await _repo.User.SaveAllAsync(); // Send Notifications string emailContent = $"Une nouvelle photo de {userFromRepo.FirstName} {userFromRepo.LastName} a été soumise pour approbation."; await SendNotificationsForAdmins(userFromRepo.Id, emailContent); var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } catch (Exception ex) { _logger.LogError($"Something went wrong inside AddPhotoForUser endpoint: {ex.Message}"); return(StatusCode(500, "Internal server error: " + ex.Message)); } }
public async Task <IActionResult> AddPhotoToSuit(int id, PhotoForCreateDto photoForCreate) { var editorRole = await isValidEditor(); if (editorRole == null) { return(Unauthorized()); } var fromDb = await _suitRepo.Find(x => x.SuitId == id); if (fromDb != null) { // assume all is well for starters var success = false; var file = photoForCreate.File; var uploadResult = new ImageUploadResult(); // did the user upload anything? SuitPhoto photo = null; if (file != null && file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams { File = new FileDescription(file.Name, stream), Folder = "suits", Transformation = new Transformation() .Width(180) .Height(180) .Crop("fill") // .Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } // if successfull if (!string.IsNullOrEmpty(uploadResult.PublicId)) { photoForCreate.Url = uploadResult.Uri.ToString(); photoForCreate.PublicId = uploadResult.PublicId; photoForCreate.InternalId = id; // // Use mapper to transfer map for updating photo = _mapper.Map <SuitPhoto>(photoForCreate); // set first upload as default if (!await _suitPhotoRepo.Any(x => x.SuitId == id)) { photo.IsDefault = true; } // on success then add to user _suitPhotoRepo.Add <SuitPhoto>(photo); success = await _suitPhotoRepo.SaveAll(); } } if (success) { var returnPhoto = _mapper.Map <PhotoForReturnDto>(photo); return(CreatedAtRoute("GetSuitPhoto", new { id = photo.Id }, returnPhoto)); } } return(BadRequest("Failed to complete add photo to suit")); }
private (string, string) GetUrlAndPublicId(ImageUploadResult uploadResult) { return(uploadResult.Url.ToString(), uploadResult.PublicId); }
// we give FromForm so that .Net Core a hint that the information is coming the form // otherwise we get input not valid error. public async Task <IActionResult> AddPhotoForUser(int userID, [FromForm] PhotoForCreationDTO photoForCreationDTO) { if (userID != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _datingRepo.GetUser(userID, true); var file = photoForCreationDTO.File; // result we get back from cloudinary var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) // Opens the request stream for reading the uploaded file. { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), // this is to transform photo square shape to round for eg Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } // Each media asset uploaded to Cloudinary is assigned an unique Public ID and is available for immediate delivery and transformation. // The upload method returns an instance of ImageUploadResult class that contains a set of properties // of the uploaded image, including the image URL and Public ID, which is what we are using below photoForCreationDTO.Url = uploadResult.Uri.ToString(); photoForCreationDTO.PublicID = uploadResult.PublicId; // map the photo to dto var photo = _mapper.Map <Photo>(photoForCreationDTO); // alternate to the above is Photo photo = new Photo(); // _mapper.Map(photoForCreationDTO, photo); // if this is the first photo and hence no main photo set for the user if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _datingRepo.SaveAll()) { var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); // returning location header with the location of the created results // CreatedAtRoute adds a Location header to the response. The Location header specifies the URI of the newly created to-do item. // for eg: http://localhost:5000/api/users/1/photos/11 after the photo with id 11 is uploaded return(CreatedAtRoute("GetPhoto", new { id = photo.ID }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> Post([FromForm] ProductModel data) { try { var server = _productService.CreateInstance(); if (server != null) { if (!User.Identity.IsAuthenticated) { return(Unauthorized()); } if (!User.IsInRole("Admin")) { return(Unauthorized()); } var user = await _userManager.GetUserAsync(User); var transaction = _productService.Transaction(server); if (data.Image == null) { return(BadRequest()); } var uploadResult = new ImageUploadResult(); using (var stream = data.Image.OpenReadStream()) { var uploadParams = new ImageUploadParams { File = new FileDescription(data.Image.Name, stream), Folder = "Products" }; uploadResult = _cloudinary.Upload(uploadParams); } var product = new Product { Description = data.Description, Name = data.Name, ImageId = uploadResult.PublicId, Image = uploadResult.SecureUrl.ToString(), Price = Convert.ToDecimal(data.Price), Quantity = int.Parse(data.Quantity), Availability = int.Parse(data.Quantity) > 0 ? true : false, Weight = Convert.ToDecimal(data.Weight), CreateUser = user.UserName, CreateDate = DateTime.Now }; try { List <string> categoryList = new List <string>(); categoryList.AddRange(data.CategoryId.SelectMany(c => c.Split(",")).ToList()); product.ProductsCategories = categoryList.Select(c => new ProductCategories { Categories_Id = int.Parse(c), Products_Id = 0 }).ToList(); var rValue = _productService.Update(product); var response = new { data = data }; transaction.Commit(); return(Ok()); } catch (Exception e) { transaction.Dispose(); _cloudinary.DeleteResources(ResourceType.Image, uploadResult.PublicId); var error = e.InnerException != null ? e.InnerException.Message : e.Message; var response = new { error = error }; return(StatusCode(512, response)); } } else { return(StatusCode(423)); } } catch (Exception e) { var error = e.InnerException != null ? e.InnerException.Message : e.Message; var response = new { error = error }; return(StatusCode(512, response)); } }
public IActionResult Add([FromForm] PostDTO model) { try { var currentUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value; var guid = Guid.NewGuid(); if (model.Photos.Count == 0) { return(StatusCode(397)); } if (model.Photos == null) { return(StatusCode(398)); } var images = new List <Image>(); foreach (var file in model.Photos) { var extention = Path.GetExtension(file.FileName); if (extention == ".jpg" || extention == ".png") { var uploadResult = new ImageUploadResult(); using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams { File = new FileDescription(file.Name, stream), }; uploadResult = _cloudinary.Upload(uploadParams); } images.Add(new Image { Id = Guid.NewGuid(), ImageUrls = uploadResult.Uri.ToString(), PostId = guid, PublicId = uploadResult.PublicId }); } if (extention == ".mp4") { var uploadvideoResult = new VideoUploadResult(); using (var stream = file.OpenReadStream()) { var uploadParams = new VideoUploadParams() { File = new FileDescription(file.Name, stream) }; uploadvideoResult = _cloudinary.Upload(uploadParams); } images.Add(new Image { Id = Guid.NewGuid(), ImageUrls = uploadvideoResult.Uri.ToString(), PostId = guid, PublicId = uploadvideoResult.PublicId }); } } _imageService.AddRange(images); if (model.Steps != null) { List <Step> steps = new List <Step>(); foreach (var step in model.Steps) { steps.Add(new Step { Id = Guid.NewGuid(), PostId = guid, Description = step }); } _stepService.AddRange(steps); } if (model.Ingredients != null) { List <Ingredients> ingredientses = new List <Ingredients>(); foreach (var ingredient in model.Ingredients) { ingredientses.Add(new Ingredients { Id = Guid.NewGuid(), PostId = guid, Ingredient = ingredient }); } _ingredientService.AddRange(ingredientses); } _postService.Add(new Post { Id = guid, Description = model.Description, UserId = Guid.Parse(currentUserId), PostDate = DateTime.Now, LikeCount = 0, Title = model.Title, StarGivenUserCount = 0, SumStar = 0, Star = 0 }); return(Ok("Success")); } catch (Exception e) { return(StatusCode(399)); } }
public async Task <IActionResult> EditGame([FromRoute] int?id) { if (!ModelState.IsValid) { GameViewModel.Developers = await _repo.GetDevelopers(); return(View(GameViewModel)); } if (id != GameViewModel.Game.Id) { SetMessage("danger", "Something went wrong"); return(RedirectToAction(nameof(Index))); } var gameFromRepo = await _repo.GetGame(id); if (gameFromRepo == null) { SetMessage("danger", "Not found"); return(RedirectToAction(nameof(Index))); } var devFromRepo = await _repo.GetDeveloper(GameViewModel.Game.DeveloperId); if (devFromRepo == null) { SetMessage("danger", "Invalid developer"); return(RedirectToAction(nameof(Index))); } var file = GameViewModel.GameImage; var uploadResult = new ImageUploadResult(); // if new image is uploaded if (file != null && file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream) }; uploadResult = _cloudinary.Upload(uploadParams); } if (uploadResult.Error == null) { if (gameFromRepo.PhotoId != null) { var deletionParams = new DeletionParams(gameFromRepo.PhotoId); var deletionResult = _cloudinary.Destroy(deletionParams); } gameFromRepo.PhotoId = uploadResult.PublicId; gameFromRepo.PhotoUrl = uploadResult.Uri.ToString(); } } gameFromRepo.Name = GameViewModel.Game.Name; gameFromRepo.Year = GameViewModel.Game.Year; gameFromRepo.Rating = GameViewModel.Game.Rating; gameFromRepo.DeveloperId = GameViewModel.Game.DeveloperId; if (await _repo.SaveAll()) { SetMessage("info", "Changes saved"); return(RedirectToAction(nameof(Index))); } SetMessage("danger", "Could not save changes to database"); return(RedirectToAction(nameof(Index))); }
public async Task <ActionResult> PostFileUploads([FromForm] FileUploadsCreate fileUploads) //[FromForm] { var file = fileUploads.File; var uploadResultImage = new ImageUploadResult(); var uploadResultRaw = new RawUploadResult(); string url; string publicId; if (file == null || file.Length == 0) { return(BadRequest("No file provided")); } if (file.Length > 400000) { return(BadRequest("File too big. Please resize it.")); } using (var stream = file.OpenReadStream()) { if (file.ContentType.Contains("image")) { var uploadParamsImage = new ImageUploadParams() { File = new FileDescription(file.Name, stream), // Name = "File", seems to work with images Transformation = new Transformation().Width(400), // this resizes the image maintaining the same aspect ratio }; uploadResultImage = _cloudinary.Upload(uploadParamsImage); if (uploadResultImage.Uri == null) { return(BadRequest("Could not upload file. Wrong file type.")); } url = uploadResultImage.Uri.ToString(); publicId = uploadResultImage.PublicId; } else { var uploadParams = new RawUploadParams() { File = new FileDescription(file.FileName, stream), // Name = "File", FileName includes file name inc extension }; uploadResultRaw = _cloudinary.Upload(uploadParams); if (uploadResultRaw.Uri == null) { return(BadRequest("Could not upload file. Wrong file type.")); } url = uploadResultRaw.Uri.ToString(); publicId = uploadResultRaw.PublicId; } }; var newFile = new FileUploads { URL = url, CaseId = fileUploads.CaseId, TimeStamp = DateTime.Now, PublicId = publicId, Description = fileUploads.Description }; try { _context.FileUploads.Add(newFile); await _context.SaveChangesAsync(); } catch { // error therefore should the uploaded file be deleted? return(StatusCode(StatusCodes.Status500InternalServerError)); } return(CreatedAtAction("GetFileUpload", new { id = newFile.Id }, newFile)); }
[HttpPost] // note that the paramter userId is already set in the main route config at the top of this file, so that's where the first arg is coming from public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto) { // the claim types on a user which contain the authorized user's id is stored as a string and it needs to be parsed to an into for comparison to the id in the url param if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(userId); var file = photoForCreationDto.File; // this variable is used to store the result we get bak from Cloudinary var uploadResult = new ImageUploadResult(); // check that there is something inside the file first: (Length is number of bytes) if (file.Length > 0) { // Read the file into memory - using is used here to dispose of the file in memory used in this filestream once the method is done //OpenReadStream reads the file into memory using (var stream = file.OpenReadStream()) { // create a Cloudinary compatible upload object using the stream read into memory to send to Cloudinary var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), // use the transformation to crop the image and focus on the users face if the file is too long Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); }; } //Now start populating the Dto with information from the upload result from Cloudinary photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; // map the dto into the photo model based on the new properties just added. the first arg passed in is the destination and the second arg passed into the method is the source var photo = _mapper.Map <Photo>(photoForCreationDto); // if the user has no photos then none are main - check this and if so, then make the first photo uploaded the main photo for the user if (!userFromRepo.Photos.Any(p => p.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _repo.SaveAll()) { //NOTE: the photo will not have an id generated by the db until after the save is complete, so it is mapped here inside the if on successful save. var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); // response from a post should return a CreatedAtRoute response which automatically does include a location header with the location of the created resource (the url to your api to get the photo - myapi.com/api/users/1/photos) // you can use this location to perform a get request to that endpoint // the first overload in this method is the route to get a photo - this is created up above in this class, // first parameter is you need to give the route a NAme to pass in which is done above on the route config //the second param or third overload is the id of the photo and core 3.0 also needs the userId //third param is the photo itself, use the dto to return the mapped props we want return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn)); } return(BadRequest("Could not update Photo.")); }
public override async Task Execute(Message message, TelegramBotClient botClient) { long chatId = message.Chat.Id; BotUser user; CreateMicroStickersRequest request; string url, result; Dictionary <string, string> query; HttpResponseMessage response; HttpClient client = new HttpClient(); StickerToResize stickerToResize; client = new HttpClient(); url = string.Format(AppSettings.Url, "api/1.0.0/users/") + chatId.ToString(); response = await client.GetAsync(url); result = await response.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject <BotUser>(result); url = string.Format(AppSettings.Url, "api/1.0.0/users/") + chatId.ToString() + "/requests"; response = await client.GetAsync(url); if (!response.IsSuccessStatusCode) { url = string.Format(AppSettings.Url, "api/1.0.0/micro-sticker-requests"); query = new Dictionary <string, string>() { ["userId"] = user.Id.ToString() }; await client.PostAsync(QueryHelpers.AddQueryString(url, query), null); user.CurentCommand = BotCommand.CreateMicroStickers; url = string.Format(AppSettings.Url, "api/1.0.0/users/") + chatId.ToString(); await client.PutAsync(url, new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json")); await botClient.SendTextMessageAsync(chatId, "Please input name of the future sticker pack.", parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); return; } result = await response.Content.ReadAsStringAsync(); request = JsonConvert.DeserializeObject <CreateMicroStickersRequest>(result); switch (request.Status) { case MicroStickersStatus.AwaitingName: string name = message.Text; request.Name = name; request.Status = MicroStickersStatus.AwaitingSticker; url = string.Format(AppSettings.Url, "api/1.0.0/micro-sticker-requests/") + user.Id; await client.PutAsync(url, new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json")); await botClient.SendTextMessageAsync(chatId, "Good. Now send me a sticker.", parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); break; case MicroStickersStatus.AwaitingSticker: Sticker updateSticker = message.Sticker; StickerSet stickerSet = await botClient.GetStickerSetAsync(updateSticker.SetName); List <string> stickerImages = new List <string>(); List <string> emojis = new List <string>(); foreach (var sticker in stickerSet.Stickers) { var file = await botClient.GetFileAsync(sticker.FileId); string baseUrl = string.Format("https://api.telegram.org/file/bot{0}/{1}", AppSettings.Key, file.FilePath); url = string.Format(AppSettings.Url, "api/1.0.0/sticker/resize"); stickerToResize = new StickerToResize() { Url = baseUrl, Width = _strickerWidth, Height = _stickerHeight }; response = await client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(stickerToResize), Encoding.UTF8, "application/json")); result = await response.Content.ReadAsStringAsync(); ImageUploadResult imageUrl = JsonConvert.DeserializeObject <ImageUploadResult>(result); stickerImages.Add(imageUrl.Url.ToString()); emojis.Add(sticker.Emoji); } int userId = message.From.Id; string stickerPackName = request.Name; string shortStickerPackName = stickerPackName.ToLower().Replace(' ', '_') + "_by_burnyaxa_bot"; await botClient.CreateNewStickerSetAsync(userId, shortStickerPackName, stickerPackName, stickerImages.First(), emojis.First()); stickerImages.RemoveAt(0); emojis.RemoveAt(0); if (stickerImages.Count() != 0 && emojis.Count() != 0) { var stickerData = stickerImages.Zip(emojis, (s, e) => new { Image = s, Emoji = e }); foreach (var element in stickerData) { await botClient.AddStickerToSetAsync(userId, shortStickerPackName, element.Image, element.Emoji); } } StickerSet newStickers = await botClient.GetStickerSetAsync(shortStickerPackName); await botClient.SendTextMessageAsync(chatId, "Enjoy your micro-stickers :)", parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); await botClient.SendStickerAsync(chatId, newStickers.Stickers.First().FileId); url = string.Format(AppSettings.Url, "api/1.0.0/micro-sticker-requests/") + user.Id; await client.DeleteAsync(url); user.CurentCommand = BotCommand.Start; url = string.Format(AppSettings.Url, "api/1.0.0/users/") + chatId.ToString(); await client.PutAsync(url, new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json")); break; } }
public async Task <IActionResult> AddPhotoForUser (int userId, [FromForm] PhotoForCreationDto photoForCreationDto) { // Check if the current User is the one that passed the token to the server // Trying to match passed id to what is in their token ... see authController line 79 // User = check the passed token and get info from it .. we are [Authorize] this request // if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // Call the repo method to return a single user from the repo <-> DB based on Id // User userFromRepo = await _repo.GetUser(userId); // call Dto instance that is being passed and get its File property (has photo) // IFormFile file = photoForCreationDto.File; //To hold the results we get back from Cloudinary. ImageUploadResult= Cloudinary class // var uploadResult = new ImageUploadResult(); if (file.Length > 0) { // read this file into memory then dispose whne done // using (var stream = file.OpenReadStream()) { // Populate the "uploadResult" from Cloudinary w/ the Photo from Client // IFormFile as file which we will read as a stream, get name tied to this object // Transform the Photo to meet our shape/size specs for the site // Use all of these as params which we use to initialize uploadresult // This is what we are going to pass to cloud storage // var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation() .Width(500).Height(500).Crop("fill").Gravity("face") }; // Calls method to upload to 3rd party storage + store in local variable // uploadResult = _cloudinary.Upload(uploadParams); } } //These are to populate Dto w/ results returned back from Cloudinay // photoForCreationDto.Url = uploadResult.Url.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; // map returned results from our Dto -> Photo object // Photo photo = _mapper.Map <Photo>(photoForCreationDto); if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } // Track changes to the User object which now has updated Photo // details that we are adding from Dto (has upload response + isMain) // userFromRepo.Photos.Add(photo); if (await _repo.SaveAll()) { // Convert updated Photo object to Dto because, we want the return // status code 201 also, include header info about this photo // Once saved the photo will have a DB generated Id // var phototoReturn = _mapper.Map <PhotoForReturnDto>(photo); // Show location header of created resource // string routeName = Name [httpGet{"{id}"}, Nme = "GetPhoto"] // object routeValues= new object with values (params) that are required // by this route to call the controler method // object value = The object being created and returned return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, phototoReturn)); } else { return(BadRequest("Could not add the Photo")); } }
public async Task <IActionResult> RegisterReel([FromForm] ReelForRegisterDto reelForRegisterDto) { var file = reelForRegisterDto.file; var uploadResult = new ImageUploadResult(); if (reelForRegisterDto.CMnf == null) { return(BadRequest("No manufacturer number ")); // pratestuoti paskui ar viskas ok, ne veliau bus ikelta } if (file != null) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(300).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } if (reelForRegisterDto.URL != null) { var uploadParams = new ImageUploadParams() { File = new FileDescription(@"data:image/png;base64," + reelForRegisterDto.URL), Transformation = new Transformation().Width(500).Height(300).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } reelForRegisterDto.PublicId = uploadResult.PublicId; var componentass = await _context.Componentass.FirstOrDefaultAsync(u => u.Mnf == reelForRegisterDto.CMnf); var ReelToCreate = new Reel { CMnf = reelForRegisterDto.CMnf, QTY = reelForRegisterDto.QTY, ComponentasId = componentass.Id, Location = "0" }; var CreateReel = await _repo.RegisterReel(ReelToCreate); var PhotoToCreate = new Photo2 { PublicId = reelForRegisterDto.PublicId, IsMain = true, Url = uploadResult.Uri.ToString(), ReelId = ReelToCreate.Id }; var createPhoto = await _repo.RegisterPhoto(PhotoToCreate); return(StatusCode(201)); }
public async Task <IActionResult> UploadPassport([FromForm] PhotoUploadViewModel uploadPhoto) { string id = User.FindFirst("id").Value; User user = await UserManager.FindByIdAsync(id); if (user == null) { return(Unauthorized()); } IFormFile file = uploadPhoto.File; UploadResult uploadResult = new ImageUploadResult(); if (file.Length <= 0) { return(BadRequest("The provided file appears to be void.")); } // Upload the file to cloudinary using (var stream = file.OpenReadStream()) { ImageUploadParams uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(413).Height(531). Crop("fill").Gravity("face") }; uploadResult = Cloudinary.Upload(uploadParams); } if (uploadResult.StatusCode != System.Net.HttpStatusCode.OK) { return(BadRequest("Failed to upload image.")); } uploadPhoto.Url = uploadResult.Uri.ToString(); uploadPhoto.PublicID = uploadResult.PublicId; var photo = Mapper.Map <Photo>(uploadPhoto); photo.Type = PhotoType.Passport; // Load the photo collection await UserDataContext.Entry(user).Collection(u => u.Photos).LoadAsync(); // Make sure there's only one passport in the photo collection. foreach (var resource in user.Photos. Where(p => p.Type == PhotoType.Passport && p.Active).ToList()) { resource.Active = false; } user.Photos.Add(photo); await UserManager.UpdateAsync(user); await UserDataContext.SaveChangesAsync(); var resultPhoto = Mapper.Map <PhotoViewModel>(photo); return(CreatedAtRoute(nameof(GetPhoto), new { id = photo.Id }, resultPhoto)); }
public IActionResult AddPhotoForFood(int foodid, [FromForm] PhotoCreateDto photoCreateDto) { try { var food = _wrapper.Food.GetFoodById(foodid); if (food == null) { return(BadRequest("Couldnt find food")); } //var currentUserId = 6;//int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); //var currentUserKitchenId = _wrapper.Kitchen.GetKitchenByUser(currentUserId).Id; //if (currentUserKitchenId != food.KitchenId) //{ // _logger.LogError($"Kullanıcının bu yemege erisimi yok"); // return Unauthorized(); //} var file = photoCreateDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams { File = new FileDescription(file.Name, stream), Folder = "food" }; uploadResult = _cloudinary.Upload(uploadParams); } } photoCreateDto.Url = uploadResult.Uri.ToString(); photoCreateDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoCreateDto); photo.Food = food; if (!food.Photos.Any(p => p.IsMain)) { photo.IsMain = true; } food.Photos.Add(photo); _wrapper.Save(); var photoToReturn = _mapper.Map <PhotoDto>(photo); _logger.LogInfo($"Fotograf bilgileri veritabanına kaydedildi"); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } catch (Exception ex) { _logger.LogError($"Fotograf yüklenirken bir hata meydana geldi : {ex.Message}"); return(StatusCode(500, "Internal server error")); } }
public async Task <IActionResult> Update([FromForm] ProductModel model) { var server = _productService.CreateInstance(); if (server != null) { if (!User.Identity.IsAuthenticated) { return(Unauthorized()); } if (!User.IsInRole("Admin")) { return(Unauthorized()); } var user = await _userManager.GetUserAsync(User); var transaction = _productService.Transaction(server); try { var product = _productService.FindById(model.Id); if (product == null) { return(NotFound()); } var uploadResult = new ImageUploadResult(); if (model.Image != null) { using (var stream = model.Image.OpenReadStream()) { _cloudinary.DeleteResources(ResourceType.Image, product.ImageId); var uploadParams = new ImageUploadParams { File = new FileDescription(model.Image.Name, stream), Folder = "Products" }; uploadResult = _cloudinary.Upload(uploadParams); } } product.Description = model.Description; product.ImageId = uploadResult.PublicId != null ? uploadResult.PublicId : product.ImageId; product.Image = uploadResult.SecureUrl != null?uploadResult.SecureUrl.ToString() : product.Image; product.Name = model.Name; product.Price = Convert.ToDecimal(model.Price); product.Quantity = int.Parse(model.Quantity); product.Availability = product.Quantity > 0 ? true : false; product.Weight = Convert.ToDecimal(model.Weight); product.UpdateUser = user.UserName; product.UpdateDate = DateTime.Now; var newProduct = _productService.Update(product); List <string> categoryList = new List <string>(); if (model.CategoryId[0] != null) { _productCategories.CreateInstance(instance: true, context: server); var pCList = _productCategories.GetAll(c => c.Products_Id == newProduct.Id); _productCategories.RemoveRange(pCList); categoryList.AddRange(model.CategoryId.SelectMany(c => c.Split(",")).ToList()); newProduct.ProductsCategories = categoryList.Select(c => new ProductCategories { Categories_Id = int.Parse(c), Products_Id = newProduct.Id }).ToList(); _productCategories.AddRange(newProduct.ProductsCategories); } transaction.Commit(); return(Ok()); } catch (Exception e) { transaction.Dispose(); var error = e.InnerException != null ? e.InnerException.Message : e.Message; var response = new { error = error }; return(StatusCode(512, response)); } } return(StatusCode(423)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { CreateCloudinary cloudinary = new CreateCloudinary(); ImageUploadResult cloudResult = null; if (model.displayPicture != null) { var filename = model.displayPicture.FileName; var filePathOriginal = Server.MapPath("/App_Data/"); string savedFileName = Path.Combine(filePathOriginal, filename); model.displayPicture.SaveAs(savedFileName); ImageUploadParams image = new ImageUploadParams { File = new FileDescription(savedFileName) }; cloudResult = cloudinary.Cloudinary.Upload(image); if (System.IO.File.Exists(savedFileName)) { System.IO.File.Delete(savedFileName); } } SocialMediaDBQuerys dbQuerys = new SocialMediaDBQuerys(); string slug = dbQuerys.GetSlug(model.Forename, model.Surname); string publicImgID; string imgFormat; if (cloudResult != null) { publicImgID = cloudResult.PublicId; imgFormat = cloudResult.Format; } else { publicImgID = "dk4ihkrrjvllglzsp9js"; imgFormat = "png"; } var user = new ApplicationUser { UserName = model.Email, Email = model.Email, BrithDate = model.BrithDate, Forename = model.Forename, Surname = model.Surname, DisplayPicture = publicImgID + "." + imgFormat, Slug = slug }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
private string GetUrl(ImageUploadResult uploadResult) { return(uploadResult.Url.ToString()); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto) { /* * we need to match the user attempting to update his profile matching the id which part of the token in the server */ if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(userId, userId == int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)); var file = photoForCreationDto.File; //uploadResult is storing the result we getting back from Cloudinary var uploadResult = new ImageUploadResult(); //if the file length we getting from the user is > 0 the we read it. if (file.Length > 0) { //stream read the file loaded into memory! using (var stream = file.OpenReadStream()) { //we provide Cloudinary params as an ImageUploadParams object! var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; //uploadResult is storing the result we getting back from Cloudinary uploadResult = _cloudinary.Upload(uploadParams); } } //fill in the info we got from Cloudinary response : url to photo in Cloudinary + publicId photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; //map the photoForCreationDto to Photo object for persistance. var photo = _mapper.Map <Photo>(photoForCreationDto); //photo.IsMain = !userFroRepo.Photos.Any(u => u.IsMain) //set main photo to true if the first photo if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _repo.SaveAll()) { var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); //we return to the user the CreatedAtRoute with the location header with the location of created result. //we have to provide the root to get an individual photo for the current user (the photo is stored in cloudinary!!!) return(CreatedAtRoute(/*string routename = */ "GetPhoto", /*routeValue= id of the photo*/ new { id = photo.Id }, /*objectValue = entity to return*/ photoToReturn)); } return(BadRequest("Could not add the photo")); }
public ActionResult AddPhotoForCity(int cityId, [FromForm] PhotoForCreationDto photoForCreationDto) { var city = _appRepository.GetCityById(cityId); // Data Templete if city is null if (city == null) { return(BadRequest("Could not find the city")); } // Find the current signed In User var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); // *** // If the user want to add a photo to a different user city // Everyone can add photo to his city if (currentUserId != city.UserId) { return(Unauthorized()); } // Reading File var file = photoForCreationDto.File; var uploadResult = new ImageUploadResult(); // there is a file if (file.Length > 0) { using (var stream = file.OpenReadStream()) { // uploading informations var uploadParams = new ImageUploadParams { File = new FileDescription(file.Name, stream) }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; // DataContext dbset we have Photo but we dont have photo type // Help>AutoMapper we create a mapping for photo to photoForCreationDto var photo = _mapper.Map <Photo>(photoForCreationDto); photo.City = city; // If there is no photo first photo is main if (!city.Photos.Any(p => p.IsMain)) { photo.IsMain = true; } city.Photos.Add(photo); // If photo is added successfully if (_appRepository.SaveAll()) { // Reverse mapping from PhotoForReturnDto to Photo var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto) { // as we are authorising we want to check the token - copy the authorisation frm UsersController if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(userId); var file = photoForCreationDto.File; // use the variable to store result we get back from cloudinary - comes from CloudinaryDotNet.Actions; var uploadResult = new ImageUploadResult(); // check if the file contains something if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), // Another thing we want to transform any image to a square image Transformation = new Transformation() .Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); // at this time we will get uploadResult from Cloudinary } } photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; // map the photoForCreationDto into our Photo var photo = _mapper.Map <Photo>(photoForCreationDto); // If this is first photo then set this as the main photo if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } // Add the photo to the repo userFromRepo.Photos.Add(photo); // save the repo if (await _repo.SaveAll()) { // If the save is successfull we want to return the photo object (photoToReturn) // when save is successfull the SqlLite will create an Id on the photo // map the photo to the PhotoForReturnDtop var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); // to return the photo object (photoToReturn), the createdAtRoute call is required // The CreatedAtRoute overload we are using takes 3 parameters: // 1. The name of the route to get the resource that has been created. // 2. The parameters needed to be passed to the route to get the resource (in this case the ID) // 3. The actual resource we want to return. // Parameters 1 and 2 allow the response to contain the route // and params needed to get the individual response in the header // and the third parameter is the photo we are returning. return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn)); } ; return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhoto(int hotelId, string photoType, int photoTypeID, [FromForm] PhotoForCreationDto photoDto) { if (photoDto == null) { return(BadRequest()); } photoDto.Description = GetDescription(photoType); photoDto.PhotoType = photoType; photoDto.PhotoTypeId = photoTypeID; var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var userFromRepo = await _hotelRepo.GetUser(currentUserId); if (userFromRepo == null) { return(BadRequest("Could not find user")); } // check if user belongs to hotel and get hotel if (userFromRepo.HotelId != hotelId) { return(Unauthorized()); } var hotelFromRepo = await _hotelRepo.GetHotel(hotelId, true); var file = photoDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } photoDto.Url = uploadResult.Uri.ToString(); photoDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoDto); photo.hotel = hotelFromRepo; if (!hotelFromRepo.Photos.Any(m => m.IsMain && (m.PhotoType == photoDto.PhotoType) && (m.PhotoTypeId == photoDto.PhotoTypeId))) { photo.IsMain = true; } hotelFromRepo.Photos.Add(photo); if (await _unitOfWork.CompleteAsync()) { var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <ActionResult> UploadRoomImage(RoomViewModel roomViewModel) { if (ModelState.IsValid) { // Check if uploadedFiles != null if (roomViewModel.Images != null && roomViewModel.Images.Count() > 0) { var roomImagesUploadModel = new RoomImagesUploadModel() { RoomId = roomViewModel.Id, Images = new List <byte[]>() }; foreach (HttpPostedFileBase file in roomViewModel.Images) { using (var reader = new BinaryReader(file.InputStream)) { roomImagesUploadModel.Images.Add(reader.ReadBytes(file.ContentLength)); } } // Set the Accept header for BSON. Client.DefaultRequestHeaders.Accept.Clear(); Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson")); // POST using the BSON formatter. MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter(); try { var response = await Client.PostAsync <RoomImagesUploadModel>("api/Image/Upload/", roomImagesUploadModel, bsonFormatter); if ((int)response.StatusCode == 200) { // Use BSON formatter to deserialize the response content MediaTypeFormatter[] formatters = new MediaTypeFormatter[] { new BsonMediaTypeFormatter() }; ImageUploadResult imageUploadResult = await response.Content.ReadAsAsync <ImageUploadResult>(formatters); for (int i = 0; i < roomViewModel.Images.Count(); i++) { // Create Dto and send to Database RoomImageDTO roomImageDTO = new RoomImageDTO() { Id = imageUploadResult.Id[i], RoomId = roomImagesUploadModel.RoomId }; roomImageService.Create(roomImageDTO); } TempData["ErrorMessage"] = "Images uploaded and a record has been creaded in database"; return(RedirectToAction("Edit", new { id = roomViewModel.Id.ToString() })); } else { TempData["ErrorMessage"] = "Bad responce, Status Code " + (int)response.StatusCode; return(RedirectToAction("Edit", new { id = roomViewModel.Id.ToString() })); } } catch { TempData["ErrorMessage"] = "Can't connect to API"; return(RedirectToAction("Edit", new { id = roomViewModel.Id.ToString() })); } // If response is Ok } else { TempData["ErrorMessage"] = "File is empty"; return(RedirectToAction("Edit", new { id = roomViewModel.Id.ToString() })); } } else { TempData["ErrorMessage"] = "Room model state is not valid"; return(RedirectToAction("Edit", new { id = roomViewModel.Id.ToString() })); } }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto) { // Compare the userID of the token to the one the user is attempting to upload to if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var file = photoForCreationDto.File; // This will be used to store the result from cloudinary var uploadResult = new ImageUploadResult(); if (file.Length > 0) { // Because this is a file stream we ahve to use using. // File.OpenReadStream will open a stream to read the file into memory using (var stream = file.OpenReadStream()) { // Create params for uploading the photo to Cloudinary var uploadParam = new ImageUploadParams() { // pass in the file anem and the stream of data File = new FileDescription(file.Name, stream), // transfomr the file in case it too long Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; // Upload the actual photo. uploadResult = _cloudinary.Upload(uploadParam); } } // Now that we've uploaded the photo we can get the URL and the PublicID of the photo and add it in to our photoForCreationDto photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; // Map the photoForCreation we recieved into a Photo object for uploading to database. var photo = _mapper.Map <Photo>(photoForCreationDto); // Get ther user becuaes we will need to use the user info. var userFromRepo = await _repo.GetUser(userId, true); // Check if the user has a main photo already, if they don't, set this new photo to be their main photo. if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _repo.SaveAll()) { // Now that the save is successfull our photo will have an ID generated by SQL. var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto) { //Using [Apicontroller] at the creation of the class doesn't allow netcore to identify //where the photoForCreationDto is coming, so we need to add [FromForm] on the parameter //so netcore can identify it is coming from the form //compares the id of the user in the context and the id passed on the httpput if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //gets user from the repo var userFromRepo = await _repo.GetUser(userId); var file = photoForCreationDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { //using for disposing memory once completed its use using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { //Transformation is used to crop an image, focusing on the face of the user, that might be very large File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreationDto); if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _repo.SaveAll()) { //Had to create new object photo, current photo has user as a navigation property which is not ok, //that is why had to make all steps on GetPhoto so we can map a different object //This is created inside the if given that the saveAll is the one that //would create the id for the object on SQL var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); //Need to provide the location of the object created (route) //Object route values like Id //Entity returning -> photo object //After NetCore 3.0, the second parameter needs all route parameters //so needed to add the userid... return(CreatedAtRoute("GetPhoto", new { id = photo.Id, userId = photo.UserId }, photoToReturn)); } return(BadRequest("could not add the photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForUploadDto photoForUploadDto) { var unauthorization = this.CheckIfLoggedInUserIsAuthorized(userId, "You are not logged in as the user you are trying to upload the photo for."); if (unauthorization != null) { return(unauthorization); } var currentUser = await this.UserService.GetUser(userId).ConfigureAwait(false); var file = photoForUploadDto.File; var uploadResult = new ImageUploadResult(); bool doesPhotoExist = file == null; if (doesPhotoExist) { return(this.BadRequest(new StatusCodeResultReturnObject(this.BadRequest(), "The photo to be uploaded was not found."))); } else { bool doesPhotoHaveData = file.Length > 0; if (doesPhotoHaveData) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation() .Width(500).Height(500).Crop("fill").Gravity(CloudinaryDotNet.Gravity.Face) }; uploadResult = this.Cloudinary.Upload(uploadParams); } } } photoForUploadDto.Url = uploadResult.Uri.ToString(); photoForUploadDto.PublicId = uploadResult.PublicId; var photo = this.Mapper.Map <Photo>(photoForUploadDto); bool AreNoneOfUserPhotosSetToMain = !currentUser.Photos.Any(u => u.IsMain); if (AreNoneOfUserPhotosSetToMain) { photo.IsMain = true; } currentUser.Photos.Add(photo); bool isDatabaseSaveSuccessful = await this.UserService.SaveAll().ConfigureAwait(false); if (isDatabaseSaveSuccessful) { var photoToReturn = this.Mapper.Map <PhotoForReturnDto>(photo); return(this.CreatedAtRoute("GetPhoto", new { userId, photo.Id }, photoToReturn)); } return(BadRequest(new StatusCodeResultReturnObject(this.BadRequest(), "Photo upload to server failed."))); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] UserPhotoForCreationDto userPhotoForCreationDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _recipeRepo.GetUser(userId); // Delete existing photo if exists var currentUserPhoto = userFromRepo.UserPhotos.FirstOrDefault(); if (currentUserPhoto != null) { if (currentUserPhoto.PublicId != null) { var deleteParams = new DeletionParams(currentUserPhoto.PublicId); var result = _cloudinary.Destroy(deleteParams); if (result.Result == "ok") { _recipeRepo.Delete(currentUserPhoto); } } if (currentUserPhoto.PublicId == null) { _recipeRepo.Delete(currentUserPhoto); } } // Adding new photo var file = userPhotoForCreationDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Folder = "RecipeApp/user_photos/", Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } userPhotoForCreationDto.Url = uploadResult.Url.ToString(); userPhotoForCreationDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <UserPhoto>(userPhotoForCreationDto); userFromRepo.UserPhotos.Add(photo); if (await _recipeRepo.SaveAll()) { var photoToReturn = _mapper.Map <UserPhotosForReturnDto>(photo); return(CreatedAtRoute("GetUserPhoto", new { userId = userId, id = photo.UserPhotoId }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // Считываем данные пользователя из базы данных var userFromRepo = await _repo.GetUser(userId); var file = photoForCreationDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { // Всегда, когда мы работаем с большими объёмами данных, что // часто происходит при использовании stream, следует использовать // using, чтобы данные были максимально быстро выгружены из // оперативной памяти using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation() .Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } // Сохраняем в базу данных информацию об изображении, которую // нам вернул сервис Cloudinary: публичный Url, публичный // идентификатор файла, и т.д. photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; // На основании полученных данных от Angular-приложения и от сервиса // Cloudinary, формируем объект типа Photo var photo = _mapper.Map <Photo>(photoForCreationDto); // Если у пользователя ещё не назначен основной файл, то назначаем // загруженный на сервис Cloudinary if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } // Сохраняем данные об изображении в базу данных userFromRepo.Photos.Add(photo); if (await _repo.SaveAll()) { // Метод CreatedAtRoute() генерирует код ответа HTTP Status 201, // который означает "Ресурс был успешно создан". Этот код ответа // отличается от 200 тем, что содержит поле "Location" - указывающее // на URL созданного документа. Чтобы корректно создать URL, // методу нужно знать фактическое имя обработчика адреса из // "Location", который указывается в первом параметре вызова // "GetPhoto". Второй параметр указывает на значение дополнительного // параметра обработчика GetPhoto(id). Третий параметр - объект, // который должен быть возвращён как JSON-Документ var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
/// <summary> /// Send a feedback to telemetry server. /// </summary> /// <param name="type">Feedback type.</param> /// <param name="title">Feedback title.</param> /// <param name="content">Feedback content.</param> /// <param name="contactInfo">Contact information (if available)</param> /// <param name="image">Image (optional)</param> /// <returns>An awaitable task.</returns> public static async Task SendfeedbackAsync(FeedbackType type, string title, string content, string contactInfo, ImageUploadResult image = null) { var currentVersion = $"{Package.Current.Id.Version.Major}." + $"{Package.Current.Id.Version.Minor}." + $"{Package.Current.Id.Version.Build}." + $"{Package.Current.Id.Version.Revision}" + $"_{Package.Current.Id.Architecture}"; var osVersion = ulong.Parse(AnalyticsInfo.VersionInfo.DeviceFamilyVersion); var osMajor = (osVersion & 0xFFFF000000000000L) >> 48; var osMinor = (osVersion & 0x0000FFFF00000000L) >> 32; var osBuild = (osVersion & 0x00000000FFFF0000L) >> 16; var osRev = osVersion & 0x000000000000FFFFL; var feedback = new Models.Feedback { Type = type, Title = title, Content = content, RequestId = Guid.NewGuid(), RequestTimeUtc = DateTime.UtcNow, Runtime = new RuntimeInfo { ApplicationVersion = currentVersion, CurrentLanguage = CultureInfo.CurrentCulture.Name, DeviceFamily = AnalyticsInfo.VersionInfo.DeviceFamily, OsReleaseVersion = $"{osMajor}.{osMinor}.{osBuild}.{osRev}" }, ContactInfo = contactInfo }; if (TelemetryHelper.OptinTelemetry) { // Track an event before getting info await TelemetryHelper.TraceEventAsync("Feedback", new Dictionary <string, string> { { "FeedbackId", feedback.RequestId.ToString() } }); feedback.TelemetryMetadata = new ApplicationInsightInfo { UniqueDeviceId = TelemetryHelper.DeviceId, UniqueInstrumentationId = TelemetryHelper.InstrumentationId, UniqueUserId = TelemetryHelper.UserId }; } if (image != null) { feedback.ImageId = image.ImageId; } // Serialize request var requestContent = JsonConvert.SerializeObject(feedback); // Send request using (var httpClient = new HttpClient()) { var uploadEndpoint = $"{RequestUrlPrefix}/api/Feedback"; var result = await httpClient.PostAsync(new Uri(uploadEndpoint), new HttpStringContent( requestContent, UnicodeEncoding.Utf8, JsonMimeType)); // Check if request is throttled. if (result.StatusCode == HttpStatusCode.TooManyRequests) { throw new RequestThrottledException(); } // For other scenarios, HTTP 200 is excepted else if (result.StatusCode != HttpStatusCode.Ok) { throw new FeedbackServerErrorException(); } } }