예제 #1
0
        public bool AddImage(int albumId, ImageFileData imageFileData, out string errorString)
        {
            IAlbumsDataManager albumsDataMan = managersFactory.CreateAlbumsManager();

            if (albumsDataMan == null)
            {
                errorString = "Failed retrieving AlbumsDataManager";
                return(false);
            }

            IImagesManager imagesMan = managersFactory.CreateImagesManager();

            if (imagesMan == null)
            {
                errorString = "Failed retrieving ImagesManager";
                return(false);
            }

            string url;

            if (!imagesMan.SaveImage(albumId, imageFileData, out url))
            {
                errorString = "Failed saving image";
                return(false);
            }

            errorString = "";
            return(true);
        }
예제 #2
0
        private string CreatePartImage(Rect puzzlePartRect)
        {
            // Load main image
            ImageFileData data = new ImageFileData();

            Bitmap imageBM = new Bitmap(Bitmap.FromFile(ImageData.URL));

            Bitmap puzzlePartBM = new Bitmap(puzzlePartRect.Width, puzzlePartRect.Height);

            for (int i = 0; i < puzzlePartRect.Width; i++)
            {
                for (int j = 0; j < puzzlePartRect.Height; j++)
                {
                    puzzlePartBM.SetPixel(i, j, imageBM.GetPixel(puzzlePartRect.MinX + i, puzzlePartRect.MinY + j));
                }
            }

            ManagersFactory factory       = ManagersFactory.Create();
            IImagesManager  imagesManager = factory.CreateImagesManager();
            string          URL;

            imagesManager.SaveImage(AlbumId, puzzlePartBM, out URL);

            return(URL);
        }
예제 #3
0
        public async Task <IActionResult> AddPost([FromForm] UserPostsWithPostToAdd post)
        {
            try
            {
                if (post.NewPost != null)
                {
                    string imagePath = null, fullImagePath = null;
                    if (post.NewPost.Picture != null)
                    {
                        (imagePath, fullImagePath) = await _imagesManager.SaveImage(post.NewPost.Picture);
                    }

                    await _postApiAccess.AddPost(_userId, new PostToAdd
                    {
                        ImageFullPath = fullImagePath,
                        Text          = post.NewPost.Text,
                        WhenAdded     = DateTime.Now,
                        ImagePath     = imagePath
                    });
                }
                return(RedirectToAction(nameof(Index), "Profile"));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong during adding post by user {_userId}");
                _logger.LogError($"Exception info: {ex.Message} {ex.Source}");
                return(RedirectToAction("Error", "Error"));
            }
        }
예제 #4
0
        //[DisableFormValueModelBinding]
        public async Task <IActionResult> PostFiles()
        {
            try
            {
                string country = (string)Request.RouteValues["country"];
                string city    = (string)Request.RouteValues["city"];
                logger.LogDebug($"Receiving photo for {country}/{city}");
                var dataSource = CyanometerDataSources.Default.GetData(city, country);
                if (dataSource != null)
                {
                    string token = Request.Headers["CyanometerToken"];
                    if (!string.Equals(dataSource.Id.ToString(), token, StringComparison.OrdinalIgnoreCase))
                    {
                        logger.LogWarning("Invalid token");
                        return(StatusCode(StatusCodes.Status401Unauthorized));
                    }
                    if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
                    {
                        ModelState.AddModelError("File", "The request couldn't be processed (Error 1).");
                        logger.LogWarning("The request couldn't be processed (Error 1).");
                        return(BadRequest(ModelState));
                    }
                    var boundary = MultipartRequestHelper.GetBoundary(
                        MediaTypeHeaderValue.Parse(Request.ContentType),
                        defaultFormOptions.MultipartBoundaryLengthLimit);
                    var reader  = new MultipartReader(boundary, HttpContext.Request.Body);
                    var section = await reader.ReadNextSectionAsync();

                    while (section != null)
                    {
                        logger.LogDebug("Reading section");
                        var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

                        if (hasContentDispositionHeader)
                        {
                            // This check assumes that there's a file
                            // present without form data. If form data
                            // is present, this method immediately fails
                            // and returns the model error.
                            if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                            {
                                ModelState.AddModelError("File", "The request couldn't be processed (Error 2)");
                                logger.LogWarning("The request couldn't be processed (Error 2)");
                                return(BadRequest(ModelState));
                            }
                            else
                            {
                                // Don't trust the file name sent by the client. To display
                                // the file name, HTML-encode the value.
                                using (var streamedFileContent = await FileHelpers.ProcessStreamedFile(logger,
                                                                                                       section, contentDisposition, ModelState,
                                                                                                       new[] { ".jpg", ".jpeg" }, 1024 * 1024 * 6)) // max 4MB file
                                {
                                    if (!ModelState.IsValid)
                                    {
                                        logger.LogWarning($"Invalid model state");
                                        foreach (var pair in ModelState)
                                        {
                                            foreach (var error in pair.Value.Errors)
                                            {
                                                logger.LogError($"{pair.Key}: {error.ErrorMessage}");
                                            }
                                        }
                                        return(BadRequest(ModelState));
                                    }

                                    try
                                    {
                                        logger.LogDebug($"Saving image {contentDisposition.FileName.Value}");
                                        imagesManager.SaveImage(dataSource, contentDisposition.FileName.Value, streamedFileContent);
                                    }
                                    catch (Exception ex)
                                    {
                                        logger.LogError(ex, "Failed saving image");
                                        return(BadRequest("Image procession failed"));
                                    }
                                }
                            }
                        }

                        // Drain any remaining section body that hasn't been consumed and
                        // read the headers for the next section.
                        section = await reader.ReadNextSectionAsync();
                    }
                    logger.LogDebug("Done reading sections");

                    return(Created(nameof(ImagesController), null));
                }
                else
                {
                    logger.LogWarning($"No data source found for given {country}/{city}");
                    return(NotFound());
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Failed processing file");
                throw;
            }
        }