예제 #1
0
        public string BeginSearch(string fromAirport, string toAirport, DateTime dateTime, int adults, int child,
                                  int infants, out string error)
        {
            error = string.Empty;

            var mode = ConfigSettings.SupplierMode;

            var supplierInfos = SupplierDataProviderFactory.GetSupplierDataProvider().GetSuppliers(mode);

            var suppliers = GetSuppliers(supplierInfos);

            var searchParams = new FlightSearchParams
                                   {
                                       FromAirport = fromAirport,
                                       Adults = adults,
                                       Children = child,
                                       Date = dateTime,
                                       Infants = infants,
                                       ToAirport = toAirport
                                   };

            var flightSearch = new FlightSearch(searchParams, suppliers, _cacheProvider);

            flightSearch.BeginSearch();

            return flightSearch.SearchKey;
        }
예제 #2
0
        // This method starts an asynchronous calculation.
        // First, it checks the supplied task ID for uniqueness.
        // If taskId is unique, it creates a new WorkerEventHandler
        // and calls its BeginInvoke method to start the calculation.
        public void SearchAsync(
            FlightSearchParams flightSearchParams,
            ISupplier supplier,
            object taskId)
        {
            // Create an AsyncOperation for taskId.
            AsyncOperation asyncOp =
                AsyncOperationManager.CreateOperation(taskId);

            // Multiple threads will access the task dictionary,
            // so it must be locked to serialize access.
            lock (_userStateToLifetime.SyncRoot)
            {
                if (_userStateToLifetime.Contains(taskId))
                {
                    throw new ArgumentException(
                        "Task ID parameter must be unique",
                        "taskId");
                }

                _userStateToLifetime[taskId] = asyncOp;
            }

            // Start the asynchronous operation.
            var workerDelegate = new WorkerEventHandler(SearchWorker);
            workerDelegate.BeginInvoke(
                flightSearchParams,
                supplier,
                asyncOp,
                null,
                null);
            IsBusy = true;
        }
예제 #3
0
        public static FlightMatrixRequestRequest CreateFlightMatrixRequest(SupplierInfo supplierInfo, FlightSearchParams searchParams, string binaryToken)
        {
            FlightMatrixRequestRequest request = new FlightMatrixRequestRequest();
            request.IsOnlyMockBooking = supplierInfo.IsOnlyMockBooking;
            request.IsMockEnabled = supplierInfo.IsMockEnabled;
            request.MessageHeader = CreateMessageHeader(supplierInfo, "FlightMatrixRQ", "GetFlightMatrix");
            request.Security = CreateSecurityHeader(supplierInfo, binaryToken);

            FlightMatrixRQ flightMatrixRq = new FlightMatrixRQ();
            //request.EchoToken = Guid.NewGuid().ToString();
            flightMatrixRq.TimeStamp = DateTime.UtcNow;
            flightMatrixRq.Target = Target.Test;
            flightMatrixRq.Version = 1.1m;
            //request.SequenceNmbr = "1";
            flightMatrixRq.POS = new[]
                              {
                                  new SourceType
                                      {
                                          ISOCountry = "IN"
                                      }
                              };

            List<TravelerInformationType> travellers = GetTravellersInfo(searchParams.Adults,searchParams.Children, searchParams.Infants);
            flightMatrixRq.TravelerInfoSummary = new TravelerInfoSummaryType();
            flightMatrixRq.TravelerInfoSummary.AirTravelerAvail = travellers.ToArray();
            if (searchParams.CabinClassSpecified)
            {
                CabinType cabinClass = CabinType.Economy;
                if (string.Equals(searchParams.CabinClass, "First")) cabinClass = CabinType.First;
                else if (string.Equals(searchParams.CabinClass, "Business")) cabinClass = CabinType.Business;
                flightMatrixRq.TravelerInfoSummary.PriceRequestInformation = new PriceRequestInformationType
                {
                    CabinType = cabinClass,
                    CabinTypeSpecified = true
                };
            }
            flightMatrixRq.AirItinerary = new AirItineraryType();
            flightMatrixRq.AirItinerary.DirectionInd = AirTripType.OneWay;
            flightMatrixRq.AirItinerary.DirectionIndSpecified = true;
            flightMatrixRq.AirItinerary.OriginDestinationOptions = new []
                                                                {
                                                                    new[]
                                                                        {
                                                                            new BookFlightSegmentType()
                                                                                {
                                                                                    DepartureAirport = new DepartureAirport() { LocationCode = searchParams.FromAirport },
                                                                                    ArrivalAirport = new ArrivalAirport {LocationCode = searchParams.ToAirport },
                                                                                    DepartureDateTime = searchParams.Date,
                                                                                    RPH = "1",
                                                                                    MarketingAirline = new MarketingAirline {Code = "9W"}
                                                                                }
                                                                        }
                                                                };

            request.FlightMatrixRQ = flightMatrixRq;
            return request;
        }
