示例#1
0
        public static IEnumerable<Shop> GetShopByRegionID(int RegionID)
        {
            List<Shop> shops;
            //List<Region> Regions;
            List<City> Cities;
            Shop[] Allshops = null;

            using (var Ctx = new dcCommonDataContext())
            {
                Cities = Ctx.Cities.Where(x => x.RegionID == RegionID).ToList();
            }

            using (var Ctx = new CmsDataContext())
            {
                shops = Ctx.Shops.Where(x => x.ShopVisible && x.RegionID == RegionID).OrderByDescending(X => X.isRMS).ThenBy(x => x.ShopPriority).ToList();
                Allshops = Ctx.Shops.ToArray();

                //Джойним с теми, которые были получены через города
                Allshops = (from sh in Allshops
                            join city in Cities on sh.CityID equals city.CityID
                            where sh.ShopVisible == true
                            select sh).ToArray();

                //Очень странно, но если вынести Это из using то получим ошибку Открыт доступ к DataContext после Dispose
                Allshops = Allshops.Union(shops).Distinct().OrderByDescending(X => X.isRMS).ThenBy(x => x.ShopPriority).ToArray();

                //TODO: Переделать формирование списка с регионами, так как еще добавяться магазины у которых город не null
                return Allshops;
            }
        }
示例#2
0
 public List<Tires> GetAllTires()
 {
     using (CmsDataContext cms = new CmsDataContext())
        {
        cms.Tires.Select(x => x);
        return null;
        }
 }
示例#3
0
 static void GetChildren( CmsDataContext dc, ref List<CatalogItem> res, int parentID )
 {
     foreach ( CatalogItem CI in _allItem.Where( t => t.ParentItemID == parentID ) )
     {
         res.Add( CI );
         GetChildren( dc, ref res, CI.CatalogItemID );
     }
 }
示例#4
0
        private const int numOfBrandColumns = 3; //Количество колонок выравнивания брендов

        #endregion Fields

        #region Methods

        protected void Page_Load(object sender, EventArgs e)
        {
            PriceWarningText.Visible = SiteContext.Current.CurrentClient.IsGuest;
            this.DiscSearchControl.MaxSearchCount = 100;
            this.QuantityWarningText.Text = "&mdash; результатов поиска слишком много, выведено " + DiscSearchControl.MaxSearchCount.ToString() + " товаров, пожалуйста уточните параметры поиска. ";
            this.PreRender += new System.EventHandler(this.BatterySearch_PreRender);
            List<DiscBrand> cmsBatteryBrandsList;
            using (CmsDataContext cms = new CmsDataContext())
            {
                cmsBatteryBrandsList = cms.DiscBrands.Where(x => x.IsVisible).ToList();
                companies.DataSource = cmsBatteryBrandsList;
                companies.DataTextField = "Name";
                companies.DataBind();
                companies.Items.Insert(0, "Все производители");
            }

            int RowCount = 0;
            if (cmsBatteryBrandsList.Count % numOfBrandColumns > 0)
                RowCount = cmsBatteryBrandsList.Count / numOfBrandColumns + 1;
            else
                RowCount = cmsBatteryBrandsList.Count / numOfBrandColumns;
            int curIndex = 0;
            for (int i = 0; i < RowCount; i++)
            {
                TableRow trLogo = new TableRow();
                BrandsTable.Rows.Add(trLogo);
                TableRow trText = new TableRow();
                BrandsTable.Rows.Add(trText);
                for (int j = 0; j < numOfBrandColumns; j++)
                {
                    if (curIndex == cmsBatteryBrandsList.Count) { break; }
                    TableCell tcLogo = new TableCell();
                    trLogo.Cells.Add(tcLogo);
                    Image im = new Image();
                    //im.ImageUrl = UrlManager.GetFileUrlRMS(cmsBatteryBrandsList[curIndex].ImageId.Value);
                    im.ImageUrl = UrlManager.GetFileUrl(cmsBatteryBrandsList[curIndex].ImageId.Value) + "?r=rms";
                    im.CssClass = "imgCat";
                    im.AlternateText = cmsBatteryBrandsList[curIndex].Name;

                    tcLogo.Controls.Add(im);

                    TableCell tcText = new TableCell();
                    trText.Cells.Add(tcText);
                    tcText.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
                    tcText.Style.Add(HtmlTextWriterStyle.MarginBottom, "10");
                    tcText.Style.Add(HtmlTextWriterStyle.VerticalAlign, "top");
                    tcText.Style.Add(HtmlTextWriterStyle.Height, "30px");

                    Label btn = new Label();
                    btn.Text = cmsBatteryBrandsList[curIndex].Name;
                    btn.CssClass = "imgCat";
                    tcText.Controls.Add(btn);
                    curIndex++;
                }

            }
        }
