/// <summary>
 /// Возвращает список альтернативных перелетов
 /// </summary>
 /// <param name="dc">Контекст БД</param>
 /// <param name="mainDc">Контекст основной БД</param>
 /// <param name="cityKeyFrom">Ключ города вылета</param>
 /// <param name="cityKeyTo">Ключ города прилета</param>
 /// <param name="charterDate">Дата перелета</param>
 /// <param name="packetKey">Ключ пакета</param>
 /// <param name="flightGroups">Группы перелета (эконом, бизнес, премиум)</param>
 /// <param name="hash">Хэш кэша</param>
 /// <returns></returns>
 public static Dictionary <int, List <FlightPlainInfo> > GetAltCharters(
     this MtSearchDbDataContext dc, MtMainDbDataContext mainDc, int cityKeyFrom, int cityKeyTo, DateTime charterDate,
     int packetKey, IDictionary <int, IEnumerable <int> > flightGroups, out string hash)
 {
     return(dc.GetAltCharters(mainDc, null, cityKeyFrom, cityKeyTo, charterDate,
                              packetKey, flightGroups, out hash));
 }
Exemple #2
0
        /// <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="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);
        }
Exemple #4
0
        /// <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);
        }
Exemple #5
0
        /// <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);
        }
Exemple #6
0
        private void LoadRoomTypesAndMens(MtMainDbDataContext mtmDc, MtSearchDbDataContext mtsDc, SftWebDbDataContext sftDc, bool isReinit)
        {
            if (RblCitiesFromFilter.Items.Count == 0 || DdlContriesToFilter.Items.Count == 0 ||
                ChblTourTypes.Items.Count == 0 || ChblCitiesToFilter.Items.Count == 0 ||
                DdlToursFilter.Items.Count == 0 || ArrivalDatesFilter.ArrivalDates == null ||
                !ArrivalDatesFilter.ArrivalDates.Any() ||
                ChblNightsFilter.Items.Count == 0 || ChblHotelCategoriesFilter.Items.Count == 0 ||
                UcHotelsFilter.Items.Count == 0 || ChblPansionsFilter.Items.Count == 0)
            {
                DdlRoomTypesFilter.Items.Clear();
                return;
            }


            // выбираем вариант поиска по номеру или по людям в зависимости от большинства туров с ценой за номер или за человека
            PnPersons.Visible = !(PnRoomTypes.Visible = mtsDc.IsCountryPriceForMen(SelectedCountryToKey));

            if (PnRoomTypes.Visible)
            {
                DdlRoomTypesFilter.DataSource = AddFirstCustomElement(-1, "- все -",
                                                                      mtsDc.GetTourRooms(sftDc, SelectedCityFromKey, SelectedCountryToKey, SelectedCitiesToKeys, SelectedTourKeys, SelectedArrivalDates, SelectedNights,
                                                                                         SelectedHotelKeys, SelectedPansionKeys).ToDictionary(k => k.Key, v => HttpUtility.HtmlEncode(v.Value)));
                DdlRoomTypesFilter.DataBind();
            }
            else
            {
                DdlRoomTypesFilter.Items.Clear();
            }
        }
Exemple #7
0
        /// <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);
        }