예제 #4
0
 public static FlightSearchParams GetSearchDetails()
 {
     FlightSearchParams searchParams = new FlightSearchParams();
     searchParams.FromAirport = "PNQ";
     searchParams.ToAirport = "DEL";
     searchParams.Adults = 1;
     searchParams.Children = 0;
     searchParams.Date = DateTime.Now.AddDays(1);
     return searchParams;
 }
예제 #5
0
        public void GetFlights(FlightsPresetSearchParams flightsPresetSearchParams, long chatId, Action <IEnumerable <Flight>, DestinationPlace, long, bool> callback)
        {
            List <FlightSearchParams> flightSearchParams = new List <FlightSearchParams>();

            // missed logic of range search
            foreach (DestinationPlace dPlace in flightsPresetSearchParams.DestinationPlaces)
            {
                FlightSearchParams flightSearchParam = new FlightSearchParams();
                flightSearchParam.DestinationPlace = dPlace;
                flightSearchParam.InboundDate      = flightsPresetSearchParams.EndDateOfRange;
                flightSearchParam.OutboundDate     = flightsPresetSearchParams.StartDateOfRange;
                flightSearchParams.Add(flightSearchParam);
            }
            int      maxRetryAttempts     = 3;
            TimeSpan pauseBetweenFailures = TimeSpan.FromMinutes(5);
            int      iteration            = 0;

            Parallel.ForEach(flightSearchParams, async(flightSearchParam) =>
            {
                log.Info("start get data for " + flightSearchParams.ToString());
                var retryPolicy = Policy
                                  .Handle <Exception>()
                                  .WaitAndRetryAsync(maxRetryAttempts, i => pauseBetweenFailures);
                try
                {
                    await retryPolicy.ExecuteAsync(async() =>
                    {
                        log.Info(string.Format("Getting data for search params {0} , try no [{1}]  ", flightSearchParams.ToString(), iteration));
                        IEnumerable <Flight> flights = GetFlights(flightSearchParam, flightsPresetSearchParams.FlightSerachFilter);
                        log.Info(string.Format("Data for search params {0} , received ", flightSearchParams.ToString()));
                        bool res;
                        lock (locker)
                        {
                            iteration++;
                            res = iteration == flightSearchParams.Count;
                        }
                        if (res)
                        {
                            callback(flights, flightSearchParam.DestinationPlace, chatId, true);
                        }
                        else
                        {
                            callback(flights, flightSearchParam.DestinationPlace, chatId, false);
                        }
                    });
                }
                catch (Exception e)
                {
                    log.Error(string.Format("Getting data for search params {0} , failed ", flightSearchParams.ToString()));
                }
            });
        }
예제 #6
0
 public FlightSearch(FlightSearchParams searchParams, List<ISupplier> suppliers,
     IFlightResultsCacheProvider flightResultsCacheProvider)
 {
     _searchParams = searchParams;
     _suppliers = suppliers;
     _flightResultsCacheProvider = flightResultsCacheProvider;
     var key = _searchParams.FromAirport + _searchParams.ToAirport +
               _searchParams.Date.ToShortDateString() + _searchParams.Adults + _searchParams.Children +
               _searchParams.Infants;
     byte[] toEncodeAsBytes
         = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
     SearchKey = System.Convert.ToBase64String(toEncodeAsBytes);
 }
예제 #7
0
        private static void SearchFlight(FlightSearchParams flightSearchParams, long chatId)
        {
            Core core = new Core();
            List <DestinationPlace> destinationPlaces = new List <DestinationPlace>()
            {
                DestinationPlace.UKRAINE_KIEV, DestinationPlace.UKRAINE_LVIV, DestinationPlace.UKRAINE_ODESA
            };

            FlightsPresetSearchParams flightsPresetSearchParams = new FlightsPresetSearchParams();

            flightsPresetSearchParams.DatesRangeSearch   = false;
            flightsPresetSearchParams.StartDateOfRange   = new DateTime(2018, 11, 14);
            flightsPresetSearchParams.EndDateOfRange     = new DateTime(2018, 11, 20);
            flightsPresetSearchParams.FlightSerachFilter = new FlightSerachFilter();
            flightsPresetSearchParams.DestinationPlaces  = destinationPlaces;
            Task.Run(() => core.GetFlights(flightsPresetSearchParams, chatId, ProcessGetFlightsCallBack));
        }