示例#5
0
partial         void OnValidate(ChangeAction action)
        {
            using (CmsDataContext dc = new CmsDataContext())
            {
                if (this.ManufaturerId == null)
                    this.ManufaturerId = dc.DiscBrands.SingleOrDefault(m => m.Name == this.Manufacturer).Id;
                if (this.ManufaturerId != null)
                    this.Manufacturer = dc.DiscBrands.SingleOrDefault(m => m.Id == this.ManufaturerId).Name;
            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     using (CmsDataContext dc = new CmsDataContext())
     {
         var vac = dc.Vacancies.Where(v => v.VacancyVisible && v.ShopID == ShopID).OrderBy(v => v.VacancyName);
         Count = vac.Count();
         _itemRepeater.DataSource = vac;
         _itemRepeater.DataBind();
     }
 }
        protected void Page_PreRender( object sender, EventArgs e )
        {
            using( CmsDataContext dc = new CmsDataContext() )
            {
                var vacancy = dc.Vacancies.Where( v => v.VacancyVisible && v.VacancyID == VacancyID ).SingleOrDefault();

                if( vacancy == null )
                    throw new HttpException( (int)HttpStatusCode.NotFound, "Not found" );

                _repeater.DataSource = new object[] { vacancy };
                _repeater.DataBind();
            }
        }
示例#8
0
partial         void OnValidate(ChangeAction action)
        {
            if (action == ChangeAction.Insert)
            {
                using (CmsDataContext dc = new CmsDataContext())
                {
                    if (dc.Brands.SingleOrDefault(
                        m => m.Name == Name && m.VehicleType == VehicleType ) != null )
                        throw new ValidationException("марка с названием '" +
                            Name +
                            "' уже существует");
                }
            }
        }
示例#9
0
partial         void OnValidate(ChangeAction action)
        {
            if (action == ChangeAction.Insert)
            {
                using (CmsDataContext dc = new CmsDataContext())
                {
                    if (dc.Manufacturers.SingleOrDefault(
                        m => m.Name == Name) != null)
                        throw new ValidationException("производитель с названием '" +
                            Name +
                            "' уже существует");
                }
            }
        }
示例#10
0
        public static IEnumerable<Shop> GetShopByCityID(int CityID)
        {
            List<Shop> shops;
            List<City> Cities;

            using (var Ctx = new RmsAuto.Store.Entities.dcCommonDataContext())
            {
                Cities = Ctx.Cities.Where(x => x.CityID == CityID).ToList();
            }

            using (var Ctx = new CmsDataContext())
            {
                shops = Ctx.Shops.Where(x => x.ShopVisible && x.CityID == CityID).OrderByDescending(X => X.isRMS).ThenBy(x => x.ShopPriority).ToList();
            }

            return shops;
        }
示例#11
0
partial         void OnValidate(ChangeAction action)
        {
            using (CmsDataContext dc = new CmsDataContext())
                {
                    try
                    {
                        if (this.ManufacturerId == null)
                            this.ManufacturerId = dc.TireBrands.SingleOrDefault(m => m.Name == this.Manufacturer).Id;
                        this.Manufacturer = dc.TireBrands.SingleOrDefault(m => m.Id == this.ManufacturerId).Name;
                    }
                    catch
                    { }
                    finally
                    {

                    }
                }
        }
示例#12
0
 protected void Page_PreRender( object sender, EventArgs e )
 {
     using( CmsDataContext dc = new CmsDataContext() )
     {
         if( VacancyID == null )
         {
             _listView.DataSource = dc.Vacancies
                 .Where( v => v.VacancyVisible )
                 .OrderBy( v => v.VacancyName );
         }
         else
         {
             _listView.DataSource = dc.Vacancies
                 .Where( v => v.VacancyVisible && v.VacancyID == VacancyID );
         }
         _listView.DataBind();
     }
 }
示例#13
0
 public static File GetFileRms(CmsDataContext cmsDataContext, int fileID)
 {
     spSelFilesFromRmsResult rmsFile = cmsDataContext.spSelFilesFromRms(fileID).SingleOrDefault();
     if (rmsFile == null) return null;
     File f = new File();
     f.ImageHeight = rmsFile.ImageHeight;
     f.ImageWidth = rmsFile.ImageWidth;
     f.FileBody = rmsFile.FileBody;
     f.FileCreationDate = rmsFile.FileCreationDate;
     f.FileID = rmsFile.FileID;
     f.FileMimeType = rmsFile.FileMimeType;
     f.FileModificationDate = rmsFile.FileModificationDate;
     f.FileName = rmsFile.FileName;
     f.FileNote = rmsFile.FileNote;
     f.FileSize = rmsFile.FileSize;
     f.FolderID = rmsFile.FolderID;
     f.IsImage = rmsFile.IsImage;
     f.Timestamp = rmsFile.Timestamp;
     return f;
 }
示例#14
0
        public void ProcessRequest( HttpContext context )
        {
            using( var dc = new CmsDataContext() )
            {
                try
                {
                    int fileID = Convert.ToInt32(CmsContext.Current.PageParameters["ID"]);
                    File file = dc.Files.SingleOrDefault(f => f.FileID == fileID);

                    if (file == null)
                    {
                        throw new HttpException((int)HttpStatusCode.NotFound, "Not Found");
                    }

                    string etag = file.Timestamp.ToString();

                    context.Response.ContentType = file.FileMimeType;
                    context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
                    context.Response.Cache.SetETag(etag);

                    if (!file.IsImage)
                    {
                        context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + EncodeFileName(file.FileName) + "\"");
                    }

                    if (context.Request.Headers["If-None-Match"] != etag)
                    {
                        context.Response.BinaryWrite(file.FileBody.ToArray());
                    }
                    else
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.NotModified;
                    }
                }

                finally
                {
                    if (dc.Connection.State == System.Data.ConnectionState.Open) { dc.Connection.Close(); }
                }
            }
        }