Exemple #8
0
        public static IList <SearchResultItem> ConvertCalcTourToNoSql(this MtMainDbDataContext mainDc, MtSearchDbDataContext searchDc, int tourKey)
        {
            var     result = new List <SearchResultItem>();
            string  hashOut;
            var     tours = searchDc.GetTPToursByKeys(new[] { tourKey }, out hashOut);
            TP_Tour tpTour;

            if (tours != null && tours.Count == 1)
            {
                tpTour = tours[0];
            }
            else
            {
                throw new ArgumentException(String.Format("Неправильный параметр tourKey"));
            }

            var tourString = searchDc.GetTourStringsByKeys(new [] { tpTour.TO_Key }, out hashOut);
            var tpPrices   = mainDc.TP_Prices.Where(t => t.TP_TOKey == tourKey && t.TP_Gross != null).ToList();

            foreach (var tpPrice in tpPrices)
            {
                var item = new SearchResultItem();
                // будет заполнен при выдаче результата в поиск
                item.PriceInRates = null;
                item.PriceKey     = tpPrice.TP_Key;
                item.Price        = tpPrice.TP_Gross.Value;
                item.RateCode     = tpTour.TO_Rate;
                item.Date         = tpPrice.TP_DateBegin;
                item.PriceFor     = tpTour.TO_PriceFor == 0 ? PriceForType.PerMen : PriceForType.PerRoom;
                item.CountryKey   = tpTour.TO_CNKey;
            }
            return(result);
        }
Exemple #9
0
        /// <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);
        }
Exemple #10
0
        /// <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);
        }
Exemple #11
0
        public static tbl_Dogovor GetDogovorByKey(this MtMainDbDataContext dc, int dogovorKey)
        {
            var result = (from d in dc.tbl_Dogovors
                          where d.DG_Key == dogovorKey
                          select d)
                         .SingleOrDefault();

            return(result);
        }
Exemple #12
0
        public string GetCountryDescription(int countryKey)
        {
            string countryDescription;

            using (var mtDc = new MtMainDbDataContext())
            {
                countryDescription = mtDc.GetCountryDescription(countryKey);
            }
            return(countryDescription);
        }
Exemple #13
0
        /// <summary>
        /// Данные по квотам на перелеты
        /// </summary>
        /// <param name="query">Параметры запроса</param>
        /// <returns></returns>
        public QuotaPriceResult GetFlightQuotaPrices(QuotaPriceQuery query)
        {
            QuotaPriceResult flightQuotaPrices;

            using (var mtsDc = new MtSearchDbDataContext())
            {
                using (var mtmDc = new MtMainDbDataContext())
                {
                    flightQuotaPrices = mtsDc.GetFlightQuotaPrices(mtmDc, query);
                }
            }
            return(flightQuotaPrices);
        }
Exemple #14
0
        /// <summary>
        /// Метод по выдаче расписаний рейсов
        /// </summary>
        /// <returns></returns>
        public FlightSchedule GetFlightSchedules()
        {
            FlightSchedule flightSchedule;

            using (var mtsDc = new MtSearchDbDataContext())
            {
                using (var mtmDc = new MtMainDbDataContext())
                {
                    flightSchedule = mtsDc.GetFlightSchedules(mtmDc);
                }
            }
            return(flightSchedule);
        }
Exemple #15
0
        ///// <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);
        }
        protected void HeaderCol_OnCommand(object sender, CommandEventArgs e)
        {
            var linkButton = sender as LinkButton;

            if (linkButton == null)
            {
                throw new ArgumentNullException("sender");
            }
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            if (e.CommandName != "Sort")
            {
                return;
            }

            var column = (SortingColumn)Enum.Parse(typeof(SortingColumn), e.CommandArgument.ToString());

            if (column == CurrentSort.Item1)
            {
                CurrentSort = new Tuple <SortingColumn, SortingDirection>(CurrentSort.Item1,
                                                                          CurrentSort.Item2 == SortingDirection.Asc ? SortingDirection.Desc : SortingDirection.Asc);
            }
            else
            {
                CurrentSort = new Tuple <SortingColumn, SortingDirection>(column, SortingDirection.Asc);
            }

            using (var mtmDc = new MtMainDbDataContext())
            {
                using (var dc = new MtSearchDbDataContext())
                {
                    var searchResult = dc.PagingOnClient(mtmDc, CityKeyFrom.Value, CountryKey.Value, TourKeys, TourDates,
                                                         TourNights,
                                                         HotelKeys, PansionKeys, MainPlaces, AddPlaces, FirstChildYears, SecondChildYears, RoomTypeKeys,
                                                         HotelQuotaMask, AviaQuotaMask | QuotesStates.None, RateKey.Value, MaxTourPrice, RowsPerPage,
                                                         SearchPages[CurrentPage],
                                                         CurrentSort);

                    RepFindedTours.DataSource = searchResult.SearchItems;
                    RepFindedTours.DataBind();
                }
            }

            Web.ScrollToElement(this, RepPagesTop.ClientID);
            linkButton.Focus();
        }
