public void Entities_with_same_id_but_different_type_should_not_be_equal() {
            int id = 10;
            var p1 = new Product { Id = id };

            var c1 = new Category { Id = id };

            Assert.AreNotEqual(p1, c1, "Entities of different types should not be equal, even if they have the same id");
        }
        public void Can_save_and_load_category()
        {
            var category = new Category
            {
                Name = "Books",
                Description = "Description 1",
                MetaKeywords = "Meta keywords",
                MetaDescription = "Meta description",
                MetaTitle = "Meta title",
                ParentCategoryId = 2,
                PictureId = 3,
                PageSize = 4,
                AllowCustomersToSelectPageSize = true,
                PageSizeOptions = "4, 2, 8, 12",
                PriceRanges = "1-3;",
                ShowOnHomePage = false,
                HasDiscountsApplied = true,
                Published = true,
                SubjectToAcl = true,
                LimitedToStores = true,
                Deleted = false,
                DisplayOrder = 5,
                CreatedOnUtc = new DateTime(2010, 01, 01),
                UpdatedOnUtc = new DateTime(2010, 01, 02),
            };

            var fromDb = SaveAndLoadEntity(category);
            fromDb.ShouldNotBeNull();
            fromDb.Name.ShouldEqual("Books");
            fromDb.Description.ShouldEqual("Description 1");
            fromDb.MetaKeywords.ShouldEqual("Meta keywords");
            fromDb.MetaDescription.ShouldEqual("Meta description");
            fromDb.ParentCategoryId.ShouldEqual(2);
            fromDb.PictureId.ShouldEqual(3);
            fromDb.PageSize.ShouldEqual(4);
            fromDb.AllowCustomersToSelectPageSize.ShouldEqual(true);
            fromDb.PageSizeOptions.ShouldEqual("4, 2, 8, 12");
            fromDb.PriceRanges.ShouldEqual("1-3;");
            fromDb.ShowOnHomePage.ShouldEqual(false);
            fromDb.HasDiscountsApplied.ShouldEqual(true);
            fromDb.Published.ShouldEqual(true);
            fromDb.SubjectToAcl.ShouldEqual(true);
            fromDb.LimitedToStores.ShouldEqual(true);
            fromDb.Deleted.ShouldEqual(false);
            fromDb.DisplayOrder.ShouldEqual(5);
            fromDb.CreatedOnUtc.ShouldEqual(new DateTime(2010, 01, 01));
            fromDb.UpdatedOnUtc.ShouldEqual(new DateTime(2010, 01, 02));
        }
        /// <summary>
        /// Inserts category
        /// </summary>
        /// <param name="category">Category</param>
        public virtual void InsertCategory(Category category)
        {
            if (category == null)
                throw new ArgumentNullException("category");

            _categoryRepository.Insert(category);

            //cache
            _cacheManager.RemoveByPattern(CATEGORIES_PATTERN_KEY);
            _cacheManager.RemoveByPattern(PRODUCTCATEGORIES_PATTERN_KEY);

            //event notification
            _eventPublisher.EntityInserted(category);
        }
		/// <summary>
        /// Delete category
        /// </summary>
        /// <param name="category">Category</param>
		/// <param name="deleteChilds">Whether to delete child categories or to set them to no parent.</param>
		public virtual void DeleteCategory(Category category, bool deleteChilds = false)
        {
            if (category == null)
                throw new ArgumentNullException("category");

            category.Deleted = true;
            UpdateCategory(category);

			var childCategories = GetAllCategoriesByParentCategoryId(category.Id, true);
			DeleteAllCategories(childCategories, deleteChilds);
        }
		private void PrepareStoresMappingModel(CategoryModel model, Category category, bool excludeProperties)
		{
			if (model == null)
				throw new ArgumentNullException("model");

			model.AvailableStores = _storeService
				.GetAllStores()
				.Select(s => s.ToModel())
				.ToList();
			if (!excludeProperties)
			{
				if (category != null)
				{
					model.SelectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(category);
				}
				else
				{
					model.SelectedStoreIds = new int[0];
				}
			}
		}
 protected void SaveCategoryAcl(Category category, CategoryModel model)
 {
     var existingAclRecords = _aclService.GetAclRecords(category);
     var allCustomerRoles = _customerService.GetAllCustomerRoles(true);
     foreach (var customerRole in allCustomerRoles)
     {
         if (model.SelectedCustomerRoleIds != null && model.SelectedCustomerRoleIds.Contains(customerRole.Id))
         {
             //new role
             if (existingAclRecords.Where(acl => acl.CustomerRoleId == customerRole.Id).Count() == 0)
                 _aclService.InsertAclRecord(category, customerRole.Id);
         }
         else
         {
             //removed role
             var aclRecordToDelete = existingAclRecords.Where(acl => acl.CustomerRoleId == customerRole.Id).FirstOrDefault();
             if (aclRecordToDelete != null)
                 _aclService.DeleteAclRecord(aclRecordToDelete);
         }
     }
 }
        private void PrepareAclModel(CategoryModel model, Category category, bool excludeProperties)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            model.AvailableCustomerRoles = _customerService
                .GetAllCustomerRoles(true)
                .Select(cr => cr.ToModel())
                .ToList();
            if (!excludeProperties)
            {
                if (category != null)
                {
                    model.SelectedCustomerRoleIds = _aclService.GetCustomerRoleIdsWithAccess(category);
                }
                else
                {
                    model.SelectedCustomerRoleIds = new int[0];
                }
            }
        }
		public IList<Category> CategoriesFirstLevel()
		{
			// pictures
			var sampleImagesPath = this._sampleImagesPath;

			var categoryTemplateInGridAndLines =
				this.CategoryTemplates().Where(pt => pt.ViewPath == "CategoryTemplate.ProductsInGridOrLines").FirstOrDefault();

			//categories

			#region category definitions

			var categoryBooks = new Category
			{
				Name = "Books",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "emblem_library.png"), "image/jpeg", GetSeName("Books")),
				Published = true,
				DisplayOrder = 1,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Books"
			};

			var categoryComputers = new Category
			{
				Name = "Computers",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "category_computers.jpeg"), "image/jpeg", GetSeName("Computers")),
				Published = true,
				DisplayOrder = 2,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Computers"
			};

			var categoryGaming = new Category
			{
				Name = "Gaming",
				Alias = "Gaming",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "category_gaming.jpg"), "image/jpeg", GetSeName("Gaming")),
				Published = true,
				DisplayOrder = 3,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Gaming"
			};

			var categoryCellPhones = new Category
			{
				Name = "Cell phones",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",

				//ParentCategoryId = categoryElectronics.Id,
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "category_cell_phones.jpeg"), "image/jpeg", GetSeName("Cell phones")),
				Published = true,
				DisplayOrder = 4,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Cell phones"
			};

			var categoryDigitalDownloads = new Category
			{
				Name = "Instant music",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "category_digital_downloads.jpeg"), "image/jpeg", GetSeName("Digital downloads")),
				Published = true,
				DisplayOrder = 6,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Instant music"
			};

			var categoryGiftCards = new Category
			{
				Name = "Gift Cards",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "category_gift_cards.jpeg"), "image/jpeg", GetSeName("Gift Cards")),
				Published = true,
				DisplayOrder = 12,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Gift cards"
			};

			var categoryWatches = new Category
			{
				Name = "Watches",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "0001514_uhren.jpeg"), "image/jpeg", GetSeName("Watches")),
				Published = true,
				DisplayOrder = 10,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Watches"
			};

			#endregion category definitions

			var entities = new List<Category>
			{
			   categoryBooks, categoryComputers, categoryCellPhones, categoryDigitalDownloads, categoryGaming, categoryGiftCards, categoryWatches
			};

			this.Alter(entities);
			return entities;
		}
        protected void UpdateLocales(Category category, CategoryModel model)
        {
            foreach (var localized in model.Locales)
            {
                _localizedEntityService.SaveLocalizedValue(category, x => x.Name, localized.Name, localized.LanguageId);

				_localizedEntityService.SaveLocalizedValue(category, x => x.FullName, localized.FullName, localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(category, x => x.Description, localized.Description, localized.LanguageId);

				_localizedEntityService.SaveLocalizedValue(category, x => x.BottomDescription, localized.BottomDescription, localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(category, x => x.MetaKeywords, localized.MetaKeywords, localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(category, x => x.MetaDescription, localized.MetaDescription, localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(category, x => x.MetaTitle, localized.MetaTitle, localized.LanguageId);

                //search engine name
                var seName = category.ValidateSeName(localized.SeName, localized.Name, false, localized.LanguageId);
                _urlRecordService.SaveSlug(category, seName, localized.LanguageId);
            }
        }
 public static Category ToEntity(this CategoryModel model, Category destination)
 {
     return Mapper.Map(model, destination);
 }
		protected void SaveStoreMappings(Category category, CategoryModel model)
		{
			var existingStoreMappings = _storeMappingService.GetStoreMappings(category);
			var allStores = _storeService.GetAllStores();
			foreach (var store in allStores)
			{
				if (model.SelectedStoreIds != null && model.SelectedStoreIds.Contains(store.Id))
				{
					//new role
					if (existingStoreMappings.Where(sm => sm.StoreId == store.Id).Count() == 0)
						_storeMappingService.InsertStoreMapping(category, store.Id);
				}
				else
				{
					//removed role
					var storeMappingToDelete = existingStoreMappings.Where(sm => sm.StoreId == store.Id).FirstOrDefault();
					if (storeMappingToDelete != null)
						_storeMappingService.DeleteStoreMapping(storeMappingToDelete);
				}
			}
		}
        protected void PrepareCategoryModel(CategoryModel model, Category category, bool excludeProperties)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            var discounts = _discountService.GetAllDiscounts(DiscountType.AssignedToCategories, null, true);
            model.AvailableDiscounts = discounts.ToList();

            if (!excludeProperties)
            {
                model.SelectedDiscountIds = category.AppliedDiscounts.Select(d => d.Id).ToArray();
            }

			if (category != null)
			{
				model.CreatedOn = _dateTimeHelper.ConvertToUserTime(category.CreatedOnUtc, DateTimeKind.Utc);
				model.UpdatedOn = _dateTimeHelper.ConvertToUserTime(category.UpdatedOnUtc, DateTimeKind.Utc);
			}
        }
        /// <summary>
        /// Delete category
        /// </summary>
        /// <param name="category">Category</param>
        public virtual void DeleteCategory(Category category)
        {
            if (category == null)
                throw new ArgumentNullException("category");

            category.Deleted = true;
            UpdateCategory(category);

			//reset a "Parent category" property of all child subcategories
            var subcategories = GetAllCategoriesByParentCategoryId(category.Id, true);
            foreach (var subcategory in subcategories)
            {
                subcategory.ParentCategoryId = 0;
                UpdateCategory(subcategory);
            }
        }
        /// <summary>
        /// Updates the category
        /// </summary>
        /// <param name="category">Category</param>
        public virtual void UpdateCategory(Category category)
        {
            if (category == null)
                throw new ArgumentNullException("category");

            //validate category hierarchy
            var parentCategory = GetCategoryById(category.ParentCategoryId);
            while (parentCategory != null)
            {
                if (category.Id == parentCategory.Id)
                {
                    category.ParentCategoryId = 0;
                    break;
                }
                parentCategory = GetCategoryById(parentCategory.ParentCategoryId);
            }

            _categoryRepository.Update(category);

            //cache
            _cacheManager.RemoveByPattern(CATEGORIES_PATTERN_KEY);
            _cacheManager.RemoveByPattern(PRODUCTCATEGORIES_PATTERN_KEY);

            //event notification
            _eventPublisher.EntityUpdated(category);
        }
 protected void UpdatePictureSeoNames(Category category)
 {
     var picture = _pictureService.GetPictureById(category.PictureId.GetValueOrDefault());
     if (picture != null)
         _pictureService.SetSeoFilename(picture.Id, _pictureService.GetPictureSeName(category.Name));
 }
        /// <summary>
        /// Update HasDiscountsApplied property (used for performance optimization)
        /// </summary>
        /// <param name="category">Category</param>
        public virtual void UpdateHasDiscountsApplied(Category category)
        {
            if (category == null)
                throw new ArgumentNullException("category");

            category.HasDiscountsApplied = category.AppliedDiscounts.Count > 0;
            UpdateCategory(category);
        }
        protected void PrepareCategoryModel(CategoryModel model, Category category, bool excludeProperties)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            var discounts = _discountService.GetAllDiscounts(DiscountType.AssignedToCategories, null, true);
            model.AvailableDiscounts = discounts.ToList();

            if (!excludeProperties)
            {
                model.SelectedDiscountIds = category.AppliedDiscounts.Select(d => d.Id).ToArray();
            }

			if (category != null)
			{
				model.CreatedOn = _dateTimeHelper.ConvertToUserTime(category.CreatedOnUtc, DateTimeKind.Utc);
				model.UpdatedOn = _dateTimeHelper.ConvertToUserTime(category.UpdatedOnUtc, DateTimeKind.Utc);
			}

            model.AvailableDefaultViewModes.Add(
                new SelectListItem { Value = "grid", Text = _localizationService.GetResource("Common.Grid"), Selected = model.DefaultViewMode.IsCaseInsensitiveEqual("grid") }
            );
            model.AvailableDefaultViewModes.Add(
                new SelectListItem { Value = "list", Text = _localizationService.GetResource("Common.List"), Selected = model.DefaultViewMode.IsCaseInsensitiveEqual("list") }
            );
        }
		public IList<Category> CategoriesSecondLevel()
		{
			// pictures
			var sampleImagesPath = this._sampleImagesPath;

			var categoryTemplateInGridAndLines =
				this.CategoryTemplates().Where(pt => pt.ViewPath == "CategoryTemplate.ProductsInGridOrLines").FirstOrDefault();

			//categories

			#region category definitions

			var categoryBooksSpiegel = new Category
			{
				Name = "SPIEGEL-Bestseller",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "0000930_spiegel-bestseller.png"), "image/png", GetSeName("SPIEGEL-Bestseller")),
				Published = true,
				ParentCategoryId = _ctx.Set<Category>().Where(x => x.MetaTitle == "Books").First().Id,
				DisplayOrder = 1,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "SPIEGEL-Bestseller"
			};

			var categoryBooksCookAndEnjoy = new Category
			{
				Name = "Cook and enjoy",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "0000936_kochen-geniesen.jpeg"), "image/jpeg", GetSeName("Cook and enjoy")),
				Published = true,
				ParentCategoryId = _ctx.Set<Category>().Where(x => x.MetaTitle == "Books").First().Id,
				DisplayOrder = 2,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Cook and enjoy"
			};

			var categoryDesktops = new Category
			{
				Name = "Desktops",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				ParentCategoryId = _ctx.Set<Category>().Where(x => x.MetaTitle == "Computers").First().Id,
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "category_desktops.jpg"), "image/jpeg", GetSeName("Desktops")),
				PriceRanges = "-1000;1000-1200;1200-;",
				Published = true,
				DisplayOrder = 1,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Desktops"
			};

			var categoryNotebooks = new Category
			{
				Name = "Notebooks",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				ParentCategoryId = _ctx.Set<Category>().Where(x => x.MetaTitle == "Computers").First().Id,
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "category_notebooks.jpg"), "image/pjpeg", GetSeName("Notebooks")),
				Published = true,
				DisplayOrder = 2,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Notebooks"
			};

			var categoryGamingAccessories = new Category
			{
				Name = "Gaming Accessories",
				Alias = "Gaming Accessories",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				ParentCategoryId = _ctx.Set<Category>().Where(x => x.MetaTitle == "Gaming").First().Id,
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "category_gaming_accessories.jpg"), "image/jpeg", GetSeName("Gaming Accessories")),
				Published = true,
				DisplayOrder = 2,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Gaming Accessories"
			};

			var categoryGamingGames = new Category
			{
				Name = "Games",
				Alias = "Games",
				CategoryTemplateId = categoryTemplateInGridAndLines.Id,
				PageSize = 12,
				AllowCustomersToSelectPageSize = true,
				PageSizeOptions = "12,18,36,72,150",
				ParentCategoryId = _ctx.Set<Category>().Where(x => x.MetaTitle == "Gaming").First().Id,
				Picture = CreatePicture(File.ReadAllBytes(sampleImagesPath + "category_games.jpg"), "image/jpeg", GetSeName("Games")),
				Published = true,
				DisplayOrder = 3,
				CreatedOnUtc = DateTime.UtcNow,
				UpdatedOnUtc = DateTime.UtcNow,
				MetaTitle = "Games"
			};

			//var categorySoftware = new Category
			//{
			//    Name = "Software",
			//    CategoryTemplateId = categoryTemplateInGridAndLines.Id,
			//    PageSize = 12,
			//    AllowCustomersToSelectPageSize = true,
			//    PageSizeOptions = "12,18,36,72,150",
			//    ParentCategoryId = _ctx.Set<Category>().Where(x => x.MetaTitle =="Computers" ).FirstOrDefault().Id,
			//    PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_software.jpg"), "image/pjpeg", pictureService.GetPictureSeName("Software"), true, false).Id,
			//    Published = true,
			//    DisplayOrder = 2,
			//    CreatedOnUtc = DateTime.UtcNow,
			//    UpdatedOnUtc = DateTime.UtcNow,
			//    MetaTitle = "Software"
			//};

			#endregion category definitions

			var entities = new List<Category>
			{
				categoryBooksSpiegel, categoryBooksCookAndEnjoy, categoryDesktops, categoryNotebooks, categoryGamingAccessories, categoryGamingGames
			};

			this.Alter(entities);
			return entities;
		}
        protected IList<Category> GetCategoryBreadCrumb(Category category, IDictionary<int, Category> mappedCategories = null)
        {
            if (category == null)
                throw new ArgumentNullException("category");

            var breadCrumb = new List<Category>();
			var alreadyProcessedCategoryIds = new List<int>();

            while (category != null && //category is not null
                !category.Deleted && //category is not deleted
                category.Published && //category is published
				_aclService.Authorize(category) && //ACL
				_storeMappingService.Authorize(category) &&	//Store mapping
				!alreadyProcessedCategoryIds.Contains(category.Id))
            {
                breadCrumb.Add(category);
                var parentId = category.ParentCategoryId;
                if (mappedCategories == null)
                {
                    category = _categoryService.GetCategoryById(parentId);
                }
                else
                {
                    category = mappedCategories.ContainsKey(parentId) ? mappedCategories[parentId] : _categoryService.GetCategoryById(parentId);
                }
            }

            breadCrumb.Reverse();
            return breadCrumb;
        }