public BookingResponse RejectBooking(BookingDetailInfor bookingDetailInfor)
 {
     using (StageBitzDB dataContext = new StageBitzDB())
     {
         InventoryBL     inventoryBL     = new InventoryBL(dataContext);
         BookingResponse bookingResponse = inventoryBL.RejectBooking(bookingDetailInfor.ItemBookingId, bookingDetailInfor.UserId);
         return(bookingResponse);
     }
 }
Beispiel #2
0
        private static void WriteBookingResult(BookingResponse response, Currency currentCurrency)
        {
            var price = response.BookingOptions.Select(option => option.BookingItems.Sum(item => item.Price)).Min();

            Write("  price: ");
            //Format price according to currency
            WriteLine(ImportantColor, currentCurrency.FormatValue(price));
            WriteLegs(response.Itinerary);
        }
Beispiel #3
0
        public async Task <BookingResponse> IsAvailable(Booking booking)
        {
            BookingResponse bookingResponse = null;

            if (booking == null)
            {
                return(bookingResponse);                 // always validate the data first before taking it down
            }
            return(await FindBooking(booking));
        }
        public static BookingResponse BookingEntityToResponse(bool booked, int numberOfSeats, int totalTicketPrice)
        {
            BookingResponse bookingResponse = new BookingResponse()
            {
                Booked        = booked,
                NumberOfSeats = numberOfSeats,
                TotalPrice    = totalTicketPrice
            };

            return(bookingResponse);
        }
Beispiel #5
0
        public ActionResult <BookingResponse> GetBooking(int Id)
        {
            BookingResponse bookingResponse = bookingServices.GetBooking(Id);

            if (bookingResponse == null)
            {
                return(NotFound());
            }

            return(bookingResponse);
        }
Beispiel #6
0
        public BaseTests()
        {
            HttpClient = new APIClient();
            Search     = new ResponseSearch();
            Compare    = new CompareHelper();

            AuthModel        = new Authentication();
            BookingModel     = new Booking();
            BookingRespModel = new BookingResponse();

            TestUrl = new BaseTestsUrls();
        }
Beispiel #7
0
        public async void BookTripNow()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            if (Email.Length == 0 || !Email.Contains("@") ||
                Name.Length == 0 || Phone.Length == 0 || Persons.Length == 0)
            {
                await showDialog("Alert!", "Please enter all information first.");
            }
            else
            {
                var dialog = UserDialogs.Instance;
                dialog.ShowLoading("Please wait...", MaskType.Black);
                string time = "";

                if (BookingTimes.Count > SelectedTimeIndex)
                {
                    time = BookingTimes[SelectedTimeIndex];
                }

                BookingResponse response = await dataService.BookTrip(RecievedBooking.id, Name, Phone, Persons,
                                                                      (string)Email.ToLower(),
                                                                      SelectedDate.ToString(), time);

                if (response != null)
                {
                    if (response.status.Equals("failure"))
                    {
                        await showDialog("Alert!", "Oops, " + response.message);
                    }
                    else if (response.status.Equals("success"))
                    {
                        dialog.HideLoading();
                        await showDialog("Success", "Your tour booking is sent, you will be contacted by administrator for confirmation. Thank you");

                        await _navigationService.NavigateAsync("MainPage");
                    }
                    dialog.HideLoading();
                }
                else
                {
                    dialog.HideLoading();
                    await showDialog("Alert!", "You are not connected to internet, please try again later.");
                }
            }

            IsBusy = false;
        }
Beispiel #8
0
        private void GetData()
        {
            BasicHttpBinding binding  = new BasicHttpBinding();
            EndpointAddress  EndPoint = new EndpointAddress("http://192.168.60.157:88/booking");
            Reservation      r        = new Reservation
            {
                HotelName = "HotelA"
            };
            HotelBookingServiceClient Cliente = new HotelBookingServiceClient(binding, EndPoint);
            BookingResponse           Result  = Cliente.BookHotel(r);

            lblResult.Text = Result.BookingReference.ToString();
        }
