public void GetByIdTest()
 {
     var modelContainer = new TimeTrackerContext();
     var service = new BookingService(modelContainer);
     var booking = service.GetById(1);
     Assert.IsNotNull(booking);
 }
 public BookingServiceFacadeImpl(BookingService bookingService, LocationRepository locationRepository,
                                 CargoRepository cargoRepository, VoyageRepository voyageRepository)
 {
     this.bookingService = bookingService;
     this.locationRepository = locationRepository;
     this.cargoRepository = cargoRepository;
     this.voyageRepository = voyageRepository;
 }
 protected void btnValidate_Click(object sender, EventArgs e)
 {
     //Object for card detail validation
     BookingService cardAuth = new BookingService();
     bool auth = cardAuth.CheckCard(txtCardNumber.Text, txtCVV.Text);
     if (auth)
     {
         lblError.Text = "";
         lblError.Text = "Validation successfull";
     }
     else
     {
         lblError.Text = "Validation Failed. Card number or CVV code is invalid";
     }
 }
Exemple #4
0
        public IActionResult  cateringInsert(int idBooking, BookingCateringModel bc)
        {
            BookingService service = new BookingService();
            var            status = true; bool result = false;

            try{
                result = service.cateringInsert(idBooking, bc);
            }catch (System.Exception)
            {
                status = false;
            }

            var rtn = new {
                status = status,
                result = result
            };

            return(Ok(rtn));
        }