Exemple #17
0
        private void LoadCountryToDesc(MtMainDbDataContext dc)
        {
            if (dc == null)
            {
                throw new ArgumentNullException("dc");
            }

            if (DdlContriesToFilter.Items.Count == 0)
            {
                LtCountryInfo.Text = String.Empty;
                return;
            }

            LtCountryInfo.Text = dc.GetCountryDescription(Convert.ToInt32(DdlContriesToFilter.SelectedValue));
        }
Exemple #18
0
        //static TouristsExtension()
        //{
        //    CacheHelper.AddCacheData(TableName, "Fake Element", TableName);
        //}

        /// <summary>
        /// Получает туриста по его ключу
        /// </summary>
        /// <param name="dc">Контекст базы данных</param>
        /// <param name="touristKey">Ключ туриста</param>
        /// <param name="hash">Хэш кэша</param>
        /// <returns></returns>
        public static tbl_Turist GetTouristByKey(this MtMainDbDataContext dc, int touristKey, out string hash)
        {
            tbl_Turist result;

            hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, touristKey);
            if ((result = CacheHelper.GetCacheItem <tbl_Turist>(hash)) != null)
            {
                return(result);
            }

            result = (from t in dc.tbl_Turists
                      where t.TU_KEY == touristKey
                      select t).SingleOrDefault();

            CacheHelper.AddCacheData(hash, result, null, Globals.Settings.Cache.MediumCacheTimeout);
            return(result);
        }
Exemple #19
0
        /// <summary>
        /// Возвращает список всех авиакомпаний по кодам перелетов
        /// </summary>
        /// <param name="dc">Контекст базы данных</param>
        /// <param name="charterCodes"></param>
        /// <param name="hash"></param>
        /// <returns></returns>
        public static List <Airline> GetAllAirlinesByCharterKeys(this MtMainDbDataContext dc, List <string> charterCodes, out string hash)
        {
            List <Airline> result;

            hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, String.Join(",", charterCodes));
            if ((result = CacheHelper.GetCacheItem <List <Airline> >(hash)) != null)
            {
                return(result);
            }

            result = dc.GetAllAirlines().Where(a => charterCodes.Contains(a.AL_CODE)).ToList();

            CacheHelper.AddCacheData(hash, result, new List <string>()
            {
                TableName
            }, Globals.Settings.Cache.LongCacheTimeout);
            return(result);
        }
        /// <summary>
        /// Возвращает онлайн-пользователя по логину / паролю
        /// </summary>
        /// <param name="dc">Контекст базы данных</param>
        /// <param name="name">Логин пользователя</param>
        /// <param name="decryptedPassword">Расшифрованный пароль (его обычно вводит пользователь)</param>
        /// <returns>Возвращает пользователя или null, если не нашли комбинации логин / пароль</returns>
        public static DUP_USER GetDupUser(this MtMainDbDataContext dc, string name, string decryptedPassword)
        {
            // для пользователей с зашифрованным паролем
            var user = dc.GetAllDupUsers().SingleOrDefault(u => u.US_ID == name &&
                                                           (u.US_Attribute & (int)DupUserAttributes.Converted) == (int)DupUserAttributes.Converted &&
                                                           CryptoManager.DecodeTripleDesString(u.US_PASSWORD) == decryptedPassword);

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

            // для пользователей с закодированным паролем
            user = dc.GetAllDupUsers().SingleOrDefault(u => u.US_ID == name &&
                                                       (u.US_Attribute & (int)DupUserAttributes.Converted) != (int)DupUserAttributes.Converted &&
                                                       u.US_PASSWORD == GetPasswordHash(decryptedPassword));
            return(user);
        }