示例#15
0
        public BrandsCollection()
        {
            RmsAuto.Store.Cms.Entities.Brand[] brands;
            int[] visibleCountryIds;
            using( var dc = new CmsDataContext() )
            {
                brands = dc.Brands.ToArray();
            }
            using( var dc = new RmsAuto.TechDoc.Entities.TecdocStoreDataContext() )
            {
                visibleCountryIds = dc.CountryVisibilities.Select( c => c.CountryID ).ToArray();
            }

            _visibleCountryIds = visibleCountryIds;

            var manufacturers = RmsAuto.TechDoc.Facade.ListManufacturers( true, visibleCountryIds ).ToDictionary( m => m.Name, StringComparer.CurrentCultureIgnoreCase );

            var list = new List<BrandItem>();
            var manList = new List<RmsAuto.TechDoc.Entities.TecdocBase.Manufacturer>();
            foreach( var brand in brands )
            {
                RmsAuto.TechDoc.Entities.TecdocBase.Manufacturer manufacturer;
                manufacturers.TryGetValue( brand.Name, out manufacturer );
                if( manufacturer != null && ( manufacturer.IsCarManufacturer == 1 && brand.VehicleType == RmsAuto.Store.Cms.Entities.VehicleType.Car
                        || manufacturer.IsTruckManufacturer == 1 && brand.VehicleType == RmsAuto.Store.Cms.Entities.VehicleType.Truck ) )
                {
                    var item = new BrandItem( brand, manufacturer );
                    list.Add( item );
                    _brandUrlCodeHash.Add( new KeyValuePair<string, VehicleType>( item.Brand.UrlCode.ToLower(), item.Brand.VehicleType ), item );
                    _brandManufacturerIdHash.Add( new KeyValuePair<int, VehicleType>( item.Manufacturer.ID, item.Brand.VehicleType ), item );

                    if( !_manufacturerNameHash.ContainsKey( manufacturer.Brand.Name ) )
                    {
                        _manufacturerNameHash.Add( manufacturer.Brand.Name, manufacturer );
                        manList.Add( manufacturer );
                    }
                }
            }
            _brands = list.OrderBy( i => i.Brand.Name ).ToArray();
            _manufactures = manList.OrderBy( i => i.Name ).ToArray();
        }