Exemple #5
0
        public IActionResult  delete(int id)
        {
            BookingService service = new BookingService();
            var            status = true; bool result = false;

            try{
                result = service.delete(id);
            }catch (System.Exception)
            {
                status = false;
            }

            var rtn = new {
                status = status,
                result = result
            };

            return(Ok(rtn));
        }
        static void Main(string[] args)
        {
            try
            {
                var fileName = Path.Combine(Directory.GetCurrentDirectory(), "meetings.txt");

                if (File.Exists(fileName))
                {
                    // Todo - use IoC library like Ninject to inject an instance
                    var          bookingService = new BookingService();
                    var          dayBookings    = bookingService.CreateBookings(fileName);
                    const string timeFormat     = "HH:mm";
                    const string dateFormat     = "yyyy-MM-dd";

                    foreach (var key in dayBookings.Keys)
                    {
                        var bookings = dayBookings[key];

                        Console.WriteLine(key.ToString(dateFormat));
                        foreach (var booking in bookings)
                        {
                            var meeting = booking.Meeting;

                            Console.WriteLine($"{meeting.StartTime.ToString(timeFormat)} {meeting.FinishTime.ToString(timeFormat)}");
                            Console.WriteLine(booking.EmployeeId);
                        }
                        ;
                    }
                }
                else
                {
                    Console.WriteLine("The input file doesn't exist.");
                }
            }
            catch (Exception)
            {
                // Todo - Log error at a global level printing out the stacktrace
                Console.WriteLine("Something went wrong!!");
            }

            Console.ReadKey();
        }
        public void AddBookingTest()
        {
            var bookingdata = GenerateTestBookingData().AsQueryable();
            var mockSet     = GetMockset(bookingdata);

            var contextOptions = new DbContextOptions <BookingContext>();
            var mockContext    = new Mock <BookingContext>(contextOptions);

            mockContext.Setup(c => c.Bookings).Returns(mockSet.Object);

            var service = new BookingService(mockContext.Object);
            var custId  = new List <int>();

            foreach (var book in bookingdata)
            {
                if (!custId.Contains(book.Customer.CustomerId))
                {
                    custId.Add(book.Customer.CustomerId);
                }
            }
            var id   = custId[new Random().Next(custId.Count)];
            var cust = new Customer()
            {
                CustomerId    = 3,
                CustomerEmail = "*****@*****.**",
                CustomerName  = "TestAdd",
                CustomerPhone = "04"
            };
            var addbooking = new BookingModel()
            {
                BookingId   = 4,
                Customer    = cust,
                TimeOfVisit = DateTime.Now.AddHours(1),
                EndTime     = DateTime.Now.AddHours(2)
            };

            service.AddBooking(addbooking);
            mockSet.Verify(m => m.Add(It.IsAny <BookingModel>()), Times.Once());
            mockContext.Verify(m => m.SaveChanges(), Times.Once());
            var res = service.GetAllBookings();
            // Assert.Equal(res, addbooking);
        }
    protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
        con.Open();
        //Object for card detail validation
        BookingService cardAuth = new BookingService();
        bool auth = cardAuth.CheckCard(txtCardNumber.Text, txtCVV.Text);
        if(txtMatchId.Text.Trim()=="" || txtSeats.Text.Trim()=="" || txtAmount.Text.Trim()=="" || txtCardNumber.Text.Trim()=="" || txtCVV.Text.Trim()=="")
            lblError.Text = "Please fill all the given fields";
        else if (auth)
        {
            lblError.Text = "";
            //Query to get the user id from DB
            string query = string.Format("SELECT user_id FROM users WHERE user_name='{0}'", Session["UserName"].ToString());
            da = new SqlDataAdapter(query, con);
            dt = new DataTable();
            da.Fill(dt);

            int user_id = Convert.ToInt32(dt.Rows[0]["user_id"].ToString());
            int match_id = Convert.ToInt32(txtMatchId.Text);
            int amount = Convert.ToInt32(txtSeats.Text) * 1500;
            string card_type;

            if (rdoCreditCard.Checked == true)
                card_type = rdoCreditCard.Text;
            else
                card_type = rdoDebitCard.Text;

            //Inserting payment details after all the validations.
            query = string.Format("INSERT INTO booking VALUES({0},{1},{2},{3},'{4}')", user_id, match_id, amount, Convert.ToInt32(txtSeats.Text), card_type);

            //Executing query
            da = new SqlDataAdapter(query, con);
            dt = new DataTable();
            da.Fill(dt);
            lblError.Text = "Booking successfull. You'll recieve your tickets through postal mail in few days";
        }
        else
        {
            lblError.Text = "Please press on \"Validate Card\" button to get your card verified.";
        }
    }
        public void BookingServiceSucceedsForBookingId2()
        {
            // Arrange
            var bookingService  = new BookingService();
            var mockDataService = new MockDataService();

            // Act
            bookingService.ProcessPendingBookings(mockDataService);
            var bookingId2 = bookingService.Bookings.FirstOrDefault(bi => bi.Id == 2);

            // Assert
            Assert.IsNotNull(bookingId2);
            Assert.IsTrue(bookingId2.IsFirstClass);
            Assert.IsTrue(bookingId2.IsReservationProcessed);
            Assert.IsTrue(bookingId2.IsReservationConfirmed);
            Assert.IsTrue(bookingId2.ReturnJourney.IsFirstClass);
            Assert.IsTrue(bookingId2.ReturnJourney.IsReservationProcessed);
            Assert.IsTrue(bookingId2.ReturnJourney.IsReservationConfirmed);
            Assert.IsFalse(bookingId2.IsBookingConfirmationCreated);
        }
 private void button3_Click(object sender, EventArgs e)
 {
     if (textBox4.Text == string.Empty)
     {
         MessageBox.Show("Booking id is required!!");
     }
     else
     {
         try
         {
             BookingService b    = new BookingService();
             Booking        book = b.GetById(Convert.ToInt32(textBox4.Text));
             textBox2.Text = Convert.ToString(book.Cost);
         }
         catch (Exception)
         {
             MessageBox.Show("Invalid");
         }
     }
 }
        private static void ShowBookings()
        {
            Console.Clear();
            var bs       = new BookingService();
            var bookings = bs.GetAllBookings();

            if (bookings != null)
            {
                foreach (var booking in bookings)
                {
                    Console.WriteLine($"Bookingnr: {booking.BookingNo}, Gæstnr: {booking.GuestNo}, Hotelnr: {booking.HotelNo}," +
                                      $" Værelsenr: {booking.RoomNo}, Fra dato: {booking.DateFrom.ToShortDateString()}," +
                                      $" Til dato: {booking.DateTo.ToShortDateString()}");
                }
            }
            else
            {
                Console.WriteLine("Ingen bookings i databasen.");
            }
        }
        public void CreateBookingReturnsNull()
        {
            var fakeBooking = new BookingResource {
                Id = 1, Number = "XYZ"
            };

            var mockedMapper            = GetMockedMapper();
            var mockedPersonRepository  = GetMockedPersonRepository();
            var mockedBookingRepository = GetMockedBookingRepository();
            var mockedFlightRepository  = GetMockedFlightRepository();

            var bookingService = new BookingService(mockedBookingRepository.Object,
                                                    mockedFlightRepository.Object,
                                                    mockedPersonRepository.Object,
                                                    mockedMapper.Object);

            var result = bookingService.CreateBooking(fakeBooking, nonExistingFlightId, nonExistingPassengerId);

            Assert.Null(result);
        }
        public void MakeBooking_BookingStartsEarlier()
        {
            var dateServiceMock = new Mock <IDateService>();

            dateServiceMock.Setup(x => x.NowUtc).Returns(DateTime.UtcNow.Date.AddDays(1));
            _dateService = dateServiceMock.Object;

            var bookingService = new BookingService(CreateRepo(), null, _costEvaluationService, null, _dateService);

            var bookingInfo = new MakeBookingInfoDto
            {
                Date = DateTime.UtcNow.Date,
                From = 0,
                To   = 20
            };

            bookingService.MakeBooking(bookingInfo, new CurrentUser {
                Phone = "1"
            });
        }
        public void ShouldGetAllBookings()
        {
            var bookingList = new List <Domain.Booking>
            {
                new Domain.Booking(
                    "100",
                    "1234",
                    "101",
                    new GeoCoordinate(13, 77),
                    new GeoCoordinate(14, 77),
                    DateTime.Now,
                    BookingStatus.Accepted
                    ),
                new Domain.Booking(
                    "102",
                    "1235",
                    "103",
                    new GeoCoordinate(13, 77),
                    new GeoCoordinate(14, 77),
                    DateTime.Now,
                    BookingStatus.Accepted),
                new Domain.Booking(
                    "104",
                    "1236",
                    "105",
                    new GeoCoordinate(13, 77),
                    new GeoCoordinate(14, 77),
                    DateTime.Now,
                    BookingStatus.Accepted
                    )
            };
            var bookingRepo = new Mock <IBookingRepository>();

            bookingRepo.Setup(b => b.GetAll()).Returns(bookingList);
            var availableCabsService = new Mock <IAvailableCabsService>();

            var bookingService = new BookingService(bookingRepo.Object, availableCabsService.Object);
            var actual         = bookingService.GetAllBookings();

            CollectionAssert.AreEqual(bookingList, actual);
        }
        public void TestCreateBookingForFlight_WhenInputValuesAreValid_ShouldCreateBookingCorrectly()
        {
            // Arrange
            var personRepository = new Mock <IRepository <Person> >();

            personRepository.Setup(x => x.Get(It.IsAny <int>())).Returns(new Person {
                Id = 1, Name = "testName"
            });
            var bookingRepository = new Mock <IRepository <Booking> >();
            var passengersList    = new[]
            {
                new Booking
                {
                    Id         = 23,
                    Passengers = new[] { new Person(), new Person(), },
                    Flight     = new Flight {
                        Id = 1, Number = "testFlight"
                    },
                }
            };

            bookingRepository.Setup(x => x.GetAll()).Returns(passengersList);
            var flightRepository = new Mock <IRepository <Flight> >();
            var flightInfo       = new Flight {
                Id = 1, Number = "testFlight"
            };

            flightRepository.Setup(x => x.GetAll()).Returns(new[] { flightInfo });
            var bookingService =
                new BookingService(personRepository.Object, bookingRepository.Object, flightRepository.Object);

            // Act
            var newBookinInfo = bookingService.CreateBookingForFlight(1, 1, "testFlight");

            // Assert
            Assert.Equal(24, newBookinInfo.Id);
            Assert.Equal(flightInfo, newBookinInfo.Flight);
            Assert.Equal(1, newBookinInfo.Customer.Id);
            Assert.Single(newBookinInfo.Passengers);
            Assert.Contains(1, newBookinInfo.Passengers.Select(x => x.Id));
        }
