public static List<Picture> GetListOfPictures(PictureModel model) { var pList = new List<Picture>(); foreach (var file in model.Files) { var pic = Path.GetFileName($"{(file.FileName + DateTime.Now.Ticks).GetHashCode()}.jpg"); var pth = $"/Content/images/{pic}"; var path = HttpContext.Current.Server.MapPath($"{pth.Insert(0, "~")}"); var tmbpath = HttpContext.Current.Server.MapPath($"{pth.Insert(pth.Length - pic.Length, "tmb/").Insert(0, "~")}"); // file is uploaded file.SaveAs(path); ToTmb(path, tmbpath); //Upload info to DB pList.Add(new Picture { Path = pth, TmbPath = pth.Insert(pth.Length - pic.Length, "tmb/"), Name = model.Name, Description = model.Description, Tag = model.Tag, Price = model.Price, AlbumId = model.AlbumId }); } return pList; }
public ActionResult Upload(PictureModel model) { if (ModelState.IsValid) { _repository.SaveImagesToDb(ImagesHelper.GetListOfPictures(model)); return RedirectToAction("Upload"); } ViewBag.alb = new List<Album>(); return View(_repository); }
public static IEnumerable <PostOverviewModel> PreparePostOverviewModels(this Controller controller, IWorkContext workContext, ICategoryService categoryService, IPostService postService, IPermissionService permissionService, ILocalizationService localizationService, IPictureService pictureService, IWebHelper webHelper, ICacheManager cacheManager, IDateTimeHelper _dateTimeHelper, CatalogSettings catalogSettings, MediaSettings mediaSettings, IEnumerable <Post> posts, bool preparePictureModel = true, int?postThumbPictureSize = null ) { if (posts == null) { throw new ArgumentNullException("posts"); } var models = new List <PostOverviewModel>(); foreach (var post in posts) { var model = new PostOverviewModel { Id = post.Id, Name = post.GetLocalized(x => x.Name), ShortDescription = post.GetLocalized(x => x.ShortDescription), FullDescription = post.GetLocalized(x => x.FullDescription), SeName = post.GetSeName(), ViewCount = post.ViewCount, ShareCount = post.ShareCount, CommentCount = post.CommentCount, PostTemplateId = post.PostTemplateId, CreatedOn = _dateTimeHelper.ConvertToUserTime(post.CreatedOnUtc), Publish = post.Published }; //picture if (preparePictureModel) { #region Prepare post picture //If a size has been set in the view, we use it in priority var pictureSize = postThumbPictureSize.HasValue ? postThumbPictureSize.Value : mediaSettings.PostThumbPictureSize; //prepare picture model var defaultPostPictureCacheKey = string.Format(ModelCacheEventConsumer.PRODUCT_DEFAULTPICTURE_MODEL_KEY, post.Id, pictureSize, true, workContext.WorkingLanguage.Id, webHelper.IsCurrentConnectionSecured()); model.DefaultPictureModel = cacheManager.Get(defaultPostPictureCacheKey, () => { var picture = pictureService.GetPicturesByPostId(post.Id, 1).FirstOrDefault(); var pictureModel = new PictureModel { ImageUrl = pictureService.GetPictureUrl(picture, pictureSize), FullSizeImageUrl = pictureService.GetPictureUrl(picture) }; //"title" attribute pictureModel.Title = (picture != null && !string.IsNullOrEmpty(picture.TitleAttribute)) ? picture.TitleAttribute : string.Format(localizationService.GetResource("Media.Post.ImageLinkTitleFormat"), model.Name); //"alt" attribute pictureModel.AlternateText = (picture != null && !string.IsNullOrEmpty(picture.AltAttribute)) ? picture.AltAttribute : string.Format(localizationService.GetResource("Media.Post.ImageAlternateTextFormat"), model.Name); return(pictureModel); }); #endregion } models.Add(model); } return(models); }
public async Task <VendorModel> Handle(GetVendor request, CancellationToken cancellationToken) { var model = new VendorModel { Id = request.Vendor.Id, Name = request.Vendor.GetLocalized(x => x.Name, request.Language.Id), Description = request.Vendor.GetLocalized(x => x.Description, request.Language.Id), MetaKeywords = request.Vendor.GetLocalized(x => x.MetaKeywords, request.Language.Id), MetaDescription = request.Vendor.GetLocalized(x => x.MetaDescription, request.Language.Id), MetaTitle = request.Vendor.GetLocalized(x => x.MetaTitle, request.Language.Id), SeName = request.Vendor.GetSeName(request.Language.Id), AllowCustomersToContactVendors = _vendorSettings.AllowCustomersToContactVendors, GenericAttributes = request.Vendor.GenericAttributes }; model.Address = await _mediator.Send(new GetVendorAddress() { Language = request.Language, Address = request.Vendor.Address, ExcludeProperties = false, }); //prepare picture model var pictureModel = new PictureModel { Id = request.Vendor.PictureId, FullSizeImageUrl = await _pictureService.GetPictureUrl(request.Vendor.PictureId), ImageUrl = await _pictureService.GetPictureUrl(request.Vendor.PictureId, _mediaSettings.VendorThumbPictureSize), Title = string.Format(_localizationService.GetResource("Media.Vendor.ImageLinkTitleFormat"), model.Name), AlternateText = string.Format(_localizationService.GetResource("Media.Vendor.ImageAlternateTextFormat"), model.Name) }; model.PictureModel = pictureModel; //view/sorting/page size var options = await _mediator.Send(new GetViewSortSizeOptions() { Command = request.Command, PagingFilteringModel = request.Command, Language = request.Language, AllowCustomersToSelectPageSize = request.Vendor.AllowCustomersToSelectPageSize, PageSize = request.Vendor.PageSize, PageSizeOptions = request.Vendor.PageSizeOptions }); model.PagingFilteringContext = options.command; IList <string> alreadyFilteredSpecOptionIds = await model.PagingFilteringContext.SpecificationFilter.GetAlreadyFilteredSpecOptionIds (_httpContextAccessor, _specificationAttributeService); //products var products = (await _mediator.Send(new GetSearchProductsQuery() { LoadFilterableSpecificationAttributeOptionIds = !_catalogSettings.IgnoreFilterableSpecAttributeOption, Customer = request.Customer, VendorId = request.Vendor.Id, StoreId = request.Store.Id, FilteredSpecs = alreadyFilteredSpecOptionIds, VisibleIndividuallyOnly = true, OrderBy = (ProductSortingEnum)request.Command.OrderBy, PageIndex = request.Command.PageNumber - 1, PageSize = request.Command.PageSize })); model.Products = (await _mediator.Send(new GetProductOverview() { Products = products.products, PrepareSpecificationAttributes = _catalogSettings.ShowSpecAttributeOnCatalogPages })).ToList(); model.PagingFilteringContext.LoadPagedList(products.products); //specs await model.PagingFilteringContext.SpecificationFilter.PrepareSpecsFilters(alreadyFilteredSpecOptionIds, products.filterableSpecificationAttributeOptionIds, _specificationAttributeService, _webHelper, _cacheBase, request.Language.Id); return(model); }
public ActionResult Pictures(int PictureGaleryId) { var PictureGalery = _PictureGaleryService.Find(PictureGaleryId); var model = new PictureModel(); model.PictureGalery = PictureGalery; model.Order = 0; return View(model); }
public ProductViewModel() { PictureModel = new PictureModel(); }
public ShoppingCartItemModel() { Picture = new PictureModel(); AllowedQuantities = new List <SelectListItem>(); Warnings = new List <string>(); }
public CategoryModel() { PictureModel = new PictureModel(); SubCategories = new List <CategorySummaryModel>(); }
public OrderItemModel() { Picture = new PictureModel(); }
internal void DeletePicture(PictureModel pictureModel) { DataAccess.Delete(new PictureModel().DataProvider, "pictures", new KeyValuePair <string, string>("Id", pictureModel.Id.ToString())); }
private void AddPicture(PictureModel picture) { picture.PictureNameChangedByUser += this.PictureNameChangedByUserEvent; this.picturesReadyForRename.Add(picture); }
public virtual void PrepareNewsItemModel(NewsItemModel model, NewsItem newsItem, bool prepareComments) { if (newsItem == null) { throw new ArgumentNullException("newsItem"); } if (model == null) { throw new ArgumentNullException("model"); } model.Id = newsItem.Id; model.MetaTitle = newsItem.GetLocalized(x => x.MetaTitle); model.MetaDescription = newsItem.GetLocalized(x => x.MetaDescription); model.MetaKeywords = newsItem.GetLocalized(x => x.MetaKeywords); model.SeName = newsItem.GetSeName(); model.Title = newsItem.GetLocalized(x => x.Title); model.Short = newsItem.GetLocalized(x => x.Short); model.Full = newsItem.GetLocalized(x => x.Full); model.AllowComments = newsItem.AllowComments; model.CreatedOn = _dateTimeHelper.ConvertToUserTime(newsItem.StartDateUtc ?? newsItem.CreatedOnUtc, DateTimeKind.Utc); model.NumberOfComments = newsItem.CommentCount; model.AddNewComment.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnNewsCommentPage; if (prepareComments) { var newsComments = newsItem.NewsComments.OrderBy(pr => pr.CreatedOnUtc); foreach (var nc in newsComments) { var customer = EngineContext.Current.Resolve <ICustomerService>().GetCustomerById(nc.CustomerId); var commentModel = new NewsCommentModel { Id = nc.Id, CustomerId = nc.CustomerId, CustomerName = customer.FormatUserName(), CommentTitle = nc.CommentTitle, CommentText = nc.CommentText, CreatedOn = _dateTimeHelper.ConvertToUserTime(nc.CreatedOnUtc, DateTimeKind.Utc), AllowViewingProfiles = _customerSettings.AllowViewingProfiles && customer != null && !customer.IsGuest(), }; if (_customerSettings.AllowCustomersToUploadAvatars) { commentModel.CustomerAvatarUrl = _pictureService.GetPictureUrl( customer.GetAttribute <string>(SystemCustomerAttributeNames.AvatarPictureId), _mediaSettings.AvatarPictureSize, _customerSettings.DefaultAvatarEnabled, defaultPictureType: PictureType.Avatar); } model.Comments.Add(commentModel); } } //prepare picture model if (!string.IsNullOrEmpty(newsItem.PictureId)) { int pictureSize = prepareComments ? _mediaSettings.NewsThumbPictureSize : _mediaSettings.NewsListThumbPictureSize; var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.NEWS_PICTURE_MODEL_KEY, newsItem.Id, pictureSize, true, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured(), _storeContext.CurrentStore.Id); model.PictureModel = _cacheManager.Get(categoryPictureCacheKey, () => { var picture = _pictureService.GetPictureById(newsItem.PictureId); var pictureModel = new PictureModel { FullSizeImageUrl = _pictureService.GetPictureUrl(picture), ImageUrl = _pictureService.GetPictureUrl(picture, pictureSize), Title = string.Format(_localizationService.GetResource("Media.News.ImageLinkTitleFormat"), newsItem.Title), AlternateText = string.Format(_localizationService.GetResource("Media.News.ImageAlternateTextFormat"), newsItem.Title) }; return(pictureModel); }); } }
public ShoppingCartItemModel() { Picture = new PictureModel(); }
public void save(PictureModel p) { throw new NotImplementedException(); }
public ShoppingCartItemModel() { Picture = new PictureModel(); Warnings = new List <string>(); }
public ManufacturerModel() { PictureModel = new PictureModel(); }
public BrandModel() { PictureModel = new PictureModel(); Products = new List <ProductOverviewModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); }
public static IEnumerable <ProductOverviewModel> PrepareProductOverviewModels(this Controller controller, IWorkContext workContext, IStoreContext storeContext, ICategoryService categoryService, IProductService productService, ISpecificationAttributeService specificationAttributeService, IPriceCalculationService priceCalculationService, IPriceFormatter priceFormatter, IPermissionService permissionService, ILocalizationService localizationService, ITaxService taxService, ICurrencyService currencyService, IPictureService pictureService, IWebHelper webHelper, ICacheManager cacheManager, CatalogSettings catalogSettings, MediaSettings mediaSettings, IEnumerable <Product> products, bool preparePriceModel = true, bool preparePictureModel = true, int?productThumbPictureSize = null, bool prepareSpecificationAttributes = false, bool forceRedirectionAfterAddingToCart = false) { if (products == null) { throw new ArgumentNullException("products"); } var models = new List <ProductOverviewModel>(); foreach (var product in products) { var model = new ProductOverviewModel { Id = product.Id, Name = product.GetLocalized(x => x.Name), ShortDescription = product.GetLocalized(x => x.ShortDescription), FullDescription = product.GetLocalized(x => x.FullDescription), SeName = product.GetSeName(), MarkAsNew = product.MarkAsNew && (!product.MarkAsNewStartDateTimeUtc.HasValue || product.MarkAsNewStartDateTimeUtc.Value < DateTime.UtcNow) && (!product.MarkAsNewEndDateTimeUtc.HasValue || product.MarkAsNewEndDateTimeUtc.Value > DateTime.UtcNow) }; //price if (preparePriceModel) { #region Prepare product price var priceModel = new ProductOverviewModel.ProductPriceModel { ForceRedirectionAfterAddingToCart = forceRedirectionAfterAddingToCart }; switch (product.ProductType) { case ProductType.GroupedProduct: { #region Grouped product var associatedProducts = productService.GetAssociatedProducts(product.Id, storeContext.CurrentStore.Id); switch (associatedProducts.Count) { case 0: { //no associated products //priceModel.DisableBuyButton = true; //priceModel.DisableWishlistButton = true; //compare products priceModel.DisableAddToCompareListButton = !catalogSettings.CompareProductsEnabled; //priceModel.AvailableForPreOrder = false; } break; default: { //we have at least one associated product //priceModel.DisableBuyButton = true; //priceModel.DisableWishlistButton = true; //compare products priceModel.DisableAddToCompareListButton = !catalogSettings.CompareProductsEnabled; //priceModel.AvailableForPreOrder = false; if (permissionService.Authorize(StandardPermissionProvider.DisplayPrices)) { //find a minimum possible price decimal?minPossiblePrice = null; Product minPriceProduct = null; foreach (var associatedProduct in associatedProducts) { //calculate for the maximum quantity (in case if we have tier prices) var tmpPrice = priceCalculationService.GetFinalPrice(associatedProduct, workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue); if (!minPossiblePrice.HasValue || tmpPrice < minPossiblePrice.Value) { minPriceProduct = associatedProduct; minPossiblePrice = tmpPrice; } } if (minPriceProduct != null && !minPriceProduct.CustomerEntersPrice) { if (minPriceProduct.CallForPrice) { priceModel.OldPrice = null; priceModel.Price = localizationService.GetResource("Products.CallForPrice"); } else if (minPossiblePrice.HasValue) { //calculate prices decimal taxRate; decimal finalPriceBase = taxService.GetProductPrice(minPriceProduct, minPossiblePrice.Value, out taxRate); decimal finalPrice = currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, workContext.WorkingCurrency); priceModel.OldPrice = null; priceModel.Price = String.Format(localizationService.GetResource("Products.PriceRangeFrom"), priceFormatter.FormatPrice(finalPrice)); priceModel.PriceValue = finalPrice; } else { //Actually it's not possible (we presume that minimalPrice always has a value) //We never should get here Debug.WriteLine("Cannot calculate minPrice for product #{0}", product.Id); } } } else { //hide prices priceModel.OldPrice = null; priceModel.Price = null; } } break; } #endregion } break; case ProductType.SimpleProduct: default: { #region Simple product //add to cart button priceModel.DisableBuyButton = product.DisableBuyButton || !permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart) || !permissionService.Authorize(StandardPermissionProvider.DisplayPrices); //add to wishlist button priceModel.DisableWishlistButton = product.DisableWishlistButton || !permissionService.Authorize(StandardPermissionProvider.EnableWishlist) || !permissionService.Authorize(StandardPermissionProvider.DisplayPrices); //compare products priceModel.DisableAddToCompareListButton = !catalogSettings.CompareProductsEnabled; //rental priceModel.IsRental = product.IsRental; //pre-order if (product.AvailableForPreOrder) { priceModel.AvailableForPreOrder = !product.PreOrderAvailabilityStartDateTimeUtc.HasValue || product.PreOrderAvailabilityStartDateTimeUtc.Value >= DateTime.UtcNow; priceModel.PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc; } //prices if (permissionService.Authorize(StandardPermissionProvider.DisplayPrices)) { if (!product.CustomerEntersPrice) { if (product.CallForPrice) { //call for price priceModel.OldPrice = null; priceModel.Price = localizationService.GetResource("Products.CallForPrice"); } else { //prices //calculate for the maximum quantity (in case if we have tier prices) decimal minPossiblePrice = priceCalculationService.GetFinalPrice(product, workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue); decimal taxRate; decimal oldPriceBase = taxService.GetProductPrice(product, product.OldPrice, out taxRate); decimal finalPriceBase = taxService.GetProductPrice(product, minPossiblePrice, out taxRate); decimal oldPrice = currencyService.ConvertFromPrimaryStoreCurrency(oldPriceBase, workContext.WorkingCurrency); decimal finalPrice = currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, workContext.WorkingCurrency); //do we have tier prices configured? var tierPrices = new List <TierPrice>(); if (product.HasTierPrices) { tierPrices.AddRange(product.TierPrices .OrderBy(tp => tp.Quantity) .ToList() .FilterByStore(storeContext.CurrentStore.Id) .FilterForCustomer(workContext.CurrentCustomer) .RemoveDuplicatedQuantities()); } //When there is just one tier (with qty 1), //there are no actual savings in the list. bool displayFromMessage = tierPrices.Count > 0 && !(tierPrices.Count == 1 && tierPrices[0].Quantity <= 1); if (displayFromMessage) { priceModel.OldPrice = null; priceModel.Price = String.Format(localizationService.GetResource("Products.PriceRangeFrom"), priceFormatter.FormatPrice(finalPrice)); priceModel.PriceValue = finalPrice; } else { if (finalPriceBase != oldPriceBase && oldPriceBase != decimal.Zero) { priceModel.OldPrice = priceFormatter.FormatPrice(oldPrice); priceModel.Price = priceFormatter.FormatPrice(finalPrice); priceModel.PriceValue = finalPrice; } else { priceModel.OldPrice = null; priceModel.Price = priceFormatter.FormatPrice(finalPrice); priceModel.PriceValue = finalPrice; } } if (product.IsRental) { //rental product priceModel.OldPrice = priceFormatter.FormatRentalProductPeriod(product, priceModel.OldPrice); priceModel.Price = priceFormatter.FormatRentalProductPeriod(product, priceModel.Price); } //property for German market //we display tax/shipping info only with "shipping enabled" for this product //we also ensure this it's not free shipping priceModel.DisplayTaxShippingInfo = catalogSettings.DisplayTaxShippingInfoProductBoxes && product.IsShipEnabled && !product.IsFreeShipping; } } } else { //hide prices priceModel.OldPrice = null; priceModel.Price = null; } #endregion } break; } model.ProductPrice = priceModel; #endregion } //picture if (preparePictureModel) { #region Prepare product picture //If a size has been set in the view, we use it in priority int pictureSize = productThumbPictureSize.HasValue ? productThumbPictureSize.Value : mediaSettings.ProductThumbPictureSize; //prepare picture model var defaultProductPictureCacheKey = string.Format(ModelCacheEventConsumer.PRODUCT_DEFAULTPICTURE_MODEL_KEY, product.Id, pictureSize, true, workContext.WorkingLanguage.Id, webHelper.IsCurrentConnectionSecured(), storeContext.CurrentStore.Id); model.DefaultPictureModel = cacheManager.Get(defaultProductPictureCacheKey, () => { var picture = pictureService.GetPicturesByProductId(product.Id, 1).FirstOrDefault(); var pictureModel = new PictureModel { ImageUrl = pictureService.GetPictureUrl(picture, pictureSize), FullSizeImageUrl = pictureService.GetPictureUrl(picture) }; //"title" attribute pictureModel.Title = (picture != null && !string.IsNullOrEmpty(picture.TitleAttribute)) ? picture.TitleAttribute : string.Format(localizationService.GetResource("Media.Product.ImageLinkTitleFormat"), model.Name); //"alt" attribute pictureModel.AlternateText = (picture != null && !string.IsNullOrEmpty(picture.AltAttribute)) ? picture.AltAttribute : string.Format(localizationService.GetResource("Media.Product.ImageAlternateTextFormat"), model.Name); return(pictureModel); }); #endregion } //specs if (prepareSpecificationAttributes) { model.SpecificationAttributeModels = PrepareProductSpecificationModel(controller, workContext, specificationAttributeService, cacheManager, product); } //reviews model.ReviewOverviewModel = controller.PrepareProductReviewOverviewModel(storeContext, catalogSettings, cacheManager, product); models.Add(model); } return(models); }
public ActionResult CategoryWithPagination(int categoryId, CatalogPagingFilteringModel command) { var category = _categoryService.GetCategoryById(categoryId); if (category == null || category.Deleted) { return(RedirectToRoute("HomePage")); } //Check whether the current user has a "Manage catalog" permission //It allows him to preview a category before publishing if (!category.Published && !_permissionService.Authorize(StandardPermissionProvider.ManageCatalog)) { return(RedirectToRoute("HomePage")); } //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false)); if (command.PageNumber <= 0) { command.PageNumber = 1; } var model = category.ToModel(); //sorting model.PagingFilteringContext.AllowProductSorting = _catalogSettings.AllowProductSorting; if (model.PagingFilteringContext.AllowProductSorting) { foreach (ProductSortingEnum enumValue in Enum.GetValues(typeof(ProductSortingEnum))) { var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null); var sortValue = enumValue.GetLocalizedEnum(_localizationService, _workContext); model.PagingFilteringContext.AvailableSortOptions.Add(new SelectListItem() { Text = sortValue, Value = sortUrl, Selected = enumValue == (ProductSortingEnum)command.OrderBy }); } } //view mode model.PagingFilteringContext.AllowProductViewModeChanging = _catalogSettings.AllowProductViewModeChanging; var viewMode = !string.IsNullOrEmpty(command.ViewMode) ? command.ViewMode : _catalogSettings.DefaultViewMode; if (model.PagingFilteringContext.AllowProductViewModeChanging) { var currentPageUrl = _webHelper.GetThisPageUrl(true); //grid model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Categories.ViewMode.Grid"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=grid", null), Selected = viewMode == "grid" }); //list model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Categories.ViewMode.List"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=list", null), Selected = viewMode == "list" }); } //page size model.PagingFilteringContext.AllowCustomersToSelectPageSize = false; if (category.AllowCustomersToSelectPageSize && category.PageSizeOptions != null) { var pageSizes = category.PageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (pageSizes.Any()) { // get the first page size entry to use as the default (category page load) or if customer enters invalid value via query string if (command.PageSize <= 0 || !pageSizes.Contains(command.PageSize.ToString())) { int temp = 0; if (int.TryParse(pageSizes.FirstOrDefault(), out temp)) { if (temp > 0) { command.PageSize = temp; } } } var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null); sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber"); foreach (var pageSize in pageSizes) { int temp = 0; if (!int.TryParse(pageSize, out temp)) { continue; } if (temp <= 0) { continue; } model.PagingFilteringContext.PageSizeOptions.Add(new SelectListItem() { Text = pageSize, Value = String.Format(sortUrl, pageSize), Selected = pageSize.Equals(command.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase) }); } if (model.PagingFilteringContext.PageSizeOptions.Any()) { model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); model.PagingFilteringContext.AllowCustomersToSelectPageSize = true; if (command.PageSize <= 0) { command.PageSize = int.Parse(model.PagingFilteringContext.PageSizeOptions.FirstOrDefault().Text); } } } } else { //customer is not allowed to select a page size command.PageSize = category.PageSize; } if (command.PageSize <= 0) { command.PageSize = category.PageSize; } //price ranges model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(category.PriceRanges, _webHelper, _priceFormatter); var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_webHelper, category.PriceRanges); decimal?minPriceConverted = null; decimal?maxPriceConverted = null; if (selectedPriceRange != null) { if (selectedPriceRange.From.HasValue) { minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _workContext.WorkingCurrency); } if (selectedPriceRange.To.HasValue) { maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _workContext.WorkingCurrency); } } //category breadcrumb model.DisplayCategoryBreadcrumb = _catalogSettings.CategoryBreadcrumbEnabled; if (model.DisplayCategoryBreadcrumb) { foreach (var catBr in GetCategoryBreadCrumb(category)) { model.CategoryBreadcrumb.Add(new CategoryModel() { Id = catBr.Id, Name = catBr.GetLocalized(x => x.Name), SeName = catBr.GetSeName() }); } } //subcategories model.SubCategories = _categoryService .GetAllCategoriesByParentCategoryId(categoryId) .Select(x => { var subCatName = x.GetLocalized(y => y.Name); var subCatModel = new CategoryModel.SubCategoryModel() { Id = x.Id, Name = subCatName, SeName = x.GetSeName(), SubCategoryDescription = x.Description }; //prepare picture model int pictureSize = _mediaSettings.CategoryThumbPictureSize; var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, x.Id, pictureSize, true, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured()); subCatModel.PictureModel = _cacheManager.Get(categoryPictureCacheKey, () => { var pictureModel = new PictureModel() { FullSizeImageUrl = _pictureService.GetPictureUrl(x.PictureId), ImageUrl = _pictureService.GetPictureUrl(x.PictureId, pictureSize), Title = string.Format(_localizationService.GetResource("Media.Category.ImageLinkTitleFormat"), subCatName), AlternateText = string.Format(_localizationService.GetResource("Media.Category.ImageAlternateTextFormat"), subCatName) }; return(pictureModel); }); return(subCatModel); }) .ToList(); model.PagingFilteringContext.TotalItems = model.SubCategories.Count; // model.SubCategories = model.SubCategories.Skip(command.PageIndex * command.PageSize).Take(command.PageSize).ToList(); IPagedList <CategoryModel.SubCategoryModel> pagedCategories = new PagedList <CategoryModel.SubCategoryModel>(model.SubCategories, command.PageNumber - 1, command.PageSize); model.PagingFilteringContext.LoadPagedList(pagedCategories); model.SubCategories = model.SubCategories.Skip(command.PageIndex * command.PageSize).Take(command.PageSize).ToList(); if (model.SubCategories.Count == 0) { //featured products //Question: should we use '_catalogSettings.ShowProductsFromSubcategories' setting for displaying featured products? if (!_catalogSettings.IgnoreFeaturedProducts && _categoryService.GetTotalNumberOfFeaturedProducts(categoryId) > 0) { //We use the fast GetTotalNumberOfFeaturedProducts before invoking of the slow SearchProducts //to ensure that we have at least one featured product IList <int> filterableSpecificationAttributeOptionIdsFeatured = null; var featuredProducts = _productService.SearchProducts(category.Id, 0, true, null, null, 0, null, false, false, _workContext.WorkingLanguage.Id, null, ProductSortingEnum.Position, 0, int.MaxValue, false, out filterableSpecificationAttributeOptionIdsFeatured); model.FeaturedProducts = PrepareProductOverviewModels(featuredProducts).ToList(); } var categoryIds = new List <int>(); categoryIds.Add(category.Id); if (_catalogSettings.ShowProductsFromSubcategories) { //include subcategories categoryIds.AddRange(GetChildCategoryIds(category.Id)); } //products IList <int> alreadyFilteredSpecOptionIds = model.PagingFilteringContext.SpecificationFilter.GetAlreadyFilteredSpecOptionIds(_webHelper); IList <int> filterableSpecificationAttributeOptionIds = null; var products = _productService.SearchProducts(categoryIds, 0, _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, minPriceConverted, maxPriceConverted, 0, string.Empty, false, false, _workContext.WorkingLanguage.Id, alreadyFilteredSpecOptionIds, (ProductSortingEnum)command.OrderBy, command.PageNumber - 1, command.PageSize, true, out filterableSpecificationAttributeOptionIds); model.Products = PrepareProductOverviewModels(products).ToList(); model.PagingFilteringContext.LoadPagedList(products); model.PagingFilteringContext.ViewMode = viewMode; //specs model.PagingFilteringContext.SpecificationFilter.PrepareSpecsFilters(alreadyFilteredSpecOptionIds, filterableSpecificationAttributeOptionIds, _specificationAttributeService, _webHelper, _workContext); } //template var templateCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_TEMPLATE_MODEL_KEY, category.CategoryTemplateId); var templateViewPath = _cacheManager.Get(templateCacheKey, () => { var template = _categoryTemplateService.GetCategoryTemplateById(category.CategoryTemplateId); if (template == null) { template = _categoryTemplateService.GetAllCategoryTemplates().FirstOrDefault(); } return(template.ViewPath); }); //activity log _customerActivityService.InsertActivity("PublicStore.ViewCategory", _localizationService.GetResource("ActivityLog.PublicStore.ViewCategory"), category.Name); return(View(templateViewPath, model)); }
public ProductAttributeValueModel() { PictureModel = new PictureModel(); }
public SubCategoryModel() { PictureModel = new PictureModel(); }
public static Picture ToEntity(this PictureModel model) { return(model.MapTo <PictureModel, Picture>()); }
public static Picture ToEntity(this PictureModel model, Picture destination) { return(model.MapTo(destination)); }
public ProductAttributeValueModel() { ImageSquaresPictureModel = new PictureModel(); }
public ActionResult DeletePicture(int id) { var Picture = _PictureGaleryService.FindPicture(id); var model = new PictureModel(); model.PictureGalery = Picture.PictureGalery; try { _PictureGaleryService.Delete(Picture); _uow.SaveChanges(); messagesForView.Clear(); messagesForView.Add("İşlemi başarılı!"); Success(messagesForView); } catch (Exception ex) { messagesForView.Clear(); messagesForView.Add("İşlem başarısız!"); messagesForView.Add(ex.Message); messagesForView.Add(ex.InnerException.Message); Error(messagesForView); } return View("Pictures", model); }
public PictureViewModelM(PictureModel model) { _model = model; Id = model.Id; }
public ActionResult AddPicture(PictureModel model) { if (ModelState.IsValid) { if (model.PictureGaleryImg.ContentLength > 0) { var image = model.PictureGaleryImg; var fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(image.FileName); var imageDirectory = Server.MapPath("~/Content/Images/uploads/PictureGalery/" + model.PictureGalery.Id); var imageDirectorySmall = Server.MapPath("~/Content/Images/uploads/PictureGalery/" + model.PictureGalery.Id + "/Small"); var imageDirectoryMiddle = Server.MapPath("~/Content/Images/uploads/PictureGalery/" + model.PictureGalery.Id + "/Middle"); var imageDirectoryBig = Server.MapPath("~/Content/Images/uploads/PictureGalery/" + model.PictureGalery.Id + "/Big"); // create directory if not exist if (!Directory.Exists(imageDirectory)) { Directory.CreateDirectory(imageDirectory); Directory.CreateDirectory(imageDirectorySmall); Directory.CreateDirectory(imageDirectoryMiddle); Directory.CreateDirectory(imageDirectoryBig); } // resmi sunucuya kaydet image.SaveAs(Path.Combine(imageDirectory, fileName)); // resmi küçük boyutta kaydet ImageManager.SaveResizedImage(Image.FromFile(Path.Combine(imageDirectory, fileName)), new Size(180, 180), imageDirectorySmall, fileName); ImageManager.SaveResizedImage(Image.FromFile(Path.Combine(imageDirectory, fileName)), new Size(360, 360), imageDirectoryMiddle, fileName); ImageManager.SaveResizedImage(Image.FromFile(Path.Combine(imageDirectory, fileName)), new Size(720, 720), imageDirectoryBig, fileName); var Picture = new Picture(); Picture.ContentSize = image.ContentLength; Picture.ContentType = image.ContentType; Picture.FileName = fileName; Picture.PictureGaleryId = model.PictureGalery.Id; Picture.InsertDate = DateTime.Now; Picture.InsertUserId = CustomMembership.CurrentUser().Id; Picture.IsActive = true; Picture.Order = model.Order; Picture.ImgUrl = Path.Combine("Content/Images/uploads/PictureGalery/" + model.PictureGalery.Id, fileName); Picture.ImgUrlSmall = Path.Combine("Content/Images/uploads/PictureGalery/" + model.PictureGalery.Id + "/Small", fileName); Picture.ImgUrlMiddle = Path.Combine("Content/Images/uploads/PictureGalery/" + model.PictureGalery.Id + "/Middle", fileName); Picture.ImgUrlBig = Path.Combine("Content/Images/uploads/PictureGalery/" + model.PictureGalery.Id + "/Big", fileName); try { _PictureGaleryService.Insert(Picture); _uow.SaveChanges(); messagesForView.Clear(); messagesForView.Add("İşlemi başarılı!"); Success(messagesForView); } catch (Exception ex) { messagesForView.Clear(); messagesForView.Add("İşlem başarısız!"); messagesForView.Add(ex.Message); messagesForView.Add(ex.InnerException.Message); Error(messagesForView); } } } return RedirectToAction("Pictures", new { PictureGaleryId = model.PictureGalery.Id }); }
protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["Picture"] != null) { List <int> ids = new List <int>(); using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "SELECT Id FROM Images ORDER BY Id"; SqlCommand command = new SqlCommand(sql, connection); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt32(0); ids.Add(id); } reader.Close(); var sas = Request.QueryString["Picture"].ToString(); int currentId = int.Parse(Request.QueryString["Picture"].ToString()); if (!ids.Contains(currentId)) { Response.Redirect("Error.aspx"); } int leftId = 0; if (currentId != ids[0]) { leftId = ids[ids.IndexOf(currentId) - 1]; } else { leftId = currentId; } int rightId = 0; if (currentId != ids[ids.Count - 1]) { rightId = ids[ids.IndexOf(currentId) + 1]; } else { rightId = currentId; } //получаю відкритий string currentSql = "SELECT * FROM Images WHERE Id = @id"; SqlCommand currentCommand = new SqlCommand(currentSql, connection); currentCommand.Parameters.Add("@id", SqlDbType.NVarChar, 50).Value = currentId; SqlDataReader currentReader = currentCommand.ExecuteReader(); PictureModel image = null; while (currentReader.Read()) { int id = currentReader.GetInt32(0); string filename = currentReader.GetString(1); string picturename = currentReader.GetString(2); string desc = currentReader.GetString(3); byte[] data = (byte[])currentReader.GetValue(4); image = new PictureModel(id, data, filename, picturename, desc); } // Image mainImg = new Image(); mainImg.ID = "img"; mainImg.ImageUrl = @"pictures\" + image.FileName; mainImg.CssClass = "picture"; HtmlGenericControl imagediv = (HtmlGenericControl)(FindControlRecursive(Page, "image")); imagediv.Controls.Add(mainImg); HtmlGenericControl left = new HtmlGenericControl("a"); left.Attributes["href"] = "Gallery.aspx?Picture=" + leftId; left.Attributes["class"] = "left"; HtmlGenericControl right = new HtmlGenericControl("a"); right.Attributes["href"] = "Gallery.aspx?Picture=" + rightId; right.Attributes["class"] = "right"; if (leftId != currentId) { imagediv.Controls.Add(left); } if (rightId != currentId) { imagediv.Controls.Add(right); } HtmlGenericControl maindiv = (HtmlGenericControl)(FindControlRecursive(Page, "maindiv")); HtmlGenericControl article = new HtmlGenericControl("div"); article.Attributes["class"] = "article"; article.InnerHtml = String.Format("<h3>{0}</h3>\n<p>{1}</p>", image.PictureName, image.Description); maindiv.Controls.Add(article); } } else { Response.Redirect("Error.aspx"); } }