示例#16
0
        public void ProcessRequest(HttpContext context)
        {
            if (SiteContext.Current.InternalFranchName == ConfigurationManager.AppSettings["InternalFranchName"])
                {
                    using (var cms = new CmsDataContext())
                    {
                        var Cats = (from x in cms.OurCatalogs.Where(x => x.Visible == true).OrderBy(x => x.Priority)
                                select new CatalogJson() { ID = x.Id, Name = x.Name, Description = x.Description, ImageUrl = x.ImageUrl, @ref = x.@ref,  }).ToList();
                        context.Response.ContentType = "application/json";
                        context.Response.Write(this.JsonSerializer(Cats));
                    }
                }
                else
                {
                    using (var cms = new DCFactory<CmsDataContext>())
                    {
                        var Cats = (from x in cms.DataContext.spSelCatalogsFromRms().Where(x => x.Visible == true).OrderBy(x => x.Priority)
                                    select new CatalogJson() { ID = x.Id, Name = x.Name, Description = x.Description, ImageUrl = x.ImageUrl, @ref = x.@ref, }).ToList();
                        context.Response.ContentType = "application/json";
                        context.Response.Write(this.JsonSerializer(Cats));
                    }

                }
        }
示例#17
0
 public static int GetMaxID(CmsDataContext dc)
 {
     var el =
            from o in dc.Banners
            select (o.BannerID);
     try
     {
         return (int)el.Max();
     }
     catch
     {
         return 0;
     }
 }