Exemple #16
0
        public HttpResponseMessage GetAllMaintenaceBookings()
        {
            var context     = new TimeTableContext(WebConfigurationManager.AppSettings["DbConnectionString"]);
            var repository  = new UserRepository(context);
            var userService = new UserService(repository);

            var user = userService.GetUserById(UserId);

            if (user.Role != TimeTableRole.Management && user.Role != TimeTableRole.Admin && user.Role != TimeTableRole.Fit)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Insufficient permissions."));
            }

            var bookingRepository   = new BookingRepository(context);
            var classroomRepository = new ClassroomRepository(context);
            var bookingService      = new BookingService(bookingRepository, classroomRepository);

            var allBookings = bookingService.GetAllMaintenanceBookings();

            return(Request.CreateResponse(HttpStatusCode.OK, allBookings));
        }
Exemple #17
0
        public void GetWeekWorkload_AllDayBooking()
        {
            var repo = CreateRepo(
                new BookingEntity {
                From = Dth(0), To = Dth(24)
            },
                new BookingEntity {
                From = Dth(0, 1), To = Dth(0, 2)
            });
            var bookingService = new BookingService(repo, null, _costEvaluationService, null, null);

            IList <DayWorkloadDto> result = bookingService.GetWeekWorkload(DateTime.Today).ToList();

            Assert.AreEqual(7, result.Count);
            Assert.AreEqual(0, result[0].FreeHours.Length);
            Assert.AreEqual(0, result[1].FreeHours.Length);
            for (int i = 2; i < result.Count; i++)
            {
                Assert.AreEqual(24, result[i].FreeHours.Length);
            }
        }
        public void ShouldThrowExceptionIfCabsAreNotAvailable()
        {
            var pickupLocation       = new GeoCoordinate(12.99711, 77.61469);
            var bookingRepo          = new Mock <IBookingRepository>();
            var availableCabsService = new Mock <IAvailableCabsService>();

            availableCabsService.Setup(a => a.GetNearestCab(pickupLocation, new CabType[] { CabType.Regular, CabType.Pink })).Returns(() => { return(null); });

            var bookingService       = new BookingService(bookingRepo.Object, availableCabsService.Object);
            var createBookingRequest = new CreateBookingRequest()
            {
                PickupLocation = pickupLocation,
                Destination    = new GeoCoordinate(13, 77),
                Time           = DateTime.Now,
                UserId         = "1"
            };

            Assert.Throws <Exception>(() => bookingService.CreateBooking(createBookingRequest));

            availableCabsService.Verify(a => a.GetNearestCab(createBookingRequest.PickupLocation, new CabType[] { CabType.Regular, CabType.Pink }));
        }
        public void ShouldGetBookingById()
        {
            var expectedBooking = new Domain.Booking(
                "100",
                "1234",
                "101",
                new GeoCoordinate(13, 77),
                new GeoCoordinate(14, 77),
                DateTime.Now,
                BookingStatus.Accepted
                );
            var bookingRepo = new Mock <IBookingRepository>();

            bookingRepo.Setup(b => b.Get("100")).Returns(expectedBooking);
            var availableCabsService = new Mock <IAvailableCabsService>();

            var bookingService = new BookingService(bookingRepo.Object, availableCabsService.Object);
            var actual         = bookingService.GetBooking("100");

            bookingRepo.Verify(b => b.Get("100"));
        }
        [Fact] // state based (black box)
        public void Successful_booking_should_be_persisted()
        {
            // arrange
            var id = Guid.NewGuid().ToString();
            var bookingRepository = new BookingRepositoryMongoDB(this.mongoClient);
            // unmanaged dependency - interface
            var paymentGateway  = A.Fake <IPaymentGateway>();
            var priceCalculator = A.Fake <IPriceCalculator>();
            var sut             = new BookingService(bookingRepository, paymentGateway, priceCalculator);

            // simulate that the payment fails
            A.CallTo(() => paymentGateway.CapturePayment(A <decimal> .Ignored)).Returns(true);

            // act
            sut.CreateBooking(new BookingService.CreateBookingRequest(id, "jason"));

            var booking = bookingRepository.GetById(id);

            // assert
            booking.Id.Should().Be(id);
        }
