public ActionResult Add(Organization org) { if (Request.Files.Count <= 0) { ModelState.AddModelError("ImageValidation", "Image seçilmedir"); } if (Request.Files[0].ContentLength <= 0) { ModelState.AddModelError("ImageValidation", "Image seçilmedir"); } if (!ModelState.IsValid) { return(View(org)); } Images image = new Images(); image.imageUrl = Request.Files[0].FileName; _imageRepository.Add(image); var imagePath = ConfigurationManager.AppSettings["ImagePath"] + "/" + image.Id + "_" + image.imageUrl; Request.Files[0].SaveAs(imagePath); org.MainImageId = image.Id; org.Organizer = ((User)Session["User"]).Id; _organizationRepository.Add(org); return(RedirectToAction("Index")); }
public bool AddShoes(ShoesAddViewModel shoesVM) { //Shoes shoes = _mapper.Map<Shoes>(shoesVM); Brand brand = _brandRepository.GetById(shoesVM.BrandId); if (brand != null) { Shoes shoes = new Shoes() { Name = shoesVM.Name, Brand = brand, Color = shoesVM.Color, IsAvaiable = true, Description = shoesVM.Description, Price = shoesVM.Price, Sex = shoesVM.Sex }; _shoesRepository.Add(shoes); foreach (var img in shoesVM.Images) { _imageRepository.Add(new Image() { IsShoes = true, Url = img, Description = shoes.Name + "'s image", OwnId = shoes.Id }); } return(true); } return(false); }
public void SLUpload() { //Get all Values from Request string filename = HttpContext.Request.QueryString["filename"].ToString(); int Mag_ID = int.Parse(HttpContext.Request.QueryString["Mag_id"].ToString()); string Mag_Issue = HttpContext.Request.QueryString["Mag_Issue"].ToString(); string Shoot = HttpContext.Request.QueryString["Shoot"].ToString(); DateTime ShootDate = DateTime.Parse(HttpContext.Request.QueryString["ShootDate"].ToString()); string keywords = HttpContext.Request.QueryString["keywords"].ToString(); string description = HttpContext.Request.QueryString["description"].ToString(); string photographer = HttpContext.Request.QueryString["photographer"].ToString(); //Save image as tempImage in "photos" folder string tempFileName = System.Guid.NewGuid().ToString("N") + ".jpg"; using (FileStream fs = System.IO.File.Create(HttpContext.Server.MapPath("~/photos/" + tempFileName))) { SaveFile(HttpContext.Request.InputStream, fs); } //Save image details to database tbl_Image newImage = new tbl_Image(); newImage.date_uploaded = DateTime.Now; newImage.magazine_id = Mag_ID; newImage.magazine_issue = Mag_Issue; newImage.shoot_description = Shoot; newImage.shoot_date = ShootDate; newImage.keywords = keywords; newImage.description = description; newImage.photographer = userdb.getUserbyUsername(photographer).id; newImage.date_updated = DateTime.Now; newImage.name = tempFileName; imagedb.Add(newImage); imagedb.Save(); //Create Thumbnail and Preview and Delete Temp string oldName = newImage.name; newImage.name = newImage.tbl_publication.name.Replace(' ', '_') + "_" + newImage.magazine_issue.Replace(' ', '_') + "_" + ((DateTime)newImage.shoot_date).ToString("dd_MMM_yyyy") + "_" + newImage.id.ToString() + ".jpg"; newImage.preview_location = "pv_" + newImage.name; newImage.thumb_location = "th_" + newImage.name; CreateThumbAndPreview("~/photos", oldName, newImage.name); DeleteCurrentFile("~/photos", oldName); imagedb.Save(); }
public async Task <decimal> GetDurationOfImageComputation(ImageTypeViewModelM imageViewModel) { var image = _imageFactoryCreation.FactoryCreate(imageViewModel); var computationType = _computationService.GetComputationType(image.Length, image.Width); var computer = _computerDefinitionService.GetComputerDefinition(); computer.ComputationType = computationType; await _imageRepository.Add(new Image(image.Length, image.Width)); return(_imageCalculationService.CalculateImage(computationType)); }
public async Task <IActionResult> CreateNew([FromForm] FileInputModel model) { await HttpContext.Session.LoadAsync(); string brandId = HttpContext.Session.GetString("brandId"); string username = HttpContext.Session.GetString("adminName"); string imageUrl = await PostImage(model.FileToUpload, brandId); Image image = new Image(); image.BrandId = brandId; image.ImageId = util.RandomString(5); image.ImageName = model.Name; image.ImageLink = imageUrl; image.Username = username; image.CreateDate = DateTime.Now; imageRepository.Add(image); if (await imageRepository.SaveChangesAsync() >= 0) { return(RedirectToAction("ShowAll")); } return(View()); }
public async Task <ObjectResult <ImageResponse> > Create(IFormFile file) { if (file?.Length > 0) { var ImageUrl = await UploadFile(file); var image = await _imageRepository.GetImageByUrl(ImageUrl); if (image != null) { return(new ObjectResult <ImageResponse> { Success = true, Object = _mapper.Map <ImageResponse>(image) }); } image = new Image(); image.ImageUrl = ImageUrl; _imageRepository.Add(image); if (await _imageRepository.SaveChangesAsync()) { return(new ObjectResult <ImageResponse> { Success = true, Object = _mapper.Map <ImageResponse>(image) }); } } return(new ObjectResult <ImageResponse> { Errors = new[] { "File couldn't be uploaded" } }); }
public async Task <CreateImageResponse> CreateImageAsync(Image image) { _imageRepository.Add(image); await _unitOfWork.CompleteAsync(); return(new CreateImageResponse(true, null, image)); }
public async Task CreateImageAsync(AddImageDto imageDto) { Image image = _mapper.Map <Image>(imageDto); _repository.Add(image); await _context.SaveChangesAsync(); }
public async Task <Guid> AddImageAsync(Image image, Stream imageStream) { if (image == null) { throw new ArgumentException(nameof(image)); } if (imageStream == null || imageStream.Length < 1) { throw new ValidationException("There is no image data."); } // Copy to byte array // Assume the original stream is handled by caller using (var ms = new MemoryStream()) { await imageStream.CopyToAsync(ms); image.Blob = ms.ToArray(); } image.Id = Guid.NewGuid(); // Ensure the user exists var user = await _userRepository.Get().Where(i => i.Id == image.UserId).FirstOrDefaultAsync(); if (user == null) { throw new ValidationException("The user with the specified UserId does not exist."); } _imageRepository.Add(image); await _imageRepository.SaveAsync(); return(image.Id); }
public ImageDTO AddImage(ImageDTO imageDTO) { if (!string.IsNullOrEmpty(imageDTO.ImageBase64Content)) { byte[] imageBytes = Convert.FromBase64String(imageDTO.ImageBase64Content); if (imageBytes.Length / 1024 > 2048) { throw new ArgumentInvalidException("图片大小不能超过2MB."); } imageDTO.HttpPath = Base64StringToImage(imageBytes, imageDTO.HttpPath); } var image = Aggregates.ImageFactory.CreateImage(imageDTO.Title, imageDTO.Description, imageDTO.HttpPath, imageDTO.CreatedBy); _imageRepository.Add(image); _dbUnitOfWork.Commit(); imageDTO.Id = image.Id; imageDTO.ImageBase64Content = string.Empty; imageDTO.CreatedOn = image.CreatedOn; return(imageDTO); }
public Image SaveImage(string authorId, IFormFile file, string title) { User author = _userRepository.GetById(authorId); string webRootPath = _hostingEnvironment.WebRootPath; string mediaUrlDirectory = Path.Combine("upload", authorId); string uploadPath = Path.Combine(webRootPath, mediaUrlDirectory); if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } string imageGuid = Guid.NewGuid().ToString(); string fileExtension = file.FileName.Split(".").Last(); string fileName = imageGuid + "." + fileExtension; string fullPath = Path.Combine(uploadPath, fileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } var mediaUrl = Path.Combine(mediaUrlDirectory, fileName); Image newImage = new Image { Id = imageGuid, Author = author, MediaUrl = mediaUrl, Title = title }; _imageRepository.Add(newImage); return(newImage); }
public ActionResult Upload(HttpPostedFileBase file, int id) { int projectId = id; if (file != null) { string renderedFileName = Path.GetRandomFileName(); string fileName = renderedFileName + Path.GetExtension(file.FileName); string filePath = Path.Combine(Server.MapPath(imagePath), fileName); file.SaveAs(filePath); string thumbnailName = renderedFileName + "_thumb.jpg"; string thumbnailPath = Path.Combine(Server.MapPath(imagePath), thumbnailName); FileHelper.SaveResizedImage(filePath, thumbnailPath, 150, 150); Images savedImage = new Images(); savedImage.ProjectId = projectId; savedImage.Name = fileName; savedImage.ThumbnailName = thumbnailName; imageRepository.Add(savedImage); } return(RedirectToAction("EditProject", new { controller = "Projects", action = "EditProject", projectId = id })); }
public async Task <Response <Guid> > UploadAsync(UploadImageRequest uploadRequest) { if (!_fileHelper.IsSupportedImageType(uploadRequest.Image.ContentType)) { return(Failure <Guid>("Unsupported image type")); } if (!_fileHelper.IsSupportedImageSize(uploadRequest.Image.Length)) { return(Failure <Guid>("Image is too large")); } var id = Guid.NewGuid(); var fileName = $"{id}_{FileName(uploadRequest.Image)}"; // database var image = new Image { Id = id, FileName = fileName, ContentType = uploadRequest.Image.ContentType, OwnerUsername = uploadRequest.Username }; _images.Add(image); await _unitOfWork.SaveChangesAsync(); // file var bytes = await GetFileBytes(uploadRequest.Image); await _fileHelper.SaveAsync(bytes, fileName); return(Success(id)); }
public ActionResult Edit(BrandDTO entity) { try { Brand brand = brandRepository.GetById(entity.BrandID); brand.BrandName = entity.BrandName; brand.Info = entity.Info; brand.Website = entity.Website; brand.Address.AddressID = entity.Address.AddressID; brand.Address.AddressTitle = entity.Address.AddressTitle; brand.Address.AddressStr = entity.Address.AddressStr; brand.Address.PostalCode = entity.Address.PostalCode; brand.Address.TownID = entity.Address.TownID; if (brand.Images.Count > 0 && entity.Images != null && entity.Images.Count > 0) { brand.Images.ToList()[0].ImagePath = entity.Images.ToList()[0].ImagePath; } else if (brand.Images.Count == 0 && entity.Images != null && entity.Images.Count > 0) { Image image = new Image(); image.ImagePath = entity.Images.ToList()[0].ImagePath; image.BrandID = brand.BrandID; imageRepository.Add(image); imageRepository.Save(); } brandRepository.Update(brand); brandRepository.Save(); return(Json(entity, JsonRequestBehavior.DenyGet)); } catch (Exception e) { return(Json(false, JsonRequestBehavior.DenyGet)); } }
public ActionResult Edit(CompanyInfoDTO entity) { try { CompanyInfo companyInfo = companyInfoRepository.GetById(entity.CompanyInfoID); companyInfo.CompanyName = entity.CompanyName; companyInfo.PhoneNumber = entity.PhoneNumber; companyInfo.Email = entity.Email; companyInfo.AboutUs = entity.AboutUs; companyInfo.Address.AddressStr = entity.Address.AddressStr; companyInfo.Address.AddressTitle = entity.Address.AddressTitle; companyInfo.Address.TownID = entity.Address.TownID; companyInfo.Address.PostalCode = entity.Address.PostalCode; if (companyInfo.LogoImages.Count > 0 && entity.LogoImages != null && entity.LogoImages.Count > 0) { companyInfo.LogoImages.ToList()[0].ImagePath = entity.LogoImages.ToList()[0].ImagePath; } else if (companyInfo.LogoImages.Count == 0 && entity.LogoImages != null && entity.LogoImages.Count > 0) { Image image = new Image(); image.ImagePath = entity.LogoImages.ToList()[0].ImagePath; image.CompanyInfoID = companyInfo.CompanyInfoID; imageRepository.Add(image); imageRepository.Save(); } companyInfoRepository.Update(companyInfo); companyInfoRepository.Save(); return(Json(entity, JsonRequestBehavior.DenyGet)); } catch (Exception e) { return(Json(false, JsonRequestBehavior.DenyGet)); } }
public void Add(Image image) { // if() image = UploadImageFile(image); _imageRepository.Add(image); _imageRepository.Save(); }
public async Task DownloadImagesAsync(IDateListProvider dateListProvider) { if (dateListProvider == null) { throw new ArgumentNullException(nameof(dateListProvider)); } var downloadTasks = new List <Task>(); foreach (DateTime day in dateListProvider.GetDates()) { var imageInfos = await _marsRoverApiClient.GetImageInfosAsync(day).ConfigureAwait(false); int imagesLeftForDay = imageInfos.Length; Console.WriteLine($"{imagesLeftForDay} images are vailable for the following day: {day:yyyy-MM-dd}"); foreach (var marsImageInfo in imageInfos) { var downloadTask = _marsRoverApiClient.DownloadImageAsync(marsImageInfo); downloadTask.ContinueWith(dt => { _imageRepository.Add(new ImageMetadata(day, marsImageInfo.RoverName, marsImageInfo.Name), dt.Result); Console.WriteLine($"Image downloaded: {marsImageInfo.RoverName}-{marsImageInfo.Name}, left for the day: {Interlocked.Decrement(ref imagesLeftForDay)}"); }); downloadTasks.Add(downloadTask); } } Task.WaitAll(downloadTasks.ToArray()); }
public Post Edit(Post post, IFormFile file) { if (file != null) { bool fileAdded = _fileRepository.Add(file); Image image = new Image { FileName = file.FileName, ContentType = file.ContentType, Timestamp = DateTime.UtcNow }; image = _imageRepository.Add(image); post.ImageId = image.ImageId; } post.Timestamp = DateTime.UtcNow; return(_postRepository.Edit(post)); }
public void Add(ImageViewModel imageViewModel) { Image image = MapFromViewModel(imageViewModel); image.UI = Guid.NewGuid(); _imagesRepository.Add(image); imageViewModel.ImageID = image.ImageID; }
public void Add(ApplicationImage image) { if (image == null) { throw new ArgumentNullException(nameof(image)); } repository.Add(image); }
public Image AddImage(Image image) { if (image == null) { return(null); } _imageRepository.Add(image); return(image); }
public ActionResult Add(IEnumerable <HttpPostedFileBase> files) { var basePath = Server.MapPath(repository.BasePath); var userDir = User.Identity.Name; var path = Path.Combine(basePath, userDir); files.ToList().ForEach(f => repository.Add(path, f)); return(RedirectToAction("Index")); }
public async Task <ImageDto> CreateImageAsync(AddImageDto addImageDto) { Image image = _mapper.Map <Image>(addImageDto); image.Id = _repository.Add(image); await _context.SaveChangesAsync(); return(_mapper.Map <ImageDto>(image)); }
public IActionResult Create([FromBody] Image value) { if (value == null) { return(BadRequest()); } _repository.Add(value); // return CreatedAtRoute("GetImages", new { id = value.ImageId }, value); return(new NoContentResult()); }
public async Task <CustomImage> Upload(IFormFile image, long articleId) { if (image == null) { return(null); } var physImg = await CreateUploadFileWithOutDbRecord(image); var res = new CustomImage() { ArticleId = articleId, Path = physImg, }; await _imageRepository.Add(res); return(res); }
public Image AddImage(FileInfo fileInfo) { var image = _imageRepository.Create(); image.AddFile(fileInfo, _fileRepository); _imageRepository.Add(image); return(image); }
private void ReceiveImage(object parameter) { var filePaths = (IEnumerable <string>)parameter; foreach (var file in filePaths) { _imageRepository.Add(file); } RaisePropertyChanged(nameof(IsContentAvailable)); }
public void createImage(Image obj) { try { ImageRepository.Add(obj); SaveChange(); } catch { } }
public async Task <ImageDTO> AddImage(ImageDTO image) { try { return((await imageRepo.Add(image.ToEntity())).toDto()); } catch (Exception e) { return(null); } }
private async Task PrepareImage(ProductUpdateRequestDto model, DbProduct create) { if (model.Image != null && model.Image.Id == null) { var dbModel = _mapper.Map <DbImage>(model.Image); dbModel.Buffer = Convert.FromBase64String(model.Image.Base64String); var dbImage = await _imageRepository.Add(dbModel); create.ImageId = dbImage.Id; } }
public IdeaSecuredModule(IIdeaRepository ideas, IUserRepository users, ISettingsRepository settings, IImageRepository imageRepository) : base("/idea") { _ideas = ideas; _settings = settings; _imageRepository = imageRepository; _users = users; this.RequiresAuthentication(); Get["/new"] = _ => { var m = Context.Model(string.Format("New Idea - {0}", _settings.Title)); m.Ideas = _ideas.GetAll(); m.Errors = false; if (Request.Query["validation"] == "failed") { m.Errors = true; } return View["Idea/New", m]; }; Get["/{id}/edit"] = parameters => { int id = parameters.id; var idea = _ideas.Get(id); if (idea == null) return View["404"]; if (idea.Author.UserName != Context.CurrentUser.UserName) return View["404"]; var m = Context.Model(string.Format(Strings.IdeaSecuredModule_EditIdea, idea.Title, _settings.Title)); m.PopularIdeas = _ideas.GetAll(); m.Idea = idea; m.StatusChoices = _settings.IdeaStatusChoices.Split(','); m.Errors = false; if (Request.Query["validation"] == "failed") { m.Errors = true; } return View["Idea/Edit", m]; }; // save result of edit to database Post["/{id}/edit"] = parameters => { int id = parameters.id; if (string.IsNullOrEmpty(Request.Form.Title) || string.IsNullOrEmpty(Request.Form.Description)) { return Response.AsRedirect(string.Format("/idea/{0}/edit?validation=failed", id)); } var idea = _ideas.Get(id); if (idea == null) return View["404"]; idea.Title = Request.Form.Title; idea.Description = Request.Form.Description; idea.Status = Request.Form.Status; //Add any images IEnumerable<string> keys = Context.Request.Form; var x = keys.Where(c => c.StartsWith("imageId")); var ids = x.Select(c => Context.Request.Form[c].ToString()).Cast<string>(); var images = ids.Select(y => _imageRepository.Get(Convert.ToInt32(y))); foreach (var i in images) { if (!idea.Images.Contains(i, i)) { idea.Images.Add(i); } } _ideas.Save(); return Response.AsRedirect(string.Format("/idea/{0}", idea.Id)); }; // save result of create to database Post["/new"] = _ => { if (string.IsNullOrEmpty(Request.Form.Title) || string.IsNullOrEmpty(Request.Form.Description)) { return Response.AsRedirect("/idea/new?validation=failed"); } var user = _users.FindBy(u => u.UserName == Context.CurrentUser.UserName).FirstOrDefault(); if (user == null) return Response.AsRedirect("/login"); var idea = new Idea { Author = user, Time = DateTime.UtcNow, Title = Request.Form.Title, Description = Request.Form.Description, Status = settings.IdeaStatusDefault }; IEnumerable<string> keys = Context.Request.Form; var parameters = keys.Where(c => c.StartsWith("imageId")); var ids = parameters.Select(c => Context.Request.Form[c].ToString()).Cast<string>(); var images = ids.Select(id => _imageRepository.Get(Convert.ToInt32(id))); idea.Images = images.ToList(); //i.Images = form.Cast<string>() // .Where(k => k.StartsWith("imageId")) // .Select(k => _imageRepository.Get(Convert.ToInt32(form[k]))) // .ToList(); //is there a way to do this using Nancy? if (idea.Votes.Any(u => u.UserId == user.Id)) idea.UserHasVoted = true; ideas.Add(idea); return Response.AsRedirect("/idea/" + idea.Id); }; // someone else votes for the idea Post["/{id}/vote"] = parameters => { var user = Context.GetCurrentUser(_users); if (user == null) return Response.AsRedirect("/login"); int ideaId = parameters.id; int votes = ideas.Vote(ideaId, user.Id, 1); return Response.AsJson(new { Status = "OK", NewVotes = votes }); }; // the user decides to repeal his vote Post["/{id}/unvote"] = parameters => { var user = Context.GetCurrentUser(_users); int votes = ideas.Unvote(parameters.id, user.Id); return Response.AsJson(new { Status = "OK", NewVotes = votes }); }; Post["/{id}/delete"] = parameters => { int id = parameters.id; ideas.Delete(id); ideas.Save(); // TODO: test return Response.AsJson(new { Status = "Error" }); }; // TODO: do we want unauthenticated users to be allowed to upload posts? Post["/uploadimage"] = parameters => { var user = Context.GetCurrentUser(_users); if (user == null) return Response.AsJson(new { status = "Error" }); var imageFile = Request.Files.FirstOrDefault(); if (imageFile == null) { return null; //TODO: handle error case } var image = new Image { Name = imageFile.Name }; var bytes = new byte[imageFile.Value.Length]; imageFile.Value.Read(bytes, 0, bytes.Length); image.ImageBits = bytes; imageRepository.Add(image); var status = new ImageFileStatus(image.Id, bytes.Length, image.Name); return Response.AsJson(new[] { status }).WithHeader("Vary", "Accept"); }; Delete["/deleteimage/{id}"] = parameters => { var user = Context.GetCurrentUser(_users); if (user == null) return Response.AsJson(new { status = "Error" }); imageRepository.Delete(parameters.id); return null; }; }