示例#18
0
        public void DoSearch(string Company, string Width, string Diameter, string Gab)
        {
            List<Disc> mQuery = null;

            using (CmsDataContext cms = new CmsDataContext())
            {
                try
                {
                    //Алгоритм фильтрации 1) сначала выбираем все

                    //IEnumerable<Disc> query = query = cms.Discs.Select(x => x);
                    IEnumerable<Disc> query = cms.Discs.ToArray();

                    // 2)Выбираем только те, которые соответствуют названию производителя
                    /*if (!String.IsNullOrEmpty(Company) && !Company.ToLower().Contains("все"))
                        //Проверяем нличие брэнда в метаданных и списке брендов он должен быть настроен видимым
                        query = query.Where(x => x.Manufacturer != null && x.Manufacturer.ToUpper().Contains(Company.ToUpper()) && cms.DiscBrands.Where(y => y.IsVisible).Select(y => y.Name.ToUpper()).Contains(Company.ToUpper()));
                    else
                        query = query.Where(x => x.Manufacturer != null && cms.DiscBrands.Where(y => y.IsVisible).Select(y => y.Name.ToUpper()).Contains(x.Manufacturer.ToUpper()));
                    */
                    if (!String.IsNullOrEmpty(Company) && !Company.ToLower().Contains("все"))
                        query = query.Where(x => x.Manufacturer.ToUpper() == Company.ToUpper());

                    // 3)Выбираем только те, которые соответствуют заданной высоте
                    if (!String.IsNullOrEmpty(Width) && !Width.ToLower().Contains("все"))
                        query = query.Where(x => x.Width == Convert.ToDecimal(Width.Replace('.', ',')));

                    // 4) и т.д.
                    if (!String.IsNullOrEmpty(Diameter) && !Diameter.ToLower().Contains("все"))
                        query = query.Where(x => x.Diameter != null && x.Diameter == Convert.ToDecimal(Diameter));

                    if (!String.IsNullOrEmpty(Gab) && !Gab.ToLower().Contains("все"))
                    {
                        Gab = Gab.Replace(" ", "");
                        if (Gab.StartsWith("<")) query = query.Where(x => x.Gab <= Convert.ToDecimal(Gab.Split('<')[1]));
                        else if (Gab.StartsWith(">")) query = query.Where(x => x.Gab >= Convert.ToDecimal(Gab.Split('>')[1]));
                        else query = query.Where(x => x.Gab >= Convert.ToDecimal(Gab.Split('-')[0]) && x.Gab <= Convert.ToDecimal(Gab.Split('-')[1]));
                    }

                    //Конец фильтрации

                    mQuery = query.ToList();
                }
                catch
                { }
                finally
                {
                   if (cms.Connection.State == System.Data.ConnectionState.Open)
                        cms.Connection.Close();
                }
            }

            using (var store = new StoreDataContext())
            {
                try
                {
                    List<Disc> BatteryPriceSearchResult = new List<Disc>();
                    ExceedMaxresult = false;

                    foreach (Disc item in mQuery)
                    {
                        List<SearchResultItem> list;
                        if (Cache.Get(item.Manufacturer + item.PartNumber) == null)
                        {
                            PartKey searchPartKey = new PartKey(item.Manufacturer, item.PartNumber);

                            SparePartItem[] parts = new SparePartItem[0];

                            if (item.Manufacturer != null)
                            {
                                //TODO: Рассмотреть применение последнего параметра -- поиска аналогов
                                parts = PricingSearch.SearchSpareParts(item.PartNumber, item.Manufacturer.ToUpper(), false);
                            }

                            //пересчитать цены, подгрузить дополнительную информацию о деталях
                            RmsAuto.Acctg.ClientGroup clientGroup = SiteContext.Current.CurrentClient.Profile.ClientGroup;
                            decimal personalMarkup = SiteContext.Current.CurrentClient.Profile.PersonalMarkup;
                            var additionalInfos = RmsAuto.TechDoc.Facade.GetAdditionalInfo(new[] { searchPartKey }.Union(parts.Select(p => new PartKey(p.SparePart.Manufacturer, p.SparePart.PartNumber))));
                            // dan 01.06.2011 task4253 Механизм отображения фотографий брака в результатах поиска.
                            var additionalInfosExt = RmsAuto.Store.Entities.Helpers.SearchHelper.GetAdditionalInfoExt( parts.Select(p => new SparePartKeyExt(p.SparePart.Manufacturer, p.SparePart.PartNumber, p.SparePart.SupplierID)));

                            //курс валюты
                            CurrencyRate currencyRate = GetCurrentCurrencyRate();

                            list = parts.Select(
                                p => new RmsAuto.Store.Web.Controls.SearchResultItem
                                {
                                    ItemType = p.ItemType,
                                    SparePart = p.SparePart,
                                    AdditionalInfo = additionalInfos.ContainsKey(new PartKey(p.SparePart.Manufacturer, p.SparePart.PartNumber)) ? additionalInfos[new PartKey(p.SparePart.Manufacturer, p.SparePart.PartNumber)] : null,
                                    // dan 01.06.2011 task4253 Механизм отображения фотографий брака в результатах поиска.
                                    AdditionalInfoExt = additionalInfosExt.ContainsKey(new SparePartKeyExt(p.SparePart.Manufacturer, p.SparePart.PartNumber, p.SparePart.SupplierID)) ?
                                        additionalInfosExt[new SparePartKeyExt(p.SparePart.Manufacturer, p.SparePart.PartNumber, p.SparePart.SupplierID)] : null,
                                    FinalSalePriceRUR = p.SparePart.GetFinalSalePrice(clientGroup, personalMarkup),
                                    FinalSalePrice = p.SparePart.GetFinalSalePrice(clientGroup, personalMarkup) / currencyRate.Rate,

                                    ShowPrices = true,
                                    ShowInfo = true
                                }).Where(p => p.FinalSalePriceRUR > 0).ToList(); //dan 19.09.2011 добавил условие чтобы убрать позиции с нулевой ценой из результатов поиска

                            Cache.Insert(item.Manufacturer + item.PartNumber, list, null, DateTime.UtcNow.AddMinutes(Convert.ToInt32(ConfigurationManager.AppSettings["CacheDuration"])), TimeSpan.Zero);
                        }
                        else
                        {
                            list = (List<SearchResultItem>)Cache.Get(item.Manufacturer + item.PartNumber);
                        }

                        if (BatteryPriceSearchResult.Count < MaxSearchCount)
                        {
                            foreach (var item2 in list)
                            {
                                Disc tmp = new Disc()
                                {
                                    Dia = item.Dia,
                                    PCD = item.PCD,
                                    Gab = item.Gab,
                                    Manufacturer = item.Manufacturer,
                                    ModelName = item.ModelName,
                                    Diameter = item.Diameter,
                                    Width = item.Width,
                                    PartNumber = item.PartNumber,
                                    ImageUrl = item.ImageUrl,
                                    Price = item2.FinalSalePriceRUR,
                                    SparePart = item2.SparePart,
                                    Ref = String.Format(@"/SearchSpareParts.aspx?mfr={0}&pn={1}&st=1", item.Manufacturer.ToUpper(), item.PartNumber)
                                };

                                BatteryPriceSearchResult.Add(tmp);

                                break; //Ищем только одно предложение
                                //TODO и зачем тут этот недостижимый участок кода???
                                if (BatteryPriceSearchResult.Count >= MaxSearchCount)
                                {
                                    ExceedMaxresult = true;
                                    break;
                                }
                            }

                        }
                        else
                        {
                            ExceedMaxresult = true;
                            break;
                        }
                    }

                    //отсортировать результаты поиска
                    CurrentSearchCount = BatteryPriceSearchResult.Count;
                    PagedDataSource = new PagedDataSource();
                    PagedDataSource.DataSource = BatteryPriceSearchResult.OrderBy(x => x.Price).ToList();
                    PagedDataSource.AllowPaging = true;

                    int count = 0;
                    if (!String.IsNullOrEmpty(Request.Params["PageSize"]) && int.TryParse(Request.Params["PageSize"], out count))
                    {
                        PagedDataSource.PageSize = Convert.ToInt32(Request.Params["PageSize"]);
                    }

                    if (PagedDataSource.PageSize == 0)
                    {
                        PagedDataSource.PageSize = 10;
                    }

                    TirePagerControl.Visible = BatteryPriceSearchResult.Count / PagedDataSource.PageSize + 1 > 1;

                    //Установка значения пейджера
                    if (BatteryPriceSearchResult.Count % PagedDataSource.PageSize > 0)
                        TirePagerControl.MaxIndex = BatteryPriceSearchResult.Count / PagedDataSource.PageSize + 1;
                    else
                        TirePagerControl.MaxIndex = BatteryPriceSearchResult.Count / PagedDataSource.PageSize + 0;

                    if (TirePagerControl.CurrentIndex > 0)
                    {
                        PagedDataSource.CurrentPageIndex = TirePagerControl.CurrentIndex - 1;
                        rptSearchResults.DataSource = PagedDataSource;
                        rptSearchResults.DataBind();
                    }

                    if (BatteryPriceSearchResult.Count > 0)
                        rptSearchResults.Visible = true;
                    else
                    {
                        var labelResult = new Label();
                        labelResult.Style.Add(HtmlTextWriterStyle.FontWeight, "Bold");
                        labelResult.Style.Add(HtmlTextWriterStyle.Color, "Green");
                        labelResult.Text = "Ничего не найдено, попробуйте изменить параметры поиска.";
                        _resultsPlaceHolder.Controls.Add(labelResult);
                        rptSearchResults.Visible = false;
                    }
                }

                catch (Exception ex)
                {
                    Logger.WriteError(ex.Message, EventLogerID.BLException, EventLogerCategory.BLError);
                }

                finally
                {
                    if (store.Connection.State == System.Data.ConnectionState.Open) { store.Connection.Close(); }
                }
            }
        }