Exemple #21
0
        public static IDictionary <string, Question> GetAllQuestionsByQuestionnaire(this MtMainDbDataContext dc, int questKey, int turistKey, out string hash)
        {
            Dictionary <string, Question> result;

            hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, questKey);
            if ((result = CacheHelper.GetCacheItem <Dictionary <string, Question> >(hash)) != null)
            {
                return(result);
            }

            var cacheDependencies = new List <string>();

            result = (from q in dc.GetAllQuestFields()
                      where q.QF_QUKey == questKey
                      select q)
                     .ToDictionary(q => q.QF_Bookmark, q => new Question
            {
                Comment = q.QF_Comment,
                Example = q.QF_Example,
                Format  = Helpers.Converters.StringToFormatType(q.QF_Format),
                Key     = q.QF_Key,
                Name    = q.QF_Name,
                Value   = q.QF_DefaultValue
            });
            cacheDependencies.Add(QuestionnaireFieldsExtension.TableName);

            foreach (var item in result.Values)
            {
                item.Cases = (from c in dc.GetAllQuestFieldCases()
                              where c.QFC_QFKey == item.Key
                              select new QuestionCase
                {
                    IsChecked = c.QFC_IsDefault,
                    Key = c.QFC_Key,
                    Order = c.QFC_Order.HasValue ? c.QFC_Order.Value : 0,
                    Value = c.QFC_Value
                })
                             .ToList();
            }
            cacheDependencies.Add(QuestionnaireFieldCasesExtension.TableName);

            CacheHelper.AddCacheData(hash, result, cacheDependencies.ToList(), Globals.Settings.Cache.LongCacheTimeout);
            return(result);
        }
        /// <summary>
        /// Возращает все услугипо заданному классу из списка туров
        /// </summary>
        /// <param name="dc">Контекст БД</param>
        /// <param name="serviceClass">Класс услуги</param>
        /// <param name="turListKeys">Список ключей туров</param>
        /// <param name="hash">Хэш кэша</param>
        /// <returns></returns>
        public static List <TurService> GetClassServicesByTurListKeys(this MtMainDbDataContext dc, ServiceClass serviceClass, IEnumerable <int> turListKeys, out string hash)
        {
            List <TurService> result;

            hash = String.Format("{0}_{1}_{2}", MethodBase.GetCurrentMethod().Name, serviceClass, String.Join("_", turListKeys));
            if ((result = CacheHelper.GetCacheItem <List <TurService> >(hash)) != null)
            {
                return(result);
            }

            result = (from serv in dc.TurServices
                      where turListKeys.Contains(serv.TS_TRKEY) &&
                      serv.TS_SVKEY == (int)serviceClass
                      select serv)
                     .ToList();

            CacheHelper.AddCacheData(hash, result, TableName);
            return(result);
        }
Exemple #23
0
        /// <summary>
        /// Получает информацию по конкретному ключу цены (кэш не используется)
        /// </summary>
        /// <param name="mainDc">Контекст основной БД</param>
        /// <param name="searchDc">Конекст поисковой БД</param>
        /// <param name="priceKey">Ключ цены</param>
        /// <returns></returns>
        public static PriceInfo GetPriceInfo(this MtMainDbDataContext mainDc, MtSearchDbDataContext searchDc, int priceKey)
        {
            var result = mainDc.GetPriceInfoByTPKey(searchDc, priceKey);


            //var tpPrice = mainDc.GetTPPriceByKey(priceKey);
            //if (tpPrice != null)
            //{
            //    var countryCityKeys = mainDc.GetCountryCityKeysByTourKey(priceKey);

            //    var searchResult = searchDc.PagingOnClient(mainDc, countryCityKeys.Item2, countryCityKeys.Item1, priceKey);

            //    if (searchResult.SearchItems.Count > 0)
            //    {
            //        result = searchResult.SearchItems[0];
            //    }
            //}

            return(result);
        }
