public ActionResult Create(CreateCategoryModel model) { try { if(ModelState.IsValid){ Category cat = new Category() { CategoryName = model.Name, ParentCategoryID = model.ParentCategoryID, AccessTypes = model.AccessTypes, CreatedDate =DateTime.Now, UpdatedDate = DateTime.Now, }; CategoryService service = new CategoryService(); service.AddCategory(cat); return RedirectToAction("Index"); }; // TODO: Add insert logic here } catch (Exception ex) { Logger.Log(ex); ModelState.AddModelError("Error", "Có lỗi hệ thống xãy ra. không thể thêm dữ liệu."); } return View(model); }
public override void Parse() { Income.Products = new List<Product>(); CategoryService categoryService = new CategoryService(); int addedCount = 0; int skippedCount = 0; int usedRangeRows = ActiveWorksheet.UsedRange.Rows.Count; string previousFirstName = ""; for (int i = FirstRow; i < usedRangeRows; i++) { OnSetProgressBarValue(CalcProgressBarValue(i, usedRangeRows)); OnPrintStatus($"Обработка позиции {i} из {usedRangeRows}"); string originalName = GetCellValue(i, NameColumn); string price = GetCellValue(i, 10); if (string.IsNullOrEmpty(originalName)) { skippedCount++; continue; } string firstName = originalName.Substring(0, originalName.IndexOf(' ')); if (categoryService.LastResult == CategoryService.CategoryChoiсeResult.Undefined || firstName != previousFirstName) categoryService.ParseCategory(firstName); } }
public static IHtmlString RenderCategoryMenu(this HtmlHelper html) { CacheService cache = new CacheService(); int currentCategoryId = 0; if (html.ViewContext.RouteData.Values.ContainsKey("categoryId")) { currentCategoryId = html.ViewContext.RouteData.Values["categoryId"].ToString().AsInt(); } return cache.Get("categoryMenu.{0}".FormatWith(currentCategoryId), () => { CategoryService categoryService = new CategoryService(); int currentTopCategoryId = categoryService.GetTopParentOf(currentCategoryId); var sb = new StringBuilder(); var categories = categoryService.GetMainCategories(); sb.AppendWithTabs("<ul>", 3); foreach (var category in categories) { var isCurrent = currentTopCategoryId == category.CategoryId; sb.AppendWithTabs("<li>", 4); sb.AppendWithTabs("<a href=\"{0}\"{1}>{2} <span class=\"count\">({3})</span></a>".FormatWith(category.Link, isCurrent ? "class=\"current\"" : "", category.Name, category.Snippets.Count), 5); if (currentTopCategoryId == category.CategoryId && category.ChildrenCategories != null) { AppendSubCategories(sb, category, currentCategoryId, 5); } sb.AppendWithTabs("</li>", 4); } sb.AppendWithTabs("</ul>", 3); return new HtmlString(sb.ToString()); }); }
/// <summary> /// Constructs the Freshbooks API authentication and wrapper class /// </summary> /// <param name="accountName">The account name for which you are trying to access</param> /// <param name="consumerKey">The developer's freshbooks account name</param> /// <param name="oauthSecret">The developer's oauth-secret provided by freshbooks</param> public FreshbooksApi(string accountName, string consumerKey, string oauthSecret) { _accountName = accountName; _consumerKey = consumerKey; _oauthSecret = oauthSecret ?? String.Empty; _baseUri = new UriBuilder { Scheme = "https", Host = accountName + ".freshbooks.com" }.Uri; _serviceUri = new Uri(_baseUri, "/api/2.1/xml-in"); Clear(); UserAgent = String.Format("{0}/{1} ({2})", GetType().Name, GetType().Assembly.GetName().Version.ToString(2), GetType().Assembly.FullName); Callback = new CallbackService(new ServiceProxy(this, "callback")); Category = new CategoryService(new ServiceProxy(this, "category")); Client = new ClientService(new ServiceProxy(this, "client")); Estimate = new EstimateService(new ServiceProxy(this, "estimate")); Expense = new ExpenseService(new ServiceProxy(this, "expense")); Gateway = new GatewayService(new ServiceProxy(this, "gateway")); Invoice = new InvoiceService(new ServiceProxy(this, "invoice")); Item = new ItemService(new ServiceProxy(this, "item")); Language = new LanguageService(new ServiceProxy(this, "language")); Payment = new PaymentService(new ServiceProxy(this, "payment")); Project = new ProjectService(new ServiceProxy(this, "project")); Recurring = new RecurringService(new ServiceProxy(this, "recurring")); System = new SystemService(new ServiceProxy(this, "system")); Staff = new StaffService(new ServiceProxy(this, "staff")); Task = new TaskService(new ServiceProxy(this, "task")); Tax = new TaxService(new ServiceProxy(this, "tax")); TimeEntry = new TimeEntryService(new ServiceProxy(this, "time_entry")); }
public CategoriesVM(CategoryService categoryService) { _categoriesService = categoryService; _addCategoryCommand = new Command(() => AddCategory()); _saveCategoriesCommand = new Command(async () => await SaveCategoriesAsync()); _loadCategoriesCommand = new Command(async () => await LoadCategoriesAsync()); _deleteSelectedCommand = new Command(async () => await DeleteSelectedItemAsync()); }
private bool disposedValue = false; // To detect redundant calls #endregion Fields #region Constructors public ServiceManager() { context = new TankshopDbContext(); Categories = new CategoryService(new CategoryRepository(context)); Products = new ProductService(new ProductRepository(context)); Images = new ImageBLL(); Accounts = new AccountBLL(); }
public CategoryModel(Category category) { Category = category; CategoryList = new CategoryService().GetCategoryList(); if (Category != null && Category.ParentCategory != null) ParentCategoryId = Category.ParentCategory.CategoryId; }
/// <summary> /// 递归调用,获取分类的所有父级分类的Id集合 /// </summary> /// <param name="categoryService">逻辑类</param> /// <param name="categoryId">当前分类的Id</param> /// <param name="checkedCategoryIds">父级分类Id集合</param> private static void GetParentCategoryIDs(CategoryService<Category> categoryService, long categoryId, List<long> checkedCategoryIds) { Category category = categoryService.Get(categoryId); if (category!=null && category.ParentId > 0) { checkedCategoryIds.Add(category.ParentId); GetParentCategoryIDs(categoryService, category.ParentId, checkedCategoryIds); } }
public ActionResult Details(int categoryId, int? page) { CategoryService categoryService = new CategoryService(); SnippetService snippetService = new SnippetService(); var category = categoryService.GetById(categoryId); var snippets = snippetService.GetByCategory(categoryId, page); ViewData.Model = new CategoryDetailsModel(category, snippets); return View(); }
public ActionResult AddBook() { var categoryService = new CategoryService(); var categories = categoryService.GetCategory(); var model = new AddProductViewModel(); model.Categories = new List<SelectListItem>(); foreach (var item in categories) { model.Categories.Add(new SelectListItem() { Value = item.Id.ToString(), Text = item.name }); } return View(model); }
public ActionResult Index(string query, int? page) { if (query.IsNullOrEmpty()) return View(new SearchModel()); SnippetService snippetService = new SnippetService(); var snippets = snippetService.Search(query, page); CategoryService categoryService = new CategoryService(); IPagedList<Category> categories = categoryService.Search(query, 1, 100, splitSearch:true); SearchModel model = new SearchModel(query, snippets, categories); return View(model); }
void MainWindow_Loaded(object sender, RoutedEventArgs e) { var productsDataProxy = new ProductRepository(); var inventoryDataProxy = new InventoryItemRepository(); var customerDataProxy = new CustomerRepository(); var orderItemDataProxy = new OrderItemRepository(); var orderRepository = new OrderRepository(customerDataProxy, orderItemDataProxy); _inventoryService = new InventoryItemService(inventoryDataProxy); _orderItemsService = new OrderItemService(orderItemDataProxy, productsDataProxy, inventoryDataProxy, new DTCTransactionContext()); _ordersService = new OrderService(orderRepository, _orderItemsService, new DTCTransactionContext()); _customersService = new CustomerService(customerDataProxy, _ordersService); _productsService = new ProductService(productsDataProxy, _ordersService, _inventoryService, new DTCTransactionContext()); _categoriesService = new CategoryService(new CategoryRepository(), _productsService); this.DataContext = new MainWindowVM(_eventAggregator, _customersService, _productsService, _categoriesService, _ordersService, _inventoryService); }
private void ConfigureEFUsage() { var productsDataProxy = new DAL.EF.ProductRepository(); var inventoryDataProxy = new DAL.EF.InventoryItemRepository(); var customerDataProxy = new DAL.EF.CustomerRepository(); var orderItemDataProxy = new DAL.EF.OrderItemRepository(); var orderRepository = new DAL.EF.OrderRepository(); var categoriesDataProxy = new DAL.EF.CategoryRepository(); _inventoryService = new InventoryItemService(inventoryDataProxy); _orderItemsService = new OrderItemService(orderItemDataProxy, productsDataProxy, inventoryDataProxy, new DTCTransactionContext()); _ordersService = new OrderService(orderRepository, _orderItemsService, new DTCTransactionContext()); _customersService = new CustomerService(customerDataProxy, _ordersService); _productsService = new ProductService(productsDataProxy, orderRepository, _inventoryService, new DTCTransactionContext()); _categoriesService = new CategoryService(categoriesDataProxy, productsDataProxy); this.DataContext = new MainWindowVM(_eventAggregator, _customersService, _productsService, _categoriesService, _ordersService, _inventoryService); }
public ServiceList(string url, ResponseToken token) { this.eventService = new EventService(url, token); this.categoryService = new CategoryService(url, token); this.clubService = new ClubService(url, token); this.userService = new UserService(url, token); this.ticketService = new TicketService(url, token); this.meetingService = new MeetingService(url, token); this.invoiceService = new InvoiceService(url, token); this.groupService = new GroupService(url, token); this.expenseService = new ExpenseService(url, token); this.emailService = new EmailService(url, token); this.depositService = new DepositService(url, token); this.customFieldService = new CustomFieldService(url, token); this.taskService = new TaskService(url, token); this.contactService = new ContactService(url, token); }
public MainWindowVM(EventAggregator eventAggregator, CustomerService customerService, ProductService productService, CategoryService categoryService, OrderService orderService, InventoryItemService inventoryService) { _customersVM = new CustomersVM(customerService); _customersVM.LoadCustomersCommand.Execute(null); _productsVM = new ProductsVM(productService, this); _productsVM.LoadProductsCommand.Execute(null); _categoriesVM = new CategoriesVM(categoryService); _categoriesVM.LoadCategoriesCommand.Execute(null); _ordersVM = new OrdersVM(orderService, this, eventAggregator); _ordersVM.LoadOrdersCommand.Execute(null); _inventoryItemsVM = new InventoryItemsVM(inventoryService, this); _inventoryItemsVM.LoadInventoryCommand.Execute(null); }
static void Main(string[] args) { ProductDbObject product1 = new ProductDbObject() { Category = new CategoryDbObject() { Name = "Pizza", PrimaryKey = new Guid() }, Name = "JakasTam", PrimaryKey = new Guid() }; CategoryDbObject PizzaCategory = new CategoryDbObject() { Name = "Pizza", PrimaryKey = new Guid() }; CategoryService catgeService = new CategoryService(new HtcEfDbContext()); catgeService.AddEntity(PizzaCategory); catgeService.SaveChange(); }
protected override IEnumerable<Navigation> GetDynamicNavigations(string presentAreaKey, long ownerId = 0) { List<Navigation> navigations = new List<Navigation>(); if (presentAreaKey != PresentAreaKeysOfBuiltIn.Channel) return navigations; CategoryService categoryService = new CategoryService(); IEnumerable<Category> categories = categoryService.GetRootCategories(TenantTypeIds.Instance().BlogThread(), ownerId); if (categories != null) { foreach (var category in categories) { string url = SiteUrls.Instance().BlogListByCategory(category.CategoryId.ToString()); int navigationId = NavigationService.GenerateDynamicNavigationId(category.CategoryId); Navigation navigation = new Navigation() { ApplicationId = ApplicationId, Depth = category.Depth + 1, NavigationId = navigationId, NavigationText = category.CategoryName, ParentNavigationId = 10100201, IsEnabled = true, NavigationTarget = "_self", NavigationUrl = url, PresentAreaKey = PresentAreaKeysOfBuiltIn.Channel, DisplayOrder = (int)category.DisplayOrder+90000000 }; navigations.Add(navigation); } } return navigations; }
public ActionResult Create(SnippetModel snippetModel) { if (!ModelState.IsValid) return View(snippetModel); var userService = new UserService(); var categoryService = new CategoryService(); var snippet = new Snippet(); snippet.BodyRaw = snippetModel.Snippet.BodyRaw; snippet.Body = new Markdown().Transform(snippetModel.Snippet.BodyRaw).ToSafeHtml(); snippet.DateCreated = DateTime.Now; snippet.DateEdited = DateTime.Now; snippet.Title = snippetModel.Snippet.Title; snippet.Slug = snippetModel.Snippet.Title.Slugify(); snippet.Author = userService.GetByUsername(User.Identity.Name); snippet.Category = categoryService.GetById(snippetModel.CategoryId.Value); _snippetService.Create(snippet); _snippetService.Save(); TempData["Message"] = "The snippet has been created. <a href=\"{0}\">View the snippet.</a>".FormatWith(snippet.Link); return RedirectToAction("Index"); }
/// <summary> /// 删除帖吧 /// </summary> /// <param name="sectionId">帖吧Id</param> public void Delete(long sectionId) { BarSection section = barSectionRepository.Get(sectionId); if (section == null) return; EventBus<BarSection>.Instance().OnBefore(section, new CommonEventArgs(EventOperationType.Instance().Delete())); //帖子 BarThreadService barThreadService = new BarThreadService(); barThreadService.DeletesBySectionId(sectionId); CategoryService categoryService = new CategoryService(); //帖吧分类 categoryService.ClearCategoriesFromItem(sectionId, null, TenantTypeIds.Instance().BarSection()); //帖子分类 var categories = categoryService.GetRootCategories(TenantTypeIds.Instance().BarThread(), sectionId); foreach (var category in categories) { categoryService.Delete(category.CategoryId); } //帖吧标签 TagService tagService = new TagService(TenantTypeIds.Instance().BarThread()); tagService.ClearTagsFromOwner(sectionId); //删除Logo DeleteLogo(sectionId); //删除推荐记录 RecommendService recommendService = new RecommendService(); recommendService.Delete(sectionId, TenantTypeIds.Instance().BarSection()); int affectCount = barSectionRepository.Delete(section); if (affectCount > 0) { EventBus<BarSection>.Instance().OnAfter(section, new CommonEventArgs(EventOperationType.Instance().Delete())); EventBus<BarSection, AuditEventArgs>.Instance().OnAfter(section, new AuditEventArgs(null, section.AuditStatus)); } }
/// <summary> /// 输出多用户选择器 /// </summary> /// <param name="htmlHelper">被扩展的htmlHelper</param> /// <param name="name">控件表单名</param> /// <param name="selectionLimit">限制选中的用户数</param> /// <param name="selectedUserIds">初始选中用户Id集合</param> /// <param name="searchScope">搜索范围</param> /// <param name="showDropDownMenu">是否显示下拉菜单</param> /// <param name="widthType">宽度</param> /// <param name="selectionAddedCallBack">添加成功事件回调方法</param> /// <remarks>仅限登录用户使用</remarks> /// <returns>MvcHtmlString</returns> public static MvcHtmlString UserSelector(this HtmlHelper htmlHelper, string name, int selectionLimit, IEnumerable<long> selectedUserIds = null, SelectorWidthType widthType = SelectorWidthType.Long, UserSelectorSearchScope searchScope = UserSelectorSearchScope.FollowedUser, bool showDropDownMenu = true, string selectionAddedCallBack = null) { if (selectedUserIds == null) selectedUserIds = new List<long>(); IUserService userService = DIContainer.Resolve<IUserService>(); var selectedUsers = userService.GetFullUsers(selectedUserIds) .Select(n => new { userId = n.UserId, displayName = n.DisplayName, trueName = n.TrueName, nickName = n.NickName, userAvatarUrl = SiteUrls.Instance().UserAvatarUrl(n, AvatarSizeType.Small) }); string followGroupsJSON = "[]"; if (showDropDownMenu) { var followGroups = new CategoryService().GetOwnerCategories(UserContext.CurrentUser.UserId, TenantTypeIds.Instance().User()).Select(n => new { name = n.CategoryName.Length > 15 ? n.CategoryName.Substring(0,15): n.CategoryName, value = n.CategoryId }); followGroupsJSON = Json.Encode(followGroups); } string widthClass = "tn-longer"; switch (widthType) { case SelectorWidthType.Short: widthClass = "tn-short"; break; case SelectorWidthType.Medium: widthClass = "tn-medium"; break; case SelectorWidthType.Long: widthClass = "tn-long"; break; case SelectorWidthType.Longer: widthClass = "tn-longer"; break; case SelectorWidthType.Longest: widthClass = "tn-longest"; break; default: widthClass = "tn-longer"; break; } htmlHelper.ViewData["controlName"] = name; htmlHelper.ViewData["widthClass"] = widthClass; htmlHelper.ViewData["selectionLimit"] = selectionLimit; htmlHelper.ViewData["searchScope"] = searchScope; htmlHelper.ViewData["showDropDownMenu"] = showDropDownMenu; htmlHelper.ViewData["selectionAddedCallBack"] = selectionAddedCallBack; return htmlHelper.EditorForModel("UserSelector", new { selectedUsers = Json.Encode(selectedUsers), followGroups = followGroupsJSON }); }
public void Setup() { repository = new Mock<IRepository<Category>>(); service = new CategoryService(repository.Object); }
public string GetMenu() { var cacheName = "MenuCatalog" + _selectedCategoryId; if (CacheManager.Contains(cacheName)) { return(CacheManager.Get <string>(cacheName)); } var result = new StringBuilder(); var rootCategories = CategoryService.GetChildCategoriesByCategoryIdForMenu(0).Where(cat => cat.Enabled).ToList(); for (int rootIndex = 0; rootIndex < rootCategories.Count; ++rootIndex) { //ѕункт в главном меню result.AppendFormat("<div class=\"{0}\"><div class=\"tree-item-inside\">", rootCategories[rootIndex].CategoryId == _selectedCategoryId ? "tree-item-selected" : "tree-item"); result.AppendFormat("<a href=\"{0}\" class=\"{1}\">{2}</a>", UrlService.GetLink(ParamType.Category, rootCategories[rootIndex].UrlPath, rootCategories[rootIndex].CategoryId), rootCategories[rootIndex].HasChild ? "tree-item-link tree-parent" : "tree-item-link", rootCategories[rootIndex].Name); if (rootCategories[rootIndex].HasChild) { //Ќачало подменю result.Append("<div class=\"tree-submenu\">\r\n"); var children = CategoryService.GetChildCategoriesByCategoryId(rootCategories[rootIndex].CategoryId, false).Where(cat => cat.Enabled).ToList(); if (rootCategories[rootIndex].DisplaySubCategoriesInMenu) { //раздел категорий result.Append("<div class=\"tree-submenu-category\">"); for (int i = 0; i < children.Count; ++i) { //колонка категорий result.Append("<div class=\"tree-submenu-column\">"); //1 уровень result.AppendFormat("<span class=\"title-column\"><a href=\"{0}\">{1}</a></span>", UrlService.GetLink(ParamType.Category, children[i].UrlPath, children[i].CategoryId), children[i].Name); result.AppendFormat("<div class=\"tree-submenu-children\">"); //2 уровень var subchildren = CategoryService.GetChildCategoriesByCategoryId(children[i].CategoryId, false).Where(cat => cat.Enabled).ToList(); for (int j = 0; j < subchildren.Count && j < 10; j++) { result.AppendFormat("<a href=\"{0}\">{1}</a>", UrlService.GetLink(ParamType.Category, subchildren[j].UrlPath, subchildren[j].CategoryId), subchildren[j].Name); } if (subchildren.Count > 10) { result.AppendFormat("<a href=\"{0}\">{1}</a>", UrlService.GetLink(ParamType.Category, children[i].UrlPath, children[i].CategoryId), Resources.Resource.Client_MasterPage_ViewMore); } result.AppendFormat("</div>"); // олонка категорий закрываетс¤ result.Append("</div>"); int columns = rootCategories[rootIndex].DisplayBrandsInMenu ? 4 : 5; if (i % columns == columns - 1) { result.Append("<br class=\"clear\" />"); } } //раздел категорий закрываетс¤ result.Append("</div>\r\n"); //раздел производителей if (rootCategories[rootIndex].DisplayBrandsInMenu) { var brands = BrandService.GetBrandsByCategoryID(rootCategories[rootIndex].CategoryId, true); if (brands.Count > 0) { result.Append("<div class=\"tree-submenu-brand\">"); result.AppendFormat("<div class=\"title-column\">{0}</div>", Resources.Resource.Client_MasterPage_Brands); result.Append("<div class=\"tree-submenu-column\">"); foreach (Brand br in brands) { result.AppendFormat("<a href=\"{0}\">{1}</a>", UrlService.GetLink(ParamType.Brand, br.UrlPath, br.BrandId), br.Name); } result.AppendFormat("</div>"); result.AppendFormat("</div>"); } } } else { //раздел категорий result.Append("<div class=\"tree-submenu-category\">"); for (int i = 0; i < children.Count; ++i) { //колонка категорий if (i % ItemsPerCol == 0) { result.Append("<div class=\"tree-submenu-column\">"); } result.AppendFormat("<a href=\"{0}\">{1}</a>", UrlService.GetLink(ParamType.Category, children[i].UrlPath, children[i].CategoryId), children[i].Name); // олонка категорий закрываетс¤ if (i % ItemsPerCol == ItemsPerCol - 1 || i == children.Count - 1) { result.Append("</div>"); } } //раздел категорий закрываетс¤ result.Append("</div>\r\n"); //раздел производителей if (rootCategories[rootIndex].DisplayBrandsInMenu) { var brands = BrandService.GetBrandsByCategoryID(rootCategories[rootIndex].CategoryId, true); if (brands.Count > 0) { result.Append("<div class=\"tree-submenu-brand\">"); result.AppendFormat("<div class=\"title-column\">{0}</div>", Resources.Resource.Client_MasterPage_Brands); result.Append("<div class=\"tree-submenu-column\">"); foreach (Brand br in brands) { result.AppendFormat("<a href=\"{0}\">{1}</a>", UrlService.GetLink(ParamType.Brand, br.UrlPath, br.BrandId), br.Name); } result.AppendFormat("</div>"); result.AppendFormat("</div>"); } } } //ѕодменю закрываетс¤ result.AppendFormat("</div>"); } //ѕункт в главном меню закрываетс¤ result.AppendFormat("</div></div>"); //spliter if (rootIndex != rootCategories.Count - 1) { result.AppendFormat("<div class=\"tree-item-split\"></div>"); } } var resultString = result.ToString(); CacheManager.Insert <string>(cacheName, resultString); return(resultString); }
protected void Page_Load(object sender, EventArgs e) { if (ProductId == 0) { Error404(); return; } //if not have category if (ProductService.GetCountOfCategoriesByProductId(ProductId) == 0) { Error404(); return; } // --- Check product exist ------------------------ CurrentProduct = ProductService.GetProduct(ProductId); if (CurrentProduct == null || CurrentProduct.Enabled == false || CurrentProduct.HirecalEnabled == false)//CategoryService.IsEnabledParentCategories(_product.CategoryID) == false) { Error404(); return; } BuyInOneClick.Visible = SettingsOrderConfirmation.BuyInOneClick; BuyInOneClick.ProductId = CurrentProduct.ProductId; BuyInOneClick.SelectedOptions = productCustomOptions.SelectedOptions; BuyInOneClick.CustomOptions = productCustomOptions.CustomOptions; if (CurrentProduct.Amount <= 0 || CurrentProduct.Price == 0) { divAmount.Visible = false; } CompareControl.Visible = SettingsCatalog.EnableCompareProducts; CompareControl.ProductId = ProductId; CompareControl.IsSelected = ShoppingCartService.CurrentCompare.Any(p => p.EntityId == ProductId); divUnit.Visible = CurrentProduct.Offers[0].Unit.IsNotEmpty(); sbShareButtons.Visible = SettingsDesign.EnableSocialShareButtons; rating.ProductId = CurrentProduct.ID; rating.Rating = CurrentProduct.Ratio; rating.ShowRating = SettingsCatalog.EnableProductRating; rating.ReadOnly = RatingService.DoesUserVote(ProductId, CustomerSession.CustomerId); pnlWishlist.Visible = SettingsDesign.WishListVisibility; pnlSize.Visible = !string.IsNullOrEmpty(CurrentProduct.Size) && (CurrentProduct.Size != "0|0|0"); //lblSize.Text = !string.IsNullOrEmpty(_product.Size) ? _product.Size.Replace("|", "x") : string.Empty; pnlWeight.Visible = CurrentProduct.Weight != 0; //lblWeight.Text = _product.Weight.ToString(); pnlBrand.Visible = CurrentProduct.Brand != null; //Commented by Evgeni //productPropertiesView.ProductId = ProductId; //productPropertiesSetView.ProductId = ProductId; //productPropertiesAddedValueView.ProductId = ProductId; //ProductVideoView.ProductID = ProductId; //Need to pass to user control List of all product properties and in each set to divide this list into categories List <PropertyValue> productProperties = PropertyService.GetPropertyValuesByProductId(ProductId); productPropertiesView.ProductProperties = productProperties; productPropertiesSetView.ProductProperties = productProperties; productPropertiesSetView.ProductId = ProductId; productPropertiesSetView.ManufacteruArtNo = CurrentProduct.ManufactureArtNo; if (productProperties == null) { productPropertiesAddedValueView.ProductProperties = new List <PropertyValue>(); } else { productPropertiesAddedValueView.ProductProperties = productProperties; } //Added by Evgeni for Stihl Viking if (CurrentProduct.Brand == null) { } else if ((CurrentProduct.Brand.Name.ToLower() == "stihl") || (CurrentProduct.Brand.Name.ToLower() == "viking")) { productPropertiesAddedValueView.ProductId = ProductId; } else { productPropertiesAddedValueView.ProductId = 0; } ProductVideoView.ProductID = ProductId; //Added By Evgeni to change long description into user friendly mode if ((CustomerSession.CurrentCustomer.CustomerGroup.GroupName == "Оптовик") || CustomerSession.CurrentCustomer.IsAdmin) { if (CurrentProduct.Offers.Where(t => t.OfferListId == 16).ToList().Count > 0 && CurrentProduct.Offers.Where(t => t.OfferListId == 16).FirstOrDefault().Price > 0) { lblSinglePriceTextForOptUser.Text = @"<font size='3'> Розничная цена: </font> <br />"; lblOptPrice.Text = string.Format("<font size='3'> Минимальная оптовая цена в евро: </font> <br /> <div class='price'> {0} € </div>", CurrentProduct.Offers.Where(t => t.OfferListId == 16).FirstOrDefault().Price.ToString("F2")); } } DescriptionModificator(); ////////////////////////////////////////////////////////// productPhotoView.Product = CurrentProduct; relatedProducts.ProductIds.Add(ProductId); alternativeProducts.ProductIds.Add(ProductId); //Added By Evgeni for Bosch Related Products relatedBoschProducts.ProductIds.Add(ProductId); // breadCrumbs.Items = CategoryService.GetParentCategories(CurrentProduct.CategoryID).Reverse().Select(cat => new BreadCrumbs() { Name = cat.Name, Url = UrlService.GetLink(ParamType.Category, cat.UrlPath, cat.ID) }).ToList(); breadCrumbs.Items.Insert(0, new BreadCrumbs() { Name = Resource.Client_MasterPage_MainPage, Url = UrlService.GetAbsoluteLink("/") }); breadCrumbs.Items.Add(new BreadCrumbs { Name = CurrentProduct.Name, Url = null }); RecentlyViewService.SetRecentlyView(CustomerSession.CustomerId, ProductId); if ((!IsPostBack) && (IsEditItem)) { if (!IsCorrectItemType) { Redirect(UrlService.GetLink(ParamType.Product, CurrentProduct.UrlPath, ProductId)); return; } switch (ItemType) { case ShoppingCartType.ShoppingCart: //txtAmount.Text = ShoppingCartService.CurrentShoppingCart[ItemIndex].Amount.ToString(); break; case ShoppingCartType.Wishlist: //txtAmount.Text = "1"; break; } } SetMeta(CurrentProduct.Meta, CurrentProduct.Name); productReviews.EntityType = EntityType.Product; productReviews.EntityId = ProductId; ltrlRightColumnModules.Text = ModulesRenderer.RenderDetailsModulesToRightColumn(); int reviewsCount = SettingsCatalog.ModerateReviews ? ReviewService.GetCheckedReviewsCount(ProductId, EntityType.Product) : ReviewService.GetReviewsCount(ProductId, EntityType.Product); if (reviewsCount > 0) { lReviewsCount.Text = string.Format("({0})", reviewsCount); } }
/// <summary> /// Gets the categorized tree items. This supports various options /// for filtering and determine how much data to load. /// </summary> /// <param name="options">The options that describe the request.</param> /// <returns>A list of view models that describe the tree of categories and items.</returns> public List <TreeItemViewModel> GetCategorizedTreeItems(CategoryItemTreeOptions options = null) { options = options ?? DefaultCategoryItemTreeOptions; // Initialize the basic query. var categoryService = new CategoryService(RockContext); var childQueryOptions = new ChildCategoryQueryOptions { ParentGuid = options.ParentGuid, EntityTypeGuid = options.EntityTypeGuid, IncludeCategoryGuids = options.IncludeCategoryGuids, ExcludeCategoryGuids = options.ExcludeCategoryGuids, EntityTypeQualifierColumn = options.EntityTypeQualifierColumn, EntityTypeQualifierValue = options.EntityTypeQualifierValue }; var qry = categoryService.GetChildCategoryQuery(childQueryOptions); // Cache the service instance for later use. If we have specified an // entity type then this ends up getting set. IService serviceInstance = null; var cachedEntityType = options.EntityTypeGuid.HasValue ? EntityTypeCache.Get(options.EntityTypeGuid.Value) : null; // If we have been requested to limit the results to a specific entity // type then apply those filters. if (cachedEntityType != null) { // Attempt to initialize the entity service instance. This also // checks if the entity supports the active flag. if (cachedEntityType.AssemblyName != null) { Type entityType = cachedEntityType.GetEntityType(); if (entityType != null) { Type[] modelType = { entityType }; Type genericServiceType = typeof(Rock.Data.Service <>); Type modelServiceType = genericServiceType.MakeGenericType(modelType); serviceInstance = Activator.CreateInstance(modelServiceType, new object[] { new RockContext() }) as IService; } } } var categoryList = qry.OrderBy(c => c.Order).ThenBy(c => c.Name).ToList(); // Get all the categories from the query and then filter on security. var categoryItemList = categoryList .Where(c => c.IsAuthorized(Authorization.VIEW, Person)) .Select(c => new TreeItemViewModel { Value = c.Guid.ToString(), Text = c.Name, IsFolder = true, IconCssClass = c.IconCssClass }) .ToList(); if (options.GetCategorizedItems) { var itemOptions = new CategorizedItemQueryOptions { CategoryGuid = options.ParentGuid, IncludeInactiveItems = options.IncludeInactiveItems, IncludeUnnamedEntityItems = options.IncludeUnnamedEntityItems, ItemFilterPropertyName = options.ItemFilterPropertyName, ItemFilterPropertyValue = options.ItemFilterPropertyValue }; var itemsQry = categoryService.GetCategorizedItemQuery(serviceInstance, itemOptions); if (itemsQry != null) { var childItems = GetChildrenItems(options, cachedEntityType, itemsQry); categoryItemList.AddRange(childItems); } } if (options.LazyLoad) { // Try to figure out which items have viewable children in // the existing list and set them appropriately. foreach (var categoryItemListItem in categoryItemList) { if (categoryItemListItem.IsFolder) { categoryItemListItem.HasChildren = DoesCategoryHaveChildren(options, categoryService, serviceInstance, categoryItemListItem.Value); } } } else { foreach (var item in categoryItemList) { var parentGuid = item.Value.AsGuidOrNull(); if (item.Children == null) { item.Children = new List <TreeItemViewModel>(); } GetAllDescendants(item, Person, categoryService, serviceInstance, cachedEntityType, options); } } // If they don't want empty categories then filter out categories // that do not have child items. if (!options.IncludeCategoriesWithoutChildren) { categoryItemList = categoryItemList .Where(a => !a.IsFolder || (a.IsFolder && a.HasChildren)) .ToList(); } return(categoryItemList); }
private void ProcessProductRow(ExportFeedProduts row, StreamWriter memoryBuffer) { memoryBuffer.Write(row.ProductID.ToString()); memoryBuffer.Write("\t"); memoryBuffer.Write(row.Name); memoryBuffer.Write("\t"); string desc = _description == "full" ? row.Description : row.BriefDescription; memoryBuffer.Write(!string.IsNullOrEmpty(desc) ? desc : Resource.ExportFeed_NoDescription); memoryBuffer.Write("\t"); var nfi = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone(); nfi.NumberDecimalSeparator = "."; memoryBuffer.Write(CatalogService.CalculatePrice(row.Price, row.Discount).ToString(nfi)); memoryBuffer.Write("\t"); memoryBuffer.Write(SettingsGeneral.AbsoluteUrl.TrimEnd('/') + "/" + UrlService.GetLink(ParamType.Product, row.UrlPath, row.ProductID)); memoryBuffer.Write("\t"); var categorizationBuffer = new StringBuilder(); Category category = CategoryService.GetCategory(row.ParentCategory); categorizationBuffer.Insert(0, category.Name); while (category.ParentCategoryId != 0) { category = CategoryService.GetCategory(category.ParentCategoryId); categorizationBuffer.Insert(0, category.Name + " >> "); } memoryBuffer.Write(categorizationBuffer.ToString()); memoryBuffer.Write("\t"); memoryBuffer.Write("None"); memoryBuffer.Write("\t"); var temp = row.Photo; if (!string.IsNullOrEmpty(temp)) { memoryBuffer.Write(GetImageProductPath(row.Photo)); } memoryBuffer.Write("\t"); memoryBuffer.Write("\t"); memoryBuffer.Write("\t"); memoryBuffer.Write("\t"); memoryBuffer.Write(row.Price.ToString(nfi)); memoryBuffer.Write("\t"); //memoryBuffer.Write(SQLDataHelper.GetBoolean(row["Enabled"])); //memoryBuffer.Write("\t"); //memoryBuffer.Write(SQLDataHelper.GetDecimal(row["ShippingPrice"]).ToString(nfi)); //memoryBuffer.Write("\t"); //memoryBuffer.Write(SQLDataHelper.GetDecimal(row["Weight"])); //memoryBuffer.Write("\n"); }
/// <summary> /// Binds the comments grid. /// </summary> private void BindCommentsGrid() { var rockContext = new RockContext(); var noteTypeService = new NoteTypeService(rockContext); var noteType = noteTypeService.Get(Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid()); var noteService = new NoteService(rockContext); var prayerComments = noteService.GetByNoteTypeId(noteType.Id); SortProperty sortProperty = gPrayerComments.SortProperty; // Filter by Category. First see if there is a Block Setting, otherwise use the Grid Filter CategoryCache categoryFilter = null; var blockCategoryGuid = GetAttributeValue("PrayerRequestCategory").AsGuidOrNull(); if (blockCategoryGuid.HasValue) { categoryFilter = CategoryCache.Read(blockCategoryGuid.Value); } if (categoryFilter == null && catpPrayerCategoryFilter.Visible) { int?filterCategoryId = catpPrayerCategoryFilter.SelectedValue.AsIntegerOrNull(); if (filterCategoryId.HasValue) { categoryFilter = CategoryCache.Read(filterCategoryId.Value); } } if (categoryFilter != null) { // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories var categoryService = new CategoryService(rockContext); var categories = new CategoryService(rockContext).GetAllDescendents(categoryFilter.Guid).Select(a => a.Id).ToList(); var prayerRequestQry = new PrayerRequestService(rockContext).Queryable().Where(a => a.CategoryId.HasValue && (a.Category.Guid == categoryFilter.Guid || categories.Contains(a.CategoryId.Value))) .Select(a => a.Id); prayerComments = prayerComments.Where(a => a.EntityId.HasValue && prayerRequestQry.Contains(a.EntityId.Value)); } // Filter by Date Range if (drpDateRange.LowerValue.HasValue) { DateTime startDate = drpDateRange.LowerValue.Value.Date; prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate); } if (drpDateRange.UpperValue.HasValue) { // Add one day in order to include everything up to the end of the selected datetime. var endDate = drpDateRange.UpperValue.Value.AddDays(1); prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate); } // Sort by the given property otherwise sort by the EnteredDate if (sortProperty != null) { gPrayerComments.DataSource = prayerComments.Sort(sortProperty).ToList(); } else { gPrayerComments.DataSource = prayerComments.OrderByDescending(n => n.CreatedDateTime).ToList(); } gPrayerComments.DataBind(); }
/// <summary> /// Gets all both category and non-category item decendents for the provided categoryItem. /// This method updates the provided categoryItem. /// </summary> /// <param name="categoryItem">The category item.</param> /// <param name="currentPerson">The current person.</param> /// <param name="categoryService">The category service.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="cachedEntityType">The cached entity type of the items.</param> /// <param name="options">The options that describe the current operation.</param> /// <returns></returns> private TreeItemViewModel GetAllDescendants(TreeItemViewModel categoryItem, Person currentPerson, CategoryService categoryService, IService serviceInstance, EntityTypeCache cachedEntityType, CategoryItemTreeOptions options) { if (categoryItem.IsFolder) { var parentGuid = categoryItem.Value.AsGuidOrNull(); var childCategories = categoryService.Queryable() .AsNoTracking() .Where(c => c.ParentCategory.Guid == parentGuid) .OrderBy(c => c.Order) .ThenBy(c => c.Name); foreach (var childCategory in childCategories) { if (childCategory.IsAuthorized(Authorization.VIEW, currentPerson)) { // This category has child categories that the person can view so add them to categoryItemList categoryItem.HasChildren = true; var childCategoryItem = new TreeItemViewModel { Value = childCategory.Guid.ToString(), Text = childCategory.Name, IsFolder = true, IconCssClass = childCategory.GetPropertyValue("IconCssClass") as string ?? options.DefaultIconCssClass }; if (childCategory is IHasActiveFlag activatedItem) { childCategoryItem.IsActive = activatedItem.IsActive; } var childCategorizedItemBranch = GetAllDescendants(childCategoryItem, currentPerson, categoryService, serviceInstance, cachedEntityType, options); if (categoryItem.Children == null) { categoryItem.Children = new List <TreeItemViewModel>(); } categoryItem.Children.Add(childCategorizedItemBranch); } } // now that we have taken care of the child categories get the items for this category. if (options.GetCategorizedItems) { var itemOptions = new CategorizedItemQueryOptions { CategoryGuid = parentGuid, IncludeInactiveItems = options.IncludeInactiveItems, IncludeUnnamedEntityItems = options.IncludeUnnamedEntityItems, ItemFilterPropertyName = options.ItemFilterPropertyName, ItemFilterPropertyValue = options.ItemFilterPropertyValue }; var childQry = categoryService.GetCategorizedItemQuery(serviceInstance, itemOptions); if (childQry != null) { var childItems = GetChildrenItems(options, cachedEntityType, childQry); categoryItem.Children = new List <TreeItemViewModel>(); categoryItem.Children.AddRange(childItems); categoryItem.HasChildren = childItems.Any(); } } } return(categoryItem); }
public HomeController() { _categoryService = new CategoryService(); }
public void Save(CategoryModel model) { StatusUpdate(StatusModel.Update("Saving")); CategoryService.Save(model); View.UpdateView(model); }
public MerchantCatalogController(MerchantCatalogService MerchantCatalogService, CategoryService CategoryService, MerchantCategoryService MerchantCategoryService) { _MerchantCatalogService = MerchantCatalogService; _CategoryService = CategoryService; _MerchantCategoryService = MerchantCategoryService; }
public CategoryController(CategoryService service, ResultService resultService) { _service = service; _resultService = resultService; }
public CategoryEditForm(Category category) { this.category = category; this.categoryService = new CategoryService(); InitializeComponent(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { BinaryFileType binaryFileType; var rockContext = new RockContext(); BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService(rockContext); AttributeService attributeService = new AttributeService(rockContext); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext); CategoryService categoryService = new CategoryService(rockContext); int binaryFileTypeId = int.Parse(hfBinaryFileTypeId.Value); if (binaryFileTypeId == 0) { binaryFileType = new BinaryFileType(); binaryFileTypeService.Add(binaryFileType); } else { binaryFileType = binaryFileTypeService.Get(binaryFileTypeId); } binaryFileType.Name = tbName.Text; binaryFileType.Description = tbDescription.Text; binaryFileType.IconCssClass = tbIconCssClass.Text; binaryFileType.AllowCaching = cbAllowCaching.Checked; binaryFileType.RequiresViewSecurity = cbRequiresViewSecurity.Checked; binaryFileType.MaxWidth = nbMaxWidth.Text.AsInteger(); binaryFileType.MaxHeight = nbMaxHeight.Text.AsInteger(); binaryFileType.PreferredFormat = ddlPreferredFormat.SelectedValueAsEnum <Format>(); binaryFileType.PreferredResolution = ddlPreferredResolution.SelectedValueAsEnum <Resolution>(); binaryFileType.PreferredColorDepth = ddlPreferredColorDepth.SelectedValueAsEnum <ColorDepth>(); binaryFileType.PreferredRequired = cbPreferredRequired.Checked; if (!string.IsNullOrWhiteSpace(cpStorageType.SelectedValue)) { var entityTypeService = new EntityTypeService(rockContext); var storageEntityType = entityTypeService.Get(new Guid(cpStorageType.SelectedValue)); if (storageEntityType != null) { binaryFileType.StorageEntityTypeId = storageEntityType.Id; } } binaryFileType.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFileType); if (!binaryFileType.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); // get it back to make sure we have a good Id for it for the Attributes binaryFileType = binaryFileTypeService.Get(binaryFileType.Guid); /* Take care of Binary File Attributes */ var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(BinaryFile)).Id; // delete BinaryFileAttributes that are no longer configured in the UI var attributes = attributeService.Get(entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString()); var selectedAttributeGuids = BinaryFileAttributesState.Select(a => a.Guid); foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid))) { Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr); } rockContext.SaveChanges(); // add/update the BinaryFileAttributes that are assigned in the UI foreach (var attributeState in BinaryFileAttributesState) { Rock.Attribute.Helper.SaveAttributeEdits(attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext); } // SaveAttributeValues for the BinaryFileType binaryFileType.SaveAttributeValues(rockContext); }); AttributeCache.FlushEntityAttributes(); NavigateToParentPage(); }
/// <summary> /// 取消关注后更新缓存 /// </summary> /// <param name="sender">关注实体</param> /// <param name="eventArgs">事件参数</param> void CancelFollowEventModule_After(FollowEntity sender, CommonEventArgs eventArgs) { if (eventArgs.EventOperationType == EventOperationType.Instance().Delete()) { CategoryService service = new CategoryService(); service.ClearCategoriesFromItem(sender.Id, sender.UserId, TenantTypeIds.Instance().User()); //更新用户缓存 ICacheService cacheService = DIContainer.Resolve<ICacheService>(); RealTimeCacheHelper realTimeCacheHelper = EntityData.ForType(typeof(User)).RealTimeCacheHelper; if (cacheService.EnableDistributedCache) { realTimeCacheHelper.IncreaseEntityCacheVersion(sender.UserId); } else { string cacheKey = realTimeCacheHelper.GetCacheKeyOfEntity(sender.UserId); User user = cacheService.Get<User>(cacheKey); if (user != null && user.FollowedCount > 0) { user.FollowedCount--; } } } }
public ProductsController(ApplicationDbContext context, CategoryService category, ILogger <ProductsController> logger) { _context = context; _category = category; _logger = logger; }
/// <summary> /// 转换成groupEntity类型 /// </summary> /// <returns></returns> public GroupEntity AsGroupEntity() { CategoryService categoryService = new CategoryService(); GroupEntity groupEntity = null; //创建群组 if (this.GroupId == 0) { groupEntity = GroupEntity.New(); groupEntity.UserId = UserContext.CurrentUser.UserId; groupEntity.DateCreated = DateTime.UtcNow; groupEntity.GroupKey = this.GroupKey; } //编辑群组 else { GroupService groupService = new GroupService(); groupEntity = groupService.Get(this.GroupId); } groupEntity.IsPublic = this.IsPublic; groupEntity.GroupName = this.GroupName; if (Logo != null) { groupEntity.Logo = this.Logo; } groupEntity.Description = Formatter.FormatMultiLinePlainTextForStorage(this.Description == null ? string.Empty : this.Description, true); groupEntity.AreaCode = this.AreaCode??string.Empty; groupEntity.JoinWay = this.JoinWay; groupEntity.EnableMemberInvite = this.EnableMemberInvite; groupEntity.IsDynamicPermission = this.IsDynamicPermission; if (JoinWay == JoinWay.ByQuestion) { groupEntity.Question = this.Question; groupEntity.Answer = this.Answer; } return groupEntity; }
private void ProcessCsv() { if (chboxDisableProducts.Checked) { ProductService.DisableAllProducts(); } long count = 0; using (var csv = new CsvHelper.CsvReader(new StreamReader(_fullPath, Encodings.GetEncoding()))) { csv.Configuration.Delimiter = Separators.GetCharSeparator(); csv.Configuration.HasHeaderRecord = _hasHeadrs; while (csv.Read()) { count++; } } ImportStatistic.TotalRow = count; using (var csv = new CsvHelper.CsvReader(new StreamReader(_fullPath, Encodings.GetEncoding()))) { csv.Configuration.Delimiter = Separators.GetCharSeparator(); csv.Configuration.HasHeaderRecord = _hasHeadrs; while (csv.Read()) { if (!ImportStatistic.IsRun) { csv.Dispose(); FileHelpers.DeleteFile(_fullPath); return; } try { //Added by Evgeni to Remove dots // csv.CurrentRecord[0] = csv.CurrentRecord[0].Replace(".", "").Replace(" ", ""); // Step by rows var productInStrings = new Dictionary <ProductFields.Fields, string>(); string nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Sku); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.Sku, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Name).Trim('*'); if (FieldMapping.ContainsKey(nameField)) { var name = Convert.ToString(csv[FieldMapping[nameField]]); if (!string.IsNullOrEmpty(name)) { productInStrings.Add(ProductFields.Fields.Name, name); } else { LogInvalidData(string.Format(Resource.Admin_ImportCsv_CanNotEmpty, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.Name), ImportStatistic.RowPosition + 2)); continue; } } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Enabled).Trim('*'); if (FieldMapping.ContainsKey(nameField)) { string enabled = Convert.ToString(csv[FieldMapping[nameField]]); productInStrings.Add(ProductFields.Fields.Enabled, enabled); //product.Enabled = !string.IsNullOrEmpty(enabled) && enabled.Trim().Equals("+"); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Discount); if (FieldMapping.ContainsKey(nameField)) { var discount = Convert.ToString(csv[FieldMapping[nameField]]); if (string.IsNullOrEmpty(discount)) { discount = "0"; } decimal tmp; if (decimal.TryParse(discount, out tmp)) { productInStrings.Add(ProductFields.Fields.Discount, tmp.ToString()); } else if (decimal.TryParse(discount, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp)) { productInStrings.Add(ProductFields.Fields.Discount, tmp.ToString()); } else { LogInvalidData(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.Discount), ImportStatistic.RowPosition + 2)); continue; } } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Weight); if (FieldMapping.ContainsKey(nameField)) { var weight = Convert.ToString(csv[FieldMapping[nameField]]); if (string.IsNullOrEmpty(weight)) { weight = "0"; } decimal tmp; if (decimal.TryParse(weight, out tmp)) { productInStrings.Add(ProductFields.Fields.Weight, tmp.ToString()); } else if (decimal.TryParse(weight, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp)) { productInStrings.Add(ProductFields.Fields.Weight, tmp.ToString()); } else { LogInvalidData(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.Weight), ImportStatistic.RowPosition + 2)); continue; } } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Size); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.Size, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.BriefDescription); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.BriefDescription, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Description); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.Description, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Price).Trim('*'); if (FieldMapping.ContainsKey(nameField)) { var price = Convert.ToString(csv[FieldMapping[nameField]]); if (string.IsNullOrEmpty(price)) { price = "0"; } decimal tmp; if (decimal.TryParse(price, out tmp)) { productInStrings.Add(ProductFields.Fields.Price, tmp.ToString()); } else if (decimal.TryParse(price, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp)) { productInStrings.Add(ProductFields.Fields.Price, tmp.ToString()); } else { LogInvalidData(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.Price), ImportStatistic.RowPosition + 2)); continue; } } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.PurchasePrice); if (FieldMapping.ContainsKey(nameField)) { var sypplyprice = Convert.ToString(csv[FieldMapping[nameField]]); if (string.IsNullOrEmpty(sypplyprice)) { sypplyprice = "0"; } decimal tmp; if (decimal.TryParse(sypplyprice, out tmp)) { productInStrings.Add(ProductFields.Fields.PurchasePrice, tmp.ToString()); } else if (decimal.TryParse(sypplyprice, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp)) { productInStrings.Add(ProductFields.Fields.PurchasePrice, tmp.ToString()); } else { LogInvalidData(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.PurchasePrice), ImportStatistic.RowPosition + 2)); continue; } } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.ShippingPrice); if (FieldMapping.ContainsKey(nameField)) { var shippingPrice = Convert.ToString(csv[FieldMapping[nameField]]); if (string.IsNullOrEmpty(shippingPrice)) { shippingPrice = "0"; } decimal tmp; if (decimal.TryParse(shippingPrice, out tmp)) { productInStrings.Add(ProductFields.Fields.ShippingPrice, tmp.ToString()); } else if (decimal.TryParse(shippingPrice, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp)) { productInStrings.Add(ProductFields.Fields.ShippingPrice, tmp.ToString()); } else { LogInvalidData(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.ShippingPrice), ImportStatistic.RowPosition + 2)); continue; } } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Amount); if (FieldMapping.ContainsKey(nameField)) { var amount = Convert.ToString(csv[FieldMapping[nameField]]); if (string.IsNullOrEmpty(amount)) { amount = "0"; } int tmp; if (int.TryParse(amount, out tmp)) { productInStrings.Add(ProductFields.Fields.Amount, amount); } else { LogInvalidData(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.Amount), ImportStatistic.RowPosition + 2)); continue; } } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Unit); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.Unit, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.ParamSynonym); if (FieldMapping.ContainsKey(nameField)) { string rewurl = Convert.ToString(csv[FieldMapping[nameField]]); productInStrings.Add(ProductFields.Fields.ParamSynonym, rewurl); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Title); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.Title, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.MetaKeywords); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.MetaKeywords, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.MetaDescription); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.MetaDescription, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Photos); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.Photos, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Markers); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.Markers, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Properties); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.Properties, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Producer); if (FieldMapping.ContainsKey(nameField)) { productInStrings.Add(ProductFields.Fields.Producer, Convert.ToString(csv[FieldMapping[nameField]])); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.OrderByRequest); if (FieldMapping.ContainsKey(nameField)) { string orderbyrequest = Convert.ToString(csv[FieldMapping[nameField]]); productInStrings.Add(ProductFields.Fields.OrderByRequest, orderbyrequest); } nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Category).Trim('*'); if (FieldMapping.ContainsKey(nameField)) { var parentCategory = Convert.ToString(csv[FieldMapping[nameField]]); if (!string.IsNullOrEmpty(parentCategory)) { productInStrings.Add(ProductFields.Fields.Category, parentCategory); } } ImportProduct.UpdateInsertProduct(productInStrings); } catch (Exception ex) { MsgErr(ex.Message + " at csv"); Debug.LogError(ex); } } CategoryService.RecalculateProductsCountManual(); } ImportStatistic.IsRun = false; LuceneSearch.CreateAllIndexInBackground(); CacheManager.Clean(); FileHelpers.DeleteFilesFromImageTempInBackground(); FileHelpers.DeleteFile(_fullPath); }
/// <summary> /// 根据帖吧搜索查询条件构建Lucene查询条件 /// </summary> /// <param name="Query">搜索条件</param> /// <param name="interestGroup">是否是查询可能感兴趣的群组</param> /// <returns></returns> private LuceneSearchBuilder BuildLuceneSearchBuilder(GroupFullTextQuery groupQuery, bool interestGroup = false) { LuceneSearchBuilder searchBuilder = new LuceneSearchBuilder(); Dictionary<string, BoostLevel> fieldNameAndBoosts = new Dictionary<string, BoostLevel>(); //关键字为空就是在搜地区时关键字为空 if (groupQuery.KeywordIsNull) { if (!string.IsNullOrEmpty(groupQuery.NowAreaCode)) searchBuilder.WithField(GroupIndexDocument.AreaCode, groupQuery.NowAreaCode.TrimEnd('0'), false, BoostLevel.Hight, false); else searchBuilder.WithFields(GroupIndexDocument.AreaCode, new string[] { "1", "2", "3" }, false, BoostLevel.Hight, false); } if (!string.IsNullOrEmpty(groupQuery.Keyword)) { //范围 switch (groupQuery.Range) { case GroupSearchRange.GROUPNAME: searchBuilder.WithPhrase(GroupIndexDocument.GroupName, groupQuery.Keyword, BoostLevel.Hight, false); break; case GroupSearchRange.DESCRIPTION: searchBuilder.WithPhrase(GroupIndexDocument.Description, groupQuery.Keyword, BoostLevel.Hight, false); break; case GroupSearchRange.TAG: searchBuilder.WithPhrase(GroupIndexDocument.Tag, groupQuery.Keyword, BoostLevel.Hight, false); break; case GroupSearchRange.CATEGORYNAME: searchBuilder.WithPhrase(GroupIndexDocument.CategoryName, groupQuery.Keyword, BoostLevel.Hight, false); break; default: fieldNameAndBoosts.Add(GroupIndexDocument.GroupName, BoostLevel.Hight); fieldNameAndBoosts.Add(GroupIndexDocument.Description, BoostLevel.Medium); fieldNameAndBoosts.Add(GroupIndexDocument.Tag, BoostLevel.Medium); fieldNameAndBoosts.Add(GroupIndexDocument.CategoryName, BoostLevel.Medium); searchBuilder.WithPhrases(fieldNameAndBoosts, groupQuery.Keyword, BooleanClause.Occur.SHOULD, false); break; } } //根据标签搜索可能感兴趣的群组 if (interestGroup) { searchBuilder.WithPhrases(GroupIndexDocument.Tag, groupQuery.Tags, BoostLevel.Hight, false); searchBuilder.NotWithFields(GroupIndexDocument.GroupId, groupQuery.GroupIds); } //筛选 //某地区 if (!string.IsNullOrEmpty(groupQuery.NowAreaCode)) { searchBuilder.WithField(GroupIndexDocument.AreaCode, groupQuery.NowAreaCode.TrimEnd('0'), false, BoostLevel.Hight, true); } //某分类 if (groupQuery.CategoryId != 0) { //fixed by wanf:发现群组已经不再用全文检索了 CategoryService categoryService = new CategoryService(); IEnumerable<Category> categories = categoryService.GetDescendants(groupQuery.CategoryId); List<string> categoryIds = new List<string> { groupQuery.CategoryId.ToString() }; if (categories != null && categories.Count() > 0) { categoryIds.AddRange(categories.Select(n => n.CategoryId.ToString())); } searchBuilder.WithFields(GroupIndexDocument.CategoryId, categoryIds, true, BoostLevel.Hight, true); } //公开的群组 searchBuilder.WithField(GroupIndexDocument.IsPublic, "1", true, BoostLevel.Hight, true); //过滤可以显示的群组 switch (publiclyAuditStatus) { case PubliclyAuditStatus.Again: case PubliclyAuditStatus.Fail: case PubliclyAuditStatus.Pending: case PubliclyAuditStatus.Success: searchBuilder.WithField(GroupIndexDocument.AuditStatus, ((int)publiclyAuditStatus).ToString(), true, BoostLevel.Hight, true); break; case PubliclyAuditStatus.Again_GreaterThanOrEqual: case PubliclyAuditStatus.Pending_GreaterThanOrEqual: searchBuilder.WithinRange(GroupIndexDocument.AuditStatus, ((int)publiclyAuditStatus).ToString(), ((int)PubliclyAuditStatus.Success).ToString(), true); break; } if (groupQuery.sortBy.HasValue) { switch (groupQuery.sortBy.Value) { case SortBy_Group.DateCreated_Desc: searchBuilder.SortByString(GroupIndexDocument.DateCreated, true); break; case SortBy_Group.MemberCount_Desc: searchBuilder.SortByString(GroupIndexDocument.MemberCount, true); break; case SortBy_Group.GrowthValue_Desc: searchBuilder.SortByString(GroupIndexDocument.GrowthValue, true); break; } } else { //时间倒序排序 searchBuilder.SortByString(GroupIndexDocument.DateCreated, true); } return searchBuilder; }
public CategoriesController() { ToBuyContext context = new ToBuyContext(); cs = new CategoryService(context); }
public override sealed CategoriesModel GetModel() { return(CategoryService.GetModel()); }
// GET: Admin/Product public ProductController() { _categoryService = new CategoryService(); _productService = new ProductService(); }
public ProductController() { _productService = new ProductService(); _categoryService = new CategoryService(); _supplierService = new SupplierService(); }
/// <summary> /// 删除群组 /// </summary> /// <param name="groupId">群组Id</param> public void Delete(long groupId) { //设计要点 //1、需要删除:群组成员、群组申请、Logo; GroupEntity group = groupRepository.Get(groupId); if (group == null) return; CategoryService categoryService = new CategoryService(); categoryService.ClearCategoriesFromItem(groupId, null, TenantTypeIds.Instance().Group()); EventBus<GroupEntity>.Instance().OnBefore(group, new CommonEventArgs(EventOperationType.Instance().Delete())); int affectCount = groupRepository.Delete(group); if (affectCount > 0) { //删除访客记录 new VisitService(TenantTypeIds.Instance().Group()).CleanByToObjectId(groupId); //用户的创建群组数-1 OwnerDataService ownerDataService = new OwnerDataService(TenantTypeIds.Instance().User()); ownerDataService.Change(group.UserId, OwnerDataKeys.Instance().CreatedGroupCount(), -1); //删除Logo LogoService logoService = new LogoService(TenantTypeIds.Instance().Group()); logoService.DeleteLogo(groupId); //删除群组下的成员 DeleteMembersByGroupId(groupId); EventBus<GroupEntity>.Instance().OnAfter(group, new CommonEventArgs(EventOperationType.Instance().Delete())); EventBus<GroupEntity, AuditEventArgs>.Instance().OnAfter(group, new AuditEventArgs(group.AuditStatus, null)); } }
public CategoryManipulatorTest() { _uof = new Mock <IUnitOfWork>(); _mapper = new Mock <IMapper>(); _manipulator = new CategoryService(_uof.Object, _mapper.Object); }
public ActionResult _PrivacySpecifyObjectSelector(long userId, string itemName, string selectUserIds, string selectUserGroupIds) { //Dictionary<int, IEnumerable<UserPrivacySpecifyObject>> userPrivacySpecifyObjects = new PrivacyService().GetUserPrivacySpecifyObjects(userId, itemKey); Dictionary<int, IEnumerable<long>> userPrivacySpecifyObjectIds = new Dictionary<int, IEnumerable<long>>(); //if (!string.IsNullOrEmpty(selectUserIds) || !string.IsNullOrEmpty(selectUserGroupIds)) //{ if (!string.IsNullOrEmpty(selectUserIds)) { List<long> privacySpecifyUserIds = new List<long>(); string[] userIds = selectUserIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in userIds) { long Id = 0; if (long.TryParse(item, out Id)) privacySpecifyUserIds.Add(Id); } userPrivacySpecifyObjectIds.Add(SpecifyObjectTypeIds.Instance().User(), privacySpecifyUserIds); } if (!string.IsNullOrEmpty(selectUserGroupIds)) { List<long> privacySpecifyUserGroupIds = new List<long>(); string[] userGroupIds = selectUserGroupIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in userGroupIds) { long Id = 0; if (long.TryParse(item, out Id)) privacySpecifyUserGroupIds.Add(Id); } userPrivacySpecifyObjectIds.Add(SpecifyObjectTypeIds.Instance().UserGroup(), privacySpecifyUserGroupIds); } //} //else //{ // foreach (var userPrivacySpecifyObject in userPrivacySpecifyObjects) // { // List<long> ids = new List<long>(); // foreach (var item in userPrivacySpecifyObject.Value) // ids.Add(item.SpecifyObjectId); // userPrivacySpecifyObjectIds.Add(userPrivacySpecifyObject.Key, ids); // } //} ViewData["specifyUserMaxCount"] = privacySettingsManager.Get().SpecifyUserMaxCount; ViewData["userPrivacySpecifyObjects"] = userPrivacySpecifyObjectIds; ViewData["categories"] = new CategoryService().GetOwnerCategories(userId, TenantTypeIds.Instance().User()); ViewData["userId"] = userId; ViewData["itemName"] = itemName; return View(); }
public CategoryManagementController(CategoryService service) { _service = service; }
/// <summary> /// 获取页面视图模型 /// </summary> /// <param name="page"></param> /// <param name="size"></param> /// <param name="orderBy"></param> /// <param name="user"></param> /// <returns></returns> private IndexPageViewModel GetIndexPageViewModel(int page, int size, OrderBy?orderBy, UserInfoOutputDto user) { IQueryable <PostOutputDto> postsQuery = PostService.GetQuery <PostOutputDto>(p => (p.Status == Status.Pended || user.IsAdmin)); //准备文章的查询 var notices = NoticeService.GetPagesFromCache <DateTime, NoticeOutputDto>(1, 5, out int _, n => (n.Status == Status.Display || user.IsAdmin), n => n.ModifyDate, false).ToList(); //加载前5条公告 var cats = CategoryService.GetQueryFromCache <string, CategoryOutputDto>(c => c.Status == Status.Available, c => c.Name).ToList(); //加载分类目录 var hotSearches = RedisHelper.Get <List <KeywordsRankOutputDto> >("SearchRank:Week").Take(10).ToList(); //热词统计 Expression <Func <PostOutputDto, double> > order = p => p.TotalViewCount; switch (new Random().Next() % 3) { case 1: order = p => p.VoteUpCount; break; case 2: order = p => p.AverageViewCount; break; } var hot6Post = postsQuery.OrderByDescending(order).Skip(0).Take(5).Cacheable().ToList(); //热门文章 var newdic = new Dictionary <string, int>(); //标签云最终结果 var tagdic = postsQuery.Where(p => !string.IsNullOrEmpty(p.Label)).Select(p => p.Label).Cacheable().SelectMany(s => s.Split(',', ',')).GroupBy(s => s).ToDictionary(g => g.Key, g => g.Count()); //统计标签 if (tagdic.Any()) { int min = tagdic.Values.Min(); tagdic.ForEach(kv => { var fontsize = (int)Math.Floor(kv.Value * 1.0 / (min * 1.0) + 12.0); newdic.Add(kv.Key, fontsize >= 36 ? 36 : fontsize); }); } IList <PostOutputDto> posts; switch (orderBy) //文章排序 { case OrderBy.CommentCount: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.CommentCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.PostDate: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.PostDate).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.ViewCount: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.TotalViewCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.VoteCount: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.VoteUpCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.AverageViewCount: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.AverageViewCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; default: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.ModifyDate).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; } if (page == 1) { posts = postsQuery.Where(p => p.IsFixedTop).OrderByDescending(p => p.ModifyDate).AsEnumerable().Union(posts).ToList(); } return(new IndexPageViewModel() { Categories = cats, HotSearch = hotSearches, Notices = notices, Posts = posts, Tags = newdic, Top6Post = hot6Post, PostsQueryable = postsQuery }); }
public MeetingController() { service = new MeetingService(); service1 = new CategoryService(); }
public EstablishmentsController(FitcardContext fitcardContext, EstablishmentService establishmentService, StatusService statusService, UFService uFService, AddressService addressService, CategoryService categoryService, AccountService accountService, CityService cityService, ContactService contactService) { _FitcardContext = fitcardContext; _EstablishmentService = establishmentService; _StatusService = statusService; _UFService = uFService; _AddressService = addressService; _CategoryService = categoryService; _AccountService = accountService; _CityService = cityService; _ContactService = contactService; }
public CategoryController() { var model = new Model(); _categoryService = new CategoryService(model); }
/// <summary> /// Handles the Click event to save the prayer request. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (!IsValid()) { return; } bool isAutoApproved = GetAttributeValue("EnableAutoApprove").AsBoolean(); bool defaultAllowComments = GetAttributeValue("DefaultAllowCommentsSetting").AsBoolean(); bool isPersonMatchingEnabled = GetAttributeValue("EnablePersonMatching").AsBoolean(); PrayerRequest prayerRequest = new PrayerRequest { Id = 0, IsActive = true, IsApproved = isAutoApproved, AllowComments = defaultAllowComments }; var rockContext = new RockContext(); prayerRequest.EnteredDateTime = RockDateTime.Now; if (isAutoApproved) { prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId; prayerRequest.ApprovedOnDateTime = RockDateTime.Now; var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays")); prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays); } // Now record all the bits... // Make sure the Category is hydrated so it's included for any Lava processing Category category; int? categoryId = bddlCategory.SelectedValueAsInt(); Guid defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid(); if (categoryId == null && !defaultCategoryGuid.IsEmpty()) { category = new CategoryService(rockContext).Get(defaultCategoryGuid); categoryId = category.Id; } else { category = new CategoryService(rockContext).Get(categoryId.Value); } prayerRequest.CategoryId = categoryId; prayerRequest.Category = category; var personContext = this.ContextEntity <Person>(); if (personContext == null) { Person person = null; if (isPersonMatchingEnabled) { var personService = new PersonService(new RockContext()); person = personService.FindPerson(new PersonService.PersonMatchQuery(tbFirstName.Text, tbLastName.Text, tbEmail.Text, pnbPhone.Number), false, true, false); if (person == null && (!string.IsNullOrWhiteSpace(tbEmail.Text) || !string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))) { var personRecordTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; var personStatusPending = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id; person = new Person(); person.IsSystem = false; person.RecordTypeValueId = personRecordTypeId; person.RecordStatusValueId = personStatusPending; person.FirstName = tbFirstName.Text; person.LastName = tbLastName.Text; person.Gender = Gender.Unknown; if (!string.IsNullOrWhiteSpace(tbEmail.Text)) { person.Email = tbEmail.Text; person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; } PersonService.SaveNewPerson(person, rockContext, cpCampus.SelectedCampusId); if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))) { var mobilePhoneType = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE)); var phoneNumber = new PhoneNumber { NumberTypeValueId = mobilePhoneType.Id }; phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode); phoneNumber.Number = PhoneNumber.CleanNumber(pnbPhone.Number); person.PhoneNumbers.Add(phoneNumber); } } } prayerRequest.FirstName = tbFirstName.Text; prayerRequest.LastName = tbLastName.Text; prayerRequest.Email = tbEmail.Text; if (person != null) { prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId; } else { prayerRequest.RequestedByPersonAliasId = CurrentPersonAliasId; } } else { prayerRequest.RequestedByPersonAliasId = personContext.PrimaryAliasId; prayerRequest.FirstName = string.IsNullOrEmpty(personContext.NickName) ? personContext.FirstName : personContext.NickName; prayerRequest.LastName = personContext.LastName; prayerRequest.Email = personContext.Email; } prayerRequest.CampusId = cpCampus.SelectedCampusId; prayerRequest.Text = dtbRequest.Text; if (this.EnableUrgentFlag) { prayerRequest.IsUrgent = cbIsUrgent.Checked; } else { prayerRequest.IsUrgent = false; } if (this.EnableCommentsFlag) { prayerRequest.AllowComments = cbAllowComments.Checked; } if (this.EnablePublicDisplayFlag) { prayerRequest.IsPublic = cbAllowPublicDisplay.Checked; } else { prayerRequest.IsPublic = this.DefaultToPublic; } if (!Page.IsValid) { return; } PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext); prayerRequestService.Add(prayerRequest); prayerRequest.LoadAttributes(rockContext); avcEditAttributes.GetEditValues(prayerRequest); if (!prayerRequest.IsValid) { // field controls render error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); prayerRequest.SaveAttributeValues(rockContext); }); StartWorkflow(prayerRequest, rockContext); bool isNavigateToParent = GetAttributeValue("NavigateToParentOnSave").AsBoolean(); if (isNavigateToParent) { NavigateToParentPage(); } else if (GetAttributeValue("RefreshPageOnSave").AsBoolean()) { NavigateToCurrentPage(this.PageParameters().Where(a => a.Value is string).ToDictionary(k => k.Key, v => v.Value.ToString())); } else { pnlForm.Visible = false; pnlReceipt.Visible = true; // Build success text that is Lava capable var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeFields.Add("PrayerRequest", prayerRequest); nbMessage.Text = GetAttributeValue("SaveSuccessText").ResolveMergeFields(mergeFields); // Resolve any dynamic url references string appRoot = ResolveRockUrl("~/"); string themeRoot = ResolveRockUrl("~~/"); nbMessage.Text = nbMessage.Text.Replace("~~/", themeRoot).Replace("~/", appRoot); } }
/// <summary> /// Binds the repeater. /// </summary> protected void BindRepeater() { if (this.CurrentPersonId == null) { return; } var rockContext = new RockContext(); var groupService = new GroupService(rockContext); var groupMemberService = new GroupMemberService(rockContext); var categoryService = new CategoryService(rockContext); int communicationListGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_COMMUNICATIONLIST.AsGuid()).Id; int?communicationListGroupTypeDefaultRoleId = GroupTypeCache.Get(communicationListGroupTypeId).DefaultGroupRoleId; // Get a list of syncs for the communication list groups where the default role is sync'd var groupSyncService = new GroupSyncService(rockContext); var commGroupSyncsForDefaultRole = groupSyncService .Queryable() .Where(a => a.Group.GroupTypeId == communicationListGroupTypeId && a.GroupTypeRoleId == communicationListGroupTypeDefaultRoleId) .Select(a => a.GroupId); // If the default role is being sync'd then don't show it, otherwise include it var communicationListQry = groupService .Queryable() .Where(a => a.GroupTypeId == communicationListGroupTypeId && !commGroupSyncsForDefaultRole.Contains(a.Id)); var categoryGuids = this.GetAttributeValue("CommunicationListCategories").SplitDelimitedValues().AsGuidList(); var communicationLists = communicationListQry.ToList(); var viewableCommunicationLists = new List <Group>(); foreach (var communicationList in communicationLists) { communicationList.LoadAttributes(rockContext); if (!categoryGuids.Any()) { // if no categories where specified, only show lists that the person has VIEW auth if (communicationList.IsAuthorized(Rock.Security.Authorization.VIEW, this.CurrentPerson)) { viewableCommunicationLists.Add(communicationList); } } else { Guid?categoryGuid = communicationList.GetAttributeValue("Category").AsGuidOrNull(); if (categoryGuid.HasValue && categoryGuids.Contains(categoryGuid.Value)) { viewableCommunicationLists.Add(communicationList); } } } viewableCommunicationLists = viewableCommunicationLists.OrderBy(a => { var name = a.GetAttributeValue("PublicName"); if (name.IsNullOrWhiteSpace()) { name = a.Name; } return(name); }).ToList(); var groupIds = viewableCommunicationLists.Select(a => a.Id).ToList(); var personId = this.CurrentPersonId.Value; showMediumPreference = this.GetAttributeValue("ShowMediumPreference").AsBoolean(); personCommunicationListsMember = new GroupMemberService(rockContext).Queryable() .Where(a => groupIds.Contains(a.GroupId) && a.PersonId == personId) .GroupBy(a => a.GroupId) .ToList().ToDictionary(k => k.Key, v => v.FirstOrDefault()); rptCommunicationLists.DataSource = viewableCommunicationLists; rptCommunicationLists.DataBind(); nbNoCommunicationLists.Visible = !viewableCommunicationLists.Any(); pnlCommunicationPreferences.Visible = viewableCommunicationLists.Any(); }
/// <summary> /// 转换成groupEntity类型 /// </summary> /// <returns></returns> public TopicEntity AsTopicEntity() { CategoryService categoryService = new CategoryService(); TopicEntity topicEntity = null; //创建专题 if (this.TopicId == 0) { topicEntity = TopicEntity.New(); topicEntity.UserId = UserContext.CurrentUser.UserId; topicEntity.DateCreated = DateTime.UtcNow; topicEntity.TopicKey = this.TopicKey; } //编辑专题 else { TopicService topicService = new TopicService(); topicEntity = topicService.Get(this.TopicId); } topicEntity.IsPublic = this.IsPublic; topicEntity.TopicName = this.TopicName; if (Logo != null) { topicEntity.Logo = this.Logo; } topicEntity.Description = Formatter.FormatMultiLinePlainTextForStorage(this.Description == null ? string.Empty : this.Description, true); topicEntity.AreaCode = this.AreaCode??string.Empty; topicEntity.JoinWay = this.JoinWay; topicEntity.EnableMemberInvite = this.EnableMemberInvite; //topickey 去掉空格,变为小写字母 topicEntity.TopicKey = this.TopicKey.ToLower().Replace(" ","-"); if (JoinWay == TopicJoinWay.ByQuestion) { topicEntity.Question = this.Question; topicEntity.Answer = this.Answer; } return topicEntity; }
public IndexModel(ILogger <IndexModel> logger, ArticleService _articleService, CategoryService _categoryService) { _logger = logger; articleService = _articleService; categoryService = _categoryService; }
/// <summary> /// 转换为Category用于数据库存储 /// </summary> public Category AsCategory() { Category category = null; if (CategoryId == 0) { category = Category.New(); } else { CategoryService categoryService = new CategoryService(); category = categoryService.Get(CategoryId); } category.Depth = Depth; category.CategoryName = CategoryName; category.Description = Formatter.FormatMultiLinePlainTextForStorage(Description, true) ?? string.Empty; category.ParentId = ParentId; category.OwnerId = OwnerId; category.TenantTypeId = TenantTypeId; category.LastModified = DateTime.UtcNow; return category; }
public CategoryImportService() { this.categoryService = new CategoryService(); this.categoryValidator = new CategoryValidator(categoryService); }
public override void Parse() { Income.Products = new List<Product>(); CategoryService categoryService = new CategoryService(); int addedCount = 0; int skippedCount = 0; bool skipCategoryPrinted = false; int usedRangeRows = ActiveWorksheet.UsedRange.Rows.Count; for (int i = FirstRow; i < usedRangeRows; i++) { if (i == 344) { } string quantityString = GetCellValue(i, QuantityColumn); int level = (int)GetOutlineLevel(i); // признак категории if (string.IsNullOrEmpty(quantityString) || level == 2) { categoryService.LastResult = CategoryService.CategoryChoiсeResult.Undefined; UpdateCategories(GetCellValue(i, 1), level); skipCategoryPrinted = false; continue; } string price = GetCellValue(i, PriceColumn); OnSetProgressBarValue(CalcProgressBarValue(i, usedRangeRows)); OnPrintStatus($"Обработка позиции {i} из {usedRangeRows}"); string originalName = _categoriesStack.Peek().CleanName; //CleanCategoriesStack(GetOutlineLevel(i)); string articul = GetCellValue(i, NameColumn).Trim(); if (string.IsNullOrEmpty(articul) || string.IsNullOrEmpty(originalName) || string.IsNullOrEmpty(price)) { OnPrintMessage($"Строка {i} пропущена. Одно из значений в строке нулевое"); skippedCount++; continue; } if (categoryService.LastResult == CategoryService.CategoryChoiсeResult.Undefined) categoryService.ParseCategory(_categoriesStack.ToList(), originalName); if (categoryService.LastResult == CategoryService.CategoryChoiсeResult.Ignore) { skippedCount++; if (skipCategoryPrinted == false) { OnPrintMessage($"Категорию '{GetCategoriesTree()}' пропускаем"); skipCategoryPrinted = true; } continue; } Brand brand = GetBrand(originalName); var remains = new List<Remain>(); if (!string.IsNullOrEmpty(quantityString)) { int quantity = 0; int.TryParse(quantityString, out quantity); if (quantity < 0) quantity = 0; remains.Add(new Remain() {Quantity = quantity, Size = GetCellValue(i, SizeColumn), Price = price}); // сбор всех размеров int nextLevel = (int)GetOutlineLevel(i+1); while (nextLevel == level) { i++; price = GetCellValue(i, PriceColumn); if (!string.IsNullOrEmpty(price)) { quantityString = GetCellValue(i, QuantityColumn); remains.Add(new Remain() { Quantity = quantity, Size = GetCellValue(i, SizeColumn), Price = price }); int.TryParse(quantityString, out quantity); if (quantity < 0) quantity = 0; } nextLevel = (int)GetOutlineLevel(i + 1); } } Product newProduct = new Product { Categories = categoryService.ChosenCategoryString, Articul = articul, Name = originalName, Brand = brand?.Name, Price = price, Remains = remains }; Income.Products.Add(newProduct); addedCount++; } OnPrintMessage($"Обработано успешно: {addedCount}; Пропущено: {skippedCount}"); }
public ActionResult PrepareEditByID(int ID, string GenCode) { var svProduct = new ProductService(); var svCategory = new CategoryService(); var svProductGroup = new ProductGroupService(); var svProductImage = new ProductImageService(); CommonService svCommon = new CommonService(); #region FindCateAll //var sqlwherein = ""; //switch (res.Common.lblWebsite) //{ // case "B2BThai": sqlwherein = " AND CategoryType IN (1,2)"; break; // case "AntCart": sqlwherein = " AND CategoryType IN (3)"; break; // case "myOtopThai": sqlwherein = " AND CategoryType IN (5)"; break; // case "AppstoreThai": sqlwherein = " AND CategoryType IN (6)"; break; // default: sqlwherein = ""; break; //} var sqlSelect = "CategoryID,CategoryName"; var sqlWhere = "CategoryLevel=1 AND RowFlag > 0 AND IsDelete=0"; var data1 = svCategory.GetCategoryByLevel(1); //var data2 = svCategory.GetCategoryByLevel(2); //var data3 = svCategory.GetCategoryByLevel(3); ViewBag.SelectCateLV1 = data1; //ViewBag.SelectCateLV2 = data2; //ViewBag.SelectCateLV3 = data3; #endregion ViewBag.QtyUnits = svCommon.SelectEnum(CommonService.EnumType.QtyUnits); #region Set Product Group var ProductGroups = svProductGroup.GetProductGroup(LogonCompID); if (ProductGroups.Count() > 0) { ViewBag.ProductGroups = ProductGroups; } else { ViewBag.ProductGroups = null; } #endregion var Product = svProduct.SelectData <b2bProduct>(" * ", "ProductID=" + ID + " And IsDelete=0", null, 1, 1).First(); ViewBag.Product = Product; sqlSelect = "ProductID,ProductImageID,ImgPath,ListNo"; sqlWhere = svProductImage.CreateWhereCause(ID); var Images = svProductImage.SelectData <b2bProductImage>(sqlSelect, sqlWhere, " ListNo ASC"); var countImg = 0; if (svProductImage.TotalRow > 0) { countImg = Images.Where(m => m.ImgPath == Product.ProductImgPath).Count(); } if (countImg == 0) { var img = new b2bProductImage(); img.ProductID = Product.ProductID; img.ListNo = 1; img.ImgPath = Product.ProductImgPath; img.ImgDetail = Product.ProductName; svProductImage.InsertProductImage(img); Images = svProductImage.SelectData <b2bProductImage>(sqlSelect, sqlWhere, " ListNo DESC"); } ViewBag.ProductImg = Images; ViewBag.ImgCount = Images.Count(); var data2 = new List <b2bCategory>(); var data3 = new List <b2bCategory>(); data2 = svCategory.LoadSubCategory(DataManager.ConvertToInteger(Product.CateLV1), 500, 2); data3 = svCategory.LoadSubCategory(DataManager.ConvertToInteger(Product.CateLV2), 500, 3); ViewBag.SelectCateLV2 = data2; ViewBag.SelectCateLV3 = data3; var a = svCategory.SearchCategoryByID((int)Product.CateLV3); //var a = svCategory.SelectData<b2bCategory>("*", "CategoryID = " + (int)Product.CateLV3, null, 1, 1,); ViewBag.Catename = a; ViewBag.ProductCode = GenCode; return(PartialView("UC/EditProduct")); }
// Games allways the same content ..must be loaded one time only public IList<Category> getGames(CometAsyncResult state) { CategoryService _categoryService = new CategoryService(); return _categoryService.GetAll(); }
public CategoryController(CategoryService categoryService, IOptions <WebStaticConfig> options) { this._categoryService = categoryService; this._webStaticConfig = options.Value; }