示例#19
0
 public static int GetMaxID()
 {
     var dc = new CmsDataContext();
     return GetMaxID(dc);
 }
示例#20
0
 public static int GetRenderTypeByBannerID(int bannerID)
 {
     var dc = new CmsDataContext();
     return GetRenderTypeByBannerID(dc, bannerID);
 }
示例#21
0
        private void LoadDiscsFromReader(SpreadsheetReader reader, LoadResult result)
        {
            //проверка наличия в файле единственного листа с заказом
            reader.CurrentSheet = 0;
            int numOfFields = 9;

            List<RmsAuto.Store.Cms.Entities.Disc> t = new List<RmsAuto.Store.Cms.Entities.Disc>();
            for (int r = 1; r < reader.RecordCount; r++)
            {
                string[] rec = new string[numOfFields];
                for (int i = 0; i < numOfFields; i++)
                    rec[i] = reader[r, i];

                rec = rec.Each(s => s.Trim()).ToArray();

                if (rec.All(s => s == ""))
                    continue;

                if (rec.All(s => string.IsNullOrEmpty(s)))
                {
                    break;
                }

                var t1 = new RmsAuto.Store.Cms.Entities.Disc();

                for (int c = 0; c < numOfFields; c++)
                {
                    string value = rec[c];
                    try
                    {
                        switch (c)
                        {
                            case 0: t1.Manufacturer = value; break;
                            case 1: t1.ModelName = value; break;
                            case 2: t1.PartNumber = value; break;
                            case 3: t1.Width = Decimal.Parse(value); break;
                            case 4: t1.Diameter = Decimal.Parse(value); break;
                            case 5: t1.Gab = Decimal.Parse(value); break;
                            case 6: t1.PCD = value; break;
                            case 7: t1.Dia = Decimal.Parse(value); break;
                        }
                    }
                    catch
                    {
                        //TODO допилить обработку ошибок
                    }
                }
                t.Add(t1);
            }

            using (CmsDataContext cms = new CmsDataContext())
            {
                try
                {
                    cms.Connection.Open();
                    cms.Transaction = cms.Connection.BeginTransaction();
                    var current = cms.Discs.Select(x => x).ToList();
                    current.Sort(new DiscComparer());
                    t.Sort(new DiscComparer());

                    t = t.Select(x => x).Distinct(new DiscComparer()).ToList();

                    //Пробегаем по каждому объекту каталога и смотрим какая у него была картинка
                    foreach (var RefObj in t)
                    {
                        var tmp = current.Where(x => x.PartNumber == RefObj.PartNumber).FirstOrDefault();
                        RefObj.ImageUrl = tmp != null && tmp.ImageUrl.HasValue ? tmp.ImageUrl : (int)NoPhotoID.Disc;
                    }

                    // "мерджим" старое и новое
                    t = t.UnionAndDistinct<RmsAuto.Store.Cms.Entities.Disc>(current, new DiscComparer());

                    cms.Discs.DeleteAllOnSubmit(current);
                    cms.Discs.InsertAllOnSubmit(t);
                    cms.SubmitChanges(ConflictMode.ContinueOnConflict);
                    cms.Transaction.Commit();
                    Response.Redirect(Request.Url.ToString());
                }
                catch (ChangeConflictException)
                {
                    //TODO допилить обработку ошибок
                    //Если не удалось изменить какую-то одну запись это не значит что нужно делать откат всего
                }
                catch (Exception)
                {
                    cms.Transaction.Rollback();
                    //ShowMessage("Указано неиспользуемое имя бренда");
                    Logger.WriteError("Ошибка при сохранении результатов загрузки дисков", EventLogerID.BLException, EventLogerCategory.BLError);
                }
                finally
                {
                    if (cms.Connection.State == System.Data.ConnectionState.Open) { cms.Connection.Close(); }
                }
            }
        }
