Beispiel #1
0
        public async Task <IActionResult> Create(CreateWorkerInputModel input)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View());
            }

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

            await this.workerService.CreateAsync(input, user.Id, $"{this.environment.WebRootPath}/images");

            return(this.Redirect("/"));
        }
        public async Task CreateAsync(CreateWorkerInputModel input, string userId, string imagePath)
        {
            var worker = new Worker
            {
                FirstName   = input.FirstName,
                LastName    = input.LastName,
                PhoneNumber = input.PhoneNumber,
                Email       = input.Email,
                Town        = input.Town,
                AboutMe     = input.AboutMe,
                UserId      = userId,
            };

            foreach (var skill in input.Skills)
            {
                var currentSkill = this.skillsRepository
                                   .All()
                                   .FirstOrDefault(x => x.Name == skill.SkillName);

                if (currentSkill == null)
                {
                    currentSkill = new Skill {
                        Name = skill.SkillName
                    };
                }

                worker.Skills.Add(new WorkerSkill
                {
                    Skill       = currentSkill,
                    Description = skill.Description,
                });
            }

            var allowedExtentions = new[] { "jpg", "png", "gif" };

            Directory.CreateDirectory($"{imagePath}/workers/");

            foreach (var image in input.Images)
            {
                var extension = Path.GetExtension(image.FileName).TrimStart('.');
                if (!allowedExtentions.Any(x => extension.EndsWith(x)))
                {
                    throw new Exception($"Invalid image format {extension}");
                }

                var dbImage = new WorkerImage
                {
                    //  UserId = userId,
                    Extension = extension,
                };
                worker.WorkerImages.Add(dbImage);

                var phisicalPath = $"{imagePath}/workers/{dbImage.Id}.{extension}";
                using Stream fileStream = new FileStream(phisicalPath, FileMode.Create);
                await image.CopyToAsync(fileStream);
            }

            await this.workersRepository.AddAsync(worker);

            await this.workersRepository.SaveChangesAsync();
        }