public async Task <IActionResult> Create(CreatePropertiesViewModel input) { if (this.propertiesService.IsPropertyWithUniqueNameAndAddress(input) == false) { this.ModelState.AddModelError("Name", "A property with this Name or Address already exists!"); return(this.View(input)); } if (!this.ModelState.IsValid) { return(this.View(input)); } input.ManagerId = this.HttpContext.User.Claims.First(c => c.Type.Contains("nameidentifier")).Value; try { await this.propertiesService.CreateAsync(input, $"{Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot")}"); } catch (Exception ex) { this.ModelState.AddModelError(string.Empty, ex.Message); return(this.View(input)); } return(this.Redirect("/")); }
public async Task CreateShouldSucceed() { var options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "CreatePropertiesTestDb").Options; using var dbContext = new ApplicationDbContext(options); using var propertyRepository = new EfDeletableEntityRepository <Property>(dbContext); var propertiesService = new PropertiesService(propertyRepository); var model = new CreatePropertiesViewModel() { Address = "33300 Main st", Name = "Peter", Owner = "Ivan Ivanov", Size = 110, Type = PMStudio.Data.Models.Enum.PropertyType.Residential, Images = new List <IFormFile>(), }; await propertiesService.CreateAsync(model, @"C:\PM.Studio.Images"); var createdModel = dbContext.Properties.FirstOrDefault(p => p.Name == "Peter"); Assert.NotNull(createdModel); }
public async Task CreateAsync(CreatePropertiesViewModel input, string imagePath) { var property = new Property() { Address = input.Address, Name = input.Name, Owner = input.Owner, Size = input.Size, ManagerId = input.ManagerId, }; Directory.CreateDirectory(Path.Combine(imagePath, "images")); 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 Image { AddedByUserId = input.ManagerId, Extension = extension, }; property.Images.Add(dbImage); var physicalPath = $"{imagePath}\\images\\{dbImage.Id}.{extension}"; using (var fileStream = new FileStream(physicalPath, FileMode.Create)) { await image.CopyToAsync(fileStream); } } await this.propertiesRepository.AddAsync(property); await this.propertiesRepository.SaveChangesAsync(); var result = property.Address; }
public bool IsPropertyWithUniqueNameAndAddress(CreatePropertiesViewModel input) { var existingPropertiesWithSameData = this.propertiesRepository.AllAsNoTracking().Count(p => p.Address == input.Address || p.Name == input.Name); return(existingPropertiesWithSameData == 0); }