Beispiel #9
0
        public async void RefreshList()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy           = true;
            isRefreshingList = true;
            StatusText       = "Getting new data...";

            BookingResponse response = await dataService.getAllBookingsOf(RecievedBookingType.booking_type_id);

            if (response != null)
            {
                if (response.status.Equals("success"))
                {
                    int colorFlipper         = 0;
                    List <BookingItem> items = new List <BookingItem>();
                    foreach (BookingItem row in response.data)
                    {
                        if (row.image == null || row.image.Length == 0)
                        {
                            row.image = "img_na_placeholder.png";
                        }

                        row.Randomise();
                        items.Add(row);
                        colorFlipper++;
                    }
                    BookingsList = new ObservableCollection <BookingItem>(items);
                    BookingsList.OrderByDescending(x => x.id);

                    if (BookingsList.Count() > 0)
                    {
                        IsHasDataFlag = false;
                    }
                    else
                    {
                        StatusText    = "No Data Available";
                        IsHasDataFlag = true;
                    }
                }
            }
            else
            {
                StatusText = "Service is Unavailable";
            }

            IsBusy           = false;
            isRefreshingList = false;
        }
Beispiel #10
0
        public async Task <IActionResult> GetCustomers(string customerId)
        {
            try
            {
                _logger.LogInformation("Start: Fetching Cookie Token");
                string cookieToken = await _authService.GetPadCookie();

                _logger.LogInformation("Ended: Fetching Cookie Token");
                _logger.LogInformation("Start: Fetching Booking Info: " + customerId);
                Booking booking = await _employeeService.GetBookingInfo(customerId, cookieToken);

                _logger.LogInformation("End: Fetching Booking Info: " + customerId);
                _logger.LogInformation("Start: Fetching Customer Info: ");
                BookingResponse bookingResponse = await _employeeService.GetBookingList(booking, cookieToken);

                _logger.LogInformation("End: Fetching Customer Info: ");
                if (bookingResponse.bookingType != Convert.ToString(HelperUtils.BookingType.NOMS_3RD_PARTY))
                {
                    _logger.LogInformation("Start: Fetching Slot Info: ");
                    V2_Checkin bookingSlot = _databaseService.GetBookingSlot(customerId, bookingResponse.contractNumber);
                    if (bookingSlot != null)
                    {
                        bookingResponse.checkinDate = bookingSlot.CheckinDate?.ToString("yyyy-MM-dd");
                        bookingResponse.checkinTime = bookingSlot.CheckinTime?.ToString();
                    }
                    _logger.LogInformation("End: Fetching Slot Info: ");
                    _logger.LogInformation("Start: Fetching Photo Info: ");
                    V2_PhotoId photoDetails = _databaseService.GetPhotoIdDetails(customerId, bookingResponse.contractNumber);
                    if (photoDetails != null)
                    {
                        // string testPath = HttpUtility.UrlDecode("https://unitestorageaccount.blob.core.windows.net/unitecontainer/10074458%2FRN20000378_Regular.png");
                        bookingResponse.photoIdPath = !string.IsNullOrEmpty(photoDetails.PhotoIdPath) ? await _storageService.GetPhotoUrlWithSasToken(HttpUtility.UrlDecode(photoDetails.PhotoIdPath)) : "";

                        //bookingResponse.photoIdPath = !string.IsNullOrEmpty(photoDetails.PhotoIdPath) ? await _storageService.GetPhotoUrlWithSasToken(testPath) : "";
                    }
                    _logger.LogInformation("End: Fetching Photo Info: ");
                }
                else
                {
                    _logger.LogInformation("NOMS_3RD_PARTY Found: " + Convert.ToString(HelperUtils.BookingType.NOMS_3RD_PARTY));
                }
                return(Ok(bookingResponse));
            }
            catch (Exception ex)
            {
                _logger.LogError("GetCustomers Error ==> " + ex.Message.ToString());
                return(BadRequest(ex.Message.ToString()));
            }
        }
        public BookingResponse GetSampleBookingResponse()
        {
            BookingResponse response = new BookingResponse()
            {
                StartPoint     = "Ashoknagar",
                Destination    = "Venkampet",
                SeatsAvailable = 4,
                RideDate       = DateTime.Now.Date.ToShortDateString(),
                RideTime       = "3am-6am",
                Price          = 500,
                Name           = "Santhu"
            };

            return(response);
        }
        /// <summary>
        /// cofirm booking
        /// </summary>
        /// <param name="bookingModel"></param>
        /// <returns></returns>
        public async Task <BookingResponse> MakeBooking(BookingRequest bookingModel, ViatorSetting setting = null)
        {
            var uri      = $"/service/booking/book";
            var response = await _httpClient.PostAsync <BookingRequest>(GenerateBaseURL(uri, setting), bookingModel);

            if (response.IsSuccessStatusCode)
            {
                var content = response.Content.ReadAsStringAsync().Result;
                var result  = BookingResponse.FromJson(content);
                return(result);
            }
            else
            {
                throw new Exception("Viator API - Booking: Api error response");
            }
        }