示例#22
0
        public static Boolean IsVisibleByBannerID(CmsDataContext dc, int bannerID, int catalogItemID, byte position)
        {
            var el =
                   from o in dc.BannersForCatalogItems
                   where o.BannerID == bannerID && o.CatalogItemID == catalogItemID && o.Position == position
                   select o.IsVisible;

            try
            {
                return (Boolean)el.First();
            }
            catch
            {
                return false;
            }
        }
示例#23
0
        public static Boolean IsBanded(CmsDataContext dc, int bannerID, int catalogItemID, byte position)
        {
            var el =
                   from o in dc.BannersForCatalogItems
                   where o.BannerID == bannerID && o.CatalogItemID == catalogItemID && o.Position == position
                   select o;

            try
            {
                if (el.First() != null)
                    return true;
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }
示例#24
0
        public static BannersForCatalogItem GetRecordRandomBanner(int catalogItemID, byte position)
        {
            using (var dc = new CmsDataContext())
            {
                try
                {
                    List<BannersForCatalogItem> wBanners = new List<BannersForCatalogItem>();
                    //var workingBannersExpression = PredicateBuilder.False<BannersForCatalogItem>();
                    foreach (var bannersForCatalogItem in dc.BannersForCatalogItems)
                    {
                        if ((bannersForCatalogItem.Banners.RenderType == (byte)RenderType.ImageHtml
                            && bannersForCatalogItem.Banners.FileID != null && bannersForCatalogItem.CatalogItemID == catalogItemID
                            && bannersForCatalogItem.Position == position && bannersForCatalogItem.IsVisible)
                            ||
                            (bannersForCatalogItem.Banners.RenderType == (byte)RenderType.Html
                            && bannersForCatalogItem.Banners.Html != null && bannersForCatalogItem.CatalogItemID == catalogItemID
                            && bannersForCatalogItem.Position == position && bannersForCatalogItem.IsVisible)
                            ||
                            (bannersForCatalogItem.Banners.RenderType == (byte)RenderType.FileHtml
                            && bannersForCatalogItem.Banners.FileID != null && bannersForCatalogItem.Banners.Html != null
                            && bannersForCatalogItem.CatalogItemID == catalogItemID
                            && bannersForCatalogItem.Position == position && bannersForCatalogItem.IsVisible)
                            )
                            //workingBannersExpression = workingBannersExpression.Or(l => l.IsVisible == true);
                            wBanners.Add(bannersForCatalogItem);
                    }

                    Random r = new Random();

                    return wBanners.OrderBy(x => r.Next()).First();
                    //var lines = dc.BannersForCatalogItems.Where(workingBannersExpression);
                    //var el = from o in dc.BannersForCatalogItems
                    //         where o.IsVisible
                    //         orderby dc.Random()
                    //         select o;
                    //return el.First();
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }
示例#25
0
 public static BannersForCatalogItem GetRecord(CmsDataContext dc, int catalogItemID, byte position)
 {
     var el =
            from o in dc.BannersForCatalogItems
            where o.CatalogItemID == catalogItemID && o.Position == position
            select o;
     try
     {
         return el.First();
     }
     catch
     {
         return null;
     }
 }
示例#26
0
        public static void RemoveLinkFromCatalogItem(int bannerID, int catalogItemID, byte position)
        {
            using (var dc = new CmsDataContext())
            {
                try
                {
                    if (BannersForCatalogItem.Locked == false)
                    {
                        BannersForCatalogItem.Locked = true;
                        Cms.Entities.BannersForCatalogItem b = Cms.Entities.BannersForCatalogItem.GetRecord(dc, bannerID, catalogItemID, position);
                        if (b != null)
                        {
                            dc.BannersForCatalogItems.DeleteOnSubmit(b);
                            dc.SubmitChanges();
                        }
                        BannersForCatalogItem.Locked = false;
                    }
                }

                catch (Exception)
                {
                    // Записать не получилось, освободим
                    BannersForCatalogItem.Locked = false;
                }
            }
        }
示例#27
0
 public static Boolean IsVisibleByBannerID(int bannerID, int catalogItemID, byte position)
 {
     using (var dc = new CmsDataContext())
     {
         return IsVisibleByBannerID(dc, bannerID, catalogItemID, position);
     }
 }
示例#28
0
 public CatalogItemLink FullDeepCopy(CmsDataContext dc, int bannerID, CatalogItem item, byte position)
 {
     var tmp = new CatalogItemLink();
     tmp.DeepPropertiesCopy(item);
     tmp.Position = position;
     tmp.Visible = IsVisibleByBannerID(dc, bannerID, tmp.CatalogItemID, position);
     tmp.Banded = IsBanded(dc, bannerID, tmp.CatalogItemID, position);
     return tmp;
 }
示例#29
0
 public static BannersForCatalogItem GetRecord(int catalogItemID, byte position)
 {
     using (var dc = new CmsDataContext())
     {
         return GetRecord(dc, catalogItemID, position);
     }
 }
示例#30
0
 public static int GetRenderTypeByBannerID(CmsDataContext dc, int bannerID)
 {
     var el =
            from o in dc.Banners
            where o.BannerID == bannerID
            select o.RenderType;
     try
     {
         return (int)el.First();
     }
     catch
     {
         return 0;
     }
 }