public List <PostImageModel> findImagesByPostId(int postId) { List <PostImageModel> result = new List <PostImageModel>(); List <Image> allImage = GetImagesByPostId(postId); PostImageModel image = null; foreach (Image m in allImage) { image = new PostImageModel(); image.id = m.id; image.url = m.url; image.thumbnailurl = m.thumbnailUrl; image.createdDate = m.createdDate.Value.ToString(AmsConstants.DateTimeFormat); image.postId = m.postId.Value; try { System.Drawing.Image img = System.Drawing.Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + image.thumbnailurl); image.width = img.Width; image.height = img.Height; } catch (Exception) { image.width = 0; image.height = 0; } result.Add(image); } return(result); }
public async Task ShouldCreateAndAddImage() { // Arrange using var scope = Factory.Services.CreateScope(); PostImageModel postImageModel = new PostImageModel { ContentType = "media/png", ImageData = new byte[0], ImageDescription = "image description", ImageTitle = "image title" }; var sut = new AddArticleImageHandler(unitOfWork, mediator, mapper, currentUserServiceMock.Object); // Act GetArticleModel sutResult = await sut.Handle(new AddArticleImageCommand(postImageModel, article.Id), new CancellationToken(false)); // Assert // Should return updated model. Assert.NotNull(sutResult); Assert.Equal(article.Id, sutResult.Id); // Should add references to image. Assert.True(0 < sutResult.AssociatedImageId); // Added image should be valid. Image image = await unitOfWork.Images.GetEntityAsync(sutResult.AssociatedImageId); Assert.NotNull(image); Assert.Equal(postImageModel.ImageTitle, image.ImageTitle); Assert.Equal(postImageModel.ImageData, image.ImageData); Assert.Equal(postImageModel.ContentType, image.ContentType); Assert.Equal(postImageModel.ImageDescription, image.ImageDescription); }
/// <summary> /// Sends image to ocr service /// </summary> /// <param name="model">Model that contains values if the request properties</param> /// <param name="callback">Action to be executed after response is received</param> public void SendImage(PostImageModel model, Action <string> callback) { Task task = taskFactory.StartNew(() => { string result = string.Empty; try { // Trys to save current model state ToXML(model); // Creating parts of the request to be sent IList <IFormPart> parts = new List <IFormPart>(); parts.Add(new FileFormPartModel("image", model.PicturePath, new Dictionary <string, string>() { { "Content-Type", GetContentType(model.PicturePath) } })); parts.Add(new StringFormPartModel("language", model.LanguageCode)); parts.Add(new StringFormPartModel("apikey", model.ApiKey)); // Creats communicator and sending request ServiceCommunicator communicator = new ServiceCommunicator(); ServiceResponse response = communicator.PostRequest(_ocrApiServiceUrl, parts, 10000); result = response.ToString(); } catch { } return(result); } ).ContinueWith(cTask => { if (callback != null) { callback(cTask.Result); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
/// <summary> /// Displays file browsing window /// </summary> /// <param name="model">Current form model</param> /// <returns>Path to the selected file</returns> public string BrowseFile(PostImageModel model) { string fileToOpen = string.Empty; using (OpenFileDialog fileDialog = new OpenFileDialog()) { //Sets initial browsing folder if (!string.IsNullOrEmpty(model.PicturePath)) { string directoryName = Path.GetDirectoryName(model.PicturePath); if (Directory.Exists(directoryName)) { fileDialog.InitialDirectory = directoryName; } } // Adds allowed file types filter if (_allowedFileTypes != null && _allowedFileTypes.Count() > 0) { fileDialog.Filter = BuildFileFilter(); } //Displays dialog if (fileDialog.ShowDialog() == DialogResult.OK) { fileToOpen = fileDialog.FileName; } } return(fileToOpen); }
public async Task <IActionResult> Register(UserRegisterViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } // Verify not logged in GetPrivateUserModel privateUser = await new GetAuthenticatedUserQuery().DefaultIfExceptionAsync(Mediator); if (privateUser != null && privateUser.Id > 0) { return(RedirectToAction("Login")); } // Regiser User registeredUser = await Mediator.Send(new RegisterUserCommand(viewModel.RegisterModel)); // Login var loginModel = new LoginModel { UserName = registeredUser.UserName, Password = viewModel.RegisterModel.Password }; await _userAuthService.LogInAsync(loginModel); // Attatch image if present var file = Request.Form.Files.FirstOrDefault(); if (file != null) { PostImageModel imageModel = _imageFileReader.ConvertImageFileToImageModel(file); await Mediator.Send(new AddUserImageCommand(imageModel, registeredUser.Id)); } return(RedirectToAction("Me")); }
/// <summary> /// Gets file path from model /// </summary> /// <param name="model">Current form model</param> /// <returns>Path from the current model or empty string if file does not exist or is of invalid type</returns> public string GetFilePath(PostImageModel model) { string pathValidationResult = ValidateFilePath(model); return(string.IsNullOrEmpty(pathValidationResult) ? model.PicturePath : string.Empty); }
public OcrApiServiceForm() { _formManager = new OcrApiServiceManager(); _formModel = _formManager.LoadLastRequest(); InitializeComponent(); SetControlsNames(); _apiCodeTextBox.Text = _formModel.ApiKey; _languageCodeTextBox.Text = _formModel.LanguageCode; _selectFileTextBox.Text = _formManager.GetFilePath(_formModel); }
private PostImageModel parseImageToModel(Image i) { PostImageModel imgModel = new PostImageModel(); imgModel.id = i.id; imgModel.originUrl = i.originalUrl; imgModel.thumbnailurl = i.thumbnailUrl; imgModel.url = i.url; imgModel.postId = i.postId.Value; return(imgModel); }
public IHttpActionResult UpdateImage(ImageModel model) { var res = new PostImageModel { Base64 = model.Image, ImageUrl = _urlProvider.ImageUrl, Path = HttpContext.Current.Server.MapPath("~/Uploads/Images"), }; _profileOperations.UpdateProfileImage(res, _currentUserProvider.CurrentUserId); return(Ok()); }
public virtual async Task <TblPostImages> PrepareTblPostImagesAsync(PostImageModel image) { var result = image.Adapt <TblPostImages>(); result.PostId = image.PostId; if (string.IsNullOrWhiteSpace(result.Alt)) { var post = await _postService.FindByIdAsync(image.PostId); result.Alt = post.GetLocalized(p => p.Title); } return(result); }
/// <summary> /// Validates file path from model /// </summary> /// <param name="model">Current form model</param> /// <returns> Error message if any or empty string</returns> public string ValidateFilePath(PostImageModel model) { if (string.IsNullOrEmpty(model.PicturePath) || !File.Exists(model.PicturePath)) { return(string.Format(ControlsResource.FILE_NOT_FOUND, model.PicturePath)); } if (!GetAllowedFileExtentions().Contains(Path.GetExtension(model.PicturePath))) { return(ControlsResource.INVALID_FILE); } return(string.Empty); }
private async Task CreateArticleImage(PostImageModel imageModel, Article article) { var imageToAdd = Mapper.Map <Image>(imageModel); imageToAdd.ArticleId = article.Id; await UnitOfWork.Images.AddEntityAsync(imageToAdd); // Add image to article article.AssociatedImage = imageToAdd; // Save UnitOfWork.SaveChanges(); }
public OcrApiServiceForm() { _formManager = new OcrApiServiceManager(); _formModel = _formManager.LoadLastRequest(); InitializeComponent(); _errorProvider.SetIconPadding(_selectFileTextBox, -20); // Sets control text from the resources SetControlsNames(); // Adds existing language codes to combobox _languageCodeComboBox.Items.AddRange(_formManager.GetCodes().ToArray()); // Fills form from model _apiCodeTextBox.Text = _formModel.ApiKey; _languageCodeComboBox.Text = _formModel.LanguageCode; _selectFileTextBox.Text = _formManager.GetFilePath(_formModel); }
/// <summary> /// Loads last saved request settings /// </summary> /// <returns>Model, created from saved settings or null</returns> public PostImageModel LoadLastRequest() { PostImageModel model = null; try { using (StreamReader streamReader = new StreamReader(_lastPostedRequest)) { model = _uiModelSerializer.Deserialize(streamReader) as PostImageModel; } } catch { } return(model ?? new PostImageModel()); }
public PostImageModel ConvertImageFileToImageModel(IFormFile file, string title, string description) { // Copy the image data to the image object PostImageModel img = new PostImageModel(); using MemoryStream ms = new MemoryStream(); file.CopyTo(ms); img.ImageData = ms.ToArray(); img.ContentType = file.ContentType; img.ImageTitle = title; img.ImageDescription = description; ms.Close(); return(img); }
public virtual async Task <PostImageModel> PreparePostImageModelAsync(TblPostImages image, int postId) { PostImageModel result; if (image == null) { result = new PostImageModel(); } else { result = image.Adapt <PostImageModel>(); result.PostId = image.PostId; await image.LoadAllLocalizedStringsToModelAsync(result); } result.PostId = postId; return(result); }
public async Task <ActionResult> Create(BoardCreateModel boardCreateModel) { if (!ModelState.IsValid) { return(View(boardCreateModel)); } GetBoardModel addedBoard = await Mediator.Send(new AddBoardCommand(boardCreateModel.Board)); var file = Request.Form.Files.FirstOrDefault(); if (file != null) { PostImageModel imageModel = _imageFileReader.ConvertImageFileToImageModel(file); await Mediator.Send(new AddBoardImageCommand(imageModel, addedBoard.Id)); } return(RedirectToAction("Details", new { id = addedBoard.Id })); }
private void ToXML(PostImageModel model) { try { string directory = Path.GetDirectoryName(_lastPostedRequest); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.Delete(_lastPostedRequest); using (StreamWriter streamWriter = new StreamWriter(_lastPostedRequest)) { _uiModelSerializer.Serialize(streamWriter, model); } } catch { } }
public virtual async Task <ActionResult> Editor(PostImageModel model, bool?saveAndContinue) { if (!ModelState.IsValid) { return(View(model)); } var record = await _postImageModelFactory.PrepareTblPostImagesAsync(model); var recordId = model.Id; try { if (model.Id == null) { //Add new record recordId = await _postImagesService.AddAsync(record); } else { //Edit record await _postImagesService.UpdateAsync(record); } await _localizedEntityService.SaveAllLocalizedStringsAsync(record, model); } catch (Exception e) { var errorCode = ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(new Error(e, System.Web.HttpContext.Current)); ModelState.AddModelError("", string.Format(_localizationService.GetResource("ErrorOnOperation"), e.Message, errorCode)); return(View(model)); } if (saveAndContinue != null && saveAndContinue.Value) { return(RedirectToAction("Editor", "PostImages", new { postId = record.PostId, id = recordId })); } return(Content(@"<script language='javascript' type='text/javascript'> window.close(); window.opener.refreshPostImagesGrid(); </script>")); }
public void UpdateProfileImage(PostImageModel model, int currUserId) { var bytes = Convert.FromBase64String(model.Base64); var filename = $"{Guid.NewGuid().ToString()}.png"; var exists = Directory.Exists(model.Path); if (!exists) { Directory.CreateDirectory(model.Path); } using (var imageFile = new FileStream(model.Path + "/" + filename, FileMode.Create)) { imageFile.Write(bytes, 0, bytes.Length); imageFile.Flush(); } _unitOfWork.Repository <UserEntity>().GetById(currUserId).Image = $"{model.ImageUrl}/{filename}"; _unitOfWork.SaveChanges(); }
public ActionResult GetPostDetail(int postId) { //Convert to post Mapping Post p = postService.findPostById(postId); MessageViewModels response = new MessageViewModels(); PostMapping pMapping = new PostMapping(); List <PostImageModel> listImage = new List <PostImageModel>(); if (p != null) { pMapping.Id = p.Id; pMapping.Body = p.Body != null?p.Body.Replace("\n", "<br/>") : ""; pMapping.CreateDate = p.CreateDate.GetValueOrDefault(); pMapping.EmbedCode = p.EmbedCode; pMapping.UserId = p.UserId; pMapping.username = p.User == null ? "Không xác định sở hữu" : p.User.Username; pMapping.userProfile = p.User == null || p.User.ProfileImage == null || p.User.ProfileImage.Equals("") ? "/Content/Images/defaultProfile.png" : p.User.ProfileImage; pMapping.userFullName = p.User == null ? "Không xác định" : p.User.Fullname; pMapping.houseName = p.User.House == null ? "Không xác định" : p.User.House.HouseName; pMapping.houseId = p.User.HouseId == null ? 0 : p.User.HouseId.Value; List <Image> listImages = imageService.GetImagesByPostId(p.Id); PostImageModel imgModel = null; foreach (var img in listImages) { imgModel = new PostImageModel(); imgModel.id = img.id; imgModel.postId = img.postId.Value; imgModel.thumbnailurl = img.thumbnailUrl; imgModel.userCropUrl = img.userCropUrl; imgModel.url = img.url; listImage.Add(imgModel); } pMapping.ListImages = listImage; response.Data = pMapping; } return(Json(response, JsonRequestBehavior.AllowGet)); }
public async Task <ActionResult> Create(ArticleCreateViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } // Create the article GetArticleModel model = await Mediator.Send(new AddArticleCommand(viewModel.Article)); // If image attatched var file = Request.Form.Files.FirstOrDefault(); if (file != null) { PostImageModel imageModel = _imageFileReader.ConvertImageFileToImageModel(file); // Add the image to the article await Mediator.Send(new AddArticleImageCommand(imageModel, model.Id)); } return(RedirectToAction("Details", new { model.Id })); }
public AddUserImageCommand(PostImageModel imageModel, int currentUserId) { ImageModel = imageModel; CurrentUserId = currentUserId; }
public AddBoardImageCommand(PostImageModel imageModel, int boardId) { ImageModel = imageModel; BoardId = boardId; }
private Image MapModelToImage(PostImageModel imageModel) { return(Mapper.Map <Image>(imageModel)); }
public void RemoveImage(PostImageModel model) { string rootFolder = HttpContext.Current.Server.MapPath($"~/Content/Posts/" + model.PostId.Value); PostManager.RemoveImage(model.PostId.Value, model.PostImageId.Value, rootFolder); }
public AddArticleImageCommand(PostImageModel imageModel, int articleId) { ImageModel = imageModel; ArticleId = articleId; }
public ActionResult Upload() { if (Request.Files?.Count > 0) { var file = Request.Files[0]; var fileName = $"{System.IO.Path.GetFileNameWithoutExtension(file.FileName)}.{PostImageModel.GenerateThumbprint()}{System.IO.Path.GetExtension(file.FileName)}"; file.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Uploads"), fileName)); return(Json(new PostImageModel() { location = $"/Uploads/{fileName}" })); } return(HttpNotFound()); }