Exemple #24
0
        /// <summary>
        /// Возвращает ключи страны и города вылета по ключу цены
        /// </summary>
        /// <param name="mainDc">Контекст основной БД</param>
        /// <param name="priceKey">Ключ цены</param>
        /// <param name="useCache">Используется ли кэш или нет</param>
        /// <param name="hash">Хэш кэша</param>
        /// <returns></returns>
        public static Tuple <int, int> GetCountryCityKeysByTourKey(this MtMainDbDataContext mainDc, int priceKey, bool useCache, out string hash)
        {
            Tuple <int, int> result = null;

            hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, priceKey);
            if (useCache && (result = CacheHelper.GetCacheItem <Tuple <int, int> >(hash)) != null)
            {
                return(result);
            }

            var cacheDependencies = new List <string>();
            var commandBuilder    = new StringBuilder();

            commandBuilder.AppendLine("select TO_CNKey, ISNULL(TL_CTDepartureKey, 0) ");
            commandBuilder.AppendLine("from tp_tours ");
            commandBuilder.AppendLine("join tbl_TurList on TL_Key = TO_TRKey ");
            commandBuilder.AppendLine(
                String.Format("where exists (select 1 from tp_prices where tp_tokey = to_key and tp_key = {0}) ", priceKey));

            using (var command = mainDc.Connection.CreateCommand())
            {
                command.CommandText = commandBuilder.ToString();

                mainDc.Connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        result = new Tuple <int, int>(reader.GetInt32(0), reader.GetInt32(1));
                    }
                }
                mainDc.Connection.Close();
            }

            cacheDependencies.Add(TPToursExtension.TableName);
            cacheDependencies.Add(TurListsExtension.TableName);

            CacheHelper.AddCacheData(hash, result, cacheDependencies.ToList(), Globals.Settings.Cache.LongCacheTimeout);

            return(result);
        }
Exemple #25
0
        /// <summary>
        /// Возвращает категорию отеля по ключу
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="hotelCatKey"></param>
        /// <returns></returns>
        public static CategoriesOfHotel GetHotelCatByKey(this MtMainDbDataContext dc, int hotelCatKey)
        {
            CategoriesOfHotel result;

            var hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, hotelCatKey);

            if ((result = CacheHelper.GetCacheItem <CategoriesOfHotel>(hash)) != null)
            {
                return(result);
            }

            result = (from c in dc.GetAllHotelCats()
                      where c.COH_Id == hotelCatKey
                      select c)
                     .FirstOrDefault();

            CacheHelper.AddCacheData(hash, result, new List <string>()
            {
                TableName
            }, Globals.Settings.Cache.LongCacheTimeout);
            return(result);
        }
Exemple #26
0
        private bool InitFiltersByQs()
        {
            using (var mtmDc = new MtMainDbDataContext())
            {
                using (var mtsDc = new MtSearchDbDataContext())
                {
                    using (var sftDc = new SftWebDbDataContext())
                    {
                        foreach (KeyValuePair <Control, FilterDetails> filterDetail in _filterDetails)
                        {
                            filterDetail.Value.LoadDataAction(mtmDc, mtsDc, sftDc, false);
                            if (!filterDetail.Value.SelectValueByQsAction())
                            {
                                return(false);
                            }
                        }
                    }
                }
            }

            if (!SetAviaQuotesByQs())
            {
                return(false);
            }
            if (!SetRoomQuotesByQs())
            {
                return(false);
            }
            if (!SetMaxPriceByQs())
            {
                return(false);
            }
            if (!SetRowsNumberByQs())
            {
                return(false);
            }
            return(true);
        }