예제 #8
0
 internal static List<AirItinerary> ParseSearchResponse(SupplierInfo  supplierInfo, JetModel.FlightMatrixRequestResponse searchResponse, FlightSearchParams searchParams, ref string securityToken)
 {
     try
     {
         securityToken = SetSecurityToken(searchResponse.Security, null);
         if(searchResponse.FlightMatrixRS == null ||
             searchResponse.FlightMatrixRS.FlightMatrices == null || searchResponse.FlightMatrixRS.FlightMatrices.Length == 0 ||
             searchResponse.FlightMatrixRS.FlightMatrixOptions == null || searchResponse.FlightMatrixRS.FlightMatrixOptions.Length == 0)
         {
             throw new Exception("Invalid FlightMatrixRequestResponse from Jet!!!");
         }
         List<AirItinerary> airItineraries = new List<AirItinerary>();
         Dictionary<int, FlightFares> jetFlightFares = GetFlightFares(searchResponse);
         airItineraries = ParseFlightFares(jetFlightFares, searchParams, supplierInfo);
         airItineraries.ForEach(itin => itin[Constants.SecurityToken] = searchResponse.Security.BinarySecurityToken);
         return airItineraries;
     }
     catch (Exception ex)
     {
         Logger.LogException(ex, Source, "ParseSearchResponse", Severity.Major);
         return new List<AirItinerary>();
     }
 }
예제 #9
0
        public IEnumerable <Flight> GetFlights(FlightSearchParams flightSearchParam, FlightSerachFilter flightSerachFilter)
        {
            IEnumerable <Flight> flightsResponse = null;

            try
            {
                FlightApiSearchParams flightApiSearchParam = new FlightApiSearchParams();
                flightApiSearchParam.DestinationPlace = flightSearchParam.DestinationPlace;
                flightApiSearchParam.InboundDate      = flightSearchParam.InboundDate;
                flightApiSearchParam.OutboundDate     = flightSearchParam.OutboundDate;
                FlightsRetriever flightsRetriever = new FlightsRetriever();
                List <Flight>    flights          = flightsRetriever.GetFlightsBySearchParams(flightSearchParam.DestinationPlace, flightSearchParam.InboundDate, flightSearchParam.OutboundDate).ToList();
                // check if flights exist in db
                if (flights.Any() == false)
                {
                    log.Info(string.Format("Flights with params : {0},{1},{2} not exist in db ", flightSearchParam.DestinationPlace, flightSearchParam.OutboundDate.ToString("dd/MM/yyyy"), flightSearchParam.InboundDate.ToString("dd/MM/yyyy")));
                    string            sessionId         = this.CreateSession(flightApiSearchParam);
                    FlightApiResponse flightApiResponse = this.PullSessionResult(sessionId);
                    flights = this.ConvertFlightApiResponseToFlight(flightApiResponse, flightSearchParam.DestinationPlace, flightSearchParam.InboundDate, flightSearchParam.OutboundDate).ToList();
                    // store flight in db
                    flightsRetriever.InsertFlights(flights);
                }
                else
                {
                    log.Info(string.Format("Flights with params : {0},{1},{2} found in db ", flightSearchParam.DestinationPlace, flightSearchParam.OutboundDate.ToString("dd/MM/yyyy"), flightSearchParam.InboundDate.ToString("dd/MM/yyyy")));
                }
                FlightFilterProcessor flightFilterProcessor = new FlightFilterProcessor();
                flightsResponse = flightFilterProcessor.FilterFlights(flights, flightSerachFilter);
            }
            catch (Exception e)
            {
                log.Info(string.Format("GetFlights error with params : {0},{1},{2}   ", flightSearchParam.DestinationPlace, flightSearchParam.InboundDate.ToString("dd/MM/yyyy"), flightSearchParam.OutboundDate.ToString("dd/MM/yyyy")));
                log.Error(string.Format("Error is : {0} stack trace is : {1} ", e.Message, e.StackTrace));
            }
            return(flightsResponse);
        }
