示例#1
0
        public async Task CreateAsync(CreateCauseInputModel input, string userId, string imagePath)
        {
            var cause = new Cause()
            {
                Title         = input.Title,
                Description   = input.Description,
                Funds         = input.Funds,
                BankAccount   = input.BankAccount,
                AccountOwner  = input.AccountOwner,
                CreatorId     = userId,
                StartOfPeriod = input.StartOfPeriod,
                EndOfPeriod   = input.EndOfPeriod,
            };

            Directory.CreateDirectory($"{imagePath}/causes/");
            foreach (var image in input.Images)
            {
                var extension = Path.GetExtension(image.FileName).TrimStart('.');

                if (!this.allowedExtensions.Any(x => extension.EndsWith(x)))
                {
                    throw new Exception($"Invalid image extension {extension}");
                }

                var dbImage = new CauseImage
                {
                    AddedByUserId = userId,
                    Extension     = extension,
                };

                cause.CauseImages.Add(dbImage);

                var physicalPath = $"{imagePath}/causes/{dbImage.Id}.{extension}";

                using Stream fileStream = new FileStream(physicalPath, FileMode.Create);
                await image.CopyToAsync(fileStream);
            }

            await this.causesRepo.AddAsync(cause);

            await this.causesRepo.SaveChangesAsync();
        }
        public async Task <IActionResult> Create(CreateCauseInputModel input)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(input));
            }

            var user = await this.userManager.GetUserAsync(this.User);

            try
            {
                await this.causesService.CreateAsync(input, user.Id, $"{this.environment.WebRootPath}/images");
            }
            catch (Exception ex)
            {
                this.ModelState.AddModelError(string.Empty, ex.Message);

                return(this.View(input));
            }

            this.TempData["Message"] = "Cause added successfully.";

            return(this.RedirectToAction("MyCauses"));
        }