Exemple #27
0
        /// <summary>
        /// Возвращает список всех анкет из базы
        /// </summary>
        /// <param name="dc">Контекст БД</param>
        /// <returns></returns>
        public static IEnumerable <Questionnaire> GetAllQuestionnaires(this MtMainDbDataContext dc)
        {
            List <Questionnaire> result;

            if ((result = CacheHelper.GetCacheItem <List <Questionnaire> >(TableName)) != default(List <Questionnaire>))
            {
                return(result);
            }
            lock (LockQuestionnaires)
            {
                if ((result = CacheHelper.GetCacheItem <List <Questionnaire> >(TableName)) != default(List <Questionnaire>))
                {
                    return(result);
                }

                result = (from q in dc.Questionnaires
                          select q)
                         .ToList();

                CacheHelper.AddCacheData(TableName, result, TableName);
            }
            return(result);
        }
Exemple #28
0
        /// <summary>
        /// Описание по стране
        /// </summary>
        /// <param name="dc">Контекст базы данных</param>
        /// <param name="countryKey">Ключ страны</param>
        /// <returns></returns>
        public static string GetCountryDescription(this MtMainDbDataContext dc, int countryKey)
        {
            var hash = String.Format("{0}_{1}", MethodBase.GetCurrentMethod().Name, countryKey);

            if (CacheHelper.IsCacheKeyExists(hash))
            {
                return(CacheHelper.GetCacheItem <string>(hash));
            }

            var result = (from d in dc.GetAllDescriptions()
                          where d.DS_DTKey == CountryDescription &&
                          d.DS_PKKey == countryKey
                          select d.DS_Value)
                         .FirstOrDefault();

            result = result ?? String.Empty;

            CacheHelper.AddCacheData(hash, result, new List <string>()
            {
                TableName
            }, Globals.Settings.Cache.LongCacheTimeout);
            return(result);
        }
Exemple #29
0
        /// <summary>
        /// Возвращает список всех категорий отелей
        /// </summary>
        /// <param name="dc">Контекст базы данных</param>
        /// <returns></returns>
        public static List <CategoriesOfHotel> GetAllHotelCats(this MtMainDbDataContext dc)
        {
            List <CategoriesOfHotel> hotelCats;

            if ((hotelCats = CacheHelper.GetCacheItem <List <CategoriesOfHotel> >(TableName)) != null)
            {
                return(hotelCats);
            }
            lock (LockHotelCats)
            {
                if ((hotelCats = CacheHelper.GetCacheItem <List <CategoriesOfHotel> >(TableName)) != null)
                {
                    return(hotelCats);
                }

                hotelCats = (from c in dc.CategoriesOfHotels
                             select c)
                            .ToList <CategoriesOfHotel>();

                CacheHelper.AddCacheData(TableName, hotelCats, TableName);
            }
            return(hotelCats);
        }
Exemple #30
0
        /// <summary>
        /// Возвращает список пакетов для бронирования авиаперелетов
        /// </summary>
        /// <param name="dc">Контекст БД</param>
        /// <param name="hash">Хэш кэша</param>
        /// <returns></returns>
        public static List <int> GetCharterBookingPackets(this MtMainDbDataContext dc, out string hash)
        {
            List <int> result;

            hash = String.Format("{0}", MethodBase.GetCurrentMethod().Name);
            if ((result = CacheHelper.GetCacheItem <List <int> >(hash)) != null)
            {
                return(result);
            }

            result = (from d in dc.GetAllDescriptions()
                      where d.DS_DTKey == AllowCharterBooking &&
                      d.DS_Value.Contains("1") &&
                      d.DS_PKKey.HasValue
                      select d.DS_PKKey.Value)
                     .ToList();

            CacheHelper.AddCacheData(hash, result, new List <string>()
            {
                TableName
            }, Globals.Settings.Cache.LongCacheTimeout);
            return(result);
        }