/// <summary> /// Возвращает список всех отелей /// </summary> /// <param name="dc">Контекст базы данных</param> /// <returns></returns> public static List <HotelSmallClass> GetAllHotels(this MtSearchDbDataContext dc) { List <HotelSmallClass> hotels; if ((hotels = CacheHelper.GetCacheItem <List <HotelSmallClass> >(TableName)) != null) { return(hotels); } lock (LockHotels) { if ((hotels = CacheHelper.GetCacheItem <List <HotelSmallClass> >(TableName)) != null) { return(hotels); } hotels = (from h in dc.HotelDictionaries select new HotelSmallClass() { Key = h.HD_KEY, Name = h.HD_NAME, RsKey = h.HD_RSKEY, Http = h.HD_HTTP, Stars = h.HD_STARS, CtKey = h.HD_CTKEY, CnKey = h.HD_CNKEY }) .ToList(); CacheHelper.AddCacheData(TableName, hotels, TableName); } return(hotels); }
/// <summary> /// Возвращает список всех accomodation's /// </summary> /// <param name="dc">Контекст базы данных</param> /// <returns></returns> public static List <Description> GetAllDescriptions(this MtMainDbDataContext dc) { List <Description> descriptions; if ((descriptions = CacheHelper.GetCacheItem <List <Description> >(TableName)) != null) { return(descriptions); } lock (LockDescription) { if ((descriptions = CacheHelper.GetCacheItem <List <Description> >(TableName)) != null) { return(descriptions); } var descTypes = new[] { AllowCharterBooking, CountryDescription }; descriptions = (from desc in dc.Descriptions where descTypes.Contains(desc.DS_DTKey.Value) select desc) .ToList <Description>(); CacheHelper.AddCacheData(TableName, descriptions, TableName); } return(descriptions); }
/// <summary> /// Возвращает список расписаний /// </summary> /// <param name="dc">Контекст базы данных</param> /// <returns></returns> public static List <AirSeason> GetAllAirSeasons(this MtSearchDbDataContext dc) { List <AirSeason> airSeasons; if ((airSeasons = CacheHelper.GetCacheItem <List <AirSeason> >(TableName)) != default(List <AirSeason>)) { return(airSeasons); } lock (LockAirSeasons) { if ((airSeasons = CacheHelper.GetCacheItem <List <AirSeason> >(TableName)) != default(List <AirSeason>)) { return(airSeasons); } airSeasons = (from a in dc.AirSeasons where a.AS_DATETO >= DateTime.Now.Date select a) .ToList <AirSeason>(); CacheHelper.AddCacheData(TableName, airSeasons, TableName); } return(airSeasons); }
/// <summary> /// Возвращает ключ и код национальной валюты /// </summary> /// <param name="dc"></param> /// <returns></returns> public static Tuple <int, string> GetNationalRateInfo(this MtSearchDbDataContext dc) { Tuple <int, string> result; var hash = String.Format("{0}", MethodBase.GetCurrentMethod().Name); if ((result = CacheHelper.GetCacheItem <Tuple <int, string> >(hash)) != null) { return(result); } var rates = dc.GetAllRatesList(); result = (from r in rates where r.RA_National == 1 select new Tuple <int, string>(r.ra_key, r.RA_CODE)) .SingleOrDefault(); CacheHelper.AddCacheData(hash, result, new List <string>() { TableName }, Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Возвращает название тура и его URL /// </summary> /// <param name="dc">Контекст базы данных</param> /// <param name="tourKeys">Ключ тура</param> public static IList <Tuple <int, string, string> > GetTourStringsByKeys(this MtSearchDbDataContext dc, IEnumerable <int> tourKeys, out string hash) { List <Tuple <int, string, string> > result; hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, String.Join(",", tourKeys)); if ((result = CacheHelper.GetCacheItem <List <Tuple <int, string, string> > >(hash)) != null) { return(result); } string hashOut; var cacheDependencies = new List <string>(); var tours = dc.GetTPToursByKeys(tourKeys, out hashOut); cacheDependencies.Add(hashOut); var tourList = dc.GetTurListsByKeys(tours.Select(t => t.TO_TRKey).Distinct().ToList(), out hashOut); cacheDependencies.Add(hashOut); result = (from tp in tours join tl in tourList on tp.TO_TRKey equals tl.TL_KEY select new Tuple <int, string, string>(tp.TO_Key, tl.TL_NAMEWEB, tl.TL_WEBHTTP)) .Distinct() .ToList(); CacheHelper.AddCacheData(hash, result, cacheDependencies.ToList(), Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Возвращает список всех отелей /// </summary> /// <param name="dc">Контекст базы данных</param> /// <returns></returns> public static List <CityDictionary> GetAllCities(this MtSearchDbDataContext dc) { List <CityDictionary> cities; if ((cities = CacheHelper.GetCacheItem <List <CityDictionary> >(TableName)) != null) { return(cities); } lock (LockCities) { if ((cities = CacheHelper.GetCacheItem <List <CityDictionary> >(TableName)) != null) { return(cities); } cities = (from c in dc.CityDictionaries select c) .ToList <CityDictionary>(); cities.Add(new CityDictionary() { CT_KEY = 0, CT_NAME = "-Без перелета-" }); CacheHelper.AddCacheData(TableName, cities, TableName); } return(cities); }
/// <summary> /// Возвращает ключ валюты по ее коду /// </summary> /// <param name="dc">Контекст базы данных</param> /// <param name="rateCode">Код валюты</param> /// <returns></returns> public static int GetRateKeyByCode(this MtSearchDbDataContext dc, string rateCode) { int result; var hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, rateCode); if (CacheHelper.IsCacheKeyExists(hash)) { result = CacheHelper.GetCacheItem <int>(hash); return(result); } var rates = dc.GetAllRatesList(); result = (from r in rates where r.RA_CODE == rateCode select r.ra_key) .SingleOrDefault(); CacheHelper.AddCacheData(hash, result, new List <string>() { TableName }, Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Возвращает объект типа перелет по его ключу /// </summary> /// <param name="dc">Контекст БД</param> /// <param name="cityKeyFrom">Ключ города "туда"</param> /// <param name="cityKeyTo">Ключ города "обратно"</param> /// <returns></returns> public static IList <Charter> GetChartersByDirection(this MtSearchDbDataContext dc, int cityKeyFrom, int cityKeyTo) { List <Charter> result; var hash = String.Format("{0}_{1}_{2}", MethodBase.GetCurrentMethod().Name, cityKeyFrom, cityKeyTo); if ((result = CacheHelper.GetCacheItem <List <Charter> >(hash)) != default(List <Charter>)) { return(result); } var cacheDependencies = new List <string> { String.Format("{0}_{1}_{2}_{3}", CacheHelper.CharterHash, (int)ServiceClass.Flight, cityKeyFrom, cityKeyTo) }; result = (from c in dc.GetAllCharters() where c.CH_CITYKEYFROM == cityKeyFrom && c.CH_CITYKEYTO == cityKeyTo select c) .ToList(); cacheDependencies.Add(TableName); CacheHelper.AddCacheData(hash, result, cacheDependencies, Globals.Settings.Cache.LongCacheTimeout); return(result); }
///// <summary> ///// Возвращает список всех hotel room's ///// </summary> ///// <param name="dc">Контекст базы данных</param> ///// <returns></returns> //public static List<HotelRoom> GetAllHotelRooms(this MtSearchDbDataContext dc) //{ // List<HotelRoom> hotelRooms; // if ((hotelRooms = CacheHelper.GetCacheItem<List<HotelRoom>>(TableName)) != null) return hotelRooms; // lock (LockHotelRooms) // { // if ((hotelRooms = CacheHelper.GetCacheItem<List<HotelRoom>>(TableName)) != null) return hotelRooms; // hotelRooms = (from hr in dc.HotelRooms // select hr) // .ToList<HotelRoom>(); // CacheHelper.AddCacheData(TableName, hotelRooms, TableName); // } // return hotelRooms; //} /// <summary> /// Возвращает hotel room по ключам /// </summary> /// <param name="dc"></param> /// <param name="hotelRoomKeys">Ключи hotel room</param> /// <param name="hash">Хэш кэша</param> /// <returns></returns> public static List <HotelRoom> GetHotelRoomByKeys(this MtSearchDbDataContext dc, IEnumerable <int> hotelRoomKeys, out string hash) { List <HotelRoom> result; hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, String.Join("_", hotelRoomKeys)); if ((result = CacheHelper.GetCacheItem <List <HotelRoom> >(hash)) != null) { return(result); } result = (from h in dc.HotelRooms where hotelRoomKeys.Contains(h.HR_KEY) select h) .ToList(); if (!CacheHelper.IsCacheKeyExists(TableName)) { CacheHelper.AddCacheData(TableName, String.Empty, TableName); } CacheHelper.AddCacheData(hash, result, new List <string>() { TableName }, Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Получаем направление по ключу перелета /// </summary> /// <param name="dc">Контекст базы данных</param> /// <param name="charterKey">Ключ перелета</param> /// <param name="cityKeyFrom">Город отправления</param> /// <param name="cityKeyTo">Город прилета</param> /// <exception cref="ArgumentNullException"></exception> public static void GetCharterCityDirection(this MtSearchDbDataContext dc, int charterKey, out int?cityKeyFrom, out int?cityKeyTo) { Tuple <int?, int?> result; var hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, charterKey); if ((result = CacheHelper.GetCacheItem <Tuple <int?, int?> >(hash)) != null) { cityKeyFrom = result.Item1; cityKeyTo = result.Item2; return; } var cacheDependencies = new List <string> { String.Format("{0}_{1}_{2}", CacheHelper.CharterHash, (int)ServiceClass.Flight, charterKey) }; var charter = dc.GetCharter(charterKey); if (charter == null) { cityKeyFrom = cityKeyTo = null; } else { cityKeyFrom = charter.CH_CITYKEYFROM; cityKeyTo = charter.CH_CITYKEYTO; } var res = new Tuple <int?, int?>(cityKeyFrom, cityKeyTo); CacheHelper.AddCacheData(hash, res, cacheDependencies, Globals.Settings.Cache.LongCacheTimeout); }
/// <summary> /// Возвращает список стран /// </summary> /// <param name="searchDc"></param> /// <param name="sftDc"></param> /// <param name="countryKey">Ключ страны (опциональный)</param> /// <param name="hash"></param> /// <returns></returns> public static List <Country> GetCountries(this MtSearchDbDataContext searchDc, SftWebDbDataContext sftDc, int?countryKey, out string hash) { List <Country> result; hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, countryKey); if ((result = CacheHelper.GetCacheItem <List <Country> >(hash)) != null) { return(result); } string hashOut; var cacheDependencies = new List <string>(); var countries = searchDc.GetCountriesTo(sftDc, null, out hashOut); cacheDependencies.Add(hashOut); result = new List <Country>(countries.Count); result.AddRange(countryKey == null ? countries.Select(c => new Country { Id = c.Key, Name = c.Value }).ToList() : countries.Where(c => c.Key == countryKey.Value) .Select(c => new Country { Id = c.Key, Name = c.Value }) .ToList()); cacheDependencies.Add(CountriesExtension.TableName); CacheHelper.AddCacheData(hash, result, cacheDependencies.ToList(), Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Питания /// </summary> /// <param name="searchDc"></param> /// <param name="pansionKey">Ключ питания</param> /// <param name="hash"></param> /// <returns></returns> public static List <Meal> GetMeals(this MtSearchDbDataContext searchDc, int?pansionKey, out string hash) { List <Meal> result; hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, pansionKey); if ((result = CacheHelper.GetCacheItem <List <Meal> >(hash)) != null) { return(result); } result = new List <Meal>(); if (pansionKey == null) { result.AddRange(searchDc.GetAllPansions().Select(p => new Meal { Id = p.PN_KEY, Name = p.PN_NAME }).ToList()); } else { var pansion = searchDc.GetPansionByKey(pansionKey.Value); result.Add(new Meal { Id = pansion.PN_KEY, Name = pansion.PN_NAME }); } CacheHelper.AddCacheData(hash, result, new List <string>() { PansionsExtension.TableName }, Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Возвращает список перелетов туда / обратно /// </summary> /// <param name="dc">Контекст поисковой БД</param> /// <param name="mainDc">Контекст основной БД</param> /// <param name="cityKeyFrom">Ключ города вылета</param> /// <param name="cityKeyTo">Ключ города прилета</param> /// <param name="hash">Хэш кэша</param> /// <returns></returns> public static IList <Tuple <DateTime, DateTime> > GetFlightDatesTwoWay(this MtSearchDbDataContext dc, MtMainDbDataContext mainDc, int cityKeyFrom, int cityKeyTo, out string hash) { List <Tuple <DateTime, DateTime> > result; hash = String.Format("{0}_{1}_{2}", MethodBase.GetCurrentMethod().Name, cityKeyFrom, cityKeyTo); if ((result = CacheHelper.GetCacheItem <List <Tuple <DateTime, DateTime> > >(hash)) != null) { return(result); } var cacheDependencies = new List <string>(); string hashOut; var packets = mainDc.GetFlightPackets(dc, out hashOut) .Where(p => p.Item2 == PacketType.TwoWayCharters) .ToList(); cacheDependencies.Add(hashOut); var schedule = dc.GetFlightSchedules(mainDc, packets, out hashOut); cacheDependencies.Add(hashOut); result = schedule.Schedule.Where(s => s.FlightParamsFrom != null && s.FlightParamsTo != null && s.FlightParamsTo.CityKeyFrom == cityKeyFrom && s.FlightParamsTo.CityKeyTo == cityKeyTo && s.FlightParamsFrom.CityKeyFrom == cityKeyTo && s.FlightParamsFrom.CityKeyTo == cityKeyFrom) .Select(s => new Tuple <DateTime, DateTime>(s.FlightParamsTo.DepartTime.Date, s.FlightParamsFrom.DepartTime.Date)) .Distinct() .ToList(); CacheHelper.AddCacheData(hash, result, cacheDependencies.ToList(), Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Возвращает список стран прилета /// </summary> /// <param name="dc">Контекст поисковой БД</param> /// <param name="mainDc">Контекст основной БД</param> /// <param name="isOneWay">Является ли перелет в одну сторону или туда/обратно</param> /// <param name="cityKeyFrom">Ключ города вылета</param> /// <param name="hash">Хэш кэша</param> /// <returns></returns> public static IList <Tuple <int, string> > GetFlightCountriesTo(this MtSearchDbDataContext dc, MtMainDbDataContext mainDc, bool isOneWay, int cityKeyFrom, out string hash) { List <Tuple <int, string> > result; hash = String.Format("{0}_{1}_{2}", MethodBase.GetCurrentMethod().Name, isOneWay, cityKeyFrom); if ((result = CacheHelper.GetCacheItem <List <Tuple <int, string> > >(hash)) != null) { return(result); } var cacheDependencies = new List <string>(); string hashOut; var cities = dc.GetFlightCitiesTo(mainDc, isOneWay, null, cityKeyFrom, out hashOut); cacheDependencies.Add(hashOut); result = (from cn in dc.GetAllCountries() join ct in dc.GetAllCities() on cn.CN_KEY equals ct.CT_CNKEY where cities.Select(c => c.Item1).ToList().Contains(ct.CT_KEY) select new Tuple <int, string>(cn.CN_KEY, cn.CN_NAME)) .Distinct() .OrderBy(c => c.Item2) .ToList(); cacheDependencies.Add(CitiesExtension.TableName); cacheDependencies.Add(CountriesExtension.TableName); CacheHelper.AddCacheData(hash, result, cacheDependencies.ToList(), Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Категории отелей /// </summary> /// <param name="mainDc"></param> /// <param name="categoryKey">Ключ категории</param> /// <param name="hash"></param> /// <returns></returns> public static List <HotelCategory> GetHotelCategories(this MtMainDbDataContext mainDc, int?categoryKey, out string hash) { List <HotelCategory> result; hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, categoryKey); if ((result = CacheHelper.GetCacheItem <List <HotelCategory> >(hash)) != null) { return(result); } result = new List <HotelCategory>(); if (categoryKey == null) { result.AddRange(mainDc.GetAllHotelCats().Select(c => new HotelCategory { Id = c.COH_Id, Name = c.COH_Name }).ToList()); } else { var hotelCat = mainDc.GetHotelCatByKey(categoryKey.Value); result.Add(new HotelCategory { Id = hotelCat.COH_Id, Name = hotelCat.COH_Name }); } CacheHelper.AddCacheData(hash, result, new List <string>() { HotelCategoriesExtension.TableName }, Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Возвращает список вариантов ответов по туристу /// </summary> /// <param name="dc">Контекст БД</param> /// <param name="touristKey">КЛюч туриста</param> /// <param name="hash">Хэш кэша</param> /// <returns></returns> public static IEnumerable <QuestionnaireTouristCase> GetQuestCasesByTourist(this MtMainDbDataContext dc, int touristKey, out string hash) { List <QuestionnaireTouristCase> result; hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, touristKey); if ((result = CacheHelper.GetCacheItem <List <QuestionnaireTouristCase> >(hash)) != null) { return(result); } result = (from q in dc.QuestionnaireTouristCases where q.QTC_TUKey == touristKey select q) .ToList(); if (!CacheHelper.IsCacheKeyExists(TableName)) { CacheHelper.AddCacheData(TableName, String.Empty, TableName); } CacheHelper.AddCacheData(hash, result, new List <string>() { TableName }, Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Получение списка параметров для квоты "мало" по классам услуг /// </summary> /// <param name="dc">Контекст базы данных</param> /// <returns></returns> public static Dictionary <uint, QuotaSmallServiceParams> GetQuotaSmallServiceParams(this MtSearchDbDataContext dc) { Dictionary <uint, QuotaSmallServiceParams> serviceSmallParams; const string hash = "ServiceSmallParams"; if ((serviceSmallParams = CacheHelper.GetCacheItem <Dictionary <uint, QuotaSmallServiceParams> >(hash)) != default(Dictionary <uint, QuotaSmallServiceParams>)) { return(serviceSmallParams); } serviceSmallParams = (from s in dc.GetAllServices() where (s.SV_KEY == 1 || s.SV_KEY == 3) select s ) .ToDictionary(s => (uint)s.SV_KEY, s => new QuotaSmallServiceParams { AndParam = s.SV_LittleAnd.HasValue && s.SV_LittleAnd.Value, PercentParam = (double?)s.SV_LittlePercent, PlaceParam = (uint?)s.SV_LittlePlace }); CacheHelper.AddCacheData(hash, serviceSmallParams, new List <string>() { TableName }, Globals.Settings.Cache.LongCacheTimeout); return(serviceSmallParams); }
/// <summary> /// Является ли значение типом мало /// </summary> /// <param name="dc">Контекст базы данных</param> /// <param name="serviceClass">Класс услуги</param> /// <param name="quotaExistCount">Число оставшихся квот</param> /// <param name="quotaAllCount">Число квот всего</param> /// <param name="hash">Хэш кэша</param> /// <returns></returns> public static bool IsSmallQuotaState(this MtSearchDbDataContext dc, ServiceClass serviceClass, uint quotaExistCount, uint quotaAllCount, out string hash) { hash = String.Format("{0}_{1}_{2}_{3}", MethodBase.GetCurrentMethod().Name, serviceClass, quotaExistCount, quotaAllCount); if (CacheHelper.IsCacheKeyExists(hash)) { var result = CacheHelper.GetCacheItem <bool>(hash); return(result); } QuotaSmallServiceParams pars = dc.GetQuotaSmallServiceParams()[(uint)serviceClass]; if (pars == null) { throw new ApplicationException("Ошибка метода: " + MethodBase.GetCurrentMethod().Name + "_" + serviceClass); } bool res; bool?placeCondition = null; bool?percentCondition = null; if (pars.PlaceParam.HasValue) { placeCondition = quotaExistCount <= pars.PlaceParam.Value; } if (pars.PercentParam.HasValue) { percentCondition = (quotaExistCount / (double)quotaAllCount) * 100 <= pars.PercentParam.Value; } if (pars.AndParam) { if (placeCondition.HasValue && placeCondition.Value == false || percentCondition.HasValue && percentCondition.Value == false) { res = false; } else { res = true; } } else { if (placeCondition.HasValue && placeCondition.Value || percentCondition.HasValue && percentCondition.Value) { res = true; } else { res = false; } } CacheHelper.AddCacheData(hash, res, new List <string>() { TableName }, Globals.Settings.Cache.LongCacheTimeout); return(res); }
/// <summary> /// Возвращает список всех HotelRooms, по которым заведены цены с заданными параметрами /// </summary> /// <param name="mainDc">Контекст БД</param> /// <param name="serviceClass">Класс услуги</param> /// <param name="code">Code услуги</param> /// <param name="date">Дата услуги</param> /// <param name="packetKey">Ключ пакета</param> /// <param name="partnerKey">Ключ партнера</param> /// <param name="hash">Хэш кэша</param> /// <returns></returns> public static List <int> GetHotelRoomsFromCosts(this MtMainDbDataContext mainDc, ServiceClass serviceClass, int code, DateTime date, int packetKey, int partnerKey, out string hash) { List <int> result; hash = String.Format("{0}_{1}_{2}_{3}_{4}", MethodBase.GetCurrentMethod().Name, (int)serviceClass, code, date, packetKey); if ((result = CacheHelper.GetCacheItem <List <int> >(hash)) != null) { return(result); } result = (from c in mainDc.tbl_Costs where c.CS_SVKEY == (int)serviceClass && c.CS_CODE == code && c.CS_PKKEY == packetKey && c.CS_PRKEY == partnerKey && c.CS_SUBCODE1.HasValue && (date >= c.CS_DATE.Value && date <= c.CS_DATEEND.Value || !c.CS_DATE.HasValue || !c.CS_DATEEND.HasValue) && (date >= c.CS_CHECKINDATEBEG.Value && date <= c.CS_CHECKINDATEEND.Value || !c.CS_CHECKINDATEBEG.HasValue || !c.CS_CHECKINDATEEND.HasValue) && (DateTime.Now >= c.cs_DateSellBeg.Value && DateTime.Now <= c.cs_DateSellEnd.Value || !c.cs_DateSellBeg.HasValue || !c.cs_DateSellEnd.HasValue) select c.CS_SUBCODE1.Value) .Distinct() .ToList(); CacheHelper.AddCacheData(hash, result, null, Globals.Settings.Cache.MediumCacheTimeout); return(result); }
public static List <Repository.MtSearch.tbl_Cost> GetFlightCostsByPacketKey(this MtSearchDbDataContext dc, int packetKey, out string hash) { List <Repository.MtSearch.tbl_Cost> result; hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, packetKey); if ((result = CacheHelper.GetCacheItem <List <Repository.MtSearch.tbl_Cost> >(hash)) != default(List <Repository.MtSearch.tbl_Cost>)) { return(result); } var cacheDependencies = new List <string> { String.Format("{0}_{1}_{2}", CacheHelper.CostHash, (int)ServiceClass.Flight, packetKey) }; result = dc.tbl_Costs .Where(c => c.CS_SVKEY == (int)ServiceClass.Flight && c.CS_SUBCODE1 != null && c.CS_PKKEY.HasValue && c.CS_PKKEY == packetKey && (!c.CS_DATEEND.HasValue || DateTime.Now.Date <= c.CS_DATEEND.Value) // todo: уточнить необходимость условия 14.08.2014 //&& (!c.CS_CHECKINDATEEND.HasValue || (DateTime.Now.Date >= c.CS_CHECKINDATEBEG.Value && DateTime.Now.Date <= c.CS_CHECKINDATEEND.Value)) ) .ToList(); CacheHelper.AddCacheData(hash, result, cacheDependencies, Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Возрвращает ключ /// </summary> /// <param name="mainDc">Контекст основной БД</param> /// <param name="priceKey">Ключ цены</param> /// <param name="hotelKey">Ключ отеля</param> /// <param name="hash">Хэш</param> /// <returns></returns> public static int GetHotelPacketKey(this MtMainDbDataContext mainDc, int priceKey, int hotelKey, out string hash) { hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, priceKey); if (CacheHelper.IsCacheKeyExists(hash)) { return(CacheHelper.GetCacheItem <int>(hash)); } var result = -1; var commandBuilder = new StringBuilder(); commandBuilder.AppendLine("select ts_oppacketkey "); commandBuilder.AppendLine("from tp_services "); commandBuilder.AppendLine(String.Format("where ts_key in (select tl_tskey from tp_servicelists where tl_tikey in (select tp_tikey from tp_prices where tp_key = {0})) ", priceKey)); commandBuilder.AppendLine(String.Format("and ts_svkey = {0} and ts_code = {1} ", (int)ServiceClass.Hotel, hotelKey)); using (var command = mainDc.Connection.CreateCommand()) { command.CommandText = commandBuilder.ToString(); command.CommandTimeout = 100; mainDc.Connection.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) { result = reader.GetInt32("ts_oppacketkey"); } } mainDc.Connection.Close(); } CacheHelper.AddCacheData(hash, result, null, Globals.Settings.Cache.MediumCacheTimeout); return(result); }
/// <summary> /// Возвращает список ключей пакетов, в которых встречаются перечисленные перелеты /// </summary> /// <param name="dc">Контекст поисковой БД</param> /// <param name="charterKeys">Список ключей перелетов</param> /// <param name="hash">Хэш кэша</param> /// <returns></returns> public static IList <Tuple <int, PacketType> > GetPacketKeysByCarterKeys(this MtSearchDbDataContext dc, IEnumerable <int> charterKeys, out string hash) { List <Tuple <int, PacketType> > result; hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, String.Join("_", charterKeys)); if ((result = CacheHelper.GetCacheItem <List <Tuple <int, PacketType> > >(hash)) != default(List <Tuple <int, PacketType> >)) { return(result); } var cacheDependencies = new List <string>(); var packetKeys = (from c in dc.tbl_Costs where c.CS_SVKEY == (int)ServiceClass.Flight && (!c.CS_DATEEND.HasValue || DateTime.Now.Date <= c.CS_DATEEND.Value) && charterKeys.Contains(c.CS_CODE) && c.CS_PKKEY.HasValue select c.CS_PKKEY.Value) .Distinct() .ToList(); cacheDependencies.Add(QDSearch.Extensions.CostsExtension.TableName); CacheHelper.AddCacheData(hash, result, cacheDependencies, Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Возвращает список классов перелетов /// </summary> /// <param name="dc">Контекст базы данных</param> /// <returns></returns> public static List <AirService> GetAllAirServices(this MtSearchDbDataContext dc) { List <AirService> airServices; if ((airServices = CacheHelper.GetCacheItem <List <AirService> >(TableName)) != null) { return(airServices); } lock (LockAirServices) { if ((airServices = CacheHelper.GetCacheItem <List <AirService> >(TableName)) != null) { return(airServices); } airServices = (from a in dc.AirServices select a) .ToList <AirService>(); CacheHelper.AddCacheData(TableName, airServices, TableName); } return(airServices); }
/// <summary> /// Возвращает список реальных курсов на сегодня /// </summary> /// <param name="dc">Контекст базы данных</param> /// <returns></returns> public static IList <CrossCourse> GetTodayCrossCourses(this MtSearchDbDataContext dc) { List <CrossCourse> crossCourses; const string hash = "CrossCourses"; if ((crossCourses = CacheHelper.GetCacheItem <List <CrossCourse> >(hash)) != null) { return(crossCourses); } lock (LockCrossCourses) { if ((crossCourses = CacheHelper.GetCacheItem <List <CrossCourse> >(hash)) != null) { return(crossCourses); } crossCourses = (from rcourse in dc.RealCourses join r1 in dc.Rates on rcourse.RC_RCOD1 equals r1.RA_CODE join r2 in dc.Rates on rcourse.RC_RCOD2 equals r2.RA_CODE where DateTime.Now.Date >= rcourse.RC_DATEBEG && DateTime.Now.Date <= rcourse.RC_DATEEND select new CrossCourse { Course = rcourse.RC_COURSE.Value, RateCodeFrom = r2.RA_CODE, RateCodeTo = r1.RA_CODE }) .ToList(); CacheHelper.AddCacheData(hash, crossCourses, TableName); } return(crossCourses); }
/// <summary> /// Возвращает список пакетов, в которых лежат цены для бронирования авиабилетов /// </summary> /// <param name="dc">Контекст базы данных</param> /// <param name="searchDc">Контекст поисковой БД</param> /// <param name="hash">Хэш кэша</param> /// <returns>Tuple int, PacketType - ключ пакета, тип пакета (направление туда, обратно или туда/обратно)</returns> public static IList <Tuple <int, PacketType> > GetFlightPackets(this MtMainDbDataContext dc, MtSearchDbDataContext searchDc, out string hash) { List <Tuple <int, PacketType> > result; hash = String.Format("{0}", MethodBase.GetCurrentMethod().Name); if ((result = CacheHelper.GetCacheItem <List <Tuple <int, PacketType> > >(hash)) != null) { return(result); } var cacheDependencies = new List <string>(); result = new List <Tuple <int, PacketType> >(); string hashOut; var packetKeys = dc.GetCharterBookingPackets(out hashOut); cacheDependencies.Add(hashOut); var packetKeysDates = dc.GetDatesByTours(packetKeys, out hashOut); cacheDependencies.Add(hashOut); var allPacketServices = dc.GetClassServicesByTurListKeys(ServiceClass.Flight, packetKeysDates.Select(p => p.Item1).Distinct().ToList(), out hashOut); cacheDependencies.Add(hashOut); var homeCountryKey = (from ct in searchDc.GetAllCities() where ct.CT_KEY == Globals.Settings.HomeCityKey select ct.CT_CNKEY) .Single(); foreach (var packetKey in packetKeysDates.Select(p => p.Item1).Distinct().ToList()) { var services = (from s in allPacketServices where s.TS_PKKEY == packetKey select s) .ToList(); if (services.Count > 1) { result.Add(new Tuple <int, PacketType>(packetKey, PacketType.TwoWayCharters)); } else if (services.Count == 1) { var serviceCountryKey = (from cn in searchDc.GetAllCities() where cn.CT_KEY == services[0].TS_SUBCODE2 select cn.CT_CNKEY) .FirstOrDefault(); result.Add(serviceCountryKey == homeCountryKey ? new Tuple <int, PacketType>(packetKey, PacketType.DirectCharters) : new Tuple <int, PacketType>(packetKey, PacketType.BackCharters)); } } CacheHelper.AddCacheData(hash, result, cacheDependencies.ToList(), Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Отели /// </summary> /// <param name="searchDc"></param> /// <param name="sftDc"></param> /// <param name="hotelKey">Ключ категории</param> /// <param name="mainDc"></param> /// <param name="hash"></param> /// <returns></returns> public static List <DataModel.Hotel> GetHotels(this MtMainDbDataContext mainDc, MtSearchDbDataContext searchDc, SftWebDbDataContext sftDc, int?hotelKey, out string hash) { List <DataModel.Hotel> result; hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, hotelKey); if ((result = CacheHelper.GetCacheItem <List <DataModel.Hotel> >(hash)) != null) { return(result); } result = new List <DataModel.Hotel>(); var cacheDependencies = new List <string>(); if (hotelKey == null) { string hashOut; var hotelCities = (from r in searchDc.GetResorts(sftDc, null, out hashOut) select r.Id) .ToList(); cacheDependencies.Add(hashOut); var hotels = (from h in searchDc.GetAllHotels() join c in mainDc.GetAllHotelCats() on h.Stars equals c.COH_Name where hotelCities.Contains(h.CtKey) select new DataModel.Hotel { Id = h.Key, Name = h.Name, ResortId = h.CtKey, HotelCategoryId = c.COH_Id }) .ToList(); result.AddRange(hotels); } else { string hashOut; var hotel = searchDc.GetHotelByKey(hotelKey.Value, out hashOut); cacheDependencies.Add(hashOut); if (hotel != null) { var cat = mainDc.GetAllHotelCats().SingleOrDefault(c => c.COH_Name == hotel.Stars); if (cat != null) { result.Add(new DataModel.Hotel { HotelCategoryId = cat.COH_Id, Id = hotel.Key, Name = hotel.Name, ResortId = hotel.CtKey }); } } } cacheDependencies.Add(HotelsExtension.TableName); cacheDependencies.Add(HotelCategoriesExtension.TableName); CacheHelper.AddCacheData(hash, result, cacheDependencies.ToList(), Globals.Settings.Cache.LongCacheTimeout); return(result); }
public void FlightState_No() { CacheHelper.AddCacheData("GetCharterCityDirection_Charter_1_3812", new Tuple <int, int>(227, 332), 0); CacheHelper.AddCacheData(StopAviaExtension.TableName, new List <StopAvia>(), 0); //CacheHelper.AddCacheData("GetPlainQuotasObjects_Quota_1_3812_뱢媘원̸ⷪ뉇靊", new List<QuotaPlain>() //GetPlainQuotasObjects_Quota_1_3812 CacheHelper.AddCacheData("GetPlainQuotasObjects_1_3812_뱢媘원̸ⷪ뉇靊", new List <QuotaPlain>() { new QuotaPlain { Busy = 180, CheckInPlaces = 180, CheckInPlacesBusy = 0, Date = new DateTime(2014, 04, 27), Duration = String.Empty, IsAllotmentAndCommitment = false, PartnerKey = 7859, Places = 180, QdId = 31136542, QoId = 112967, Release = null, SsId = 20152512, SsQdId = 31136542, SubCode1 = 98, SubCode2 = -1, Type = QuotaType.Commitment } }, 0); int?subCode2 = null; using (var searchDc = new MtSearchDbDataContext()) { string hash; const ServiceClass serviceClass = ServiceClass.Flight; const int code = 3812; const int subCode1 = 89; const int partnerKey = 7859; var serviceDateFrom = new DateTime(2014, 04, 27); var serviceDateTo = new DateTime(2014, 05, 22); const int requestedPlaces = 2; var result = searchDc.CheckServiceQuota(serviceClass, code, subCode1, subCode2, partnerKey, serviceDateFrom, serviceDateTo, requestedPlaces, out hash); Assert.AreEqual(result.QuotaState, QuotesStates.No); Assert.AreEqual(result.Places, (uint)0); Assert.AreEqual(result, new QuotaStatePlaces() { IsCheckInQuota = false, Places = 0, QuotaState = QuotesStates.No }); } }
public static PriceValue GetFlightPriceByParams(this MtSearchDbDataContext dc, int code, int subCode1, int partnerKey, int packetKey, DateTime date, int duration, out string hash) { PriceValue result; hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, CacheHelper.GetCacheKeyHashed(new[] { code.ToString(), subCode1.ToString(), partnerKey.ToString(), packetKey.ToString(), date.ToString("yyyy-MM-dd"), duration.ToString() })); if ((result = CacheHelper.GetCacheItem <PriceValue>(hash)) != null) { return(result); } string hashOut; var dayOfWeek = ((int)date.DayOfWeek).ToString(); //koshelev,сортировка как в хранимке GetServiceCost //CS_CheckInDateBEG Desc, CS_CheckInDateEnd, CS_Date Desc, CS_DATEEND, CS_LONGMIN desc, //CS_LONG, CS_DateSellBeg Desc, CS_DateSellEnd, CS_BYDAY, CS_WEEK ASC var costsList = (from c in dc.GetFlightCostsByPacketKey(packetKey, out hashOut) where c.CS_CODE == code && c.CS_SUBCODE1 == subCode1 && c.CS_PRKEY == partnerKey && c.CS_PKKEY == packetKey && (c.cs_DateSellBeg == null || c.cs_DateSellBeg <= DateTime.Now) && (c.cs_DateSellEnd == null || c.cs_DateSellEnd >= DateTime.Now) && (duration < 0 || c.CS_LONGMIN == null || c.CS_LONGMIN <= duration) && (duration < 0 || c.CS_LONG == null || c.CS_LONG >= duration) && (c.CS_DATE == null || c.CS_DATE <= date.Date) && (c.CS_DATEEND == null || c.CS_DATEEND >= date.Date) && (String.IsNullOrEmpty(c.CS_WEEK) || c.CS_WEEK.IndexOf(dayOfWeek) >= 0) select c) .OrderByDescending(c => c.CS_CHECKINDATEBEG) .ThenBy(c => c.CS_CHECKINDATEEND) .ThenByDescending(c => c.CS_DATE) .ThenBy(c => c.CS_DATEEND) .ThenByDescending(c => c.CS_LONGMIN) .ThenBy(c => c.CS_LONG) .ThenByDescending(c => c.cs_DateSellBeg) .ThenBy(c => c.cs_DateSellEnd) .ThenBy(c => c.CS_BYDAY) .ThenBy(c => c.CS_WEEK) .ToList(); result = (from c in costsList select new PriceValue { Price = c.CS_COST, Rate = c.CS_RATE }) .FirstOrDefault() ?? new PriceValue { Price = null, Rate = String.Empty }; CacheHelper.AddCacheData(hash, result, new List <string>() { hashOut }, Globals.Settings.Cache.LongCacheTimeout); return(result); }
/// <summary> /// Реальный курс на дату /// </summary> /// <param name="dc">Контекст базы данных</param> /// <param name="date">Дата курса</param> /// <param name="rateFrom">Валюта, из которой конвертируем</param> /// <param name="rateTo">Валюта, в которую конвертируем</param> /// <returns></returns> public static decimal GetRateRealCourse(this MtSearchDbDataContext dc, DateTime date, int rateFrom, int rateTo) { if (rateFrom == rateTo) { return(1); } var hash = String.Format("{0}_{1}_{2}_{3}", MethodBase.GetCurrentMethod().Name, date.ToString("dd.MM.yyyy"), rateFrom, rateTo); if (CacheHelper.IsCacheKeyExists(hash)) { return(CacheHelper.GetCacheItem <decimal>(hash)); } var realCourses = dc.GetActualRealCourses(); var result = (from rc in realCourses where date >= rc.DateFrom && date <= rc.DateTo && rc.RateKeyFrom == rateFrom && rc.RateKeyTo == rateTo select rc.Course) .FirstOrDefault(); if (result == 0) { result = (from rc in realCourses where date >= rc.DateFrom && date <= rc.DateTo && rc.RateKeyFrom == rateTo && rc.RateKeyTo == rateFrom select rc.Course) .FirstOrDefault(); if (result != 0) { result = 1 / result; } } if (result == 0) { throw new ApplicationException(MethodBase.GetCurrentMethod().Name + ". Отсутствует реальный курс на дату " + date.ToString("dd.MM.yyyy")); } CacheHelper.AddCacheData(hash, result, new List <string>() { TableName }, Globals.Settings.Cache.LongCacheTimeout); return(result); }
///// <summary> ///// Возвращает список цен ///// </summary> ///// <param name="dc">Контекст базы данных</param> ///// <returns></returns> //public static List<Repository.MtSearch.tbl_Cost> GetAllFlightCosts(this MtSearchDbDataContext dc) //{ // List<Repository.MtSearch.tbl_Cost> costs; // if ((costs = CacheHelper.GetCacheItem<List<Repository.MtSearch.tbl_Cost>>(TableName)) != default(List<Repository.MtSearch.tbl_Cost>)) return costs; // lock (LockCosts) // { // if ((costs = CacheHelper.GetCacheItem<List<Repository.MtSearch.tbl_Cost>>(TableName)) != default(List<Repository.MtSearch.tbl_Cost>)) return costs; // costs = (from c in dc.tbl_Costs // where (!c.CS_CHECKINDATEEND.HasValue || c.CS_CHECKINDATEEND.Value >= DateTime.Now.Date) // && (!c.CS_DATEEND.HasValue || c.CS_DATEEND.Value >= DateTime.Now.Date) // && (c.CS_SVKEY == (int)ServiceClass.Flight) // select c) // .ToList<Repository.MtSearch.tbl_Cost>(); // CacheHelper.AddCacheData(TableName, costs, TableName); // } // return costs; //} /// <summary> /// Расчет цены по услуге через хранимку Мегатек /// </summary> /// <param name="dc">Контекст БД</param> /// <param name="svKey">Класс услуги</param> /// <param name="code">Code услуги</param> /// <param name="subCode1">SubCode1 услуги</param> /// <param name="subCode2">SubCode2 услуги</param> /// <param name="partnerKey">Ключ партнера</param> /// <param name="packetKey">Ключ пакета</param> /// <param name="startDate">Дата начала услуги</param> /// <param name="days">Продолжительность услуги</param> /// <param name="rate">Валюта, в которой должен быть произведен расчет</param> /// <param name="nmen">Число людей по услуге</param> /// <param name="hash">Хэш кэша</param> /// <returns></returns> public static decimal?GetServiceCost(this MtMainDbDataContext dc, int svKey, int code, int subCode1, int subCode2, int partnerKey, int packetKey, DateTime startDate, int days, string rate, int nmen, out string hash) { decimal?result; hash = String.Format("{0}_{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}_{9}_{10}", MethodBase.GetCurrentMethod().Name, svKey, code, subCode1, subCode2, partnerKey, packetKey, startDate, days, rate, nmen); if ((result = CacheHelper.GetCacheItem <decimal?>(hash)) != default(decimal?)) { return(result); } var cacheDependencies = new List <string> { String.Format("{0}_{1}_{2}", CacheHelper.CostHash, svKey, code) }; var commandBuilder = new StringBuilder(); commandBuilder.AppendFormat(@"declare @nNetto decimal(14,2), @nBrutto decimal(14,2), @nDiscount decimal(14,2) declare @nettoDetail varchar(100), @sBadRate varchar(2), @dtBadDate DateTime declare @sDetailed varchar(100), @nSPId int, @useDiscountDays int declare @tourKey int, @turdate datetime, @tourDays int, @includeAddCost bit declare @saleDate DateTime set @saleDate = GetDate() set @includeAddCost = 1 exec GetServiceCost {0}, {1}, {2}, {3}, {4}, {5}, '{6:yyyy-MM-dd}', {7}, '{8}', {9}, 0, 0, 0, @saleDate, @nNetto output, @nBrutto output, @nDiscount output, @nettoDetail output, @sBadRate output, @dtBadDate output, @sDetailed output, @nSPId output, 0, @tourKey, @turdate, @tourDays, @includeAddCost select @nBrutto", svKey, code, subCode1, subCode2, partnerKey, packetKey, startDate, days, rate, nmen); using (var command = dc.Connection.CreateCommand()) { command.CommandText = commandBuilder.ToString(); dc.Connection.Open(); var bruttoTemp = command.ExecuteScalar(); if (bruttoTemp.ToString() != String.Empty) { result = (decimal)bruttoTemp; } dc.Connection.Close(); } CacheHelper.AddCacheData(hash, result, cacheDependencies.ToList(), Globals.Settings.Cache.LongCacheTimeout); return(result); }