예제 #10
0
        private static async Task <bool> ProcessSearchMessageOld(string msg, long chatId)
        {
            string responseMsg = string.Empty;

            switch (msg.ToLower())
            {
            // send custom keyboard
            case "ukraine":
                // return true;
                ReplyKeyboardMarkup ReplyKeyboard = new[]
                {
                    new[] { "Kiev,Odesa,Lviv" }
                };

                await Bot.SendTextMessageAsync(
                    chatId,
                    "Choose Where to Flight",
                    replyMarkup : ReplyKeyboard);

                return(true);

            case "kiev,odesa,lviv":
                responseMsg = "plese send outbound flight date (in format dd/mm/yyyy)";
                await Bot.SendTextMessageAsync(
                    chatId,
                    responseMsg,
                    replyMarkup : new ReplyKeyboardRemove());

                return(true);

            default:
                DateTime date;
                try
                {
                    date = DateTime.ParseExact(msg, "dd/MM/yyyy",
                                               System.Globalization.CultureInfo.InvariantCulture);
                    if (flightSearchParams.OutboundDate == default(DateTime))
                    {
                        flightSearchParams.OutboundDate = date;
                        responseMsg = "plese send inbound flight date (in format dd/mm/yyyy)";
                        await Bot.SendTextMessageAsync(
                            chatId,
                            responseMsg,
                            replyMarkup : new ReplyKeyboardRemove());
                    }
                    else
                    {
                        flightSearchParams.InboundDate      = date;
                        flightSearchParams.DestinationPlace = DestinationPlace.UKRAINE_KIEV;
                        try
                        {
                            SearchFlight(flightSearchParams, chatId);
                            flightSearchParams = new FlightSearchParams();
                            responseMsg        = "The search process is started";
                            await Bot.SendTextMessageAsync(
                                chatId,
                                responseMsg,
                                ParseMode.Html,
                                replyMarkup : new ReplyKeyboardRemove());
                        }
                        catch (Exception ex)
                        {
                            flightSearchParams = new FlightSearchParams();
                            responseMsg        = "Flight api error";
                            await Bot.SendTextMessageAsync(
                                chatId,
                                responseMsg,
                                replyMarkup : new ReplyKeyboardRemove());

                            return(true);
                        }
                    }
                    return(true);
                }
                catch (Exception e)
                {
                    return(false);
                }
            }
        }
예제 #11
0
        private void SearchWorker(FlightSearchParams searchParams, ISupplier supplier, AsyncOperation asyncOperation)
        {
            Exception exception = null;
            List<AirItinerary> itineraries = null;
            // Check that the task is still active.
            // The operation may have been canceled before
            // the thread was scheduled.
            if (!TaskCanceled(asyncOperation.UserSuppliedState))
            {
                try
                {
                    //DOWORK
                    itineraries = supplier.Search(searchParams);
                }
                catch (Exception ex)
                {
                    exception = ex;
                }

            }

            IsBusy = false;
            CompletionMethod(
                itineraries,
                supplier,
                exception,
                TaskCanceled(asyncOperation.UserSuppliedState),
                asyncOperation);
        }
예제 #12
0
 public List<AirItinerary> GetSearchResults(string searchId, out string errorMessage, out bool isComplete)
 {
     errorMessage = string.Empty;
     isComplete = true;
     var search = (FlightSearchParams) HttpRuntime.Cache[searchId];
     var itineraries = new List<AirItinerary>();
     if (search == null)
     {
         search = new FlightSearchParams
                      {
                          Adults = 1,
                          Children = 0,
                          Date = DateTime.Today.AddDays(30),
                          FromAirport =
                              _airportCityDictionary.ElementAt(Rand.Next(_airportCityDictionary.Count)).Key,
                          Infants = 0,
                          ToAirport =
                              _airportCityDictionary.ElementAt(Rand.Next(_airportCityDictionary.Count)).Key
                      };
     }
     if (search != null)
     {
         int max = Rand.Next(50);
         for (int i = 0; i < max; i++)
         {
             itineraries.Add(GetRandomItinerary(search.FromAirport, search.ToAirport, search.Date));
             itineraries[itineraries.Count - 1].Index = i + 1;
         }
     }
     itineraries.Sort((x, y) => x.AirFare.TotalFare.CompareTo(y.AirFare.TotalFare));
     return itineraries;
 }