Beispiel #13
0
        public ActionResult <BookingResponse> PostBooking(BookingEntity bookingEntity)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            BookingResponse bookingResponse = bookingServices.BookMovie(bookingEntity);

            if (bookingResponse == null)
            {
                return(BadRequest());
            }

            return(CreatedAtAction("GetBooking", new { bookingEntity.Id }, bookingResponse));
        }
Beispiel #14
0
        public bool SetBookingRequestComplete(BookingResponse bookingResponse, IQueueConfig queueConfig)
        {
            try
            {
                try
                {
                    string fileName = bookingResponse.ReservationId + ".txt";

                    if (File.Exists(Path.Combine(queueConfig.PendingBookingQueuePath, fileName)))
                    {
                        string queuePathToMove = string.Empty;
                        switch (bookingResponse.BookingStatus)
                        {
                        case BookingStatus.Confirmed:
                            queuePathToMove = queueConfig.ConfirmedBookingQueuePath;
                            break;

                        case BookingStatus.Rejected:
                            queuePathToMove = queueConfig.RejectedNotificationQueuePath;
                            break;

                        case BookingStatus.Booked:
                            queuePathToMove = queueConfig.PendingBookingQueuePath;
                            break;

                        default:
                            queuePathToMove = queueConfig.ErrorQueuePath;
                            break;
                        }

                        // move file to error queue
                        File.Move(Path.Combine(queueConfig.PendingBookingQueuePath, fileName), Path.Combine(queuePathToMove, fileName));

                        return(true);
                    }
                }
                catch
                {
                }
            }
            catch
            {
                // todo logging
            }

            return(false);
        }