Exemple #21
0
        public void BookingServiceSavesBookingIfValidationPasses()
        {
            var now            = DateTime.Now;
            var bookingRequest = new BookingRequest
            {
                DoctorId  = _doctorId,
                PatientId = _patientId,
                StartTime = now
            };

            var validator = new Mock <IBookingRequestValidator>();

            validator.Setup(r => r.ValidateRequest(bookingRequest)).Returns(new PdrValidationResult(true));
            var service = new BookingService(_context, validator.Object);

            service.MakeBooking(bookingRequest);

            validator.Verify(r => r.ValidateRequest(bookingRequest), Times.Once);

            Assert.That(_context.Order.Count(b => b.StartTime == now), Is.EqualTo(1));
        }
Exemple #22
0
        public void GetAllBookings()
        {
            var bookingdata = GenerateTestBookingData().AsQueryable();
            var mockSet     = GetMockset(bookingdata);

            /*var bm = new List<BookingModel>();
             * foreach (var mock in mockSet.Object)
             * {
             *  bm.Add(new BookingModel{BookingId = mock.BookingId, Customer = mock.Customer, TimeOfVisit = mock.TimeOfVisit, EndTime = mock.EndTime});
             * }
             * var bmq = bm.AsQueryable();*/

            var contextOptions = new DbContextOptions <BookingContext>();
            var mockContext    = new Mock <BookingContext>(contextOptions);

            mockContext.Setup(c => c.Bookings).Returns(mockSet.Object);

            var service  = new BookingService(mockContext.Object);
            var bookings = service.GetAllBookings().AsQueryable();

            Assert.Equal(bookingdata, bookings);
        }
        public static async Task <Models.BookingStatus> BookingRooms(BookingReq value, string SessionID, string BN)
        {
            BookingRes    hotels  = new BookingRes();
            BookingStatus booking = new BookingStatus();

            try
            {
                //yyyy-mm-dd

                BookingMapping.MapRequestToDB(value, SessionID, BN);
                hotels = await BookingService.BookingRoomsService(value, SessionID);

                if (hotels == null)
                {
                    booking.status = 2;
                    return(booking);
                }
                BookingMapping.MapResponseToDB(hotels, SessionID, BN);
                booking.status  = 0;
                booking.booking = hotels.booking;
                return(booking);
            }
            catch (Exception ex)
            {
                var requestData = JsonConvert.SerializeObject(ex);

                LoggingHelper.WriteToFile("HBLogs/BookingException", "BookingException_" + SessionID, "BookingException", requestData);
                if (hotels != null)
                {
                    booking.status  = 1;
                    booking.booking = hotels.booking;
                    return(booking);
                }

                booking.status  = 2;
                booking.booking = null;
                return(booking);
            }
        }
        public void Create_ShouldAddNewBookingWithTeGivenParamsIntoTheDb()
        {
            //Arrange
            var homeId       = 1;
            var checkInDate  = DateTime.UtcNow.AddDays(10);
            var checkOutDate = DateTime.UtcNow.AddDays(11);

            var db      = LendYourHomeDbMock.New();
            var service = new BookingService(db);

            //Act
            service.Create(guestId, homeId, checkInDate, checkOutDate);

            //Assert
            db.Bookings
            .Any(b => b.GuestId == guestId &&
                 b.HomeId == homeId &&
                 b.CheckInDate == checkInDate &&
                 b.CheckOutDate == checkOutDate)
            .Should()
            .BeTrue();
        }
        public void GetDayWorkload_BookingOutsideOfTheDay()
        {
            var repo = CreateRepo(
                new BookingEntity {
                From = Dth(12, -1), To = Dth(1)
            },
                new BookingEntity {
                From = Dth(23), To = Dth(12, 1)
            });
            var bookingService = new BookingService(repo, null, _costEvaluationService, null, null);

            IList <DayHourDto> result = bookingService.GetDayWorkload(DateTime.Today).ToList();

            Assert.AreEqual(24, result.Count);
            Assert.AreEqual(2, result.Count(x => !x.Available));
            Assert.IsTrue(result
                          .Where(x => !x.Available)
                          .Select(x => x.Hour)
                          .All(x =>
                               x == 0 || x == 23
                               ));
        }
        // Helpers

        private async Task RunInContextAsync(Func <RoomsController, PeopleController, BookingsController, Task> func)
        {
            var dbOptions = new DbContextOptionsBuilder <RoomBookingsContext>().UseInMemoryDatabase(databaseName: "RoomBookings" + new Random().Next(1, 100000))
                            .Options;

            using (var context = new RoomBookingsContext(dbOptions))
            {
                var _mockBookingRepository = new Repository <Booking>(context);
                var _mockPersonRepository  = new Repository <Person>(context);
                var _mockPersonService     = new PersonService(_mockPersonRepository);
                var _mockPeopleController  = new PeopleController(_mockPersonService);
                var _mockBookingService    = new BookingService(_mockBookingRepository);

                var _mockRoomRepository  = new Repository <Room>(context);
                var _mockRoomService     = new RoomService(_mockRoomRepository, _mockBookingRepository);
                var _mockRoomsController = new RoomsController(_mockRoomService);

                var _mockBookingsController = new BookingsController(_mockBookingService);

                await func(_mockRoomsController, _mockPeopleController, _mockBookingsController);
            }
        }