예제 #13
0
        public string BeginSearch(string fromAirport, string toAirport, DateTime dateTime, int adults, int child,
                                  int infants, out string error)
        {
            string key = Guid.NewGuid().ToString();

            try
            {
                error = string.Empty;
                var flightParams = new FlightSearchParams
                                       {
                                           Adults = adults,
                                           Children = child,
                                           Date = dateTime,
                                           FromAirport = fromAirport,
                                           Infants = infants,
                                           ToAirport = toAirport
                                       };
                HttpRuntime.Cache.Add(key, flightParams, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration,
                                      CacheItemPriority.Normal,
                                      null);
            }
            catch (Exception exception)
            {
                error = exception.Message;
            }
            return key;
        }
예제 #14
0
 private static List<AirItinerary> ParseFlightFares(Dictionary<int, FlightFares> jetFlightFares, FlightSearchParams searchParams,
     SupplierInfo supplierInfo)
 {
     List<AirItinerary> airItineraries = new List<AirItinerary>();
     foreach (int flightKey in jetFlightFares.Keys)
     {
         foreach (int fareKey in jetFlightFares[flightKey].MatrixRowOptions.Keys)
         {
             try
             {
                 JetModel.FlightMatrixOption fareOption = jetFlightFares[flightKey].MatrixRowOptions[fareKey];
                 if (fareOption != null)
                 {
                     AirFare airFare = ParsePassengerFareBreadowns(fareOption.PTC_FareBreakdown, searchParams.Adults, searchParams.Children, searchParams.Infants, false);
                     if (airFare != null)
                     {
                         List<Flight> flights = ParseFlightMatrixRow(jetFlightFares[flightKey].MatrixRow);
                         if (flights == null || flights.Count == 0) continue;
                         //Assign CabinClass, FareBasisCodesm and ClassOfService to each flight segment.
                         string[] cabinClasses = airFare.PassengerFares[0].CabinClass.Split(',');
                         string[] fareBasisCodes = airFare.PassengerFares[0].FareBasisCode.Split(',');
                         string[] classOfServices = airFare.PassengerFares[0].ClassOfService.Split(',');
                         for (int i = 0; i < flights.Count; i++)
                         {
                             int index = i >= cabinClasses.Length ? cabinClasses.Length - 1 : i;
                             flights[i].CabinClass = cabinClasses[index];
                             index = i >= classOfServices.Length ? classOfServices.Length - 1 : i;
                             flights[i].ClassOfService = classOfServices[index];
                             index = i >= fareBasisCodes.Length ? fareBasisCodes.Length - 1 : i;
                             flights[i].FareBasisCode = fareBasisCodes[index];
                         }
                         AirItinerary itinerary = new AirItinerary();
                         itinerary.JourneyType = "OneWay";
                         itinerary.AirFare = airFare;
                         itinerary.Flights = flights;
                         itinerary.Index = airItineraries.Count;
                         itinerary.Provider = supplierInfo.Provider;
                         itinerary.Mode = supplierInfo.Mode;
                         airItineraries.Add(itinerary);
                     }
                 }
             }
             catch (Exception ex)
             {
                 Logger.LogException(ex, Source, "ParseFlightFares", Severity.Major);
             }
         }
     }
     return airItineraries;
 }
예제 #15
0
 public List<AirItinerary> Search(FlightSearchParams searchParams)
 {
     using (new ApplicationContextScope(new ApplicationContext()))
     {
         ApplicationContext.Current.Items["SessionId"] = _supplierInfo["SessionId"];
         string securityToken = string.Empty;
         List<AirItinerary> itineraries = new List<AirItinerary>();
         try
         {
             //1. Get the securityToken
             securityToken = CreateJetSession();
             //2. Search flights
             JetConnector connector = new JetConnector(_supplierInfo.GetFlightMatrixService());
             JetModel.FlightMatrixRequestRequest searchRequest =
                 RequestTranslators.CreateFlightMatrixRequest(_supplierInfo, searchParams, securityToken);
             JetModel.FlightMatrixRequestResponse searchResponse =
                 connector.DoTransaction
                     <JetModel.FlightMatrixRequestRequest, JetModel.FlightMatrixRequestResponse>(
                         searchRequest);
             itineraries = ResponseTranslators.ParseSearchResponse(_supplierInfo, searchResponse, searchParams,
                                                                   ref securityToken);
             itineraries = itineraries.Distinct(new AirItinerary()).ToList();
         }
         catch (Exception ex)
         {
             Logger.LogException(ex, Source, "Search", Severity.Major);
         }
         finally
         {
             Task.Factory.StartNew(() => CloseJetSession(securityToken, _supplierInfo["SessionId"]));
         }
         return itineraries;
     }
 }