コード例 #1
0
        public static void Initialize()
        {
            if (Settings != null)
                return;

            _settings = new Settings();

            // run this first as it has the information in it we need
            GetDatabaseSettings();

            // now get email setting as database hits will send email out if does not work
            EmailSettings();

            // Aggregator settings
            GetAggregatorSettings();

            // get logging settings
            GetLoggingSettings();

            // Get the data used for mark-up etc
            GetLookupSettings();

            _settings.WriteData = new WriteData();

            // set the logging going
            _settings.LoggingSettings.AccommodationJobHost = new AccommodationJobHost(_settings);

            AccommodationTimer.Start(_settings);

            // set this last as we need
            Settings = _settings;
        }
コード例 #2
0
ファイル: LookupData.cs プロジェクト: jamiedanquah/Aggregator
        internal static Dictionary<int, string> CityAsIata(Settings settings)
        {
            var returnData = new Dictionary<int, string>();

            // Create and open the connection in a using block. This
            // ensures that all resources will be closed and disposed
            // when the code exits.
            using (var connection = new SqlConnection(settings.DatabaseSettings.ReadConnectionString))
            {
                // Create the Command and Parameter objects.
                var command = new SqlCommand("dbo.[spPtsCityGetAll]", connection) { CommandType = CommandType.StoredProcedure };

                // Open the connection in a try/catch block.
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        returnData.Add((int)reader["CityCode"], (string)reader["Iata"]);
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    ErrorHelper.SendErrorEmail(ex, "Error getting CityAsIata", settings);
                }

                return returnData;
            }
        }
コード例 #3
0
ファイル: PtsService.cs プロジェクト: jamiedanquah/Aggregator
        private static string GetH2H(long cityCode, AggregatorSetting aggregatorSetting, Settings settings)
        {
            if (settings.LookupSettings.H2HToSearch.ContainsKey(cityCode))
                return settings.LookupSettings.H2HToSearch[cityCode];

            return aggregatorSetting.H2HDefault;
        }
コード例 #4
0
ファイル: LookupData.cs プロジェクト: jamiedanquah/Aggregator
        public static List<AggregatorSetting> GetAggregatorAuthentication(Settings settings)
        {
            var returnData = new List<AggregatorSetting>();

            // Create and open the connection in a using block. This
            // ensures that all resources will be closed and disposed
            // when the code exits.
            using (var connection = new SqlConnection(settings.DatabaseSettings.ReadConnectionString))
            {
                // Create the Command and Parameter objects.
                var command = new SqlCommand("dbo.spAuthenticationGetAll", connection) {CommandType = CommandType.StoredProcedure};

                // Open the connection in a try/catch block.
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        var setting = new AggregatorSetting
                        {
                            Enabled = (bool)reader["Enabled"],
                            H2HDefault = (string)reader["H2HDefault"],
                            UserName = (string)reader["UserName"],
                            Password = (string)reader["Password"],
                            Id = (int)reader["Id"],
                            PtsPassword = (string)reader["PTSPassword"],
                            PtsUserName = (string)reader["PTSUserName"],
                            HotelConcurrentSearches = (int)reader["HotelConcurrentSearches"],
                            Tracker = (string)reader["Tracker"],
                            PtsNetwork = (string)reader["PtsNetwork"],
                            PtsTimeOut = (int)reader["PtsTimeOut"],
                            PtsUrl = (string)reader["PtsUrl"],
                        };
                        var featureCode = (string)reader["PtsFeatureCode"];
                        setting.PtsFeatureCode = featureCode.Contains(",") ? featureCode.Split(',') : new[] { featureCode };

                        returnData.Add(setting);
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    ErrorHelper.SendErrorEmail(ex, "Error getting GetAggregatorAuthentication", settings);
                }

                return returnData;
            }
        }
コード例 #5
0
        public static bool CheckIfWeAreOkToSearch(AggregatorSetting aggregatorSetting, Settings settings)
        {
            AddToSearchCount(aggregatorSetting);

            lock (ThisLock)
            {
                if (aggregatorSetting.CurrentSearches > aggregatorSetting.HotelConcurrentSearches)
                {
                    ErrorHelper.SendErrorEmail(new Exception("Speed limit error"), "Too many searches was carried out: <br />Aggregator: " + aggregatorSetting.UserName + "<br />Current Searches: " + GetCurrentSearchCount(aggregatorSetting) + "<br />Maximum Searches: " + aggregatorSetting.HotelConcurrentSearches, settings);
                    return false;
                }
            }

            return true;
        }