Exemple #27
0
        public void SetUp()
        {
            // Boilerplate
            _mockRepository = new MockRepository(MockBehavior.Strict);
            _fixture        = new Fixture();

            //Prevent fixture from generating from entity circular references
            _fixture.Behaviors.Add(new OmitOnRecursionBehavior(1));

            // Mock setup
            _context   = new PatientBookingContext(new DbContextOptionsBuilder <PatientBookingContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
            _validator = _mockRepository.Create <IAddBookingRequestValidator>();

            // Mock default
            SetupMockDefaults();

            // Sut instantiation
            _bookingService = new BookingService(
                _context,
                _validator.Object
                );
        }
Exemple #28
0
        public BookingServiceTests()
        {
            _mockdistributedCacheExpirationConfiguration.Setup(_ => _.Value).Returns(_cacheConfig);
            _mockMappingService
            .Setup(_ => _.MapBookingRequest(It.IsAny <string>(), It.IsAny <IElement>(), It.IsAny <Dictionary <string, object> >(), It.IsAny <string>()))
            .ReturnsAsync(new BookingRequest {
                Customer = new Customer()
            });
            _bookingProvider.Setup(_ => _.ProviderName).Returns("testBookingProvider");
            _bookingProviders = new List <IBookingProvider>
            {
                _bookingProvider.Object
            };

            _service = new BookingService(
                _mockDistributedCache.Object,
                _mockPageHelper.Object,
                _bookingProviders,
                _mockPageFactory.Object,
                _mockMappingService.Object,
                _mockdistributedCacheExpirationConfiguration.Object);
        }
Exemple #29
0
        public async Task ShouldCancelBooking()
        {
            using var connection = new SqliteConnection("Filename=:memory:");
            connection.Open();

            var options = new DbContextOptionsBuilder <DiallogDbContext>()
                          .UseSqlite(connection)
                          .Options;

            using var dbContext = new DiallogDbContext(options);
            dbContext.Database.EnsureCreated();

            var bookingService = new BookingService(dbContext);

            var booking = new Booking
            {
                GuestUserId = "XXXXXX",
                GuestName   = "XXXXXX",
                Car         = new Car {
                    DailyRentalCost = 100, GasConsumption = "XXXXX", NumberOfUnits = 3
                },
                StartDateUtc = DateTime.UtcNow,
                EndDateUtc   = DateTime.UtcNow.AddDays(3)
            };

            var result = await bookingService.AddBooking(booking);

            Assert.True(result.Success);
            Assert.Equal(1, result.Id);
            Assert.Empty(result.ValidationErrors);

            var bookingId = result.Id.Value;

            result = await bookingService.CancelBooking("tester", bookingId);

            booking = await bookingService.GetBooking(bookingId);

            Assert.Equal(BookingStatus.Cancelled, booking.Status);
        }
Exemple #30
0
        public async Task ShouldReturnPayments()
        {
            using var connection = new SqliteConnection("Filename=:memory:");
            connection.Open();

            var options = new DbContextOptionsBuilder <DiallogDbContext>()
                          .UseSqlite(connection)
                          .Options;

            using var dbContext = new DiallogDbContext(options);
            dbContext.Database.EnsureCreated();

            var paymentService = new StripePaymentService(dbContext);
            var bookingService = new BookingService(dbContext);

            var booking = new Booking
            {
                GuestUserId = "XXXXXX",
                GuestName   = "XXXXXX",
                Car         = new Car {
                    DailyRentalCost = 100, GasConsumption = "XXXXX", NumberOfUnits = 3
                },
                StartDateUtc = DateTime.UtcNow,
                EndDateUtc   = DateTime.UtcNow.AddDays(3)
            };

            var result = await bookingService.AddBooking(booking);

            booking.Id = result.Id.Value;
            booking.AddPayment(100);
            booking.AddPayment(200);

            await bookingService.UpdateBooking("tester", booking);

            var payments = await paymentService.GetPayments();

            Assert.NotEmpty(payments);
            Assert.Equal(2, payments.Count);
        }
Exemple #31
0
        public void Get_WhenIncorrectData_ShouldThrowAppropriateException()
        {
            // Arrange
            var flight = PrepareFlightDetails();
            var person = new Person {
                Id = 1, Name = "Test", DateBirth = DateTime.Now.Date, Gender = GenderType.Male, Address = "TestAddress", Email = "*****@*****.**"
            };

            var testBooking = new Booking {
                Id = 77, Number = "54321", Flight = flight, Customer = person, DateBooking = DateTime.Now, Passengers = new List <Person> {
                    person
                }
            };
            var bookings = new List <Booking>
            {
                testBooking,
                new Booking {
                    Id = 87, Number = "12345", Flight = flight, Customer = person, DateBooking = DateTime.Now, Passengers = new List <Person> {
                        person
                    }
                }
            };

            Mapper.Reset();
            Mapper.Initialize(cfg => cfg.CreateMap <Booking, BookingDto>());

            var mockPersonRepository  = new Mock <IRepository <Person> >();
            var mockBookingRepository = new Mock <IRepository <Booking> >();
            var mockFlightRepository  = new Mock <IRepository <Flight> >();

            mockBookingRepository.Setup(x => x.GetAll()).Returns(bookings);

            var bookingService = new BookingService(Mapper.Instance, mockPersonRepository.Object, mockBookingRepository.Object, mockFlightRepository.Object);

            // Act & Assert
            var exception = Assert.Throws <WingsOnNotFoundException>(() => bookingService.GetBookingByNumber("Not existing number"));

            Assert.AreEqual(exception.Message, "Booking with specified ID is not found.");
        }
        private void button3_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (textBox1.Text == string.Empty || textBox2.Text == string.Empty)
                {
                    MessageBox.Show("Check Booking Id or Feedback");
                }
                else
                {
                    BookingService bs   = new BookingService();
                    Booking        b    = bs.GetById(Convert.ToInt32(textBox2.Text));
                    string         type = b.EventType;

                    FeedbackService feedService = new FeedbackService();
                    int             result      = feedService.Insert(new Feedback()
                    {
                        Feedback_Details = textBox1.Text, Id = Convert.ToInt32(textBox2.Text), Event_Type = type
                    });

                    if (result > 0)
                    {
                        MessageBox.Show("Feedback added.");
                        Customer_Home ch = new Customer_Home();
                        this.Hide();
                        ch.Show();
                    }
                    else
                    {
                        MessageBox.Show("Error");
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Incorrect Input");
            }
        }
Exemple #33
0
        // TODO Ajax this when we have some spare time and pass a message back
        public ActionResult CancelFlight(string flightNumber)
        {
            // TODO Setup some sort of DI and inject this, to remove EF reference and east testing
            MonarchContext context = new MonarchContext();
            BookingService service = new BookingService(context);

            var    vm     = new CancellationViewModel();
            Flight flight = service.GetFlight(flightNumber);

            // Display error if the flight Can#t be found
            if (flight == null)
            {
                vm.Message = "Flight not found";
            }

            // Check if the flight is already Cancelled
            else if (flight.FlightStatus == FlightStatus.Cancelled)
            {
                //TODO Add Logger and log exception
                vm.Message = string.Format("Flight {0} is already cancelled", flight.FlightNumber);
            }
            else
            {
                var cancelled = service.UpdateStatus(flightNumber, FlightStatus.Cancelled);
                if (cancelled)
                {
                    vm.Success = true;
                    vm.Message = string.Format("Flight Number {0} has been cancelled", flight.FlightNumber);
                }
                else
                {
                    //TODO Add Logger and log exception
                    vm.Message = string.Format("Error cancelling Flight Number {0}", flight.FlightNumber);
                }
            }

            return(View(vm));
        }
Exemple #34
0
        public static async Task <Models.Booking> BookingRooms(BookingReq value, string SessionID)
        {
            try
            {
                //yyyy-mm-dd
                BookingMapping.MapRequestToDB(value, SessionID);
                var hotels = await BookingService.BookingRoomsService(value, SessionID);

                if (hotels == null)
                {
                    return(new Models.Booking());
                }
                BookingMapping.MapResponseToDB(hotels, SessionID);
                return(hotels.booking);
            }
            catch (Exception ex)
            {
                var requestData = JsonConvert.SerializeObject(ex);

                LogData.WriteToFile("c:/HotelsB2C/Logs/HBLogs/BookingException", "BookingException_" + SessionID, "BookingException", requestData);
                return(new Models.Booking());
            }
        }
        public void SetUp()
        {
            routingService = new RoutingServiceImpl();

            applicationEvents = new SynchronousApplicationEventsStub();

            // In-memory implementations of the repositories
            handlingEventRepository = new HandlingEventRepositoryInMem();
            cargoRepository = new CargoRepositoryInMem();
            locationRepository = new LocationRepositoryInMem();
            voyageRepository = new VoyageRepositoryInMem();

            // Actual factories and application services, wired with stubbed or in-memory infrastructure
            handlingEventFactory = new HandlingEventFactory(cargoRepository, voyageRepository, locationRepository);

            cargoInspectionService = new CargoInspectionService(applicationEvents, cargoRepository,
                                                                handlingEventRepository);
            handlingEventService = new HandlingEventService(handlingEventRepository, applicationEvents,
                                                            handlingEventFactory);
            bookingService = new BookingService(cargoRepository, locationRepository, routingService);

            // Circular dependency when doing synchrounous calls
            ((SynchronousApplicationEventsStub) applicationEvents).SetCargoInspectionService(cargoInspectionService);
        }