Beispiel #15
0
        /// <summary>
        /// Metoda zwracająca listę wcześniejszych rezerwacji.
        /// </summary>
        /// <returns>Informacje o wcześniejszych rezerwacjach</returns>
        internal BookingResponse[] GetBookings()
        {
            if (loggedUser != null)
            {
                RezerwacjaRepository        rezerwacjaRepository        = new RezerwacjaRepository();
                MiejsceRezerwacjaRepository miejsceRezerwacjaRepository = new MiejsceRezerwacjaRepository();
                MiejsceRepository           miejsceRepository           = new MiejsceRepository();
                FilmRepository  filmRepository  = new FilmRepository();
                SeansRepository seansRepository = new SeansRepository();

                List <RezerwacjaEntity> rezerwacje = rezerwacjaRepository.FindAllByUzytkownikId(loggedUser.Id);
                List <BookingResponse>  bookings   = new List <BookingResponse>();
                foreach (RezerwacjaEntity rezerwacja in rezerwacje)
                {
                    BookingResponse booking = new BookingResponse();

                    SeansEntity seans = seansRepository.FindById(rezerwacja.IdSeansu).OrElseThrow("Nie istnieje seans o podanym ID");
                    booking.DateTime = seans.Kiedy;

                    FilmEntity film = filmRepository.FindById(seans.IdFilmu).OrElseThrow("Nie można odnaleźć w bazie danych filmu o podanym ID");
                    booking.FilmName = film.Nazwa;

                    List <BookedSeatResponse>      bookedSeats       = new List <BookedSeatResponse>();
                    List <MiejsceRezerwacjaEntity> miejscaRezerwacje = miejsceRezerwacjaRepository.FindAllByRezerwacjaId(rezerwacja.Id);
                    foreach (MiejsceRezerwacjaEntity miejsceRezerwacja in miejscaRezerwacje)
                    {
                        BookedSeatResponse bookedSeat = new BookedSeatResponse();

                        MiejsceEntity miejsce = miejsceRepository.FindById(miejsceRezerwacja.IdMiejsca).OrElseThrow("Nie istnieje miejsce o podanym ID");
                        bookedSeat.PosX = miejsce.Numer;
                        bookedSeat.PosY = miejsce.Rzad;

                        bookedSeats.Add(bookedSeat);
                    }
                    booking.Seats = bookedSeats.ToArray();

                    bookings.Add(booking);
                }

                return(bookings.ToArray());
            }
            else
            {
                throw new Exception("Nie uzyskano autoryzacji do wykonania zadania");
            }
        }
        public async Task Booking_ShouldCreateUser_ifsuccesswithmorethan1Category()
        {
            //Arrange
            string userid = "222", userName = "******", subEventID = "2", TotalAmt = "12000", eventID = "1";
            string BookingID = "", NoofTickets = "2", TicketCategory = "1";

            Random ObjRan = new Random();

            BookingID = Convert.ToString(ObjRan.Next(1000000, 99999999));

            Booking objBooking = new Booking();

            objBooking.UserID      = userid;
            objBooking.UserName    = userName;
            objBooking.EventID     = eventID;
            objBooking.SubEventID  = subEventID;
            objBooking.TotalAmount = TotalAmt;

            BookingRequest objBookingRequest = new BookingRequest();

            objBookingRequest.NoofTickets    = NoofTickets;
            objBookingRequest.TicketCategory = TicketCategory;

            objBooking.Request.Add(objBookingRequest);
            objBooking.Request.Add(objBookingRequest);

            _eventRepoMock.Setup(x => x.BookingDB(objBooking, BookingID, It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync("Booking Confirmed");

            BookingResponse objBookingResponse = new BookingResponse();

            objBookingResponse.BookingID       = BookingID;
            objBookingResponse.ResponseMessage = "Booking Confirmed";
            objBookingResponse.UserID          = userid;
            objBookingResponse.UserName        = userName;
            //Act

            var customer = await _EventBookingService.Booking(objBooking, BookingID);

            //Assert

            Assert.Equal(objBookingResponse.ResponseMessage, customer.ResponseMessage);
            Assert.Equal(objBookingResponse.BookingID, customer.BookingID);
            Assert.Equal(objBookingResponse.UserID, customer.UserID);
            Assert.Equal(objBookingResponse.UserName, customer.UserName);
        }
Beispiel #17
0
        public async Task Booking_ShouldCreateUser_ifsuccess()
        {
            //Arrange
            string userid = "222", userName = "******", subEventID = "2", TotalAmt = "12000", eventID = "1";
            string BookingID = "", NoofTickets = "2", TicketCategory = "1";

            Random ObjRan = new Random();

            BookingID = Convert.ToString(ObjRan.Next(1000000, 99999999));

            Booking objBooking = new Booking();

            objBooking.UserID      = userid;
            objBooking.UserName    = userName;
            objBooking.EventID     = eventID;
            objBooking.SubEventID  = subEventID;
            objBooking.TotalAmount = TotalAmt;

            BookingRequest objBookingRequest = new BookingRequest();

            objBookingRequest.NoofTickets    = NoofTickets;
            objBookingRequest.TicketCategory = TicketCategory;

            objBooking.Request.Add(objBookingRequest);

            string queryString = "";

            queryString = "sp_BookingConfirmation @userName,@BookingID,@StatusInfo,@EventID,@SubEventID,@TicketCategory,@nNoofTickets,@TotalAmount,@MessageStatus Out";

            _eventDBMock.Setup(x => x.ExecuteAsyncSql(It.IsAny <SqlParameter[]>(), queryString, 8)).ReturnsAsync("Booking Confirmed");

            BookingResponse objBookingResponse = new BookingResponse();

            objBookingResponse.BookingID       = BookingID;
            objBookingResponse.ResponseMessage = "Booking Confirmed";
            objBookingResponse.UserID          = userid;
            objBookingResponse.UserName        = userName;
            //Act

            var customer = await _eventBookingRepository.BookingDB(objBooking, BookingID, TicketCategory, NoofTickets);

            //Assert

            Assert.Equal(objBookingResponse.ResponseMessage, customer);
        }
Beispiel #18
0
        public async void SubmitNow()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            if (Email.Length == 0 || !Email.Contains("@") ||
                Name.Length == 0 ||
                Phone.Length == 0 ||
                Comments.Length == 0
                )
            {
                await showDialog("Alert!", "Please enter all information first.");
            }
            else
            {
                var dialog = UserDialogs.Instance;
                dialog.ShowLoading("Please wait...", MaskType.Black);
                BookingResponse response = await dataService.PostFeedback(Name, Phone, (string)Email.ToLower(), Comments);

                if (response != null)
                {
                    if (response.status.Equals("failure"))
                    {
                        await showDialog("Alert!", "Oops, " + response.message);
                    }
                    else if (response.status.Equals("success"))
                    {
                        dialog.HideLoading();
                        await showDialog("Feedback is Sent,", "Thank you for your feedback.");

                        await _navigationService.NavigateAsync("MainPage");
                    }
                    dialog.HideLoading();
                }
                else
                {
                    dialog.HideLoading();
                    await showDialog("Alert!", "You are not connected to internet, please try again later.");
                }
            }
            IsBusy = false;
        }
        public void ReturnsLessonBookingResultWIthRequestValues()
        {
            //Arrange
            var request = _factory.GetBaseBooking();

            //Act
            BookingResponse response = _service.BookLesson(request);

            //Assert
            Assert.NotNull(response);
            Assert.Equal(request.StudentId, response.StudentId);
            Assert.Equal(request.FirstName, response.FirstName);
            Assert.Equal(request.LastName, response.LastName);
            Assert.Equal(request.Email, response.Email);
            Assert.Equal(request.Date, response.Date);
            Assert.Equal(request.Hours, response.Hours);
            Assert.Equal(request.Minutes, response.Minutes);
        }
Beispiel #20
0
        public List <BookingResponse> BookingRequests(long userId)
        {
            User                   user                 = _userRepository.Get(userId);
            List <Booking>         rideBookings         = _repository.GetAll().Where(r => r.RideOfferId == user.LastOfferRideId && r.Status == BookingStatus.Requested).ToList();
            List <BookingResponse> RideBookingResponses = new List <BookingResponse>();

            foreach (Booking booking in rideBookings)
            {
                BookingResponse rideDetails = _mapper.Map <Booking, BookingResponse>(booking);
                rideDetails.Name        = _userRepository.Get(booking.BookingUserId).Name;
                rideDetails.StartPoint  = booking.StartPoint.Split(",")[0];
                rideDetails.Destination = booking.Destination.Split(",")[0];
                rideDetails.RideDate    = booking.RideBookingDate.ToString("dd/MM/yyyy");

                RideBookingResponses.Add(rideDetails);
            }
            return(RideBookingResponses);
        }
Beispiel #21
0
        public async Task <BookingResponse> IsAvailable(Booking booking)
        {
            BookingResponse bookingResponse = null;

            if (booking == null)
            {
                return(bookingResponse);                 // always validate the data first before taking it down
            }
            try
            {
                bookingResponse = await _sampleBookingData.IsAvailable(booking);
            }
            catch (Exception)
            {
                //yell / shout //catch // log
            }

            return(bookingResponse);
        }
Beispiel #22
0
        /// <summary>
        ///  Reservar assento para um cliente em um voo e indicar um link do site onde ele possa pagar o assento
        ///  depois de deixar o booking negativo
        ///  Nesta função, irei repetir algumas chamadas do método ConsultarAssentosDisponiveisEmUmVoo,
        ///  pois a marcação de assento segue o mesmo princípio da exibição do mapa de assento.
        ///  Outro ponto é que para que eu possa marcar um assento, se faz necessário o unityKey,
        ///  que é retornado justamente na função que traz o mapa de assento. Com relação a marcação de assentos,
        ///  estamos usando apenas um fluxo feliz, ou seja o passageiro que iremos utilizar não possui assento,
        ///  caso contrário teríamos que  remover o assento, para após marcar um novo.
        ///  Outro ponto é que o usuário não pode realizar mudança de assento, para um assento de valor inferior ao já registrado na reserva.
        ///  Pois hoje a Azul não trabalha com reembolso do valor do assento.
        /// </summary>
        static async Task ComprarAssentoParaClienteEmUmVoo()
        {
            ///Obtendo o token necessário para consumir o serviço da Navitaire.
            string token = await(new LoginBusiness()).LogonAndGetTokenNavitaire();

            BookingBusiness bookingBusiness = new BookingBusiness(token);
            SeatBusiness    seatBusiness    = new SeatBusiness(token);

            ///Para que possamos fazer qualquer alteração de uma reserva, se faz necessário estamos com ela em sessão.
            ///por esse motivo realizamos usamos a função ReatriveBooking. Desta forma inserindo em sessão o booking que iremos trabalhar.
            BookingResponse booking = await bookingBusiness.ReatriveBooking("G7VIVI");

            ///Para facilitar o desenvolvimento, estamos sempre usando a chave do primeiro seguinto, da primeira jornada.
            List <SeatMapResponse> seatMapResponseList = await seatBusiness.GetSeatMapAvailabilityBySegmentKey(booking.Journeys[0].Segments[0].SegmentKey);

            ///Caso o tenhamos assento para o primeiro segmento, realizamos a remoção, assim prosseguindo com o fluxo de marcação.
            if (seatBusiness.ThereIsSeatReservedFirstPassenger(booking))
            {
                Seat seat = booking.Journeys[0]?.Segments[0]?.PassengersSegment[0].Value?.Seats[0];
                await seatBusiness.UnassignPassengerSegmentSeat(seat.PassengerKey, seat.UnitKey);
            }

            ///Função retorna os assentos disponíveis, usando como base os atributos Type e Assignable, do objeto unit.
            ///O objeto unit representa uma unidade de espaço dentro a aeronave, ou seja posso ter unit, que representam
            ///espaços em brancos ou por exemplo o banheiro de uma determinada aeronave.
            ///Para trazermos apenas unidades que representam assento, estamos verificando sei o campo Type,
            ///está sendo preenchido com o valor “NormalSeat”. Alem de verificar se o valor do objeto Assignable está como true,
            ///indicando que o assento está disponível para marcação.
            ///Outro filtro que tive que incluir, pois a Navitaire estava me levantando erro é quando o assento está disponível para marcação,
            ///porém ele está em espera, por esse motivo, colocamos um filtro no campo Availability, trazendo apenas assentos com o valor
            ///deste campo igual a open (disponível).
            List <Unit> units = seatBusiness.GetAvailabilitySeat(seatMapResponseList);

            ///Está função realiza a marcação de assento, usando como base o booking em sessão, a key do passageiro informado e a
            ///key do assento que será atrelado ao usuário.Caso o assento tenha valor a pagar será incluído uma fee(taxa) referente
            ///ao valor do assento.
            await seatBusiness.AssingnmentSeat(booking.Passengers[0].Key, units[0].UnitKey);

            ///Está função é responsavel por salvar as alterações feitas no booking em sessão.
            ///Ela tem como o booking, porém estou apenas retornando informações referente ao valor pago, valor a pagar.
            BookingCommitResponse bookingCommitResult = await bookingBusiness.CommitBooking();
        }
        public async Task Booking_ShouldnotCreateUser_TotalAmountToBePaidnotSent()
        {
            //Arrange
            string userid = "222", userName = "******", subEventID = "2", TotalAmt = "", eventID = "1";
            string BookingID = "", NoofTickets = "2", TicketCategory = "1";

            Random ObjRan = new Random();

            BookingID = Convert.ToString(ObjRan.Next(1000000, 99999999));

            Booking objBooking = new Booking();

            objBooking.UserID      = userid;
            objBooking.UserName    = userName;
            objBooking.EventID     = eventID;
            objBooking.SubEventID  = subEventID;
            objBooking.TotalAmount = TotalAmt;

            BookingRequest objBookingRequest = new BookingRequest();

            objBookingRequest.NoofTickets    = NoofTickets;
            objBookingRequest.TicketCategory = TicketCategory;

            objBooking.Request.Add(objBookingRequest);

            _eventRepoMock.Setup(x => x.BookingDB(objBooking, BookingID, TicketCategory, NoofTickets)).ReturnsAsync("TotalAmount not generated, please try again!!!");

            BookingResponse objBookingResponse = new BookingResponse();

            objBookingResponse.ResponseMessage = "TotalAmount not generated, please try again!!!";
            objBookingResponse.UserID          = userid;
            objBookingResponse.UserName        = userName;
            //Act

            var customer = await _EventBookingService.Booking(objBooking, BookingID);

            //Assert

            Assert.Equal(objBookingResponse.ResponseMessage, customer.ResponseMessage);
            Assert.Equal(objBookingResponse.UserID, customer.UserID);
            Assert.Equal(objBookingResponse.UserName, customer.UserName);
        }
Beispiel #24
0
 /// <summary>
 /// To serialize object to json
 /// </summary>
 /// <param name="BookingResponse"></param>
 /// <returns></returns>
 public static string SerializeJson(BookingResponse response, ITracingService trace)
 {
     if (trace == null)
     {
         throw new InvalidPluginExecutionException("trace is null.");
     }
     if (response == null)
     {
         throw new InvalidPluginExecutionException("Booking response is null;");
     }
     trace.Trace("Processing Serialization of BookingResponse - start");
     using (var memoryStream = new MemoryStream())
     {
         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(BookingResponse));
         serializer.WriteObject(memoryStream, response);
         byte[] json = memoryStream.ToArray();
         trace.Trace("Processing Serialization of BookingResponse - end");
         return(Encoding.UTF8.GetString(json, 0, json.Length));
     }
 }
        static void Main(string[] args)
        {
            IHotelBookingService proxy = null; // TODO channel Factory

            Reservation reservation = new Reservation
            {
                HotelName    = "HotelA",
                GuestName    = "John",
                NumberOfDays = 3,
                CheckinDate  = DateTime.Now
            };

            BookingResponse response = proxy.BookHotel(reservation);

            Console.WriteLine
                ("Booking response: {0}, booking reference: {1}",
                response.IsApproved ? "Approved" : "Declined",
                response.BookingReference);

            Console.ReadLine();
        }
        async Task <BokkingResponseStats> Book(string hotelKey, string guestKey)
        {
            Console.Write(".");
            DateTime start = DateTime.Now;

            //Console.WriteLine($"Book {guestKey} {hotelKey}");
            var hotelAGrain = _client.GetGrain <IHotelGrain>(hotelKey);
            var guest1Grain = _client.GetGrain <IGuestGrain>(guestKey);

            DateTime fromDate = new DateTime(2020, 6, 1).AddDays(_random.Next(0, 180));
            DateTime toDate   = fromDate.AddDays(_random.Next(1, 20));

            var             requestRooms = _random.Next(1, 4);
            BookingResponse response     = null;

            try
            {
                response = await hotelAGrain.BookRoom(guest1Grain.GetPrimaryKeyString(), fromDate, toDate, requestRooms);

                if (response.Sucessfull)
                {
                    Console.Write("+");
                    Interlocked.Increment(ref _bookingsSuccessful);
                }
                else
                {
                    Console.Write("@");
                    Interlocked.Increment(ref _bookingsNoRoom);
                }
            }
            catch (Exception exp)
            {
                Console.Write("E[" + exp.Message + "]");
                Interlocked.Increment(ref _bookingsFailed);
            }
            return(new BokkingResponseStats()
            {
                Response = response, Duration = DateTime.Now - start
            });
        }
        public async Task Booking_ShouldCreateUser_ifsuccess()
        {
            //Arrange
            string userid = "222", userName = "******", subEventID = "2", TotalAmt = "12000", eventID = "1";
            string BookingID = "", NoofTickets = "2", TicketCategory = "1";

            Random ObjRan = new Random();

            BookingID = Convert.ToString(ObjRan.Next(1000000, 99999999));

            Booking objBooking = new Booking();

            objBooking.UserID      = userid;
            objBooking.UserName    = userName;
            objBooking.EventID     = eventID;
            objBooking.SubEventID  = subEventID;
            objBooking.TotalAmount = TotalAmt;

            BookingRequest objBookingRequest = new BookingRequest();

            objBookingRequest.NoofTickets    = NoofTickets;
            objBookingRequest.TicketCategory = TicketCategory;

            objBooking.Request.Add(objBookingRequest);

            BookingResponse objBookingResponse = new BookingResponse();

            objBookingResponse.BookingID       = BookingID;
            objBookingResponse.ResponseMessage = "Booking Confirmed";
            objBookingResponse.UserID          = userid;
            objBookingResponse.UserName        = userName;

            _eventBookingService.Setup(x => x.Booking(objBooking, BookingID)).ReturnsAsync(objBookingResponse);

            //Act
            var customer = await _EventBookingController.Booking(objBooking);

            //Assert
            Assert.NotNull(customer);
        }