コード例 #6
0
        public static bool SendErrorEmail(Exception exception, string errorMessage, Settings settings)
        {
            var sb = new StringBuilder();
            sb.AppendLine("<h2>Error on aggregator</h2>");

            sb.Append("<p>Server: ");
            sb.Append(Environment.MachineName);
            sb.Append("</p>");

            sb.Append("<p>Date: ");
            sb.Append(DateTime.Now);
            sb.Append("</p>");

            sb.Append("<p>Error Message: ");
            sb.Append(errorMessage);
            sb.Append("</p>");

            sb.Append("<p>Exception: ");
            sb.Append(exception.Message);
            sb.Append("</p>");

            sb.Append("<p>Exception: ");
            sb.Append(exception.StackTrace);
            sb.Append("</p>");

            try
            {
                var mail = new MailMessage
                {
                    Subject = "Aggregator Error " + DateTime.Now,
                    From = new MailAddress(settings.MailSettings.ErrorMailFrom),
                    IsBodyHtml = true,
                    Body = sb.ToString()
                };
                mail.To.Add(settings.MailSettings.ErrorMailTo);

                var smtpClient = new SmtpClient(settings.MailSettings.SmtpServer);
                smtpClient.Send(mail);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
コード例 #7
0
ファイル: WriteData.cs プロジェクト: jamiedanquah/Aggregator
 public void WriteLog(DataTable dataTable, Settings settings)
 {
     using (var connection = new SqlConnection(settings.DatabaseSettings.WriteConnectionString))
     {
         try
         {
             connection.Open();
             using (var s = new SqlBulkCopy(connection))
             {
                 s.DestinationTableName = dataTable.TableName;
                 foreach (var column in dataTable.Columns)
                     s.ColumnMappings.Add(column.ToString(), column.ToString());
                 s.WriteToServer(dataTable);
             }
         }
         catch (Exception ex)
         {
             ErrorHelper.SendErrorEmail(ex, "Error saving log " + dataTable.TableName, settings);
             throw;
         }
     }
 }
コード例 #8
0
ファイル: PtsService.cs プロジェクト: jamiedanquah/Aggregator
        /// <summary>
        /// </summary>
        /// <param name="request"></param>
        /// <param name="aggregatorSetting"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        private static AvailabilityRequest GetRequest(AccommodationSearchRequest request, AggregatorSetting aggregatorSetting, Settings settings)
        {
            var availabilityRequest = new AvailabilityRequest
            {
                HotelId = request.SuperIds == null ? null :  string.Join(",",  request.SuperIds),
                H2H = GetH2H(request.CityCode, aggregatorSetting, settings),
                FeatureCode = aggregatorSetting.PtsFeatureCode,
                DetailLevel = 5,
                CityCode = request.CityCode,
                ConfirmationLevel = 0
            };

            TimeSpan ts = request.CheckOut - request.CheckIn;
            availabilityRequest.Nites = (sbyte)ts.Days;
            availabilityRequest.SvcDate = request.CheckIn;
            availabilityRequest.NoOfAdults = (sbyte)request.NumberOfAdults;
            availabilityRequest.NoOfChildren = (sbyte)(request.ChildAge == null ? 0 : request.ChildAge.Count + request.NumberOfInfants ?? 0);
            if (request.ResortCode.HasValue && request.ResortCode.Value > 0)
                availabilityRequest.Location = (int)request.ResortCode.Value;

            var ages = new List<sbyte>();

            if (request.ChildAge != null)
                foreach (var i in request.ChildAge)
                {
                    ages.Add((sbyte)i);
                }

            for (var i = 0; i < request.NumberOfInfants; i++)
            {
                ages.Add(1);
            }

            availabilityRequest.ChildAge = ages.ToArray();
            availabilityRequest.Units = (sbyte)request.NumberOfRooms;

            return availabilityRequest;
        }
コード例 #9
0
ファイル: PtsService.cs プロジェクト: jamiedanquah/Aggregator
        public static SuperAvailabilityResponse Search(AccommodationSearchRequest request, Settings settings, AggregatorSetting aggregatorSetting, out int searchTime)
        {
            var availabilityRequest = GetRequest(request, aggregatorSetting, settings);

            var authSoapHd = new AuthSoapHd
            {
                strUserName = aggregatorSetting.PtsUserName,
                strNetwork = aggregatorSetting.PtsNetwork,
                strPassword = aggregatorSetting.PtsPassword,
                strUserRef = "",
                strCustomerIP = "" //HttpContext.Current == null ? String.Empty : (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim()
            };

            //"http://172.16.200.174/Tritonroomswsdev/AccommodationServicev2.svc";
            var service = new  AccommodationService { Url = aggregatorSetting.PtsUrl, AuthSoapHdValue = authSoapHd, Timeout = aggregatorSetting.PtsTimeOut };
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            SuperAvailabilityResponse response =  service.GetSuperAvailability(availabilityRequest);
            stopwatch.Stop();
            searchTime = (int)stopwatch.ElapsedMilliseconds;

            return response;
        }
コード例 #10
0
        public static AggregatorSetting CheckAuth(Settings settings, Authentication authentication)
        {
            // see if they are in the dictionary as if not they are not going to be a valid user
            if (!settings.AggregatorSettings.ContainsKey(authentication.UserName))
                return new AggregatorSetting
                {
                    Enabled = false,
                    LoginSuccess = false,
                    Error = LogonFailMessage
                };

            // get the settings from the dictionary
            var aggregatorSettings = settings.AggregatorSettings[authentication.UserName];

            // now we have there details check if there password is correct
            if (aggregatorSettings.Password != authentication.Password)
                return new AggregatorSetting
                {
                    Enabled = false,
                    LoginSuccess = false,
                    Error = LogonFailMessage
                };

            // now see if there account is disabled
            if (!aggregatorSettings.Enabled)
                return new AggregatorSetting
                {
                    Enabled = false,
                    LoginSuccess = false,
                    Warning = LogonDisabledMessage
                };

            // everything is fine
            aggregatorSettings.LoginSuccess = true;
            return aggregatorSettings;
        }
コード例 #11
0
        public static AccommodationSearchResponse Process(Settings settings, SuperAvailabilityResponse superAvailabilityResponse, AggregatorSetting aggregatorSetting, string rooms)
        {
            if (superAvailabilityResponse == null)
            {
                return new AccommodationSearchResponse
                {
                    Message = new Message
                    {
                        Success = false,
                        Errors = new List<string> { "There was no Search results returned due to an error" }
                    },
                    Results = null,
                    SearchResultSetGuid = new Guid()
                };
            }
            var returnHotels = new List<AccommodationSearchResponseHotel>();

            var getTheIataFromCity =  (settings.LookupSettings.CityAsIata.ContainsKey((int) superAvailabilityResponse.AvailabilityRequest.CityCode) ?  settings.LookupSettings.CityAsIata[(int) superAvailabilityResponse.AvailabilityRequest.CityCode] : null) ?? "-1";
            var destinationMarkup = (settings.LookupSettings.DestinationMarkup.ContainsKey(getTheIataFromCity) ? settings.LookupSettings.DestinationMarkup[getTheIataFromCity] : null) ?? settings.LookupSettings.DestinationMarkup["-1"];

            var transfers = new Dictionary<int, decimal>();

            // loop through each hotel
            if (superAvailabilityResponse.SuperHotelAvailabilityDetail != null)
            {
                if (aggregatorSetting.UserName.ToLower() == "tripadvisor")
                {
                    // loop through the hotels and see if there are any compulsory
                    foreach (var hotel in superAvailabilityResponse.SuperHotelAvailabilityDetail)
                    {
                        foreach (var room in hotel.Hotels)
                        {
                            if (room.TransferCompulsory && room.HotelLocationID.HasValue && !transfers.ContainsKey(room.HotelLocationID.Value))
                            {
                                transfers.Add(room.HotelLocationID.Value, -1);
                            }
                        }
                    }

                    TransferService.GetTransfers(transfers, superAvailabilityResponse, aggregatorSetting);
                }

                foreach (var hotel in superAvailabilityResponse.SuperHotelAvailabilityDetail)
                {
                    int star;
                    if (!string.IsNullOrEmpty(hotel.SuperHotelCategory) && int.TryParse(hotel.SuperHotelCategory.Substring(0, 1), out star))
                    {
                        // do nothing
                    }
                    else
                        star = 0;

                    // convert the hotel ready
                    var returnHotel = ConvertService.Convert(hotel, star);
                    var hotelId = int.Parse(hotel.SuperHotelID);
                    var hotelMarkups = settings.LookupSettings.HotelMarkup.ContainsKey(hotelId) ? settings.LookupSettings.HotelMarkup[hotelId] : null;

                    // loop through each room
                    foreach (var room in hotel.Hotels)
                    {
                        // see if we need to find out transfers

                        // hotel markup rules
                        if (hotelMarkups != null)
                        {
                            if (hotelMarkups.IsPercentageMarkup)
                                room.Price += (room.Price/100m)*hotelMarkups.Markup;
                            else
                                room.Price += hotelMarkups.Markup;
                        }
                        else
                        {
                            // now apply a destination markup
                            foreach (var markupDestination in destinationMarkup)
                            {
                                if (room.Price > markupDestination.MinPriceTakesEffect)
                                {
                                    if (markupDestination.IsPercentageMarkup)
                                        room.Price += (room.Price / 100m) * markupDestination.Markup;
                                    else
                                        room.Price += markupDestination.Markup;
                                    break;
                                }
                            }
                        }

                        // apply transfers if needed
                        //if (room.HotelLocationID.HasValue && room.TransferCompulsory && transfers.ContainsKey(room.HotelLocationID.Value))
                        //{
                        //    if (transfers[room.HotelLocationID.Value] == -1)
                        //        continue;
                        //    room.MarkupTotals.FixedTotal += transfers[room.HotelLocationID.Value];/}

                        // round the price off
                        room.Price = Math.Round(room.Price, 2);

                        // convert to the object to return
                        returnHotel.Rooms.Add(ConvertService.Convert(room,  aggregatorSetting, hotel.SuperHotelID, rooms));
                    }

                    if (returnHotel.Rooms.Any())
                        returnHotels.Add(returnHotel);
                }
            }
            var returnResult = new AccommodationSearchResponse
            {
                Message = new Message
                {
                    Success = true
                },
                Results = returnHotels,
                SearchResultSetGuid = superAvailabilityResponse.ResultID == null ? new Guid() : new Guid(superAvailabilityResponse.ResultID)
            };

            return returnResult;
        }
コード例 #12
0
        public static AccommodationSearchResponse Search(AccommodationSearchRequest accommodationSearchRequest, Settings settings)
        {
            // this so we know when we got the request
            var dateOfSearch = DateTime.Now;

            // this is so we can time how long we take to process
            var startOfSearch = new Stopwatch();
            startOfSearch.Start();

            // Check login credentials
            var auth = AuthenticationHelper.CheckAuth(settings, accommodationSearchRequest.Authentication);
            if (!auth.LoginSuccess)
            {
                // they failed to login
                var message = new Message {Success = false};

                // add error message if there
                if (!String.IsNullOrEmpty(auth.Error))
                    message.Errors.Add(auth.Error);

                // add warning if not there
                if (!String.IsNullOrEmpty(auth.Warning))
                    message.Warnings.Add(auth.Warning);

                return new AccommodationSearchResponse {Message = message};
            }

            // now we need to check how many searches they have done
            var areWeOkToSearch = TooManySearchesHelper.CheckIfWeAreOkToSearch(auth, settings);
            if (!areWeOkToSearch)
            {
                TooManySearchesHelper.MinusToSearchCount(auth);
                throw new Exception("Speed Limit: Sorry but we have had too many searches at once please try again in a minute");
            }

            try
            {

                //Debug.WriteLine(TooManySearchesHelper.GetCurrentSearchCount(auth));

                // validate Search
                var errors = ValidationHelper.ValidateSearch(accommodationSearchRequest);
                if (errors.Count != 0)
                {
                    // they failed validation
                    var message = new Message {Success = false};
                    // add error messages in
                    foreach (var error in errors)
                        message.Errors.Add(error);
                    TooManySearchesHelper.MinusToSearchCount(auth);
                    return new AccommodationSearchResponse {Message = message};
                }

                var log = new AccommodationSearchLog();

                // do the search
                var isError = false;
                var errorMessage = String.Empty;
                int timeToSearchPts = 0;
                SuperAvailabilityResponse ptsResults = null;
                try
                {
                    ptsResults = PtsService.Search(accommodationSearchRequest, settings, auth, out timeToSearchPts);
                }
                catch (Exception exception)
                {

                    log.ConvertSearch(accommodationSearchRequest, auth);
                    log.StartOfSearch = dateOfSearch;
                    log.TimeToSearchSupplier = timeToSearchPts;
                    log.TimeToSearchTotal = (int) startOfSearch.ElapsedMilliseconds;
                    log.NumberOfHotelResults = 0;
                    log.Error = exception.Message;
                    settings.LoggingSettings.AccommodationJobHost.AddLog(log);
                    isError = true;
                    errorMessage = exception.Message;
                }
                // process and add in mark-ups
                var processdResults = ProcessService.Process(settings, ptsResults, auth, accommodationSearchRequest.PassengerUrl());
                if (isError)
                {
                    processdResults.Message.Success = false;
                    processdResults.Message.Errors.Add(errorMessage);
                }

                startOfSearch.Stop();
                log.ConvertSearch(accommodationSearchRequest, auth);
                log.StartOfSearch = dateOfSearch;
                log.TimeToSearchSupplier = timeToSearchPts;
                log.TimeToSearchTotal = (int) startOfSearch.ElapsedMilliseconds;
                log.NumberOfHotelResults = processdResults.Results == null ? 0 : processdResults.Results.Count;
                settings.LoggingSettings.AccommodationJobHost.AddLog(log);

                TooManySearchesHelper.MinusToSearchCount(auth);
                return processdResults;
            }
            catch (Exception ex)
            {
                ErrorHelper.SendErrorEmail(ex, "Error In Search", settings);
                TooManySearchesHelper.MinusToSearchCount(auth);
                throw;
            }
        }
コード例 #13
0
ファイル: LookupData.cs プロジェクト: jamiedanquah/Aggregator
        internal static Dictionary<string, List<MarkupDestination>> GetDestinationMarkup(Settings settings)
        {
            var returnData = new Dictionary<string, List<MarkupDestination>>();

            // Create and open the connection in a using block. This
            // ensures that all resources will be closed and disposed
            // when the code exits.
            using (var connection = new SqlConnection(settings.DatabaseSettings.ReadConnectionString))
            {
                // Create the Command and Parameter objects.
                var command = new SqlCommand("dbo.[spMarkupDestinationGetAll]", connection) { CommandType = CommandType.StoredProcedure };

                // Open the connection in a try/catch block.
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        var key = (string) reader["Iata"];

                        if (returnData.ContainsKey(key))
                        {
                            returnData[key].Add(new MarkupDestination
                                {
                                    Iata = key,
                                    Id = (int) reader["Id"],
                                    IsPercentageMarkup = (bool) reader["IsPercentageMarkup"],
                                    Markup = (decimal) reader["Markup"],
                                    MinPriceTakesEffect = (decimal) reader["MinPriceTakesEffect"]
                                });
                        }
                        else
                        {
                            returnData.Add(key, new List<MarkupDestination>
                                {
                                    new MarkupDestination
                                        {
                                            Iata = key,
                                            Id = (int) reader["Id"],
                                            IsPercentageMarkup = (bool) reader["IsPercentageMarkup"],
                                            Markup = (decimal) reader["Markup"],
                                            MinPriceTakesEffect = (decimal) reader["MinPriceTakesEffect"]
                                        }
                                });
                        }
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    ErrorHelper.SendErrorEmail(ex, "Error getting GetDestinationMarkup", settings);
                }

                return returnData;
            }
        }
コード例 #14
0
ファイル: LookupData.cs プロジェクト: jamiedanquah/Aggregator
        internal static Dictionary<int, MarkupHotel> GetHotelMarkup(Settings settings)
        {
            var returnData = new Dictionary<int, MarkupHotel>();

            // Create and open the connection in a using block. This
            // ensures that all resources will be closed and disposed
            // when the code exits.
            using (var connection = new SqlConnection(settings.DatabaseSettings.ReadConnectionString))
            {
                // Create the Command and Parameter objects.
                var command = new SqlCommand("dbo.[spMarkupHotelGetAll]", connection) { CommandType = CommandType.StoredProcedure };

                // Open the connection in a try/catch block.
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        var key = (int)reader["SuperId"];

                        returnData.Add(key, new MarkupHotel
                            {
                                Id = (int)reader["Id"],
                                IsPercentageMarkup = (bool)reader["IsPercentageMarkup"],
                                Markup = (decimal)reader["Markup"],
                                SuperId = key
                            });
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    ErrorHelper.SendErrorEmail(ex, "Error getting GetHotelMarkup", settings);
                }

                return returnData;
            }
        }
コード例 #15
0
 public AccommodationJobHost(Settings settings)
 {
     this.settings = settings;
     HostingEnvironment.RegisterObject(this);
     SetTableCols();
 }
コード例 #16
0
 public static void Start(Settings settings)
 {
     _accommodationJobHost = settings.LoggingSettings.AccommodationJobHost;
     var timer = new System.Timers.Timer
     {
         Interval = settings.LoggingSettings.TimeInMillisecondsToLog,
         Enabled = true
     };
     timer.Elapsed += timScheduledTask_Elapsed;
 }