public async Task <IActionResult> PutApartment(int id, Apartment apartment)
        {
            if (id != apartment.Id)
            {
                return(BadRequest());
            }

            _context.Entry(apartment).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ApartmentExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #2
0
        UpdateCommentAsync(CommentDTOAdministration comment, CancellationToken cancellationToken = default(CancellationToken))
        {
            comment.Update = DateTime.UtcNow;
            Comment commentForUpdate = _mapper.Map <Comment>(comment);

            _db.Entry(commentForUpdate).Property(c => c.Title).IsModified = true;
            _db.Entry(commentForUpdate).Property(c => c.Text).IsModified  = true;

            _db.Entry(commentForUpdate).Property(c => c.Update).IsModified = true;

            try
            {
                await _db.SaveChangesAsync(cancellationToken);

                return((Result <CommentDTOAdministration>) Result <CommentDTOAdministration>
                       .Ok(comment));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return((Result <CommentDTOAdministration>) Result <CommentDTOAdministration>
                       .Fail <CommentDTOAdministration>($"Cannot update model. {ex.Message}"));
            }
            catch (DbUpdateException ex)
            {
                return((Result <CommentDTOAdministration>) Result <CommentDTOAdministration>
                       .Fail <CommentDTOAdministration>($"Cannot update model. {ex.Message}"));
            }
        }
        public async Task <IActionResult> Edit(int id, [Bind("ContractId,ContractNo,RoomId,CustomerId,EngageMonth,BeginDate,ContractValue")] Contract contract)
        {
            if (id != contract.ContractId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(contract);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ContractExists(contract.ContractId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Index"));
            }
            ViewData["CustomerId"] = new SelectList(_context.Customer, "CustomerId", "CustomerName", contract.CustomerId);
            ViewData["RoomId"]     = new SelectList(_context.Room, "RoomId", "RoomNo", contract.RoomId);
            return(View(contract));
        }
Example #4
0
        public async Task <IActionResult> PutUser(int id, User user)
        {
            if (id != user.Id)
            {
                return(BadRequest());
            }
            var hashed = GetHashedPassword(user.Password, out byte[] salt);

            user.Password     = hashed;
            user.PasswordSalt = salt;

            _context.Entry(user).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #5
0
        CreateCommentAsync(AddComment comment, string authorId, CancellationToken cancellationToken = default(CancellationToken))
        {
            var addedComment = _mapper.Map <Comment>(comment);

            addedComment.AuthorId = Guid.Parse(authorId);

            _db.Comments.Add(addedComment);

            try
            {
                await _db.SaveChangesAsync(cancellationToken);

                Comment commentAfterAdding = await _db.Comments.Where(_ => _.AuthorId == addedComment.AuthorId)
                                             .Select(_ => _)
                                             .AsNoTracking().FirstOrDefaultAsync(cancellationToken);

                return((Result <CommentDTO>) Result <CommentDTO>
                       .Ok(_mapper.Map <CommentDTO>(commentAfterAdding)));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return((Result <CommentDTO>) Result <CommentDTO>
                       .Fail <CommentDTO>($"Cannot save model. {ex.Message}"));
            }
            catch (DbUpdateException ex)
            {
                return((Result <CommentDTO>) Result <CommentDTO>
                       .Fail <CommentDTO>($"Cannot save model. {ex.Message}"));
            }
            catch (ArgumentNullException ex)
            {
                return((Result <CommentDTO>) Result <CommentDTO>
                       .Fail <CommentDTO>($"Source is null. {ex.Message}"));
            }
        }
        public async void CreateOrderAsync_Positive_TestAsync()
        {
            var options = new DbContextOptionsBuilder <ApartmentContext>()
                          .UseInMemoryDatabase(databaseName: "CreateOrderAsync_PositiveAndNegative_TestAsync")
                          .Options;

            using (var context = new ApartmentContext(options))
            {
                context.AddRange(_users);
                await context.SaveChangesAsync();

                User userWithApartments = context.Users.AsNoTracking().FirstOrDefault();

                foreach (var item in _addresses)
                {
                    item.CountryId = context.Countries.FirstOrDefault().Id;
                }

                for (int i = 0; i < 2; i++)
                {
                    _apartments[i].OwnerId = userWithApartments.Id;
                    _apartments[i].Address = _addresses[i];
                }

                context.AddRange(_apartments);
                await context.SaveChangesAsync();
            }

            using (var context = new ApartmentContext(options))
            {
                var service = new OrderUserService(context, _mapper);

                var user      = context.Users.AsNoTracking().FirstOrDefault();;
                var apartment = context.Apartments.AsNoTracking().FirstOrDefault();;

                IEnumerable <DateTime> dateTimes = new List <DateTime>()
                {
                    DateTime.Now.Date
                };

                AddOrder order = new AddOrder()
                {
                    ApartmentId = apartment.Id.ToString(),
                    Dates       = dateTimes
                };

                var resultPositive = await service.CreateOrderAsync(order, user.Id.ToString());

                resultPositive.IsSuccess.Should().BeTrue();
                resultPositive.Data.Apartment.Title.Should().BeEquivalentTo(apartment.Title);
                resultPositive.Data.Order.Dates.FirstOrDefault().Should().BeSameDateAs(dateTimes.First());

                context.BusyDates.FirstOrDefault().Date.Should().BeSameDateAs(dateTimes.First());
            }
        }
        public async Task <IActionResult> Create([Bind("ID,LastName,FirstName,Email,PhoneNumber,EnrollmentDate,Street,City,Zip")] User user)
        {
            if (ModelState.IsValid)
            {
                _context.Add(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(user));
        }
Example #8
0
        public async Task <IActionResult> Create([Bind("ApartmentId,AptAddress,SqFootage,MonthUtilityFee,MonthParkfee,LastCleanDate,IsVacant")] Apartment apartment)
        {
            if (ModelState.IsValid)
            {
                _context.Add(apartment);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(apartment));
        }
Example #9
0
        public async Task <IActionResult> Create([Bind("FirstName,LastName,Phone,Email")] Tenant tenant)
        {
            if (ModelState.IsValid)
            {
                _context.Add(tenant);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(tenant));
        }
Example #10
0
        public async Task <IActionResult> Create([Bind("ApartmentID,Name,Garage,Shares")] Apartment apartment)
        {
            if (ModelState.IsValid)
            {
                _context.Add(apartment);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(apartment));
        }
Example #11
0
 private async Task Save(Payload <IPayload> payload)
 {
     await ResilientTransaction.New(_context).ExecuteAsync(async() =>
     {
         _context.Apartment.Add(payload.Apartment);
         await _context.SaveChangesAsync();
         payload.InObject.ApartmentId = payload.Apartment.Id;
         _context.Add(payload.InObject);
         await _context.SaveChangesAsync();
     });
 }
Example #12
0
        public async Task <IActionResult> Create([Bind("ID,MaintenanceFees,Title,Price,SuitesNumber,Size,Cep,City,District,PhoneNumber,ParkingSpace,Leasing,Sale")] Apartment apartment)
        {
            if (ModelState.IsValid)
            {
                _context.Add(apartment);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(apartment));
        }
Example #13
0
        public async void GetAllApartmentByUserIdAsync_PositiveAndNegative_TestAsync()
        {
            var options = new DbContextOptionsBuilder <ApartmentContext>()
                          .UseInMemoryDatabase(databaseName: "GetAllApartmentByUserIdAsync_PositiveAndNegative_TestAsync")
                          .Options;

            User userWithApartments;

            using (var context = new ApartmentContext(options))
            {
                context.AddRange(_users);
                await context.SaveChangesAsync();

                userWithApartments = context.Users.AsNoTracking().FirstOrDefault();

                foreach (var item in _addresses)
                {
                    item.CountryId = context.Countries.FirstOrDefault().Id;
                }

                for (int i = 0; i < 2; i++)
                {
                    _apartments[i].OwnerId = userWithApartments.Id;
                    _apartments[i].Address = _addresses[i];
                }

                context.AddRange(_apartments);
                await context.SaveChangesAsync();
            }

            using (var context = new ApartmentContext(options))
            {
                var service = new ApartmentUserService(context, _mapper);

                var apartmentsInBase = await context.Apartments.AsNoTracking().ToListAsync();

                var userWithoutApartments = await context.Users.Where(_ => _.Id != userWithApartments.Id).FirstOrDefaultAsync();

                var resultPositive = await service.GetAllApartmentByOwnerIdAsync(userWithApartments.Id.ToString(), new Common.PagedRequest());

                var resultNegative = await service.GetAllApartmentByOwnerIdAsync(userWithoutApartments.Id.ToString(), new Common.PagedRequest());

                foreach (var item in apartmentsInBase)
                {
                    resultPositive.Data.Data
                    .Where(_ => _.Apartment.Id == item.Id.ToString())
                    .FirstOrDefault()
                    .Should().NotBeNull();
                }

                resultNegative.Data.Data.Should().BeEmpty();
            }
        }
        public async Task <IActionResult> Create([Bind("UserApartmentID,UserID,ApartmentID,Owner,Resident")] UserApartment userApartment)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userApartment);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ApartmentID"] = new SelectList(_context.Apartments, "ApartmentID", "Name", userApartment.ApartmentID);
            ViewData["UserID"]      = new SelectList(_context.Users, "ID", "LastName", userApartment.UserID);
            return(View(userApartment));
        }
        public async Task <IActionResult> Create([Bind("RoomId,RoomNo,RoomTypeId,Price,Area,Status")] Room room)
        {
            if (ModelState.IsValid)
            {
                _context.Add(room);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            ViewData["RoomTypeId"] = new SelectList(_context.RoomType, "RoomTypeId", "RoomTypeName", room.RoomTypeId);

            return(View(room));
        }
Example #16
0
        public async Task <IActionResult> Create([Bind("ContractId,StartDate,EndDate,MonthlyRent,ApartmentId,TenantId")] Contract contract)
        {
            if (ModelState.IsValid)
            {
                _context.Add(contract);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            ViewData["ApartmentId"] = new SelectList(_context.Apartments, "ApartmentId", "ApartmentId", contract.ApartmentId);
            ViewData["TenantId"]    = new SelectList(_context.Tenants, "TenantId", "TenantId", contract.TenantId);
            return(View(contract));
        }
        public async void DeleteCommentByIdAsync_PositiveAndNegative_TestAsync()
        {
            var options = new DbContextOptionsBuilder <ApartmentContext>()
                          .UseInMemoryDatabase(databaseName: "DeleteCommentByIdAsync_PositiveAndNegative_TestAsync")
                          .Options;

            using (var context = new ApartmentContext(options))
            {
                foreach (var item in _comments)
                {
                    item.AuthorId = Guid.NewGuid();
                }

                context.AddRange(_comments);
                await context.SaveChangesAsync();
            }

            using (var context = new ApartmentContext(options))
            {
                var comment = await context.Comments.AsNoTracking().FirstOrDefaultAsync();

                var service = new CommentUserService(context, _mapper);

                var resultPositive = await service.DeleteCommentByIdAsync(comment.Id.ToString(), comment.AuthorId.ToString());

                var resultNegative = await service.DeleteCommentByIdAsync(new Guid().ToString(), new Guid().ToString());

                resultPositive.IsSuccess.Should().BeTrue();
                resultPositive.Message.Should().BeNull();

                resultNegative.IsSuccess.Should().BeFalse();
                resultNegative.Message.Should().Contain("Comment was not found");
            }
        }
        public async Task <IActionResult> Create([Bind("CustomerId,CustomerName,BirthDay,IdentityCardNo,PhoneNo,Email,Gender,Status,DistrictId,ProvinceId")] Customer customer)
        {
            if (ModelState.IsValid)
            {
                _context.Add(customer);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            if (customer.ProvinceId != null)
            {
                ViewBag.Districts = new SelectList(_context.District.Where(x => x.ProvinceId == customer.ProvinceId), "DistrictId", "DistrictName");
            }
            ViewData["ProvinceId"] = new SelectList(_context.Province, "ProvinceId", "ProvinceName", customer.ProvinceId);
            return(View(customer));
        }
        public async void GetCommentByIdAsync_PositiveAndNegative_TestAsync()
        {
            var options = new DbContextOptionsBuilder <ApartmentContext>()
                          .UseInMemoryDatabase(databaseName: "GetCommentByIdAsync_PositiveAndNegative_TestAsync")
                          .Options;

            using (var context = new ApartmentContext(options))
            {
                context.AddRange(_comments);
                await context.SaveChangesAsync();
            }

            using (var context = new ApartmentContext(options))
            {
                var comment = await context.Comments.AsNoTracking().FirstOrDefaultAsync();

                var service = new CommentAdministrationService(context, _mapper);

                var resultPositive = await service.GetCommentByIdAsync(comment.Id.ToString());

                var resultNegative = await service.GetCommentByIdAsync(new Guid().ToString());

                resultPositive.IsSuccess.Should().BeTrue();
                resultPositive.Data.Title.Should().BeEquivalentTo(comment.Title);

                resultNegative.IsSuccess.Should().BeFalse();
                resultNegative.Data.Should().BeNull();
            }
        }
Example #20
0
        DeleteUserProfileByIdentityIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
        {
            Guid identityId = Guid.Parse(id);

            var profile = await _db.Users.IgnoreQueryFilters()
                          .Include(_ => _.Apartments).FirstOrDefaultAsync(_ => _.Id == identityId, cancellationToken);


            if (profile is null)
            {
                return(await Task.FromResult(Result.NotOk("Profile is not exist")));
            }

            try
            {
                //todo: rewrite, because there is no time to write as it should
                _db.Apartments.RemoveRange(profile.Apartments);
                await _db.SaveChangesAsync(cancellationToken);

                return(await Task.FromResult(Result.Ok()));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(await Task.FromResult(Result.Fail($"Cannot delete profile. {ex.Message}")));
            }
            catch (DbUpdateException ex)
            {
                return(await Task.FromResult(Result.Fail($"Cannot delete profile. {ex.Message}")));
            }
        }
        public async void CreateCommentAsync_Positive_TestAsync()
        {
            var options = new DbContextOptionsBuilder <ApartmentContext>()
                          .UseInMemoryDatabase(databaseName: "CreateCommentAsync_PositiveAndNegative_TestAsync")
                          .Options;

            using (var context = new ApartmentContext(options))
            {
                context.AddRange(_users);
                context.AddRange(_apartments);

                await context.SaveChangesAsync();
            }

            using (var context = new ApartmentContext(options))
            {
                var user      = context.Users.AsNoTracking().FirstOrDefault();;
                var apartment = context.Apartments.AsNoTracking().FirstOrDefault();;

                AddComment comment = new AddComment()
                {
                    ApartmentId = apartment.Id.ToString(),
                    Title       = "Title",
                    Text        = "Text"
                };

                var service = new CommentUserService(context, _mapper);

                var resultPositive = await service.CreateCommentAsync(comment, user.Id.ToString());

                resultPositive.IsSuccess.Should().BeTrue();
                resultPositive.Data.Title.Should().BeEquivalentTo(comment.Title);
            }
        }
Example #22
0
        public async void DeleteUserProfileByIdentityIdAsync_PositiveAndNegative_TestAsync()
        {
            var options = new DbContextOptionsBuilder <ApartmentContext>()
                          .UseInMemoryDatabase(databaseName: "DeleteUserProfileByIdentityIdAsync_PositiveAndNegative_TestAsync")
                          .Options;

            using (var context = new ApartmentContext(options))
            {
                context.AddRange(_users);
                await context.SaveChangesAsync();
            }

            using (var context = new ApartmentContext(options))
            {
                var user = await context.Users.AsNoTracking().FirstOrDefaultAsync();

                var service = new UserAdministrationService(context, _mapper);

                var resultPositive = await service.DeleteUserProfileByIdentityIdAsync(user.Id.ToString());

                var resultNegative = await service.DeleteUserProfileByIdentityIdAsync(new Guid().ToString());

                resultPositive.IsSuccess.Should().BeTrue();
                resultPositive.Message.Should().BeNull();

                resultNegative.IsSuccess.Should().BeFalse();
                resultNegative.Message.Should().Contain("not exist");
            }
        }
Example #23
0
        public async void DeleteApartmentByIdAsync_PositiveAndNegative_TestAsync()
        {
            var options = new DbContextOptionsBuilder <ApartmentContext>()
                          .UseInMemoryDatabase(databaseName: "DeleteApartmentByIdAsync_PositiveAndNegative_TestAsync")
                          .Options;

            using (var context = new ApartmentContext(options))
            {
                await context.AddRangeAsync(_users);

                await context.SaveChangesAsync();

                var userWithApartments = context.Users.AsNoTracking().FirstOrDefault();

                foreach (var item in _addresses)
                {
                    item.CountryId = context.Countries.FirstOrDefault().Id;
                }

                for (int i = 0; i < 2; i++)
                {
                    _apartments[i].OwnerId = userWithApartments.Id;
                    _apartments[i].Address = _addresses[i];
                }

                await context.AddRangeAsync(_apartments);

                await context.SaveChangesAsync();
            }

            using (var context = new ApartmentContext(options))
            {
                var apartmenr = await context.Apartments.AsNoTracking().FirstOrDefaultAsync();

                var service = new ApartmentUserService(context, _mapper);

                var resultPositive = await service.DeleteApartmentByIdAsync(apartmenr.Id.ToString(), apartmenr.OwnerId.ToString());

                var resultNegative = await service.DeleteApartmentByIdAsync(new Guid().ToString(), new Guid().ToString());

                resultPositive.IsSuccess.Should().BeTrue();
                resultPositive.Message.Should().BeNull();

                resultNegative.IsSuccess.Should().BeFalse();
                resultNegative.Message.Should().Contain("Apartment was not found");
            }
        }
Example #24
0
        public async void GetApartmentByIdAsync_PositiveAndNegative_TestAsync()
        {
            var options = new DbContextOptionsBuilder <ApartmentContext>()
                          .UseInMemoryDatabase(databaseName: "GetApartmentByIdAsync_PositiveAndNegative_TestAsync")
                          .Options;

            using (var context = new ApartmentContext(options))
            {
                context.AddRange(_users);
                await context.SaveChangesAsync();

                var userWithApartments = context.Users.AsNoTracking().FirstOrDefault();

                foreach (var item in _addresses)
                {
                    item.CountryId = context.Countries.FirstOrDefault().Id;
                }

                for (int i = 0; i < 2; i++)
                {
                    _apartments[i].OwnerId = userWithApartments.Id;
                    _apartments[i].Address = _addresses[i];
                }

                context.AddRange(_apartments);
                await context.SaveChangesAsync();
            }

            using (var context = new ApartmentContext(options))
            {
                var apartment = await context.Apartments.AsNoTracking()
                                .Include(_ => _.Address.Country).FirstOrDefaultAsync();

                var service = new ApartmentUserService(context, _mapper);

                var resultPositive = await service.GetApartmentByIdAsync(apartment.Id.ToString());

                var resultNegative = await service.GetApartmentByIdAsync(new Guid().ToString());

                resultPositive.IsSuccess.Should().BeTrue();
                resultPositive.Data.Apartment.Title.Should().BeEquivalentTo(apartment.Title);
                resultPositive.Data.Country.Name.Should().BeEquivalentTo(apartment.Address.Country.Name);

                resultNegative.IsSuccess.Should().BeFalse();
                resultNegative.Data.Should().BeNull();
            }
        }
        public async void GetAllCommentsByApartmentIdAsync_PositiveAndNegative_TestAsync()
        {
            var options = new DbContextOptionsBuilder <ApartmentContext>()
                          .UseInMemoryDatabase(databaseName: "GetAllCommentsByApartmentIdAsync_PositiveAndNegative_TestAsync")
                          .Options;

            Apartment apartmentWithComments;

            using (var context = new ApartmentContext(options))
            {
                context.AddRange(_apartments);
                await context.SaveChangesAsync();

                apartmentWithComments = context.Apartments.AsNoTracking().FirstOrDefault();

                foreach (var item in _comments)
                {
                    item.ApartmentId = apartmentWithComments.Id;
                }

                context.AddRange(_comments);
                await context.SaveChangesAsync();
            }

            using (var context = new ApartmentContext(options))
            {
                var service = new CommentAdministrationService(context, _mapper);

                var commentsInBase = await context.Comments.AsNoTracking().ToListAsync();

                var apartmentWithoutComments = context.Apartments.Where(_ => _.Id != apartmentWithComments.Id).FirstOrDefault();

                var resultPositive = await service.GetAllCommentsByApartmentIdAsync(new PagedRequest <string>(apartmentWithComments.Id.ToString()));

                var resultNegative = await service.GetAllCommentsByApartmentIdAsync(new PagedRequest <string>(apartmentWithoutComments.Id.ToString()));

                foreach (var item in commentsInBase)
                {
                    resultPositive.Data.Data
                    .Where(_ => _.Id == item.Id.ToString())
                    .FirstOrDefault()
                    .Should().NotBeNull();
                }

                resultNegative.Data.Data.Should().BeEmpty();
            }
        }
Example #26
0
        CreateUserProfileAsync(string identityId, string nick, CancellationToken cancellationToken = default(CancellationToken))
        {
            AddUser newProfile = new AddUser()
            {
                Id       = identityId,
                NickName = nick
            };

            var addedUser = _mapper.Map <User>(newProfile);

            _db.Users.Add(addedUser);

            try
            {
                await _db.SaveChangesAsync(cancellationToken);

                User userAfterAdding = await _db.Users.Where(_ => _.Id == addedUser.Id)
                                       .Select(_ => _)
                                       .AsNoTracking().FirstOrDefaultAsync(cancellationToken);

                return((Result <UserDTO>) Result <UserDTO>
                       .Ok(_mapper.Map <UserDTO>(userAfterAdding)));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return((Result <UserDTO>) Result <UserDTO>
                       .Fail <UserDTO>($"Cannot save model. {ex.Message}"));
            }
            catch (DbUpdateException ex)
            {
                return((Result <UserDTO>) Result <UserDTO>
                       .Fail <UserDTO>($"Cannot save model. {ex.Message}"));
            }
            catch (ArgumentNullException ex)
            {
                return((Result <UserDTO>) Result <UserDTO>
                       .Fail <UserDTO>($"Source is null. {ex.Message}"));
            }
        }
Example #27
0
        public async Task SaveEventAndApartmentContextChangesAsync(IntegrationEvent evt)
        {
            _logger.LogInformation("----- CatalogIntegrationEventService - Saving changes and integrationEvent: {IntegrationEventId}", evt.Id);

            //Use of an EF Core resiliency strategy when using multiple DbContexts within an explicit BeginTransaction():
            //See: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
            await ResilientTransaction.New(_apartmentContext).ExecuteAsync(async() =>
            {
                // Achieving atomicity between original apartment database operation and the IntegrationEventLog thanks to a local transaction
                await _apartmentContext.SaveChangesAsync();
                await _eventLogService.SaveEventAsync(evt, _apartmentContext.Database.CurrentTransaction);
            });
        }
        public async Task <bool> Handle(UpdatePicCommand request, CancellationToken cancellationToken)
        {
            var apartment = await _context.Apartment.FirstOrDefaultAsync(a => a.RequestId == request.RequestId);

            if (apartment == null)
            {
                return(false);
            }
            apartment.PictureUri      = request.PictureUri;
            apartment.PictureFileName = request.PictureFileName;
            _context.Apartment.Update(apartment);
            _logger.LogInformation($"Starting Updating Pic info for request No: {request.RequestId} - Command: {request}");
            return(await _context.SaveChangesAsync() > 0);
        }
Example #29
0
        CreateApartmentAsync(AddApartment apartment, string ownerId, CancellationToken cancellationToken = default(CancellationToken))
        {
            var addedApartment = _mapper.Map <Apartment>(apartment);

            addedApartment.OwnerId = Guid.Parse(ownerId);

            _db.Apartments.Add(addedApartment);

            try
            {
                await _db.SaveChangesAsync(cancellationToken);

                Apartment apartmentAfterAdding = await _db.Apartments.Where(_ => _.Title == addedApartment.Title)
                                                 .Select(_ => _).Include(_ => _.Address.Country).Include(_ => _.Address)
                                                 .AsNoTracking().FirstOrDefaultAsync(cancellationToken);

                ApartmentView view = MakeApartmentView(apartmentAfterAdding);

                return((Result <ApartmentView>) Result <ApartmentView>
                       .Ok(view));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return((Result <ApartmentView>) Result <ApartmentView>
                       .Fail <ApartmentView>($"Cannot save model. {ex.Message}"));
            }
            catch (DbUpdateException ex)
            {
                return((Result <ApartmentView>) Result <ApartmentView>
                       .Fail <ApartmentView>($"Cannot save model. {ex.Message}"));
            }
            catch (ArgumentNullException ex)
            {
                return((Result <ApartmentView>) Result <ApartmentView>
                       .Fail <ApartmentView>($"Source is null. {ex.Message}"));
            }
        }
Example #30
0
        public async void CreateApartmentAsync_Positive_TestAsync()
        {
            var options = new DbContextOptionsBuilder <ApartmentContext>()
                          .UseInMemoryDatabase(databaseName: "CreateApartmentAsync_PositiveAndNegative_TestAsync")
                          .Options;

            using (var context = new ApartmentContext(options))
            {
                context.AddRange(_users);
                await context.SaveChangesAsync();
            }

            using (var context = new ApartmentContext(options))
            {
                var service = new ApartmentUserService(context, _mapper);

                User user = await context.Users.FirstOrDefaultAsync();

                AddAddress address = new AddAddress()
                {
                    CountryId         = context.Countries.FirstOrDefault().Id.ToString(),
                    City              = "MyCity",
                    Street            = "Street",
                    Home              = "Home",
                    NumberOfApartment = 1
                };

                AddApartment apartmentOk = new AddApartment()
                {
                    Address       = address,
                    Area          = 54,
                    IsOpen        = true,
                    Price         = 15M,
                    Title         = "Apartment",
                    Text          = "AddedApartment",
                    NumberOfRooms = 2
                };

                var resultPositive = await service.CreateApartmentAsync(apartmentOk, user.Id.ToString());

                resultPositive.IsSuccess.Should().BeTrue();
                resultPositive.Data.Country.Id.Should().BeEquivalentTo(address.CountryId);
                resultPositive.Data.Address.Street.Should().BeEquivalentTo(address.Street);
                resultPositive.Data.Apartment.Title.Should().BeEquivalentTo(apartmentOk.Title);
            }
        }