Beispiel #28
0
        public void it_can_be_deserialized()
        {
            var expected = new BookingResponse
            {
                Consignments = new List <BookingResponse.Consignment>
                {
                    new BookingResponse.Consignment
                    {
                        CorrelationId = "INTERNAL-123456",
                        Confirmation  = new BookingResponse.Confirmation
                        {
                            ConsignmentNumber = "70438101268018539",
                            Links             = new BookingResponse.Links
                            {
                                Labels   = new Uri("https://www.mybring.com/booking/labels/2968466?auth-token=5cf1dcee-4f01-4c9a-9870-3ba6d9ba050b"),
                                Tracking = new Uri("http://sporing.bring.no/sporing.html?q=70438101268018539")
                            },
                            DateAndTimes = new BookingResponse.DateAndTimes
                            {
                                EarliestPickup   = null,
                                ExpectedDelivery = DateTime.Parse("Sat, 22 Nov 2014 13:33:56.515")
                            },
                            Packages = new List <BookingResponse.Package>
                            {
                                new BookingResponse.Package
                                {
                                    CorrelationId = "PACKAGE-123",
                                    PackageNumber = "370438101268058536"
                                }
                            }
                        },
                        Errors = null
                    }
                }
            };

            var actual = JsonConvert.DeserializeObject <BookingResponse>(SuccessJsonResponse, new MilisecondEpochConverter());

            expected.ShouldBeEquivalentTo(actual);
        }
Beispiel #29
0
        public async Task <BookingResponse> SaveAsync(BookingSaveResource bookingSaveResource)
        {
            try
            {
                BookingResponse bookingResponse = await CommonValidations(bookingSaveResource);

                if (bookingResponse != null)
                {
                    return(bookingResponse);
                }

                var item = _mapper.Map <BookingSaveResource, Booking>(bookingSaveResource);
                await _bookingRepository.AddAsync(item);

                var responseResource = _mapper.Map <Booking, BookingResource>(item);
                return(new BookingResponse(responseResource));
            }
            catch (Exception ex)
            {
                return(new BookingResponse(400, "Unexpected error", "Error", ex.Message));
            }
        }
Beispiel #30
0
        public BookingResponse ReadQueue(BookingRequest request)
        {
            var response = new BookingResponse();

            using (var context = new SpartanHotelsEntities())
            {
                var queue = context.Queues.FirstOrDefault(q => (q.ReservationID == request.BookingId));

                if (queue != null)
                {
                    response.ReservationId = queue.ReservationID;
                    response.ReservationId = queue.ReservationID;
                    response.ReservationId = queue.ReservationID;
                }
                else
                {
                    //return.. invalid input, queue doesnt exists
                }
            }

            return(response);
        }