Summary description for CategoryInfo
Example #1
0
 public CateModel()
 {
     Category = new CategoryInfo();
     CateSelectItem = new List<SelectListItem>();
     CateType = new List<SelectListItem>();
     CateList = new List<CategoryInfo>();
 }
Example #2
0
        public int UpdateCategory(CategoryInfo category)
        {
            CheckSlug(category);

            string cmdText = string.Format(@"update [{0}category] set
                                [Type]=@Type,
                                [ParentId]=@ParentId,
                                [CateName]=@CateName,
                                [Slug]=@Slug,
                                [Description]=@Description,
                                [SortNum]=@SortNum,
                                [PostCount]=@PostCount,
                                [CreateTime]=@CreateTime
                                where categoryid=@categoryid", ConfigHelper.Tableprefix);
            OleDbParameter[] prams = {
                                OleDbHelper.MakeInParam("@Type",OleDbType.Integer,1,(int)CategoryType.Category),
                                OleDbHelper.MakeInParam("@ParentId",OleDbType.Integer,4,category.ParentId),
                                OleDbHelper.MakeInParam("@CateName",OleDbType.VarWChar,255,category.CateName),
                                OleDbHelper.MakeInParam("@Slug",OleDbType.VarWChar,255,category.Slug),
                                OleDbHelper.MakeInParam("@Description",OleDbType.VarWChar,255,category.Description),
                                OleDbHelper.MakeInParam("@SortNum",OleDbType.Integer,4,category.SortNum),
                                OleDbHelper.MakeInParam("@PostCount",OleDbType.Integer,4,category.PostCount),
                                OleDbHelper.MakeInParam("@CreateTime",OleDbType.Date,8,category.CreateTime),
                                OleDbHelper.MakeInParam("@categoryid",OleDbType.Integer,1,category.CategoryId),
                            };
            return Convert.ToInt32(OleDbHelper.ExecuteScalar(CommandType.Text, cmdText, prams));
        }
Example #3
0
    protected override void ShowPage()
    {
        crootinfo = TaoBaos.GetChanelInfoByCache(chanelid);

        if (crootinfo == null)
        {
            AddErrLine("频道信息出错!");
            SetMetaRefresh(2, LogicUtils.GetReUrl());
            return;
        }

        cbrandlist = TaoBaos.GetGoodsBrandListByClass(chanelid);
        csubclasslist = TaoBaos.GetCategoryListByParentID(chanelid);
        //rproductlist = TaoBaos.GetProductWithRecommend(Convert.ToInt16(TaoChanel.Chanel), chanelid);

        adlist1 = Advertisements.GetTaoRandomAd(chanelid * 10 + 1, AdType.TaoChanelAd);
        adlist2 = Advertisements.GetTaoRandomAd(chanelid * 10 + 2, AdType.TaoChanelAd);
        adlist3 = Advertisements.GetTaoRandomAd(chanelid * 10 + 3, AdType.TaoChanelAd);
        adlist4 = Advertisements.GetTaoRandomAd(chanelid * 10 + 4, AdType.TaoChanelAd);
        adlist5 = Advertisements.GetTaoRandomAd(chanelid * 10 + 5, AdType.TaoChanelAd);

        pagetitle = crootinfo.Name + "频道-" + crootinfo.Name + "类型商品导购";
        seokeyword = string.Format("{0}频道,{0}类别,{0}商品,{0}导购,{0}类目,{0}搜索", crootinfo.Name);
        seodescription = string.Format("{0}频道,淘之购提供专业的{0}淘宝商品导购与商品推荐。", crootinfo.Name);
    }
Example #4
0
        public int UpdateCategory(CategoryInfo category)
        {
            CheckSlug(category);

            string cmdText = @"update [loachs_terms] set
                                [Type]=@Type,
                                [Name]=@Name,
                                [Slug]=@Slug,
                                [Description]=@Description,
                                [Displayorder]=@Displayorder,
                                [Count]=@Count,
                                [CreateDate]=@CreateDate
                                where termid=@termid";
            OleDbParameter[] prams = {
                                OleDbHelper.MakeInParam("@Type",OleDbType.Integer,1,(int)TermType.Category),
                                OleDbHelper.MakeInParam("@Name",OleDbType.VarWChar,255,category.Name),
                                OleDbHelper.MakeInParam("@Slug",OleDbType.VarWChar,255,category.Slug),
                                OleDbHelper.MakeInParam("@Description",OleDbType.VarWChar,255,category.Description),
                                OleDbHelper.MakeInParam("@Displayorder",OleDbType.Integer,4,category.Displayorder),
                                OleDbHelper.MakeInParam("@Count",OleDbType.Integer,4,category.Count),
                                OleDbHelper.MakeInParam("@CreateDate",OleDbType.Date,8,category.CreateDate),
                                OleDbHelper.MakeInParam("@termid",OleDbType.Integer,1,category.CategoryId),
                            };
            return Convert.ToInt32(OleDbHelper.ExecuteScalar(CommandType.Text, cmdText, prams));
        }
Example #5
0
        /// <summary>
        /// 添加分类
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public int InsertCategory(CategoryInfo category)
        {
            CheckSlug(category);

            string cmdText = @"insert into [loachs_terms]
                            (
                            [Type],[Name],[Slug],[Description],[Displayorder],[Count],[CreateDate]
                            )
                            values
                            (
                            @Type,@Name,@Slug,@Description,@Displayorder,@Count,@CreateDate
                            )";
            OleDbParameter[] prams = {
                                OleDbHelper.MakeInParam("@Type",OleDbType.Integer,1,(int)TermType.Category),
                                OleDbHelper.MakeInParam("@Name",OleDbType.VarWChar,255,category.Name),
                                OleDbHelper.MakeInParam("@Slug",OleDbType.VarWChar,255,category.Slug),
                                OleDbHelper.MakeInParam("@Description",OleDbType.VarWChar,255,category.Description),
                                OleDbHelper.MakeInParam("@Displayorder",OleDbType.Integer,4,category.Displayorder),
                                OleDbHelper.MakeInParam("@Count",OleDbType.Integer,4,category.Count),
                                OleDbHelper.MakeInParam("@CreateDate",OleDbType.Date,8,category.CreateDate)
                            };
            OleDbHelper.ExecuteScalar(CommandType.Text, cmdText, prams);

            int newId = Convert.ToInt32(OleDbHelper.ExecuteScalar("select top 1 [termid] from [loachs_terms] order by [termid] desc"));

            return newId;
        }
Example #6
0
        public JsonResult Save(CategoryInfo cat)
        {
            if (string.IsNullOrEmpty(cat.PageName))
            {
                cat.PageName = cat.CateName;
            }

            cat.PageName = HttpHelper.HtmlEncode(StringHelper.FilterPageName(cat.PageName, "cate"));

            if (cat.CategoryId > 0)
            {
                var  oldcat = _categoryService.GetCategory(cat.CategoryId);
                cat.CreateTime = oldcat.CreateTime;
                cat.PostCount = oldcat.PostCount;
                _categoryService.UpdateCategory(cat);
            }
            else
            {
                cat.CreateTime = DateTime.Now;
                cat.PostCount = 0;
                cat.CategoryId = _categoryService.InsertCategory(cat);
            }
            cat.TreeChar = _categoryService.GetCategoryTreeList().Find(c => c.CategoryId == cat.CategoryId).TreeChar;

            return Json(cat, JsonRequestBehavior.AllowGet);
        }
Example #7
0
 public int Compare(CategoryInfo info)
 {
     if (this.Equals(info)) {
         return 0;
     }
     try {
         Text[] texts = info.GetComponentsInChildren<Text>();
         for (int i = 0; i < texts.Length; i++) {
             if (texts[i].name.Equals("Rate")) {
                 float otherNumber = float.Parse(texts[i].text);
                 float myNumber = float.Parse(this.rate.text);
                 //There's no equal or approximate relations. Being thorough here.
                 if (myNumber < otherNumber) {
                     //Other number is larger, so we are smaller in comparison.
                     return -1;
                 }
                 else if (myNumber > otherNumber) {
                     //Other number is smaller, so we are larger in comparison.
                     return 1;
                 }
                 break;
             }
         }
     }
     catch (System.Exception e) {
         Debug.LogError("Error parsing data from Category Info: " + e.ToString());
     }
     return -1;
 }
Example #8
0
 /// <summary>
 /// 更新
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public static int Update(CategoryInfo model)
 {
     string strSQL = "UPDATE Categories SET Name = @Name,Sort = @Sort,ImageUrl = @ImageUrl,LinkUrl = @LinkUrl,Introduction = @Introduction,Alias = @Alias,TemplateType = @TemplateType,IsShowFirstChildNode = @IsShowFirstChildNode,BannerAdImageUrl = @BannerAdImageUrl,IsEnabled = @IsEnabled,IsDeleted = @IsDeleted WHERE ID = @ID";
     SqlParameter[] parms = { 
                             new SqlParameter("ParentId",SqlDbType.Int),
                             new SqlParameter("ParentIdList",SqlDbType.NVarChar),
                             new SqlParameter("Sort",SqlDbType.Int),
                             new SqlParameter("Name",SqlDbType.NVarChar),
                             new SqlParameter("ImageUrl",SqlDbType.NVarChar),
                             new SqlParameter("LinkUrl",SqlDbType.NVarChar),
                             new SqlParameter("Introduction",SqlDbType.NVarChar),
                             new SqlParameter("Alias",SqlDbType.NVarChar),
                             new SqlParameter("TemplateType",SqlDbType.Int),
                             new SqlParameter("IsShowFirstChildNode",SqlDbType.Int),
                             new SqlParameter("BannerAdImageUrl",SqlDbType.NVarChar),
                             new SqlParameter("IsEnabled",SqlDbType.Int),
                             new SqlParameter("IsDeleted",SqlDbType.Int),
                             new SqlParameter("Id",SqlDbType.Int),
                            };
     parms[0].Value = model.ParentId;
     parms[1].Value = model.ParentIdList;
     parms[2].Value = model.Sort;
     parms[3].Value = model.Name == null ? string.Empty : model.Name;
     parms[4].Value = model.ImageUrl == null ? string.Empty : model.ImageUrl;
     parms[5].Value = model.LinkUrl == null ? string.Empty : model.LinkUrl;
     parms[6].Value = model.Introduction == null ? string.Empty : model.Introduction;
     parms[7].Value = model.Alias == null ? string.Empty : model.Alias;
     parms[8].Value = model.TemplateType;
     parms[9].Value = model.IsShowFirstChildNode;
     parms[10].Value = model.BannerAdImageUrl == null ? string.Empty : model.BannerAdImageUrl;
     parms[11].Value = model.IsEnabled;
     parms[12].Value = model.IsDeleted;
     parms[13].Value = model.Id;
     return Goodspeed.Library.Data.SQLPlus.ExecuteNonQuery(CommandType.Text,strSQL,parms);
 }
Example #9
0
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="mod">CategoryInfo</param>
        /// <returns>受影响行数</returns>
        public int Update(CategoryInfo mod)
        {
           using (DbConnection conn = db.CreateConnection())
			{
				conn.Open();
				using (DbTransaction tran = conn.BeginTransaction())
				{ 
					try
					{ 
						using (DbCommand cmd = db.GetStoredProcCommand("SP_Category_Update"))
						{
							db.AddInParameter(cmd, "@CategoryID", DbType.Int32, mod.CategoryID); 
							db.AddInParameter(cmd, "@CategoryName", DbType.String, mod.CategoryName); 
							db.AddInParameter(cmd, "@State", DbType.Int32, mod.State); 
							db.AddInParameter(cmd, "@IsDeleted", DbType.Int32, mod.IsDeleted); 
							db.AddInParameter(cmd, "@Sort", DbType.Int32, mod.Sort); 
							tran.Commit();
							return db.ExecuteNonQuery(cmd);
						} 
					}
					catch (Exception e)
					{
						tran.Rollback();
						throw e;
					}
					finally
					{
						conn.Close();
					}
				}
			}
        }  
Example #10
0
 /// <summary>
 /// 删除分类
 /// </summary>
 /// <param name="category"></param>
 /// <returns></returns>
 public int Delete(CategoryInfo category)
 {
     string cmdText = string.Format("delete from [{0}category] where [categoryid] = @categoryid", ConfigHelper.Tableprefix);
     using (var conn = new DapperHelper().OpenConnection())
     {
         return conn.Execute(cmdText, new { categoryid = category.CategoryId });
     }
 }
 private void SerializeInternal(CategoryInfo model, IDictionary<string, object> result)
 { 
     result.Add("categoryid", model.CategoryID);
     result.Add("categoryname", model.CategoryName);
     result.Add("state", model.State);
     result.Add("isdeleted", model.IsDeleted);
     result.Add("sort", model.Sort);
 }
 private void CheckReadPermission(CategoryInfo category)
 {
     if ((category != null) && (category.CategoryUserID != currentUser.UserID))
     {
         // Check read permission for Categories module
         if (!currentUser.IsAuthorizedPerResource("CMS.Categories", "Read"))
         {
             RedirectToAccessDenied("CMS.Categories", "Read");
         }
     }
 }
Example #13
0
 public int InsertCategory(CategoryInfo category)
 {
     SqlConnection conn;
     int count = 0;
     using (conn = SqlHelper.CreateConntion())
     {
         conn.Open();
         count = categoryDal.InsertCategory(category, conn);
         conn.Close();
     }
     return count;
 }
Example #14
0
        public ActionResult RenderLeftCategoryMenu(CategoryInfo currentCategoryInfo, CategoryInfo rootCategoryInfo,string linkFormat)
        {          

            int rootId = rootCategoryInfo.Id;
            StringBuilder sbHtml = new StringBuilder();
            var allCatList = CategoryService.ListAllSubCatById(rootId).Where(p => p.IsDeleted == false && p.IsEnabled == true);

            Action<IEnumerable<CategoryInfo>, int, int, StringBuilder> fb = null;
            fb = (catList, parentId, level, sb) =>
            {
                var tempList = catList.Where(p => p.ParentId == parentId).OrderBy(p => p.Sort);

                string className = parentId == rootId ? "category-menu" : "none";
                sb.AppendFormat("<ul class=\"{0}\" {1}>", className, parentId == rootId ? "id=\"category_menu\"" : string.Empty);

                if (tempList.Count() == 0)
                {
                    //如果没有分类,则显示父分类名称
                    sbHtml.AppendFormat("<li class=\"on\"><a href=\"{1}\">{0}</a></li>", rootCategoryInfo.Name, Request.Url.AbsolutePath);
                }
                else
                {

                    foreach (var item in tempList)
                    {
                        //判断是否子分类
                        var ishasChild = catList.Where(p => p.ParentId == item.Id).Count() > 0;

                        if (currentCategoryInfo != null && currentCategoryInfo.Id == item.Id)
                        {
                            sb.Append("<li class=\"on\">");
                        }
                        else
                        {
                            sb.Append("<li>");
                        }
                        sb.AppendFormat("<a href=\"{3}\" id=\"d_menu_{1}\" title=\"{0}\" class=\"{2}\">{0}</a>", item.Name, item.Id, ishasChild ? "sub-icon" : string.Empty,string.IsNullOrEmpty(linkFormat) ? item.Url : string.Format(linkFormat,item.Id));


                        if (ishasChild)
                        {
                            fb(catList, item.Id, level + 1, sb);
                        }
                        sb.Append("</li>");
                    }
                }
                sb.Append("</ul>");
            };
            fb(allCatList, rootId, 0, sbHtml);

            return Content(sbHtml.ToString());
        }
Example #15
0
 /// <summary>
 /// 添加或更新分类信息
 /// </summary>
 /// <param name="model"></param>
 /// <returns>主键ID</returns>
 public static int Create(CategoryInfo model)
 {
     if (model.Id == 0)
     {
         //Insert
         int i = CategoryManage.Insert(model);
         model.Id = i;
     }
     else
     {
         //Update
         CategoryManage.Update(model);
     }
     return model.Id;
 }
Example #16
0
        private void LoadExtensionInfo(CategoryInfo currentCatInfo) {
            CategoryInfo rootCatInfo = currentCatInfo;

            //获取当前节点的顶级父节点
            //可以是未启用的,因为有的列表就是页面顶部导航不显示,但是左边需要显示
            //不显示已删除的
            var _rootCatInfo = CategoryService.ListUpById(currentCatInfo.Id).Where(p => p.IsDeleted == false).FirstOrDefault();
            if (_rootCatInfo != null)
            {
                rootCatInfo = _rootCatInfo;
            }
            //是否显示子分类的首节点
            //如果是,当前节点更改为子节点
            //只显示启用的以及未删除的
            if (currentCatInfo.IsShowFirstChildNode)
            {
                var firstChildNode = CategoryService.ListByParentId(currentCatInfo.Id).Where(p => (p.IsDeleted == false && p.IsEnabled == true)).FirstOrDefault();
                if (firstChildNode != null)
                {
                    currentCatInfo = firstChildNode;
                }
            }
            ViewBag.RootCategoryInfo = rootCatInfo;
            ViewBag.CurrentCategoryInfo = currentCatInfo;

            //模板类型
            switch (currentCatInfo.TemplateType)
            {
                case (int)TemplateType.ArticleList:
                case (int)TemplateType.ArticleListWithImage:
                    int pageIndex = CECRequest.GetQueryInt("page", 1);
                    ViewBag.ArticleList = ArticleService.List(new ArticleSearchSetting
                    {
                        PageIndex = pageIndex,
                        CategoryId = currentCatInfo.Id,
                        IsOnlyShowPublished = true
                    });
                    break;
            }
            
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            CategoryInfo term = new CategoryInfo();
            if (Operate == OperateType.Update)
            {
                term = CategoryManager.GetCategory(categoryId);
            }
            else
            {
                term.CreateDate = DateTime.Now;
                term.Count = 0;
            }
            term.Name = StringHelper.HtmlEncode(txtName.Text);
            term.Slug = txtSlug.Text.Trim();
            if (string.IsNullOrEmpty(term.Slug))
            {
                term.Slug = term.Name;
            }

            term.Slug = StringHelper.HtmlEncode(PageUtils.FilterSlug(term.Slug, "cate"));

            term.Description = StringHelper.HtmlEncode(txtDescription.Text);
            term.Displayorder = StringHelper.StrToInt(txtDisplayOrder.Text, 1000);

            if (term.Name == "")
            {
                ShowError("请输入名称!");
                return;
            }

            if (Operate == OperateType.Update)
            {
                CategoryManager.UpdateCategory(term);
                Response.Redirect("categorylist.aspx?result=2");
            }
            else
            {
                CategoryManager.InsertCategory(term);
                Response.Redirect("categorylist.aspx?result=1");
            }
        }
    protected void CreateCategoryDialog_OkButtonClicked(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            CategoryInfo entity = new CategoryInfo();
            entity.CategoryName = CategoryNameTextBox.Text.ToString().Trim();
            entity.Visible = VisibleCheckBox.Checked;
            ClassroomController.InsertCategory(ref entity);

            CreateCategoryDialog.Reset();
            DataBind();
            OnCategoryCreated(EventArgs.Empty);
            //Response.Redirect("~/Admin/Categories/Default.aspx");

        }
        else
        {
            ValidationHelper.SetFocusToFirstError(this.Page, "create_category");
        }
       
    }
Example #19
0
        /// <summary>
        /// 添加分类
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public int InsertCategory(CategoryInfo category)
        {
            CheckSlug(category);

            string cmdText = string.Format(@"insert into [{0}category]
                            ([Type],[ParentId],[CateName],[Slug],[Description],[SortNum],[PostCount],[CreateTime])
                            values
                            ( @Type,@ParentId,@CateName,@Slug,@Description,@SortNum,@PostCount,@CreateTime)", ConfigHelper.Tableprefix);
            OleDbParameter[] prams = {
                                OleDbHelper.MakeInParam("@Type",OleDbType.Integer,1,(int)CategoryType.Category),
                                OleDbHelper.MakeInParam("@ParentId",OleDbType.Integer,4,category.ParentId),
                                OleDbHelper.MakeInParam("@CateName",OleDbType.VarWChar,255,category.CateName),
                                OleDbHelper.MakeInParam("@Slug",OleDbType.VarWChar,255,category.Slug),
                                OleDbHelper.MakeInParam("@Description",OleDbType.VarWChar,255,category.Description),
                                OleDbHelper.MakeInParam("@SortNum",OleDbType.Integer,4,category.SortNum),
                                OleDbHelper.MakeInParam("@PostCount",OleDbType.Integer,4,category.PostCount),
                                OleDbHelper.MakeInParam("@CreateTime",OleDbType.Date,8,category.CreateTime)
                            };
            OleDbHelper.ExecuteScalar(CommandType.Text, cmdText, prams);

            int newId = Convert.ToInt32(OleDbHelper.ExecuteScalar(string.Format("select top 1 [categoryid] from [{0}category] order by [categoryid] desc",ConfigHelper.Tableprefix)));

            return newId;
        }
Example #20
0
        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static int Insert(CategoryInfo model)
        {
            string strSQL = "INSERT INTO Categories(ParentId,ParentIdList,Sort,Name,ImageUrl,LinkUrl,Introduction,CreateDateTime,Alias,TemplateType,IsShowFirstChildNode,BannerAdImageUrl,IsEnabled,[Language]) VALUES(@parentId,@parentIdList,@Sort,@Name,@ImageUrl,@LinkUrl,@Introduction,GETDATE(),@Alias,@TemplateType,@IsShowFirstChildNode,@BannerAdImageUrl,@IsEnabled,@Language);SELECT @@IDENTITY;";
            SqlParameter[] parms = {
                                    new SqlParameter("ParentId",SqlDbType.Int),
                                    new SqlParameter("ParentIdList",SqlDbType.NVarChar),
                                    new SqlParameter("Sort",SqlDbType.Int),
                                    new SqlParameter("Name",SqlDbType.NVarChar),
                                    new SqlParameter("ImageUrl",SqlDbType.NVarChar),
                                    new SqlParameter("LinkUrl",SqlDbType.NVarChar),
                                    new SqlParameter("Introduction",SqlDbType.NVarChar),
                                    new SqlParameter("Alias",SqlDbType.NVarChar),
                                    new SqlParameter("TemplateType",SqlDbType.Int),
                                    new SqlParameter("IsShowFirstChildNode",SqlDbType.Int),
                                    new SqlParameter("BannerAdImageUrl",SqlDbType.NVarChar),
                                    new SqlParameter("IsEnabled",SqlDbType.Int),
                                    new SqlParameter("IsDeleted",SqlDbType.Int),
                                    new SqlParameter("Language",SqlDbType.SmallInt),
                                   };
            parms[0].Value = model.ParentId;
            parms[1].Value = model.ParentIdList;
            parms[2].Value = model.Sort;
            parms[3].Value = model.Name ?? string.Empty;
            parms[4].Value = model.ImageUrl ?? string.Empty ;
            parms[5].Value = model.LinkUrl ?? string.Empty;
            parms[6].Value = model.Introduction ?? string.Empty;
            parms[7].Value = model.Alias ?? string.Empty;
            parms[8].Value = model.TemplateType;
            parms[9].Value = model.IsShowFirstChildNode;
            parms[10].Value = model.BannerAdImageUrl ?? string.Empty ;
            parms[11].Value = model.IsEnabled;
            parms[12].Value = model.IsDeleted;
            parms[13].Value = (int)model.Language;

            return Convert.ToInt32(Goodspeed.Library.Data.SQLPlus.ExecuteScalar(CommandType.Text,strSQL,parms));
        }
        /// <summary>
        /// Finds place for given category in subtree and creates node. Category is placed under root when no suitable place found.
        /// </summary>
        /// <param name="category">Category to be added.</param>
        public bool AddCategory(CategoryInfo category)
        {
            // Add to child list when suitable parent found
            if (category.CategoryParentID == ID)
            {
                AddChild(category);

                return true;
            }

            // Else look for place in all subtrees recursively
            foreach (CategoryNode node in Nodes)
            {
                if (node.AddCategory(category))
                {
                    return true;
                }
            }

            // When not found and current node is the root, add to child list
            if (ID == 0)
            {
                AddChild(category);

                return true;
            }

            // No suitable place found
            return false;
        }
Example #22
0
    /// <summary>
    /// 加载文章列表
    /// </summary>
    protected void LoadPostList()
    {
        int    categoryId = -1;
        int    tagId      = -1;
        int    userId     = -1;
        string keyword    = string.Empty;
        string data       = string.Empty;
        string begindate  = string.Empty;
        string enddate    = string.Empty;

        int pageindex = RequestHelper.QueryInt("page", 1);

        string messageinfo = string.Empty;

        string url = MakeUrl(string.Empty, string.Empty, string.Empty);

        if (pageType == "category")
        {
            string       slug = RequestHelper.QueryString("slug");
            CategoryInfo cate = CategoryManager.GetCategory(slug);
            if (cate != null)
            {
                categoryId = cate.CategoryId;
                th.Put(TagFields.META_KEYWORDS, cate.Name);
                th.Put(TagFields.META_DESCRIPTION, cate.Description);
                th.Put(TagFields.PAGE_TITLE, cate.Name);
                messageinfo = string.Format("<h2 class=\"post-message\">分类:{0}</h2>", cate.Name);

                url = MakeUrl("category", "slug", Server.UrlEncode(slug));
            }
        }
        else if (pageType == "tag")
        {
            string  slug = RequestHelper.QueryString("slug");
            TagInfo tag  = TagManager.GetTagBySlug(slug);
            if (tag != null)
            {
                tagId = tag.TagId;
                th.Put(TagFields.META_KEYWORDS, tag.Name);
                th.Put(TagFields.META_DESCRIPTION, tag.Description);
                th.Put(TagFields.PAGE_TITLE, tag.Name);
                messageinfo = string.Format("<h2 class=\"post-message\">标签:{0}</h2>", tag.Name);

                url = MakeUrl("tag", "slug", Server.UrlEncode(slug));
            }
        }
        else if (pageType == "author")
        {
            string   userName = RequestHelper.QueryString("username");
            UserInfo user     = UserManager.GetUser(userName);
            if (user != null)
            {
                userId = user.UserId;
                th.Put(TagFields.META_KEYWORDS, user.Name);
                th.Put(TagFields.META_DESCRIPTION, user.Description);
                th.Put(TagFields.PAGE_TITLE, user.Name);
                messageinfo = string.Format("<h2 class=\"post-message\">作者:{0}</h2>", user.Name);

                url = MakeUrl("author", "username", Server.UrlEncode(userName));
            }
        }
        else if (pageType == "search")
        {
            keyword = StringHelper.CutString(StringHelper.SqlEncode(RequestHelper.QueryString("keyword")), 15);
            th.Put(TagFields.META_KEYWORDS, keyword);
            th.Put(TagFields.META_DESCRIPTION, keyword);
            th.Put(TagFields.PAGE_TITLE, keyword);
            th.Put(TagFields.SEARCH_KEYWORD, keyword);
            messageinfo = string.Format("<h2 class=\"post-message\">搜索:{0}</h2>", keyword);

            url = MakeUrl("search", "keyword", Server.UrlEncode(keyword));
        }
        else if (pageType == "archive")     //先按月归档
        {
            string datestr = RequestHelper.QueryString("date");

            string   year  = datestr.Substring(0, 4);
            string   month = datestr.Substring(4, 2);
            DateTime date  = Convert.ToDateTime(year + "-" + month);
            begindate = date.ToString();
            enddate   = date.AddMonths(1).ToString();
            th.Put(TagFields.META_KEYWORDS, "归档");
            th.Put(TagFields.META_DESCRIPTION, SettingManager.GetSetting().SiteName + date.ToString("yyyy-MM") + "的归档");
            th.Put(TagFields.PAGE_TITLE, "归档:" + date.ToString("yyyy-MM"));
            messageinfo = string.Format("<h2 class=\"post-message\">归档:{0}</h2>", date.ToString("yyyy-MM"));

            url = MakeUrl("archive", "date", datestr);
        }

        else    //首页
        {
            if (pageindex == 1)
            {
                th.Put(TagFields.IS_DEFAULT, "1");
            }
        }

        th.Put(TagFields.POST_MESSAGE, messageinfo);
        //     th.Put(TagFields.PAGER_INDEX, pageindex);

        int recordCount = 0;

        th.Put(TagFields.POSTS, PostManager.GetPostList(SettingManager.GetSetting().PageSizePostCount, pageindex, out recordCount, categoryId, tagId, userId, -1, 1, -1, 0, begindate, enddate, keyword));
        th.Put(TagFields.PAGER, Pager.CreateHtml(SettingManager.GetSetting().PageSizePostCount, recordCount, url));

        Display("default.html");
    }
Example #23
0
    private void CatForumGrouping()
    {
        const int catColumnIndex   = 1;
        const int forumColumnIndex = 2;

        // Reference the Table the GridView has been rendered into
        var gridTable = (Table)ActiveTable.Controls[0];
        // Enumerate each TableRow, adding a sorting UI header if
        // the sorted value has changed
        string lastCat   = string.Empty;
        string lastForum = string.Empty;

        foreach (GridViewRow gvr in ActiveTable.Rows)
        {
            string currentCat   = gvr.Cells[catColumnIndex].Text;
            string currentForum = gvr.Cells[forumColumnIndex].Text;

            if (lastCat.CompareTo(currentCat) != 0)
            {
                CategoryInfo category = Categories.GetCategory(Convert.ToInt32(currentCat));
                string       catLink  = String.Format("<a href=\"/default.aspx?CAT={0}\" title=\"{1}\">{1}</a>", category.Id,
                                                      category.Name);

                // there's been a change in value in the category column
                int rowIndex = gridTable.Rows.GetRowIndex(gvr);
                // Add a new category header row
                var sortRow  = new GridViewRow(rowIndex, rowIndex, DataControlRowType.DataRow, DataControlRowState.Normal);
                var sortCell = new TableCell
                {
                    Text     = catLink,
                    CssClass = "tableheader"
                };
                if (IsAuthenticated)
                {
                    sortCell.ColumnSpan = ActiveTable.Columns.Count;
                }
                else
                {
                    sortCell.ColumnSpan = ActiveTable.Columns.Count - 1;
                }
                sortRow.Cells.Add(sortCell);
                gridTable.Controls.AddAt(rowIndex, sortRow);
                // Update lastValue
                lastCat = currentCat;
            }
            if (lastForum.CompareTo(currentForum) != 0)
            {
                ForumInfo forum     = Forums.GetForum(Convert.ToInt32(currentForum));
                string    forumLink = String.Format("<a class=\"bbcode\" href=\"/Content/Forums/forum.aspx?FORUM={0}\" title=\"{1}\">{2}</a>", forum.Id,
                                                    forum.Subject, forum.Subject);
                // there's been a change in value in the forum column
                int rowIndex = gridTable.Rows.GetRowIndex(gvr);
                // Add a new forum header row
                var sortRow = new GridViewRow(rowIndex, rowIndex, DataControlRowType.DataRow, DataControlRowState.Normal);
                var spacer  = new TableCell {
                    Text = "", CssClass = " ForumHeaderRow iconCol"
                };
                var sortCell = new TableCell
                {
                    Text     = forumLink,
                    CssClass = "ForumHeaderRow"
                };
                if (IsAuthenticated)
                {
                    sortCell.ColumnSpan = ActiveTable.Columns.Count;
                }
                else
                {
                    sortCell.ColumnSpan = ActiveTable.Columns.Count - 1;
                }

                //sortRow.Cells.Add(spacer);
                sortRow.Cells.Add(sortCell);
                gridTable.Controls.AddAt(rowIndex, sortRow);
                // Update lastValue
                lastForum = currentForum;
            }

            gvr.Cells.RemoveAt(2);
            gvr.Cells.RemoveAt(1);
            gvr.Cells[1].ColumnSpan = 3;
            if (_currentUser == "")
            {
                //gvr.Cells.RemoveAt(5);
                //gvr.Cells[2].ColumnSpan = 2;
            }
        }
        if (ActiveTable.BottomPagerRow != null)
        {
            GridViewRow pagerRow = ActiveTable.BottomPagerRow;
            pagerRow.Cells[0].CssClass = "pagerCol";
            //pagerRow.Cells[0].Attributes.Add("colspan",(ActiveTable.Columns.Count-1).ToString());
            pagerRow.Cells[0].Attributes.Add("colspan",
                                             IsAuthenticated
                                                    ? ActiveTable.Columns.Count.ToString()
                                                    : (ActiveTable.Columns.Count - 1).ToString());
        }
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        int categoryId       = 0;
        int categoryParentId = 0;

        // Get selected category and its parent IDs
        CategoryInfo category = SelectionElem.SelectedCategory;

        if (category != null)
        {
            categoryId       = category.CategoryID;
            categoryParentId = category.CategoryParentID;

            // Check if user can manage selected category
            bool canModify = SelectionElem.CanModifySelectedCategory;
            lnkDelete.Enabled = canModify;
            lnkUp.Enabled     = canModify;
            lnkDown.Enabled   = canModify;

            if (!category.CategoryIsPersonal)
            {
                // Display New button when authorized to modify site categories
                lnkNew.Enabled = SelectionElem.CanModifySiteCategories;

                // Additionaly check GlobalModify under global categories
                if (category.CategoryIsGlobal)
                {
                    lnkNew.Enabled |= SelectionElem.CanModifyGlobalCategories;
                }
            }
        }
        else
        {
            categoryParentId = SelectionElem.SelectedCategoryParentID;

            lnkNew.Enabled = SelectionElem.CategoriesRootSelected ? SelectionElem.CanModifyGlobalCategories || SelectionElem.CanModifySiteCategories : true;
        }

        // Enable/disable actions
        if (categoryId == 0)
        {
            lnkDelete.Enabled = false;
            lnkEdit.Enabled   = false;
            lnkUp.Enabled     = false;
            lnkDown.Enabled   = false;
        }
        else
        {
            lnkEdit.OnClientClick = "modalDialog('" + ResolveUrl("~/CMSModules/Categories/Dialogs/CategoryEdit.aspx?categoryId=" + categoryId) + "', 'CategoryEdit', 500, 450); return false;";
        }

        // Enable/disable actions visualy
        if (!lnkDelete.Enabled)
        {
            lnkDelete.CssClass     += " MenuItemDisabled";
            lnkDelete.OnClientClick = "";
        }
        lnkEdit.CssClass = lnkEdit.Enabled ? lnkEdit.CssClass.Replace(" MenuItemDisabled", "") : lnkEdit.CssClass + " MenuItemDisabled";
        lnkUp.CssClass   = lnkUp.Enabled ? lnkUp.CssClass.Replace(" MenuItemDisabled", "") : lnkUp.CssClass + " MenuItemDisabled";
        lnkDown.CssClass = lnkDown.Enabled ? lnkDown.CssClass.Replace(" MenuItemDisabled", "") : lnkDown.CssClass + " MenuItemDisabled";
        lnkNew.CssClass  = lnkNew.Enabled ? lnkNew.CssClass.Replace(" MenuItemDisabled", "") : lnkNew.CssClass + " MenuItemDisabled";

        string createPersonal = "";

        if ((SelectionElem.CategoriesRootSelected) || ((category != null) && !category.CategoryIsPersonal))
        {
            createPersonal = "&personal=0";
        }

        if (lnkNew.Enabled)
        {
            lnkNew.OnClientClick = "modalDialog('" + ResolveUrl("~/CMSModules/Categories/Dialogs/CategoryEdit.aspx?parentId=" + categoryId + createPersonal) + "', 'CategoryEdit', 500, 450); return false;";
        }
    }
Example #25
0
        /// <summary>
        /// 分类
        /// </summary>
        public ActionResult Category()
        {
            //分类id
            int cateId = GetRouteInt("cateId");

            if (cateId == 0)
            {
                cateId = WebHelper.GetQueryInt("cateId");
            }
            //品牌id
            int brandId = GetRouteInt("brandId");

            if (brandId == 0)
            {
                brandId = WebHelper.GetQueryInt("brandId");
            }
            //筛选价格
            int filterPrice = GetRouteInt("filterPrice");

            if (filterPrice == 0)
            {
                filterPrice = WebHelper.GetQueryInt("filterPrice");
            }
            //筛选属性
            string filterAttr = GetRouteString("filterAttr");

            if (filterAttr.Length == 0)
            {
                filterAttr = WebHelper.GetQueryString("filterAttr");
            }
            //是否只显示有货
            int onlyStock = GetRouteInt("onlyStock");

            if (onlyStock == 0)
            {
                onlyStock = WebHelper.GetQueryInt("onlyStock");
            }
            //排序列
            int sortColumn = GetRouteInt("sortColumn");

            if (sortColumn == 0)
            {
                sortColumn = WebHelper.GetQueryInt("sortColumn");
            }
            //排序方向
            int sortDirection = GetRouteInt("sortDirection");

            if (sortDirection == 0)
            {
                sortDirection = WebHelper.GetQueryInt("sortDirection");
            }
            //当前页数
            int page = GetRouteInt("page");

            if (page == 0)
            {
                page = WebHelper.GetQueryInt("page");
            }

            //分类信息
            CategoryInfo categoryInfo = Categories.GetCategoryById(cateId);

            if (categoryInfo == null)
            {
                return(PromptView("/", "此分类不存在"));
            }

            //分类关联品牌列表
            List <BrandInfo> brandList = Categories.GetCategoryBrandList(cateId);
            //分类筛选属性及其值列表
            List <KeyValuePair <AttributeInfo, List <AttributeValueInfo> > > cateAAndVList = Categories.GetCategoryFilterAAndVList(cateId);

            //分类价格范围列表
            string[] catePriceRangeList = StringHelper.SplitString(categoryInfo.PriceRange, "\r\n");

            //筛选属性处理
            List <int> attrValueIdList = new List <int>();

            string[] filterAttrValueIdList = StringHelper.SplitString(filterAttr, "-");
            if (filterAttrValueIdList.Length != cateAAndVList.Count)//当筛选属性和分类的筛选属性数目不对应时,重置筛选属性
            {
                if (cateAAndVList.Count == 0)
                {
                    filterAttr = "0";
                }
                else
                {
                    int           count = cateAAndVList.Count;
                    StringBuilder sb    = new StringBuilder();
                    for (int i = 0; i < count; i++)
                    {
                        sb.Append("0-");
                    }
                    filterAttr = sb.Remove(sb.Length - 1, 1).ToString();
                }
            }
            else
            {
                foreach (string attrValueId in filterAttrValueIdList)
                {
                    int temp = TypeHelper.StringToInt(attrValueId);
                    if (temp > 0)
                    {
                        attrValueIdList.Add(temp);
                    }
                }
            }

            //分页对象
            PageModel pageModel = new PageModel(20, page, Products.GetCategoryProductCount(cateId, brandId, filterPrice, catePriceRangeList, attrValueIdList, onlyStock));
            //视图对象
            CategoryModel model = new CategoryModel()
            {
                CateId             = cateId,
                BrandId            = brandId,
                FilterPrice        = filterPrice,
                FilterAttr         = filterAttr,
                OnlyStock          = onlyStock,
                SortColumn         = sortColumn,
                SortDirection      = sortDirection,
                CategoryInfo       = categoryInfo,
                BrandList          = brandList,
                CatePriceRangeList = catePriceRangeList,
                AAndVList          = cateAAndVList,
                PageModel          = pageModel,
                ProductList        = Products.GetCategoryProductList(pageModel.PageSize, pageModel.PageNumber, cateId, brandId, filterPrice, catePriceRangeList, attrValueIdList, onlyStock, sortColumn, sortDirection)
            };

            return(View(model));
        }
Example #26
0
        /// <summary>
        /// Certain Categories like Stairs contain elements of different Categories, that are hosted
        /// to them. We need to handle these approprietely.
        /// </summary>
        /// <param name="doc">Document</param>
        /// <param name="catInfo">Category Info object.</param>
        /// <param name="element">Element to check.</param>
        private static void RunCategoryAction(Document doc, CategoryInfo catInfo, Element element)
        {
            try
            {
                switch (catInfo.BltCategory)
                {
                case BuiltInCategory.OST_Topography:
                    var surface      = (TopographySurface)element;
                    var subRegionIds = surface.GetHostedSubRegionIds();
                    if (subRegionIds?.Count > 0)
                    {
                        foreach (var eId in subRegionIds)
                        {
                            var subRegion = doc.GetElement(eId);
                            if (null != subRegion)
                            {
                                CreateDirectShape(doc, subRegion);
                            }
                        }
                    }
                    break;

                case BuiltInCategory.OST_Stairs:
                    if (Stairs.IsByComponent(doc, element.Id))
                    {
                        var stair      = (Stairs)element;
                        var railingIds = stair.GetAssociatedRailings();
                        if (railingIds.Count > 0)
                        {
                            foreach (var eId in railingIds)
                            {
                                var railing = doc.GetElement(eId);
                                if (null != railing)
                                {
                                    CreateDirectShape(doc, railing);
                                }
                            }
                        }
                    }
                    else
                    {
                        var railings = new FilteredElementCollector(doc)
                                       .OfClass(typeof(Railing))
                                       .WhereElementIsNotElementType()
                                       .Cast <Railing>()
                                       .Where(x => x.HasHost && x.HostId == element.Id)
                                       .ToList();

                        if (railings.Any())
                        {
                            foreach (var railing in railings)
                            {
                                CreateDirectShape(doc, railing);
                            }
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message + "-" + element.Id);
            }
        }
Example #27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register JQuery
        ScriptHelper.RegisterJQuery(Page);

        SelectSite.StopProcessing = !DisplaySiteSelector;
        plcSelectSite.Visible     = DisplaySiteSelector;

        bool hasSelected = SelectedCategory != null;

        // Check if selection is valid
        CheckSelection();

        // Stop processing grids, when no category selected
        gridDocuments.UniGrid.StopProcessing            = !hasSelected;
        gridDocuments.UniGrid.FilterForm.StopProcessing = !hasSelected;
        gridDocuments.UniGrid.Visible = hasSelected;

        gridSubCategories.StopProcessing            = !hasSelected;
        gridSubCategories.FilterForm.StopProcessing = !hasSelected;
        gridSubCategories.Visible = hasSelected;

        if (!StopProcessing)
        {
            if (!URLHelper.IsPostback())
            {
                // Start in mode of creating new category when requested
                if (StartInCreatingMode)
                {
                    SwitchToNew();
                }
            }

            // Use images according to culture
            if (CultureHelper.IsUICultureRTL())
            {
                this.treeElemG.LineImagesFolder = GetImageUrl("RTL/Design/Controls/Tree", false, false);
                this.treeElemP.LineImagesFolder = GetImageUrl("RTL/Design/Controls/Tree", false, false);
            }
            else
            {
                this.treeElemG.LineImagesFolder = GetImageUrl("Design/Controls/Tree", false, false);
                this.treeElemP.LineImagesFolder = GetImageUrl("Design/Controls/Tree", false, false);
            }

            treeElemG.StopProcessing = !DisplaySiteCategories;
            treeElemP.StopProcessing = !DisplayPersonalCategories;

            // Prepare node templates
            treeElemP.SelectedNodeTemplate = treeElemG.SelectedNodeTemplate = "<span id=\"node_##NODECODENAME####NODEID##\" class=\"ContentTreeItem ContentTreeSelectedItem\" onclick=\"SelectNode('##NODECODENAME####NODEID##'); if (NodeSelected) { NodeSelected(##NODEID##, ##PARENTID##); return false;}\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";
            treeElemP.NodeTemplate         = treeElemG.NodeTemplate = "<span id=\"node_##NODECODENAME####NODEID##\" class=\"ContentTreeItem\" onclick=\"SelectNode('##NODECODENAME####NODEID##'); if (NodeSelected) { NodeSelected(##NODEID##, ##PARENTID##); return false;}\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";

            // Init tree provider objects
            treeElemG.ProviderObject = CreateTreeProvider(SiteID, 0);
            treeElemP.ProviderObject = CreateTreeProvider(0, UserID);

            // Expand first level by default
            treeElemP.ExpandPath = treeElemG.ExpandPath = "/";

            catNew.CategoryID            = 0;
            catNew.AllowCreateOnlyGlobal = SiteID == 0;
            catNew.SiteID = SiteID;
            CategoryInfo categoryObj = SelectedCategory;
            if (categoryObj != null)
            {
                catEdit.UserID     = categoryObj.CategoryUserID;
                catEdit.CategoryID = categoryObj.CategoryID;

                catNew.UserID           = categoryObj.CategoryUserID;
                catNew.ParentCategoryID = categoryObj.CategoryID;

                gridDocuments.SiteName = filterDocuments.SelectedSite;

                PreselectCategory(categoryObj, false);
            }
            else
            {
                catNew.UserID           = CustomCategoriesRootSelected ? UserID : 0;
                catNew.SiteID           = CustomCategoriesRootSelected ? 0 : SiteID;
                catNew.ParentCategoryID = 0;
            }

            // Create root node for global and site categories
            string rootIcon = "";
            string rootName = "<span class=\"TreeRoot\">" + GetString("categories.rootcategory") + "</span>";
            string rootText = treeElemG.ReplaceMacros(treeElemG.NodeTemplate, 0, 6, rootName, rootIcon, 0, null, null);

            rootText = rootText.Replace("##NODECUSTOMNAME##", rootName);
            rootText = rootText.Replace("##NODECODENAME##", "CategoriesRoot");
            rootText = rootText.Replace("##PARENTID##", CATEGORIES_ROOT_PARENT_ID.ToString());

            treeElemG.SetRoot(rootText, "NULL", GetImageUrl("Objects/CMS_Category/list.png"), null, null);

            // Create root node for personal categories
            rootName = "<span class=\"TreeRoot\">" + GetString("categories.rootpersonalcategory") + "</span>";
            rootText = "";
            rootText = treeElemP.ReplaceMacros(treeElemP.NodeTemplate, 0, 6, rootName, rootIcon, 0, null, null);

            rootText = rootText.Replace("##NODECUSTOMNAME##", rootName);
            rootText = rootText.Replace("##NODECODENAME##", "PersonalCategoriesRoot");
            rootText = rootText.Replace("##PARENTID##", PERSONAL_CATEGORIES_ROOT_PARENT_ID.ToString());
            treeElemP.SetRoot(rootText, "NULL", GetImageUrl("Objects/CMS_Category/list.png"), null, null);

            // Prepare post abck reerence for selecting nodes and confirmation message
            string postBackRef = ControlsHelper.GetPostBackEventReference(hdnButton, "");
            string script      = "var menuHiddenId = '" + hidSelectedElem.ClientID + "';";
            script += "function deleteConfirm() {";
            script += "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");";
            script += "}";
            script += "function RaiseHiddenPostBack(){" + postBackRef + ";}";

            ltlScript.Text = ScriptHelper.GetScript(script);
        }
    }
Example #28
0
    /// <summary>
    /// Shows forms acording to mode of control and initializes breadcrumbs.
    /// </summary>
    private void ShowForms()
    {
        plcNew.Visible  = IsCreating;
        plcEdit.Visible = IsEditing && SelectedCategory != null;
        plcInfo.Visible = !plcNew.Visible && !plcEdit.Visible;

        if (plcNew.Visible || plcEdit.Visible)
        {
            string[] idSplits = { };

            // Figure out breadcrumbs count
            int breadcrumbsCount = plcNew.Visible ? 2 : 1;
            if (SelectedCategory != null)
            {
                idSplits          = SelectedCategory.CategoryIDPath.Trim('/').Split('/');
                breadcrumbsCount += idSplits.Length;
            }

            // Init breadcrumbs
            string[,] breadcrumbs = new string[breadcrumbsCount, 4];
            int bi = 0;

            // Prepare root item
            if (CustomCategoriesRootSelected || ((SelectedCategory != null) && (SelectedCategory.CategoryUserID > 0)))
            {
                breadcrumbs[bi, 0] = GetString("categories.rootpersonalcategory");
                breadcrumbs[bi, 3] = "SelectNode('PersonalCategoriesRoot'); if (NodeSelected) { NodeSelected(0, -2);} return false;";
            }
            else
            {
                breadcrumbs[bi, 0] = GetString("categories.rootcategory");
                breadcrumbs[bi, 3] = "SelectNode('CategoriesRoot'); if (NodeSelected) { NodeSelected(0, -1);} return false;";
            }
            breadcrumbs[bi, 1] = " ";
            breadcrumbs[bi, 2] = "";
            bi++;

            // Create bradcrumbs for whole path
            if (SelectedCategory != null)
            {
                CategoryInfo currentCategory = null;
                int[]        ids             = ValidationHelper.GetIntegers(idSplits, 0);

                foreach (int id in ids)
                {
                    currentCategory = CategoryInfoProvider.GetCategoryInfo(id);
                    if ((currentCategory != null) && (bi < breadcrumbsCount))
                    {
                        breadcrumbs[bi, 0] = ResHelper.LocalizeString(currentCategory.CategoryDisplayName);
                        breadcrumbs[bi, 1] = " ";
                        breadcrumbs[bi, 2] = "";
                        breadcrumbs[bi, 3] = GetCategorySelectionScript(currentCategory);
                        bi++;
                    }
                }
            }

            // Add new category item
            if (plcNew.Visible)
            {
                breadcrumbs[bi, 0] = GetString("categories.new");
                breadcrumbs[bi, 1] = "";
                breadcrumbs[bi, 2] = "";
            }

            titleElem.Breadcrumbs = breadcrumbs;
        }

        // Display title when creating a new category
        if (plcNew.Visible)
        {
            titleElem.TitleText  = GetString("categories.new");
            titleElem.TitleImage = GetImageUrl("Objects/CMS_Category/new.png");
        }
    }
Example #29
0
        public CategoryInfo[] getCategories(
            string blogid,
            string username,
            string password)
        {
            if (ValidateUser(username, password))
            {
                Channel userChannel = new Channel(username);
                if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "")
                {
                    // Find the propertytype via the document type
                    ContentType  blogPostType = ContentType.GetByAlias(userChannel.DocumentTypeAlias);
                    PropertyType categoryType = blogPostType.getPropertyType(userChannel.FieldCategoriesAlias);

                    // check if the datatype uses tags or prevalues
                    CategoryInfo[]      returnedCategories = null;
                    interfaces.IUseTags tags = UseTags(categoryType);
                    if (tags != null)
                    {
                        List <interfaces.ITag> alltags = tags.GetAllTags();
                        if (alltags != null)
                        {
                            returnedCategories = new CategoryInfo[alltags.Count];
                            int counter = 0;
                            foreach (interfaces.ITag t in alltags)
                            {
                                CategoryInfo ci = new CategoryInfo();
                                ci.title       = t.TagCaption;
                                ci.categoryid  = t.Id.ToString();
                                ci.description = "";
                                ci.rssUrl      = "";
                                ci.htmlUrl     = "";
                                returnedCategories[counter] = ci;
                                counter++;
                            }
                        }
                        else
                        {
                            returnedCategories = new CategoryInfo[0];
                        }
                    }
                    else
                    {
                        SortedList categories = PreValues.GetPreValues(categoryType.DataTypeDefinition.Id);
                        returnedCategories = new CategoryInfo[categories.Count];
                        IDictionaryEnumerator ide = categories.GetEnumerator();
                        int counter = 0;
                        while (ide.MoveNext())
                        {
                            PreValue     category = (PreValue)ide.Value;
                            CategoryInfo ci       = new CategoryInfo();
                            ci.title       = category.Value;
                            ci.categoryid  = category.Id.ToString();
                            ci.description = "";
                            ci.rssUrl      = "";
                            ci.htmlUrl     = "";
                            returnedCategories[counter] = ci;
                            counter++;
                        }
                    }

                    return(returnedCategories);
                }
            }

            throw new ArgumentException("Categories doesn't work for this channel, they might not have been activated. Contact your umbraco administrator.");
        }
Example #30
0
        private void btnSave_Click(object sender, System.EventArgs e)
        {
            if (this.categoryId == 0)
            {
                this.categoryId = (int)this.ViewState["ProductCategoryId"];
            }
            int     displaySequence;
            decimal salePrice;
            decimal?costPrice;
            decimal?marketPrice;
            int     stock;
            int     factstock;
            decimal?num3;
            decimal?referralDeduct;
            decimal?subMemberDeduct;
            decimal?subReferralDeduct;
            decimal?deductFee;
            int     buyCardinality;
            decimal?grossweight;

            if (!this.ValidateConverts(this.chkSkuEnabled.Checked, out displaySequence, out salePrice, out costPrice, out marketPrice, out stock, out factstock, out num3, out referralDeduct, out subMemberDeduct, out subReferralDeduct, out deductFee, out buyCardinality, out grossweight))
            {
                return;
            }
            decimal adminFraction = 0m;

            if (string.IsNullOrWhiteSpace(txtAdminFraction.Text) || !decimal.TryParse(txtAdminFraction.Text, out adminFraction))
            {
                this.ShowMsg("请输入正确的提升权重值", false);
                return;
            }
            int ConversionRelation;

            if (!int.TryParse(this.txtConversionRelation.Text, out ConversionRelation))
            {
                this.ShowMsg("输入换算关系不正确", false);
                return;
            }
            string text = Globals.StripScriptTags(this.txtProductName.Text.Trim());

            text = Globals.StripHtmlXmlTags(text).Replace("\\", "").Replace("'", "");
            if (string.IsNullOrEmpty(text) || text == "")
            {
                this.ShowMsg("商品名称不能为空,且不能包含脚本标签、HTML标签、XML标签、反斜杠(\\)、单引号(')!", false);
                return;
            }
            if (!this.chkSkuEnabled.Checked)
            {
                if (salePrice <= 0m)
                {
                    this.ShowMsg("商品一口价必须大于0", false);
                    return;
                }
                if (costPrice.HasValue && (costPrice.Value > salePrice || costPrice.Value < 0m))
                {
                    this.ShowMsg("商品成本价必须大于0且小于商品一口价", false);
                    return;
                }
                if (!costPrice.HasValue)              //|| !deductFee.HasValue
                {
                    this.ShowMsg("商品成本价不能为空", false); //与扣点
                    return;
                }
                if (string.IsNullOrEmpty(txtProductStandard.Text))
                {
                    this.ShowMsg("未开启多规格时,商品规格必填", false);
                    return;
                }
            }
            //判断是否存在广告关键字
            Dictionary <string, string> msg;

            if (!ValidateKeyWordHelper.ValidateKeyWord(new Dictionary <string, string>()
            {
                { "商品名称", this.txtProductName.Text }, { "商品简介", this.txtShortDescription.Text }
            }, out msg))
            {
                string showM = "";
                foreach (string k in msg.Keys)
                {
                    showM += k + "中不能包含广告词:" + msg[k] + ";";
                }
                this.ShowMsg(showM, false);
                return;
            }



            string text2 = this.fckDescription.Text;
            string text3 = this.fckmobbileDescription.Text;

            if (this.ckbIsDownPic.Checked)
            {
                text2 = base.DownRemotePic(text2);
                text3 = base.DownRemotePic(text3);
            }

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("<script[^>]*?>.*?</script>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);


            ProductInfo productInfo = ProductHelper.GetProductDetails(this.productId);


            if (productInfo.ConversionRelation != ConversionRelation)
            {
                if (productInfo.Stock > 0)
                {
                    this.ShowMsg("销售库存大于0不允许修改换算系数", false);
                    return;
                }
            }
            //ProductInfo productInfo = new ProductInfo
            //{
            productInfo.ProductId          = this.productId;
            productInfo.CategoryId         = this.categoryId;
            productInfo.TypeId             = this.dropProductTypes.SelectedValue;
            productInfo.ProductName        = text;
            productInfo.ProductCode        = this.txtProductCode.Text;
            productInfo.AdminFraction      = adminFraction;
            productInfo.DisplaySequence    = displaySequence;
            productInfo.MarketPrice        = marketPrice;
            productInfo.Unit               = this.ddlUnit.SelectedItem.Text;
            productInfo.ImageUrl1          = this.uploader1.UploadedImageUrl;
            productInfo.ImageUrl2          = this.uploader2.UploadedImageUrl;
            productInfo.ImageUrl3          = this.uploader3.UploadedImageUrl;
            productInfo.ImageUrl4          = this.uploader4.UploadedImageUrl;
            productInfo.ImageUrl5          = this.uploader5.UploadedImageUrl;
            productInfo.ThumbnailUrl40     = this.uploader1.ThumbnailUrl40;
            productInfo.ThumbnailUrl60     = this.uploader1.ThumbnailUrl60;
            productInfo.ThumbnailUrl100    = this.uploader1.ThumbnailUrl100;
            productInfo.ThumbnailUrl160    = this.uploader1.ThumbnailUrl160;
            productInfo.ThumbnailUrl180    = this.uploader1.ThumbnailUrl180;
            productInfo.ThumbnailUrl220    = this.uploader1.ThumbnailUrl220;
            productInfo.ThumbnailUrl310    = this.uploader1.ThumbnailUrl310;
            productInfo.ThumbnailUrl410    = this.uploader1.ThumbnailUrl410;
            productInfo.ShortDescription   = this.txtShortDescription.Text;
            productInfo.IsfreeShipping     = this.ChkisfreeShipping.Checked;
            productInfo.IsCustomsClearance = this.ChkisCustomsClearance.Checked;

            productInfo.IsDisplayDiscount = this.ChkisDisplayDiscount.Checked;

            productInfo.IsPromotion = this.ChkisPromotion.Checked;

            productInfo.Description        = (!string.IsNullOrEmpty(text2) && text2.Length > 0) ? regex.Replace(text2, "") : null;
            productInfo.MobblieDescription = (!string.IsNullOrEmpty(text3) && text3.Length > 0) ? regex.Replace(text3, "") : null;
            productInfo.Title              = this.txtTitle.Text;
            productInfo.MetaDescription    = this.txtMetaDescription.Text;
            productInfo.MetaKeywords       = this.txtMetaKeywords.Text;
            productInfo.AddedDate          = System.DateTime.Now;
            productInfo.BrandId            = this.dropBrandCategories.SelectedValue;
            productInfo.ReferralDeduct     = referralDeduct;
            productInfo.SubMemberDeduct    = subMemberDeduct;
            productInfo.SubReferralDeduct  = subReferralDeduct;
            productInfo.TaxRateId          = this.dropTaxRate.SelectedValue;
            productInfo.TemplateId         = this.ddlShipping.SelectedValue;
            productInfo.SupplierId         = this.ddlSupplier.SelectedValue;
            productInfo.ImportSourceId     = this.ddlImportSourceType.SelectedValue;
            productInfo.BuyCardinality     = buyCardinality;
            productInfo.UnitCode           = this.ddlUnit.SelectedValue;
            productInfo.Manufacturer       = txtManufacturer.Text;
            productInfo.ItemNo             = txtItemNo.Text;
            productInfo.BarCode            = txtBarCode.Text;
            productInfo.Ingredient         = txtIngredient.Text;
            productInfo.ProductStandard    = txtProductStandard.Text;
            productInfo.ConversionRelation = ConversionRelation;
            productInfo.ProductTitle       = this.txtProductTitle.Text;//商品副标题
            productInfo.SaleType           = string.IsNullOrWhiteSpace(this.dropSaleType.SelectedValue) ? 1 : Convert.ToInt32(this.dropSaleType.SelectedValue);
            productInfo.EnglishName        = this.txtEnglishName.Text;
            productInfo.SysProductName     = this.txtsysProductName.Text;
            productInfo.Purchase           = int.Parse(this.Rd_Purchase.SelectedValue);
            productInfo.SectionDay         = int.Parse(this.txtSectionDay.Text);
            productInfo.PurchaseMaxNum     = int.Parse(this.txtMaxCount.Text.ToString());

            //};
            ProductSaleStatus saleStatus = ProductSaleStatus.OnSale;

            if (this.radInStock.Checked)
            {
                saleStatus = ProductSaleStatus.OnStock;
            }
            if (this.radUnSales.Checked)
            {
                saleStatus = ProductSaleStatus.UnSale;
            }
            if (this.radOnSales.Checked)
            {
                saleStatus = ProductSaleStatus.OnSale;

                if (productInfo.SaleStatus != ProductSaleStatus.OnSale && ProductHelper.IsExitNoClassifyProduct(this.productId.ToString()))
                {
                    if (productInfo.SaleType != 2)
                    {
                        this.ShowMsg("商品还未完成归类操作,不能出售", false);
                        return;
                    }
                }
            }
            productInfo.SaleStatus = saleStatus;
            CategoryInfo category = CatalogHelper.GetCategory(this.categoryId);

            if (category != null)
            {
                productInfo.MainCategoryPath = category.Path + "|";
            }
            System.Collections.Generic.Dictionary <int, System.Collections.Generic.IList <int> > attrs = null;
            System.Collections.Generic.Dictionary <string, SKUItem> dictionary;
            if (this.chkSkuEnabled.Checked)
            {
                productInfo.HasSKU = true;
                dictionary         = base.GetSkus(this.txtSkus.Text);

                if (!string.IsNullOrEmpty(ArrhidProductRegistrationNumber.Value))
                {
                    Dictionary <string, string>[] dic = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string>[]>(ArrhidProductRegistrationNumber.Value);

                    foreach (string item in dictionary.Keys)
                    {
                        foreach (Dictionary <string, string> d in dic)
                        {
                            if (d["SKU"] == dictionary[item].SKU)
                            {
                                dictionary[item].ProductRegistrationNumber = d["ProductRegistrationNumber"];
                                dictionary[item].LJNo = d["LJNo"];
                                int wmsstock;
                                int.TryParse(d["WMSStock"], out wmsstock);
                                dictionary[item].WMSStock = wmsstock;
                                //decimal dcgrossweight=0m;
                                //decimal.TryParse(d["GrossWeight"], out dcgrossweight);
                                //dictionary[item].GrossWeight = dcgrossweight;
                                //decimal dcweight = 0m;
                                //decimal.TryParse(d["Weight"], out dcweight);
                                //dictionary[item].Weight = dcweight;
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                AutoCalcCostPriceAndDeductFee(salePrice, ref costPrice, ref deductFee);
                dictionary = new System.Collections.Generic.Dictionary <string, SKUItem>
                {
                    {
                        "0",
                        new SKUItem
                        {
                            SkuId     = "0",
                            SKU       = Globals.HtmlEncode(Globals.StripScriptTags(this.txtSku.Text.Trim()).Replace("\\", "")),
                            SalePrice = salePrice,
                            CostPrice = costPrice.HasValue ? costPrice.Value : 0m,
                            Stock     = stock,
                            FactStock = factstock,
                            Weight    = num3.HasValue ? num3.Value : 0m,
                            DeductFee = deductFee.HasValue ? deductFee.Value : 0m,
                            ProductRegistrationNumber = hidProductRegistrationNumber.Value,
                            LJNo        = hidLJNo.Value,
                            WMSStock    = productInfo.DefaultSku.WMSStock,
                            GrossWeight = grossweight.HasValue?grossweight.Value:0m
                        }
                    }
                };
                if (this.txtMemberPrices.Text.Length > 0)
                {
                    base.GetMemberPrices(dictionary["0"], this.txtMemberPrices.Text);
                }
            }
            if (!string.IsNullOrEmpty(this.txtAttributes.Text) && this.txtAttributes.Text.Length > 0)
            {
                attrs = base.GetAttributes(this.txtAttributes.Text);
            }
            ValidationResults validationResults = Validation.Validate <ProductInfo>(productInfo);

            if (!validationResults.IsValid)
            {
                this.ShowMsg(validationResults);
                return;
            }
            System.Collections.Generic.IList <int> list = new System.Collections.Generic.List <int>();
            if (!string.IsNullOrEmpty(this.txtProductTag.Text.Trim()))
            {
                string   text4 = this.txtProductTag.Text.Trim();
                string[] array;
                if (text4.Contains(","))
                {
                    array = text4.Split(new char[]
                    {
                        ','
                    });
                }
                else
                {
                    array = new string[]
                    {
                        text4
                    };
                }
                string[] array2 = array;
                for (int i = 0; i < array2.Length; i++)
                {
                    string value = array2[i];
                    list.Add(System.Convert.ToInt32(value));
                }
            }

            #region   ==组合商品
            List <ProductsCombination> combinations = new List <ProductsCombination>();
            string   combinationInfos = base.Request.Form["selectProductsinfo"];
            string[] curCom           = combinationInfos.Split(new char[]
            {
                ','
            });
            string[] curCom2 = curCom;
            for (int i = 0; i < curCom2.Length; i++)
            {
                string combinationInfo     = curCom2[i];
                ProductsCombination com    = new ProductsCombination();
                string[]            array3 = combinationInfo.Split(new char[]
                {
                    '|'
                });
                if (array3.Length == 10)
                {
                    com.SkuId         = array3[0];
                    com.ProductId     = array3[1] == "" ? 0 : Convert.ToInt32(array3[1]);
                    com.ProductName   = array3[2];
                    com.ThumbnailsUrl = array3[3];
                    decimal tempweight;
                    if (decimal.TryParse(array3[4], out tempweight))
                    {
                        com.Weight = tempweight;
                    }
                    com.SKU        = array3[5];
                    com.SKUContent = array3[6];
                    com.Quantity   = array3[8] == "" ? 0 : Convert.ToInt32(array3[8]);
                    decimal tempprice;
                    if (decimal.TryParse(array3[9], out tempprice))
                    {
                        com.Price = tempprice;
                    }
                    combinations.Add(com);
                }
            }
            productInfo.CombinationItemInfos = combinations;
            #endregion

            if (productInfo.SaleType == 2)
            {
                decimal CombinationTotalPrice = 0M;
                foreach (var item in productInfo.CombinationItemInfos)
                {
                    CombinationTotalPrice += item.Price * item.Quantity;
                }

                if (Math.Round(CombinationTotalPrice, 2) != Math.Round(salePrice, 2))
                {
                    this.ShowMsg("添加商品失败,组合商品一口价和组合商品明细总价不一致", false);
                    return;
                }
            }

            ProductActionStatus productActionStatus = ProductHelper.UpdateProduct(productInfo, dictionary, attrs, list, combinations);
            if (productActionStatus == ProductActionStatus.Success)
            {
                this.litralProductTag.SelectedValue = list;
                this.ShowMsg("修改商品成功", true);
                base.Response.Redirect(Globals.GetAdminAbsolutePath(string.Format("/product/AddProductComplete.aspx?categoryId={0}&productId={1}&IsEdit=1", this.categoryId, productInfo.ProductId)), true);
                return;
            }
            if (productActionStatus == ProductActionStatus.AttributeError)
            {
                this.ShowMsg("修改商品失败,保存商品属性时出错", false);
                return;
            }
            if (productActionStatus == ProductActionStatus.DuplicateName)
            {
                this.ShowMsg("修改商品失败,商品名称不能重复", false);
                return;
            }
            if (productActionStatus == ProductActionStatus.DuplicateSKU)
            {
                this.ShowMsg("修改商品失败,商家编码不能重复", false);
                return;
            }
            if (productActionStatus == ProductActionStatus.SKUError)
            {
                this.ShowMsg("修改商品失败,商家编码不能重复", false);
                return;
            }
            if (productActionStatus == ProductActionStatus.ProductTagEroor)
            {
                this.ShowMsg("修改商品失败,保存商品标签时出错", false);
                return;
            }
            this.ShowMsg("修改商品失败,未知错误", false);
        }
    /// <summary>
    /// Creates HTML code for category link.
    /// </summary>
    /// <param name="category">Category object to create link for.</param>
    protected string CreateCategoryPartLink(CategoryInfo category)
    {
        string categoryDisplayName = category.CategoryDisplayName;
        int categoryId = category.CategoryID;

        // Get target url
        string url = (String.IsNullOrEmpty(DocumentListUrl) ? RequestContext.CurrentURL : DocumentURLProvider.GetUrl(DocumentListUrl));

        // Append category parameter
        if (UseCodeNameInQuery)
        {
            url = URLHelper.AddParameterToUrl(url, "categoryname", category.CategoryName);
        }
        else
        {
            url = URLHelper.AddParameterToUrl(url, "categoryid", categoryId.ToString());
        }

        StringBuilder attrs = new StringBuilder();

        // Append target attribute
        if (!string.IsNullOrEmpty(DocumentListTarget))
        {
            attrs.Append(" target=\"").Append(DocumentListTarget).Append("\"");
        }

        // Append title attribute
        if (RenderLinkTitle)
        {
            attrs.Append(" title=\"").Append(HTMLHelper.HTMLEncode(categoryDisplayName)).Append("\"");
        }

        return string.Format("<a href=\"{0}\"{1}>{2}</a>", HTMLHelper.EncodeForHtmlAttribute(url), attrs, FormatCategoryDisplayName(categoryDisplayName));
    }
Example #32
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            bool wasVisible = pnlPageName.Visible;

            pnlPageName.Visible = true;

            if (!wasVisible && Settings.AutoGeneratePageNames && txtName.Enabled)
            {
                txtName.Text = GenerateAutoName(txtTitle.Text);
            }

            txtName.Text = txtName.Text.Trim();

            Page.Validate("nametitle");
            Page.Validate("captcha");
            if (!Page.IsValid)
            {
                if (!rfvTitle.IsValid || !rfvName.IsValid || !cvName1.IsValid || !cvName2.IsValid)
                {
                    pnlPageName.Visible               = true;
                    pnlManualName.Visible             = false;
                    pnlPageName.UpdateAfterCallBack   = true;
                    pnlManualName.UpdateAfterCallBack = true;
                }

                return;
            }

            pnlPageName.Visible = wasVisible;

            // Check permissions
            if (currentPage == null)
            {
                // Check permissions for creating new pages
                if (!canCreateNewPages)
                {
                    UrlTools.Redirect("AccessDenied.aspx");
                }
            }
            else
            {
                // Check permissions for editing current page
                if (!canEdit && !canEditWithApproval)
                {
                    UrlTools.Redirect("AccessDenied.aspx");
                }
            }

            chkMinorChange.Visible = true;
            chkSaveAsDraft.Visible = true;

            // Verify edit with approval
            if (!canEdit && canEditWithApproval)
            {
                chkSaveAsDraft.Checked = true;
            }

            // Check for scripts (Administrators can always add SCRIPT tags)
            if (!SessionFacade.GetCurrentGroupNames().Contains(Settings.AdministratorsGroup) && !Settings.ScriptTagsAllowed)
            {
                Regex r = new Regex(@"\<script.*?\>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (r.Match(editor.GetContent()).Success)
                {
                    lblResult.Text = @"<span style=""color: #FF0000;"">" + Properties.Messages.ScriptDetected + "</span>";
                    return;
                }
            }

            bool redirect = true;

            if (sender == btnSaveAndContinue)
            {
                redirect = false;
            }

            lblResult.Text     = "";
            lblResult.CssClass = "";

            string username = "";

            if (SessionFacade.LoginKey == null)
            {
                username = Request.UserHostAddress;
            }
            else
            {
                username = SessionFacade.CurrentUsername;
            }

            IPagesStorageProviderV30 provider = FindAppropriateProvider();

            // Create list of selected categories
            List <CategoryInfo> categories = new List <CategoryInfo>();

            for (int i = 0; i < lstCategories.Items.Count; i++)
            {
                if (lstCategories.Items[i].Selected)
                {
                    CategoryInfo cat = Pages.FindCategory(lstCategories.Items[i].Value);

                    // Sanity check
                    if (cat.Provider == provider)
                    {
                        categories.Add(cat);
                    }
                }
            }

            txtComment.Text     = txtComment.Text.Trim();
            txtDescription.Text = txtDescription.Text.Trim();

            SaveMode saveMode = SaveMode.Backup;

            if (chkSaveAsDraft.Checked)
            {
                saveMode = SaveMode.Draft;
            }
            if (chkMinorChange.Checked)
            {
                saveMode = SaveMode.Normal;
            }

            if (txtName.Enabled)
            {
                // Find page, if inexistent create it
                PageInfo pg = Pages.FindPage(NameTools.GetFullName(DetectNamespace(), txtName.Text), provider);
                if (pg == null)
                {
                    Pages.CreatePage(DetectNamespaceInfo(), txtName.Text, provider);
                    pg       = Pages.FindPage(NameTools.GetFullName(DetectNamespace(), txtName.Text), provider);
                    saveMode = SaveMode.Normal;
                    attachmentManager.CurrentPage = pg;
                }
                Log.LogEntry("Page update requested for " + txtName.Text, EntryType.General, username);

                Pages.ModifyPage(pg, txtTitle.Text, username, DateTime.Now, txtComment.Text, editor.GetContent(),
                                 GetKeywords(), txtDescription.Text, saveMode);

                // Save categories binding
                Pages.Rebind(pg, categories.ToArray());

                // If not a draft, remove page draft
                if (saveMode != SaveMode.Draft)
                {
                    Pages.DeleteDraft(currentPage);
                    isDraft = false;
                }
                else
                {
                    isDraft = true;
                }

                ManageDraft();

                lblResult.CssClass = "resultok";
                lblResult.Text     = Properties.Messages.PageSaved;

                // This is a new page, so only who has page management permissions can execute this code
                // No notification must be sent for drafts awaiting approval
                if (redirect)
                {
                    Collisions.CancelEditingSession(pg, username);
                    string target = UrlTools.BuildUrl(Tools.UrlEncode(txtName.Text), Settings.PageExtension, "?NoRedirect=1");
                    UrlTools.Redirect(target);
                }
                else
                {
                    // Disable PageName, because the name cannot be changed anymore
                    txtName.Enabled       = false;
                    pnlManualName.Visible = false;
                }
            }
            else
            {
                // Used for redirecting to a specific section after editing it
                string anchor = "";

                if (currentPage == null)
                {
                    currentPage = Pages.FindPage(NameTools.GetFullName(DetectNamespace(), txtName.Text));
                }

                // Save data
                Log.LogEntry("Page update requested for " + currentPage.FullName, EntryType.General, username);
                if (!isDraft && currentSection != -1)
                {
                    PageContent   cont = Content.GetPageContent(currentPage, false);
                    StringBuilder sb = new StringBuilder(cont.Content.Length);
                    int           start, len;
                    ExtractSection(cont.Content, currentSection, out start, out len, out anchor);
                    if (start > 0)
                    {
                        sb.Append(cont.Content.Substring(0, start));
                    }
                    sb.Append(editor.GetContent());
                    if (start + len < cont.Content.Length - 1)
                    {
                        sb.Append(cont.Content.Substring(start + len));
                    }
                    Pages.ModifyPage(currentPage, txtTitle.Text, username, DateTime.Now, txtComment.Text, sb.ToString(),
                                     GetKeywords(), txtDescription.Text, saveMode);
                }
                else
                {
                    Pages.ModifyPage(currentPage, txtTitle.Text, username, DateTime.Now, txtComment.Text, editor.GetContent(),
                                     GetKeywords(), txtDescription.Text, saveMode);
                }

                // Save Categories binding
                Pages.Rebind(currentPage, categories.ToArray());

                // If not a draft, remove page draft
                if (saveMode != SaveMode.Draft)
                {
                    Pages.DeleteDraft(currentPage);
                    isDraft = false;
                }
                else
                {
                    isDraft = true;
                }

                ManageDraft();

                lblResult.CssClass = "resultok";
                lblResult.Text     = Properties.Messages.PageSaved;

                // This code is executed every time the page is saved, even when "Save & Continue" is clicked
                // This causes a draft approval notification to be sent multiple times for the same page,
                // but this is the only solution because the user might navigate away from the page after
                // clicking "Save & Continue" but not "Save" or "Cancel" - in other words, it is necessary
                // to take every chance to send a notification because no more chances might be available
                if (!canEdit && canEditWithApproval)
                {
                    Pages.SendEmailNotificationForDraft(currentPage, txtTitle.Text, txtComment.Text, username);
                }

                if (redirect)
                {
                    Collisions.CancelEditingSession(currentPage, username);
                    string target = UrlTools.BuildUrl(Tools.UrlEncode(currentPage.FullName), Settings.PageExtension, "?NoRedirect=1",
                                                      (!string.IsNullOrEmpty(anchor) ? ("#" + anchor + "_" + currentSection.ToString()) : ""));
                    UrlTools.Redirect(target);
                }
            }
        }
    /// <summary>
    /// Invoked when new tree node is created.
    /// </summary>
    /// <param name="itemData">Category data.</param>
    /// <param name="defaultNode">Default node.</param>
    protected TreeNode treeElem_OnNodeCreated(DataRow itemData, TreeNode defaultNode)
    {
        defaultNode.Selected     = false;
        defaultNode.SelectAction = TreeNodeSelectAction.None;
        defaultNode.NavigateUrl  = "";

        if (itemData != null)
        {
            CategoryInfo category = new CategoryInfo(itemData);

            var catLevel = category.CategoryLevel;
            if ((StartingCategoryObj != null) && (category.CategoryIDPath.StartsWithCSafe(StartingCategoryObj.CategoryIDPath)))
            {
                catLevel -= StartingCategoryObj.CategoryLevel - 1;
            }

            string cssClass = GetCssClass(catLevel);

            string caption = category.CategoryDisplayName;
            if (String.IsNullOrEmpty(caption))
            {
                caption = category.CategoryName;
            }

            // Get target URL
            string url = GetUrl(category);
            caption = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(caption));

            StringBuilder attrs = new StringBuilder();

            // Append target attribute
            if (!string.IsNullOrEmpty(CategoriesPageTarget))
            {
                attrs.Append(" target=\"").Append(CategoriesPageTarget).Append("\"");
            }

            // Append title attribute
            if (RenderLinkTitle)
            {
                attrs.Append(" title=\"").Append(caption).Append("\"");
            }

            // Append CSS class
            if (!string.IsNullOrEmpty(cssClass))
            {
                attrs.Append(" class=\"" + cssClass + "\"");
            }

            // Append before/after texts
            caption  = (CategoryContentBefore ?? "") + caption;
            caption += CategoryContentAfter ?? "";

            if (category.IsGlobal && !category.CategoryIsPersonal)
            {
                caption += " <sup>" + GetString("general.global") + "</sup>";
            }

            // Set caption
            defaultNode.Text = defaultNode.Text.Replace("##NODECUSTOMNAME##", caption);
            defaultNode.Text = defaultNode.Text.Replace("##NODECODENAME##", HTMLHelper.HTMLEncode(category.CategoryName));
            defaultNode.Text = defaultNode.Text.Replace("##PARENTID##", category.CategoryParentID.ToString());
            defaultNode.Text = defaultNode.Text.Replace("##ID##", category.CategoryID.ToString());
            defaultNode.Text = defaultNode.Text.Replace("##BEFORENAME##", string.Format("<a href=\"{0}\" {1}>", HTMLHelper.EncodeForHtmlAttribute(url), attrs));
            defaultNode.Text = defaultNode.Text.Replace("##AFTERNAME##", "</a>");

            // Expand node if all nodes are to be expanded
            if (ExpandAll)
            {
                defaultNode.Expand();
            }
            else
            {
                // Check if selected category exists
                if (Category != null)
                {
                    if ((Category.CategoryID != category.CategoryID) || RenderSubItems)
                    {
                        // Expand whole path to selected category
                        string strId = category.CategoryID.ToString().PadLeft(CategoryInfoProvider.CategoryIDLength, '0');
                        if (Category.CategoryIDPath.Contains(strId))
                        {
                            defaultNode.Expand();
                        }
                    }
                }
            }

            return(defaultNode);
        }

        return(null);
    }
Example #34
0
        private void btnSaveCategory_Click(object sender, EventArgs e)
        {
            if (this.categoryid > 0)
            {
                CategoryInfo category = CatalogHelper.GetCategory(this.categoryid);
                if (category == null)
                {
                    this.ShowMsg("编缉商品分类错误,未知", false);
                }
                else
                {
                    category.IconUrl               = this.uploader1.UploadedImageUrl;
                    category.Name                  = this.txtCategoryName.Text;
                    category.SKUPrefix             = this.txtSKUPrefix.Text;
                    category.RewriteName           = this.txtRewriteName.Text;
                    category.MetaTitle             = this.txtPageKeyTitle.Text;
                    category.MetaKeywords          = this.txtPageKeyWords.Text;
                    category.MetaDescription       = this.txtPageDesc.Text;
                    category.AssociatedProductType = this.dropProductTypes.SelectedValue;
                    category.Notes1                = "";
                    category.Notes2                = "";
                    category.Notes3                = "";
                    if (category.Depth > 1)
                    {
                        CategoryInfo info2 = CatalogHelper.GetCategory(category.ParentCategoryId.Value);
                        if (string.IsNullOrEmpty(category.Notes1))
                        {
                            category.Notes1 = info2.Notes1;
                        }
                        if (string.IsNullOrEmpty(category.Notes2))
                        {
                            category.Notes2 = info2.Notes2;
                        }
                        if (string.IsNullOrEmpty(category.Notes3))
                        {
                            category.Notes3 = info2.Notes3;
                        }
                    }
                    ValidationResults results = Hishop.Components.Validation.Validation.Validate <CategoryInfo>(category, new string[] { "ValCategory" });
                    string            msg     = string.Empty;
                    if (!results.IsValid)
                    {
                        foreach (ValidationResult result in (IEnumerable <ValidationResult>)results)
                        {
                            msg = msg + Formatter.FormatErrorMessage(result.Message);
                        }
                        this.ShowMsg(msg, false);
                    }
                    else
                    {
                        switch (CatalogHelper.UpdateCategory(category))
                        {
                        case CategoryActionStatus.Success:
                            this.ShowMsgAndReUrl(this.operatorName + "成功", true, this.reurl);
                            return;

                        case CategoryActionStatus.UpdateParentError:
                            this.ShowMsg("不能自己成为自己的上级分类", false);
                            return;
                        }
                        this.ShowMsg(this.operatorName + "商品分类错误", false);
                    }
                }
            }
            else
            {
                CategoryInfo info3 = this.GetCategory();
                if (info3 != null)
                {
                    if (CatalogHelper.AddCategory(info3) == CategoryActionStatus.Success)
                    {
                        this.ShowMsgAndReUrl("成功" + this.operatorName + "了商品分类", true, this.reurl);
                    }
                    else
                    {
                        this.ShowMsg(this.operatorName + "失败", false);
                    }
                }
            }
        }
Example #35
0
        private CategoryInfo GetCategory()
        {
            CategoryInfo target = new CategoryInfo();

            target.Name                  = this.txtCategoryName.Text.Trim();
            target.ParentCategoryId      = this.dropCategories.SelectedValue;
            target.SKUPrefix             = this.txtSKUPrefix.Text.Trim();
            target.AssociatedProductType = this.dropProductTypes.SelectedValue;
            if (!string.IsNullOrEmpty(this.txtRewriteName.Text.Trim()))
            {
                target.RewriteName = this.txtRewriteName.Text.Trim();
            }
            else
            {
                target.RewriteName = null;
            }
            target.MetaTitle       = this.txtPageKeyTitle.Text.Trim();
            target.MetaKeywords    = this.txtPageKeyWords.Text.Trim();
            target.MetaDescription = this.txtPageDesc.Text.Trim();
            target.Notes1          = this.fckNotes1.Text;
            target.Notes2          = this.fckNotes2.Text;
            target.Notes3          = this.fckNotes3.Text;
            target.DisplaySequence = 0;
            if (target.ParentCategoryId.HasValue)
            {
                CategoryInfo category = CatalogHelper.GetCategory(target.ParentCategoryId.Value);
                if ((category == null) || (category.Depth >= 5))
                {
                    this.ShowMsg(string.Format("您选择的上级分类有误,商品分类最多只支持{0}级分类", 5), false);
                    return(null);
                }
                if (string.IsNullOrEmpty(target.Notes1))
                {
                    target.Notes1 = category.Notes1;
                }
                if (string.IsNullOrEmpty(target.Notes2))
                {
                    target.Notes2 = category.Notes2;
                }
                if (string.IsNullOrEmpty(target.Notes3))
                {
                    target.Notes3 = category.Notes3;
                }
                if (string.IsNullOrEmpty(target.RewriteName))
                {
                    target.RewriteName = category.RewriteName;
                }
            }
            ValidationResults results = Hishop.Components.Validation.Validation.Validate <CategoryInfo>(target, new string[] { "ValCategory" });
            string            msg     = string.Empty;

            if (results.IsValid)
            {
                return(target);
            }
            foreach (ValidationResult result in (IEnumerable <ValidationResult>)results)
            {
                msg = msg + Formatter.FormatErrorMessage(result.Message);
            }
            this.ShowMsg(msg, false);
            return(null);
        }
Example #36
0
 /// <summary>
 /// 创建分类
 /// </summary>
 public static int CreateCategory(CategoryInfo categoryInfo)
 {
     return(BrnShop.Core.BSPData.RDBS.CreateCategory(categoryInfo));
 }
Example #37
0
        /// <summary>
        /// 搜索
        /// </summary>
        public ActionResult Search()
        {
            //搜索词
            string word = WebHelper.GetQueryString("word");
            //分类id
            int cateId = WebHelper.GetQueryInt("cateId");
            //品牌id
            int brandId = WebHelper.GetQueryInt("brandId");
            //筛选价格
            int filterPrice = WebHelper.GetQueryInt("filterPrice");
            //筛选属性
            string filterAttr = WebHelper.GetQueryString("filterAttr");
            //是否只显示有货
            int onlyStock = WebHelper.GetQueryInt("onlyStock");
            //排序列
            int sortColumn = WebHelper.GetQueryInt("sortColumn");
            //排序方向
            int sortDirection = WebHelper.GetQueryInt("sortDirection");
            //当前页数
            int page = WebHelper.GetQueryInt("page");

            //搜索词处理
            WorkContext.SearchWord = word;
            if (word.Length == 0)
            {
                return(PromptView(WorkContext.UrlReferrer, "请输入搜索词"));
            }

            //检查当前页数
            if (page < 1)
            {
                page = 1;
            }

            //筛选属性处理
            List <int> attrValueIdList = new List <int>();

            string[] filterAttrValueIdList = StringHelper.SplitString(filterAttr, "-");
            foreach (string attrValueId in filterAttrValueIdList)
            {
                int temp = TypeHelper.StringToInt(attrValueId);
                if (temp > 0)
                {
                    attrValueIdList.Add(temp);
                }
            }

            //分类信息
            CategoryInfo categoryInfo = null;

            //分类价格范围列表
            string[] catePriceRangeList = null;
            //分类筛选属性及其值列表
            List <KeyValuePair <AttributeInfo, List <AttributeValueInfo> > > cateAAndVList = null;
            //分类列表
            List <CategoryInfo> categoryList = null;
            //品牌信息
            BrandInfo brandInfo = null;
            //品牌列表
            List <BrandInfo> brandList = null;
            //商品总数量
            int totalCount = 0;
            //商品列表
            List <StoreProductInfo> productList = null;

            //搜索
            Searches.SearchMallProducts(20, page, word, cateId, brandId, filterPrice, attrValueIdList, onlyStock, sortColumn, sortDirection, ref categoryInfo, ref catePriceRangeList, ref cateAAndVList, ref categoryList, ref brandInfo, ref brandList, ref totalCount, ref productList);

            if (productList == null)
            {
                return(PromptView(WorkContext.UrlReferrer, "您搜索的商品不存在"));
            }

            //当筛选属性和分类的筛选属性数目不对应时,重置筛选属性
            if (cateAAndVList == null)
            {
                filterAttr = "0";
            }
            else
            {
                if (filterAttrValueIdList.Length != cateAAndVList.Count)
                {
                    if (cateAAndVList.Count == 0)
                    {
                        filterAttr = "0";
                    }
                    else
                    {
                        int           count = cateAAndVList.Count;
                        StringBuilder sb    = new StringBuilder();
                        for (int i = 0; i < count; i++)
                        {
                            sb.Append("0-");
                        }
                        filterAttr = sb.Remove(sb.Length - 1, 1).ToString();
                    }
                }
            }

            //用户浏览历史
            List <PartProductInfo> userBrowseHistory = BrowseHistories.GetUserBrowseHistory(WorkContext.Uid, 0);

            //分页对象
            PageModel pageModel = new PageModel(20, page, totalCount);
            //视图对象
            MallSearchModel model = new MallSearchModel()
            {
                Word                  = word,
                CateId                = cateId,
                BrandId               = brandId,
                FilterPrice           = filterPrice,
                FilterAttr            = filterAttr,
                OnlyStock             = onlyStock,
                SortColumn            = sortColumn,
                SortDirection         = sortDirection,
                FilterAttrValueIdList = attrValueIdList,
                CategoryInfo          = categoryInfo,
                CatePriceRangeList    = catePriceRangeList,
                AAndVList             = cateAAndVList,
                CategoryList          = categoryList,
                BrandInfo             = brandInfo,
                BrandList             = brandList,
                PageModel             = pageModel,
                ProductList           = productList,
                UserBrowseHistory     = userBrowseHistory
            };

            //异步保存搜索历史
            Asyn.UpdateSearchHistory(WorkContext.Uid, word);

            return(View(model));
        }
Example #38
0
        private CategoryInfo GetCategory()
        {
            CategoryInfo categoryInfo = new CategoryInfo();

            categoryInfo.IconUrl               = this.uploader1.UploadedImageUrl;
            categoryInfo.Name                  = this.txtCategoryName.Text.Trim();
            categoryInfo.ParentCategoryId      = this.dropCategories.SelectedValue;
            categoryInfo.SKUPrefix             = this.txtSKUPrefix.Text.Trim();
            categoryInfo.AssociatedProductType = this.dropProductTypes.SelectedValue;
            if (!string.IsNullOrEmpty(this.txtRewriteName.Text.Trim()))
            {
                categoryInfo.RewriteName = this.txtRewriteName.Text.Trim();
            }
            else
            {
                categoryInfo.RewriteName = null;
            }
            categoryInfo.MetaTitle       = this.txtPageKeyTitle.Text.Trim();
            categoryInfo.MetaKeywords    = this.txtPageKeyWords.Text.Trim();
            categoryInfo.MetaDescription = this.txtPageDesc.Text.Trim();
            categoryInfo.Notes1          = "";
            categoryInfo.Notes2          = "";
            categoryInfo.Notes3          = "";
            categoryInfo.DisplaySequence = 0;
            if (categoryInfo.ParentCategoryId.HasValue)
            {
                CategoryInfo category = CatalogHelper.GetCategory(categoryInfo.ParentCategoryId.Value);
                if (category == null || category.Depth >= 5)
                {
                    this.ShowMsg(string.Format("您选择的上级分类有误,商品分类最多只支持{0}级分类", 5), false);
                    return(null);
                }
                if (string.IsNullOrEmpty(categoryInfo.Notes1))
                {
                    categoryInfo.Notes1 = category.Notes1;
                }
                if (string.IsNullOrEmpty(categoryInfo.Notes2))
                {
                    categoryInfo.Notes2 = category.Notes2;
                }
                if (string.IsNullOrEmpty(categoryInfo.Notes3))
                {
                    categoryInfo.Notes3 = category.Notes3;
                }
                if (string.IsNullOrEmpty(categoryInfo.RewriteName))
                {
                    categoryInfo.RewriteName = category.RewriteName;
                }
            }
            if (string.IsNullOrEmpty(this.txtCategoryName.Text.Trim()))
            {
                this.ShowMsg("分类名称不能为空!", false);
                return(null);
            }
            string text  = Globals.RequestFormStr(this.txtfirst.ClientID.Replace("_", "$"));
            string text2 = Globals.RequestFormStr(this.txtsecond.ClientID.Replace("_", "$"));
            string text3 = Globals.RequestFormStr(this.txtthird.ClientID.Replace("_", "$"));

            if (string.IsNullOrEmpty(text))
            {
                text = "0";
            }
            if (string.IsNullOrEmpty(text2))
            {
                text2 = "0";
            }
            if (string.IsNullOrEmpty(text3))
            {
                text3 = "0";
            }
            categoryInfo.FirstCommission  = text;
            categoryInfo.SecondCommission = text2;
            categoryInfo.ThirdCommission  = text3;
            bool flag = false;

            if (System.Convert.ToDecimal(categoryInfo.FirstCommission) < 0m || System.Convert.ToDecimal(categoryInfo.FirstCommission) > 100m)
            {
                this.ShowMsg("输入的佣金格式不正确!", false);
                flag = true;
            }
            if (System.Convert.ToDecimal(categoryInfo.SecondCommission) < 0m || System.Convert.ToDecimal(categoryInfo.SecondCommission) > 100m)
            {
                this.ShowMsg("输入的佣金格式不正确!", false);
                flag = true;
            }
            if (System.Convert.ToDecimal(categoryInfo.ThirdCommission) < 0m || System.Convert.ToDecimal(categoryInfo.ThirdCommission) > 100m)
            {
                this.ShowMsg("输入的佣金格式不正确!", false);
                flag = true;
            }
            if (flag)
            {
                return(null);
            }
            ValidationResults validationResults = Validation.Validate <CategoryInfo>(categoryInfo, new string[]
            {
                "ValCategory"
            });
            string text4 = string.Empty;

            if (!validationResults.IsValid)
            {
                foreach (ValidationResult current in ((System.Collections.Generic.IEnumerable <ValidationResult>)validationResults))
                {
                    text4 += Formatter.FormatErrorMessage(current.Message);
                }
                this.ShowMsg(text4, false);
                return(null);
            }
            return(categoryInfo);
        }
Example #39
0
        private CategoryInfo GetCategory()
        {
            CategoryInfo target = new CategoryInfo {
                IconUrl               = this.uploader1.UploadedImageUrl,
                Name                  = this.txtCategoryName.Text.Trim(),
                ParentCategoryId      = this.dropCategories.SelectedValue,
                SKUPrefix             = this.txtSKUPrefix.Text.Trim(),
                AssociatedProductType = this.dropProductTypes.SelectedValue
            };

            if (!string.IsNullOrEmpty(this.txtRewriteName.Text.Trim()))
            {
                target.RewriteName = this.txtRewriteName.Text.Trim();
            }
            else
            {
                target.RewriteName = null;
            }
            target.MetaTitle       = this.txtPageKeyTitle.Text.Trim();
            target.MetaKeywords    = this.txtPageKeyWords.Text.Trim();
            target.MetaDescription = this.txtPageDesc.Text.Trim();
            target.Notes1          = "";
            target.Notes2          = "";
            target.Notes3          = "";
            target.DisplaySequence = 0;
            if (target.ParentCategoryId.HasValue)
            {
                CategoryInfo category = CatalogHelper.GetCategory(target.ParentCategoryId.Value);
                if ((category == null) || (category.Depth >= 5))
                {
                    this.ShowMsg(string.Format("您选择的上级分类有误,商品分类最多只支持{0}级分类", 5), false);
                    return(null);
                }
                if (string.IsNullOrEmpty(target.Notes1))
                {
                    target.Notes1 = category.Notes1;
                }
                if (string.IsNullOrEmpty(target.Notes2))
                {
                    target.Notes2 = category.Notes2;
                }
                if (string.IsNullOrEmpty(target.Notes3))
                {
                    target.Notes3 = category.Notes3;
                }
                if (string.IsNullOrEmpty(target.RewriteName))
                {
                    target.RewriteName = category.RewriteName;
                }
            }
            if (string.IsNullOrEmpty(this.txtCategoryName.Text.Trim()))
            {
                this.ShowMsg("分类名称不能为空!", false);
                return(null);
            }
            string str  = Globals.RequestFormStr(this.txtfirst.ClientID.Replace("_", "$"));
            string str2 = Globals.RequestFormStr(this.txtsecond.ClientID.Replace("_", "$"));
            string str3 = Globals.RequestFormStr(this.txtthird.ClientID.Replace("_", "$"));

            if (string.IsNullOrEmpty(str))
            {
                str = "0";
            }
            if (string.IsNullOrEmpty(str2))
            {
                str2 = "0";
            }
            if (string.IsNullOrEmpty(str3))
            {
                str3 = "0";
            }
            target.FirstCommission  = str;
            target.SecondCommission = str2;
            target.ThirdCommission  = str3;
            bool flag = false;

            if ((Convert.ToDecimal(target.FirstCommission) < 0M) || (Convert.ToDecimal(target.FirstCommission) > 100M))
            {
                this.ShowMsg("输入的佣金格式不正确!", false);
                flag = true;
            }
            if ((Convert.ToDecimal(target.SecondCommission) < 0M) || (Convert.ToDecimal(target.SecondCommission) > 100M))
            {
                this.ShowMsg("输入的佣金格式不正确!", false);
                flag = true;
            }
            if ((Convert.ToDecimal(target.ThirdCommission) < 0M) || (Convert.ToDecimal(target.ThirdCommission) > 100M))
            {
                this.ShowMsg("输入的佣金格式不正确!", false);
                flag = true;
            }
            if (!flag)
            {
                ValidationResults results = Hishop.Components.Validation.Validation.Validate <CategoryInfo>(target, new string[] { "ValCategory" });
                string            msg     = string.Empty;
                if (results.IsValid)
                {
                    return(target);
                }
                foreach (ValidationResult result in (IEnumerable <ValidationResult>)results)
                {
                    msg = msg + Formatter.FormatErrorMessage(result.Message);
                }
                this.ShowMsg(msg, false);
            }
            return(null);
        }
Example #40
0
        private int ProcessProduct(long paraCategory, long paraShopCategory, long paraBrand, int paraSaleStatus, long _shopid, long _userid, string mainpath, string imgpath1, string imgpath2)
        {
            string          str;
            ProductQuery    productQuery;
            IProductService productService;
            long            nextProductId;
            long            num;
            decimal         num1;
            ProductInfo     productInfo;
            int             num2     = 0;
            string          str1     = mainpath;
            CategoryInfo    category = ServiceHelper.Create <ICategoryService>().GetCategory(paraCategory);

            if (Directory.Exists(str1))
            {
                string[] files     = Directory.GetFiles(str1, "*.csv", SearchOption.AllDirectories);
                string   empty     = string.Empty;
                string[] strArrays = new string[0];
                for (int i = 0; i < files.Length; i++)
                {
                    using (StreamReader streamReader = System.IO.File.OpenText(files[i]))
                    {
                        int           num3 = 0;
                        List <string> strs = new List <string>();
                        while (true)
                        {
                            string str2 = streamReader.ReadLine();
                            empty = str2;
                            if (str2 == null || string.IsNullOrEmpty(empty))
                            {
                                break;
                            }
                            num3++;
                            if (num3 >= 4)
                            {
                                strs.Add(empty);
                            }
                        }
                        Cache.Insert(CacheKeyCollection.UserImportProductTotal(_userid), strs.Count);
                        foreach (string str3 in strs)
                        {
                            string[] strArrays1 = new string[] { "\t" };
                            strArrays = str3.Split(strArrays1, StringSplitOptions.None);
                            int length = strArrays.Length;
                            if (length == 58)
                            {
                                str          = strArrays[0].Replace("\"", "");
                                productQuery = new ProductQuery()
                                {
                                    CategoryId = new long?(category.Id),
                                    ShopId     = new long?(_shopid),
                                    KeyWords   = str
                                };
                                productService = ServiceHelper.Create <IProductService>();
                                if (productService.GetProducts(productQuery).Total <= 0)
                                {
                                    nextProductId = productService.GetNextProductId();
                                    num           = 0;
                                    num1          = decimal.Parse((strArrays[7] == string.Empty ? "0" : strArrays[7]));
                                    ProductInfo productInfo1 = new ProductInfo()
                                    {
                                        Id                   = nextProductId,
                                        TypeId               = category.TypeId,
                                        AddedDate            = DateTime.Now,
                                        BrandId              = paraBrand,
                                        CategoryId           = category.Id,
                                        CategoryPath         = category.Path,
                                        MarketPrice          = num1,
                                        ShortDescription     = string.Empty,
                                        ProductCode          = strArrays[33].Replace("\"", ""),
                                        ImagePath            = "",
                                        DisplaySequence      = 1,
                                        ProductName          = strArrays[0].Replace("\"", ""),
                                        MinSalePrice         = num1,
                                        ShopId               = _shopid,
                                        HasSKU               = true,
                                        ProductAttributeInfo = new List <ProductAttributeInfo>()
                                    };
                                    List <ProductShopCategoryInfo> productShopCategoryInfos = new List <ProductShopCategoryInfo>();
                                    ProductShopCategoryInfo        productShopCategoryInfo  = new ProductShopCategoryInfo()
                                    {
                                        ProductId      = nextProductId,
                                        ShopCategoryId = paraShopCategory
                                    };
                                    productShopCategoryInfos.Add(productShopCategoryInfo);
                                    productInfo1.Himall_ProductShopCategories = productShopCategoryInfos;
                                    ProductDescriptionInfo productDescriptionInfo = new ProductDescriptionInfo()
                                    {
                                        AuditReason          = "",
                                        Description          = strArrays[20].Replace("\"", ""),
                                        DescriptiondSuffixId = 0,
                                        DescriptionPrefixId  = 0,
                                        Meta_Description     = string.Empty,
                                        Meta_Keywords        = string.Empty,
                                        Meta_Title           = string.Empty,
                                        ProductId            = nextProductId
                                    };
                                    productInfo1.ProductDescriptionInfo = productDescriptionInfo;
                                    ProductInfo    productInfo2 = productInfo1;
                                    List <SKUInfo> sKUInfos     = new List <SKUInfo>();
                                    List <SKUInfo> sKUInfos1    = sKUInfos;
                                    SKUInfo        sKUInfo      = new SKUInfo();
                                    object[]       objArray     = new object[] { nextProductId, "0", "0", "0" };
                                    sKUInfo.Id        = string.Format("{0}_{1}_{2}_{3}", objArray);
                                    sKUInfo.Stock     = (long.TryParse(strArrays[9], out num) ? num : 0);
                                    sKUInfo.SalePrice = num1;
                                    sKUInfo.CostPrice = num1;
                                    sKUInfos1.Add(sKUInfo);
                                    productInfo2.SKUInfo     = sKUInfos;
                                    productInfo1.SaleStatus  = (paraSaleStatus == 1 ? ProductInfo.ProductSaleStatus.OnSale : ProductInfo.ProductSaleStatus.InStock);
                                    productInfo1.AuditStatus = ProductInfo.ProductAuditStatus.WaitForAuditing;
                                    productInfo = productInfo1;
                                    long id = productInfo.Id;
                                    productInfo.ImagePath = string.Concat(imgpath1, "//", id.ToString());
                                    if (strArrays[28] != string.Empty)
                                    {
                                        ImportProductImg(productInfo.Id, _shopid, files[i], strArrays[28]);
                                    }
                                    productService.AddProduct(productInfo);
                                    num2++;
                                    Log.Debug(strArrays[0].Replace("\"", ""));
                                    Cache.Insert(CacheKeyCollection.UserImportProductCount(_userid), num2);
                                }
                                else
                                {
                                    num2++;
                                    Log.Debug(string.Concat(strArrays[0].Replace("\"", ""), " : 商品不能重复导入"));
                                    Cache.Insert(CacheKeyCollection.UserImportProductCount(_userid), num2);
                                }
                            }
                            else if (length == 63)
                            {
                                str          = strArrays[0].Replace("\"", "");
                                productQuery = new ProductQuery()
                                {
                                    CategoryId = new long?(category.Id),
                                    ShopId     = new long?(_shopid),
                                    KeyWords   = str
                                };
                                productService = ServiceHelper.Create <IProductService>();
                                if (productService.GetProducts(productQuery).Total <= 0)
                                {
                                    nextProductId = productService.GetNextProductId();
                                    num1          = decimal.Parse((strArrays[7] == string.Empty ? "0" : strArrays[7]));
                                    ProductInfo productInfo3 = new ProductInfo()
                                    {
                                        Id                   = nextProductId,
                                        TypeId               = category.TypeId,
                                        AddedDate            = DateTime.Now,
                                        BrandId              = paraBrand,
                                        CategoryId           = category.Id,
                                        CategoryPath         = category.Path,
                                        MarketPrice          = num1,
                                        ShortDescription     = string.Empty,
                                        ProductCode          = strArrays[33].Replace("\"", ""),
                                        ImagePath            = "",
                                        DisplaySequence      = 1,
                                        ProductName          = strArrays[0].Replace("\"", ""),
                                        MinSalePrice         = num1,
                                        ShopId               = _shopid,
                                        HasSKU               = true,
                                        ProductAttributeInfo = new List <ProductAttributeInfo>()
                                    };
                                    List <ProductShopCategoryInfo> productShopCategoryInfos1 = new List <ProductShopCategoryInfo>();
                                    ProductShopCategoryInfo        productShopCategoryInfo1  = new ProductShopCategoryInfo()
                                    {
                                        ProductId      = nextProductId,
                                        ShopCategoryId = paraShopCategory
                                    };
                                    productShopCategoryInfos1.Add(productShopCategoryInfo1);
                                    productInfo3.Himall_ProductShopCategories = productShopCategoryInfos1;
                                    ProductDescriptionInfo productDescriptionInfo1 = new ProductDescriptionInfo()
                                    {
                                        AuditReason          = "",
                                        Description          = strArrays[20].Replace("\"", ""),
                                        DescriptiondSuffixId = 0,
                                        DescriptionPrefixId  = 0,
                                        Meta_Description     = string.Empty,
                                        Meta_Keywords        = string.Empty,
                                        Meta_Title           = string.Empty,
                                        ProductId            = nextProductId
                                    };
                                    productInfo3.ProductDescriptionInfo = productDescriptionInfo1;
                                    ProductInfo    productInfo4 = productInfo3;
                                    List <SKUInfo> sKUInfos2    = new List <SKUInfo>();
                                    List <SKUInfo> sKUInfos3    = sKUInfos2;
                                    SKUInfo        sKUInfo1     = new SKUInfo();
                                    object[]       objArray1    = new object[] { nextProductId, "0", "0", "0" };
                                    sKUInfo1.Id        = string.Format("{0}_{1}_{2}_{3}", objArray1);
                                    sKUInfo1.Stock     = (long.TryParse(strArrays[9], out num) ? num : 0);
                                    sKUInfo1.SalePrice = num1;
                                    sKUInfo1.CostPrice = num1;
                                    sKUInfos3.Add(sKUInfo1);
                                    productInfo4.SKUInfo     = sKUInfos2;
                                    productInfo3.SaleStatus  = (paraSaleStatus == 1 ? ProductInfo.ProductSaleStatus.OnSale : ProductInfo.ProductSaleStatus.InStock);
                                    productInfo3.AuditStatus = ProductInfo.ProductAuditStatus.WaitForAuditing;
                                    productInfo = productInfo3;
                                    long id1 = productInfo.Id;
                                    productInfo.ImagePath = string.Concat(imgpath1, "//", id1.ToString());
                                    if (strArrays[28] != string.Empty)
                                    {
                                        ImportProductImg(productInfo.Id, _shopid, files[i], strArrays[28]);
                                    }
                                    productService.AddProduct(productInfo);
                                    num2++;
                                    Log.Debug(strArrays[0].Replace("\"", ""));
                                    Cache.Insert(CacheKeyCollection.UserImportProductCount(_userid), num2);
                                }
                                else
                                {
                                    num2++;
                                    Log.Debug(string.Concat(strArrays[0].Replace("\"", ""), " : 商品不能重复导入"));
                                    Cache.Insert(CacheKeyCollection.UserImportProductCount(_userid), num2);
                                }
                            }
                        }
                    }
                }
            }
            return(num2);
        }
Example #41
0
 /// <summary>
 /// 更新分类
 /// </summary>
 public static void UpdateCategory(CategoryInfo categoryInfo)
 {
     BrnShop.Core.BSPData.RDBS.UpdateCategory(categoryInfo);
 }
Example #42
0
    /// <summary>
    /// 加载默认数据
    /// </summary>
    protected void LoadDefault()
    {
        List<CategoryInfo> list = CategoryManager.GetCategoryList();
        if (list.Count == 0)
        {
            CategoryInfo c = new CategoryInfo();
            c.Name = "默认分类";
            c.CreateDate = DateTime.Now;
            c.Description = "这是系统自动添加的默认分类";
            c.Slug = "default";
            c.Displayorder = 1000;

            c.Count = 0;
            CategoryManager.InsertCategory(c);
        }
        list = CategoryManager.GetCategoryList();
        ddlCategory.Items.Clear();
        ddlCategory.Items.Add(new ListItem("无分类", "0"));
        foreach (CategoryInfo c in list)
        {
            ddlCategory.Items.Add(new ListItem(c.Name + " (" + c.Count + ") ", c.CategoryId.ToString()));
        }

        ddlUrlType.Items.Clear();
        //  ddlUrlFormat.Items.Add(new ListItem("默认(由程序决定)", "0"));
        ddlUrlType.Items.Add(new ListItem(ConfigHelper.SiteUrl + "post/" + DateTime.Now.ToString(@"yyyy\/MM\/dd") + "/slug" + setting.RewriteExtension, "1"));
        ddlUrlType.Items.Add(new ListItem(ConfigHelper.SiteUrl + "post/slug" + setting.RewriteExtension, "2"));

        //   ddlUrlType.Items.Add(new ListItem(ConfigHelper.AppUrl + "post/分类别名/别名或ID" + setting.RewriteExtension, "3"));

        ddlTemplate.Items.Clear();
        System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Server.MapPath(ConfigHelper.SitePath + "themes/" + setting.Theme + "/template"));
        foreach (System.IO.FileInfo file in dir.GetFiles("post*", System.IO.SearchOption.TopDirectoryOnly))
        {
            ddlTemplate.Items.Add(new ListItem(file.Name));
        }
    }
Example #43
0
 private void btnSaveCategory_Click(object sender, System.EventArgs e)
 {
     if (this.categoryid > 0)
     {
         CategoryInfo category = CatalogHelper.GetCategory(this.categoryid);
         if (category == null)
         {
             this.ShowMsg("编缉商品分类错误,未知", false);
             return;
         }
         string arg_2D_0 = string.Empty;
         category.IconUrl               = this.uploader1.UploadedImageUrl;
         category.Name                  = this.txtCategoryName.Text;
         category.SKUPrefix             = this.txtSKUPrefix.Text;
         category.RewriteName           = this.txtRewriteName.Text;
         category.MetaTitle             = this.txtPageKeyTitle.Text;
         category.MetaKeywords          = this.txtPageKeyWords.Text;
         category.MetaDescription       = this.txtPageDesc.Text;
         category.AssociatedProductType = this.dropProductTypes.SelectedValue;
         category.Notes1                = "";
         category.Notes2                = "";
         category.Notes3                = "";
         if (category.Depth > 1)
         {
             CategoryInfo category2 = CatalogHelper.GetCategory(category.ParentCategoryId.Value);
             if (string.IsNullOrEmpty(category.Notes1))
             {
                 category.Notes1 = category2.Notes1;
             }
             if (string.IsNullOrEmpty(category.Notes2))
             {
                 category.Notes2 = category2.Notes2;
             }
             if (string.IsNullOrEmpty(category.Notes3))
             {
                 category.Notes3 = category2.Notes3;
             }
         }
         ValidationResults validationResults = Validation.Validate <CategoryInfo>(category, new string[]
         {
             "ValCategory"
         });
         string text = string.Empty;
         if (!validationResults.IsValid)
         {
             foreach (ValidationResult current in ((System.Collections.Generic.IEnumerable <ValidationResult>)validationResults))
             {
                 text += Formatter.FormatErrorMessage(current.Message);
             }
             this.ShowMsg(text, false);
             return;
         }
         CategoryActionStatus categoryActionStatus = CatalogHelper.UpdateCategory(category);
         if (categoryActionStatus == CategoryActionStatus.Success)
         {
             this.ShowMsgAndReUrl(this.operatorName + "成功", true, this.reurl);
             return;
         }
         if (categoryActionStatus == CategoryActionStatus.UpdateParentError)
         {
             this.ShowMsg("不能自己成为自己的上级分类", false);
             return;
         }
         this.ShowMsg(this.operatorName + "商品分类错误", false);
         return;
     }
     else
     {
         CategoryInfo category3 = this.GetCategory();
         if (category3 == null)
         {
             return;
         }
         if (CatalogHelper.AddCategory(category3) == CategoryActionStatus.Success)
         {
             this.ShowMsgAndReUrl("成功" + this.operatorName + "了商品分类", true, this.reurl);
             return;
         }
         this.ShowMsg(this.operatorName + "失败", false);
         return;
     }
 }
 public void DeleteCategoryInfo(CategoryInfo categoryInfo)
 {
     if (categoryInfo != null)
         categoriesInfolList.Remove(categoryInfo);
     SaveCategoryInfo();
 }
Example #45
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (string.IsNullOrEmpty(this.reurl))
            {
                this.reurl = "managecategories.aspx";
            }
            this.btnSaveCategory.Click    += new System.EventHandler(this.btnSaveCategory_Click);
            this.btnSaveAddCategory.Click += new System.EventHandler(this.btnSaveAddCategory_Click);
            if (this.categoryid > 0)
            {
                this.operatorName = "编辑";
                this.btnSaveAddCategory.Visible = false;
            }
            bool flag = !string.IsNullOrEmpty(base.Request["isCallback"]) && base.Request["isCallback"] == "true";

            if (flag)
            {
                int categoryId = 0;
                int.TryParse(base.Request["parentCategoryId"], out categoryId);
                CategoryInfo category = CatalogHelper.GetCategory(categoryId);
                if (category != null)
                {
                    base.Response.Clear();
                    base.Response.ContentType = "application/json";
                    base.Response.Write("{ ");
                    base.Response.Write(string.Format("\"SKUPrefix\":\"{0}\",\"f\":\"{1}\",\"s\":\"{2}\",\"t\":\"{3}\"", new object[]
                    {
                        category.SKUPrefix,
                        category.FirstCommission,
                        category.SecondCommission,
                        category.ThirdCommission
                    }));
                    base.Response.Write("}");
                    base.Response.End();
                }
            }
            if (!this.Page.IsPostBack)
            {
                if (this.categoryid > 0)
                {
                    CategoryInfo category2 = CatalogHelper.GetCategory(this.categoryid);
                    this.dropProductTypes.DataBind();
                    this.dropProductTypes.SelectedValue = category2.AssociatedProductType;
                    if (category2 == null)
                    {
                        base.GotoResourceNotFound();
                        return;
                    }
                    Globals.EntityCoding(category2, false);
                    this.BindCategoryInfo(category2);
                    if (category2.Depth > 1)
                    {
                        this.liURL.Style.Add("display", "none");
                        return;
                    }
                }
                else
                {
                    this.dropProductTypes.DataBind();
                    this.dropCategories.DataBind();
                }
            }
        }
Example #46
0
    private string GetCategorySelectionScript(CategoryInfo category)
    {
        string script = string.Empty;
        if (category != null)
        {
            script = string.Format("SelectNode('{0}{1}'); if (NodeSelected) {{ NodeSelected({1}, {2});}} return false;", category.CategoryName, category.CategoryID, category.CategoryParentID);
        }

        return script;
    }
Example #47
0
    /// <summary>
    /// Returns true if the given category and level is completed
    /// </summary>
    public bool IsLevelCompleted(CategoryInfo categoryInfo, int levelIndex)
    {
        string boardId = Utilities.FormatBoardId(categoryInfo.name, levelIndex);

        return(CompletedLevels.ContainsKey(boardId) && CompletedLevels[boardId]);
    }
Example #48
0
        private string BuildHtml(List <ArticlesInfo> list, CommonSettings settings)
        {
            var categoryService = WorkContext.Resolve <ICategoriesService>();

            categoryService.LanguageCode = WorkContext.CurrentCulture;
            var html = new StringBuilder();

            for (int i = 0; i < list.Count; i++)
            {
                var item = list[i];
                var cate = categoryService.GetById(item.CategoryId);
                var url  = Url.Action("NewsDetails", "News", new { categoryAlias = cate.Alias, alias = item.Alias });
                if (i == 0)
                {
                    html.Append("<div class=\"col-md-6 item-news\"><div class=\"zoom-hidden\">");
                    html.AppendFormat("<a href=\"{0}\">", url);
                    html.AppendFormat("<img class=\"img-responsive height-img image-center grow\" src=\"{0}\" />", item.Image);
                    html.Append("</a></div>");
                    html.Append("<div class=\"box-caption\">");
                    html.AppendFormat("<a href=\"{0}\">", url);
                    html.AppendFormat("<h3>{0}</h3>", item.Title);
                    html.Append("</a>");
                    html.AppendFormat("<p>{0}</p>", item.Summary);
                    html.Append("</div>");
                    html.Append("</div>");
                }
                if (i == 1)
                {
                    html.Append("<div class=\"col-md-6\">");
                    html.Append("<div class=\"row\">");
                    html.Append("<div class=\"col-md-4 item-news\"><div class=\"zoom-hidden\">");
                    html.AppendFormat("<a href=\"{0}\">", url);
                    html.AppendFormat("<img class=\"cover grow\" src=\"{0}\" />", item.Image);
                    html.Append("</a></div>");
                    html.Append("<div class=\"box-caption\">");
                    html.AppendFormat("<a href=\"{0}\">", url);
                    html.AppendFormat("<h3 class=\"text-right\">{0}</h3>", item.Title);
                    html.Append("</a>");
                    html.Append("</div>");
                    html.Append("</div>");
                }

                if (i == 2)
                {
                    html.Append("<div class=\"col-md-4 item-news\"><div class=\"zoom-hidden\">");
                    html.AppendFormat("<a href=\"{0}\">", url);
                    html.AppendFormat("<img class=\"cover grow\" src=\"{0}\" />", item.Image);
                    html.Append("</a>");
                    html.Append("<div class=\"box-caption\">");
                    html.AppendFormat("<a href=\"{0}\">", url);
                    html.AppendFormat("<h3 class=\"text-right\">{0}</h3>", item.Title);
                    html.Append("</a></div>");
                    html.Append("</div>");
                    html.Append("</div>");
                }

                if (i == 3)
                {
                    html.Append("<div class=\"col-md-4 item-news\"><div class=\"zoom-hidden\">");
                    html.AppendFormat("<a href=\"{0}\">", url);
                    html.AppendFormat("<img class=\"cover grow\" src=\"{0}\" />", item.Image);
                    html.Append("</a>");
                    html.Append("<div class=\"box-caption\">");
                    html.AppendFormat("<a href=\"{0}\">", url);
                    html.AppendFormat("<h3 class=\"text-right\">{0}</h3>", item.Title);
                    html.Append("</a></div>");
                    html.Append("</div>");
                    html.Append("</div>");
                    html.Append("</div>");
                }
            }

            CategoryInfo category  = categoryService.GetById((int)Category.News);
            CategoryInfo category2 = categoryService.GetById((int)Category.Blog);
            var          url2      = Url.Action("Index", "News", new { categoryAlias = category2.Alias });

            html.Append("<div class=\"row\">");
            html.Append("<div class=\"col-md-12\">");
            html.Append("<div class=\"our-blog\">");
            html.AppendFormat("<h2>{0}</h2>", settings.TextOurBlog);
            html.AppendFormat("<p>{0}</p>", category.Notes);
            html.Append("<div class=\"btn-news-readmore float-fix\">");
            html.AppendFormat("<a href=\"{0}\">{1}</a>", url2, settings.TextReadMore);
            html.Append("</div>");
            html.Append("<div class=\"clearfix\"></div>");
            html.Append("</div>");
            html.Append("</div>");
            html.Append("</div>");
            html.Append("</div>");

            return(html.ToString());
        }
 /// <summary>
 /// Constructor for specified category object.
 /// </summary>
 /// <param name="categoryObj">Category info object to create node for.</param>
 public CategoryNode(CategoryInfo categoryObj)
 {
     ID = categoryObj.CategoryID;
     Category = categoryObj;
 }
Example #50
0
        public static int AddCategory(CategoryInfo category)
        {
            ICategory dal = Factory <ICategory> .Create("Category");

            return(dal.Add(category));
        }
        /// <summary>
        /// Creates and appends child node for given category if not exists. Return true when successfully added.
        /// </summary>
        /// <param name="category">Category to be added.</param>
        public bool AddChild(CategoryInfo category)
        {
            if (!Contains(category.CategoryID))
            {
                Nodes.Add(new CategoryNode(category));

                return true;
            }

            return false;
        }
Example #52
0
        public static void UpdateCategory(CategoryInfo category)
        {
            ICategory dal = Factory <ICategory> .Create("Category");

            dal.Update(category);
        }
Example #53
0
 public abstract CategoryActionStatus UpdateCategory(CategoryInfo category);
Example #54
0
        private static async Task SetDataset()
        {
            var TempClass = await StoreClassesAsync();

            var TermsData = await GetTermsAsync();

            Globals.TermsData             = TermsData;
            ClientInitializor.CurrentTerm = TermsData[TermsData.Count - 1].Code;
            foreach (Classes c in TempClass)
            {
                Data obj = new Data();

                obj.StudentName = c.Student;
                obj.SectionCode = c.SectionId;

                String name = c.CourseName;
                if (name.Contains("AP "))
                {
                    obj.ClassType  = "AP";
                    obj.CourseName = name.Replace("AP ", "");
                }
                else if (name.Contains("HON "))
                {
                    obj.ClassType  = "HON";
                    obj.CourseName = name.Replace("HON ", "");
                }
                else if (name.Contains("ADV "))
                {
                    obj.ClassType  = "ADV ";
                    obj.CourseName = name.Replace("ADV ", "");
                }
                else
                {
                    obj.ClassType  = "REG";
                    obj.CourseName = name;
                }

                obj.TermCode = c.Termid;
                foreach (Terms t in TermsData)
                {
                    if (t.Code == obj.TermCode)
                    {
                        obj.TermName = t.Termname;
                    }
                }

                obj.OverallGrade = c.OverallGrade;

                obj.OverallPercent = await GetSubjectOverview(c.SectionId, c.Termid);

                obj.OverallColor = ColorGet.ColorFromPercent((int)Math.Round(obj.OverallPercent, 0));

                obj.TeachersName  = c.Teacher;
                obj.TeachersEmail = c.Email_Addr;
                obj.Period        = c.Period;

                var Cats = await SetCategoriesDataAsync(c.SectionId, c.Termid);

                foreach (CategoryInfo cats1 in Cats)
                {
                    cats1.WeightPercent = (cats1.Percent * cats1.Weight) / 100;
                }

                var Asss = await SetAssignmentsData(c.SectionId, c.Termid);

                foreach (Assignments asses in Asss)
                {
                    asses.AssignmentType = Regex.Replace(asses.AssignmentType, "[^a-zA-Z]", "");
                    if (asses.Points == 0)
                    {
                        if (asses.Grade == "")
                        {
                            asses.Grade = "NG";
                        }
                        else
                        {
                            if (asses.Grade != "X")
                            {
                                asses.Grade = "Z";
                            }
                        }
                    }
                    if (Math.Abs(asses.Possible) > 0)
                    {
                        asses.Percent = (asses.Points / asses.Possible) * 100;
                    }
                    else
                    {
                        asses.Percent = 100;
                    }
                }

                for (int i = 0; i < Asss.Count; i++)
                {
                    Asss[i].Id = i;
                }
                foreach (Assignments asses in Asss)
                {
                    int counter = 0;
                    foreach (CategoryInfo cats2 in Cats)
                    {
                        if (cats2.Description == asses.AssignmentType)
                        {
                            asses.CatIndex = counter;
                            asses.Weight   = cats2.Weight;
                        }
                        counter += 1;
                    }
                    if (asses.AssignmentType.Contains("Ungraded"))
                    {
                        asses.AssignmentType = "Ungraded";
                        asses.Weight         = 0;
                        asses.CatIndex       = (counter);
                    }

                    asses.BackColor = ColorGet.ColorFromPercent((int)Math.Round(asses.Percent, 0));
                }
                if (Asss.Where(x => x.AssignmentType.Contains("Ungraded")).Count() > 0)
                {
                    CategoryInfo uCat = new CategoryInfo();
                    uCat.Description = "Ungraded";
                    uCat.Weight      = 0;
                    Cats.Add(uCat);
                }

                obj.NoOfCat     = Cats.Count;
                obj.UCatInfoSet = Cats;

                List <CategoryInfo> tempCats = new List <CategoryInfo>();
                foreach (CategoryInfo cats3 in Cats)
                {
                    if (cats3.PointsPossible != 0)
                    {
                        tempCats.Add(cats3);
                    }
                }
                if (tempCats.Count > 1)
                {
                    CategoryInfo finalCat = new CategoryInfo();
                    finalCat.Description   = "Overall";
                    finalCat.Percent       = obj.OverallPercent;
                    finalCat.Weight        = 100;
                    finalCat.WeightPercent = obj.OverallPercent;
                    tempCats.Add(finalCat);
                }

                foreach (Assignments asses in Asss)
                {
                    if (asses.Grade != "" && asses.Grade != "NG" && asses.Grade != "X")
                    {
                        if (asses.Points == 0)
                        {
                            if (asses.Possible > 0)
                            {
                                asses.Grade = "Z";
                            }
                        }
                        else
                        {
                            if (asses.Grade != "X")
                            {
                                asses.Grade = "Graded";
                            }
                        }
                    }
                }

                obj.CatInfoSet = tempCats;

                obj.AssignmentsList = Asss;

                Globals.Dataset.Add(obj);
            }
        }
 public void AddCategoryInfo(CategoryInfo categoryInfo)
 {
     if (categoryInfo!=null)
         categoriesInfolList.Add(categoryInfo);
     SaveCategoryInfo();
 }
Example #56
0
 public abstract int CreateCategory(CategoryInfo category);
Example #57
0
    private void DeleteCategory(CategoryInfo categoryObj)
    {
        // Check if category
        if ((categoryObj != null) && CanModifyCategory(categoryObj.CategoryIsPersonal, categoryObj.CategoryIsGlobal))
        {
            CategoryInfo parentCategory = CategoryInfoProvider.GetCategoryInfo(categoryObj.CategoryParentID);

            // Check if deleted category has parent
            if (parentCategory != null)
            {
                // Switch to editing of parent category
                SwitchToEdit();
                catEdit.UserID = parentCategory.CategoryUserID;
                catEdit.CategoryID = parentCategory.CategoryID;
                catEdit.ReloadData();

                SelectedCategoryID = parentCategory.CategoryID;
                PreselectCategory(parentCategory, false);
            }
            else
            {
                SelectedCategoryID = 0;
                SelectedCategoryParentID = categoryObj.CategoryIsPersonal ? PERSONAL_CATEGORIES_ROOT_PARENT_ID : CATEGORIES_ROOT_PARENT_ID;
                SwitchToInfo();
            }

            // Delete category
            CategoryInfoProvider.DeleteCategoryInfo(categoryObj);

            pnlUpdateTree.Update();
            pnlUpdateContent.Update();
        }
    }
Example #58
0
        protected override void AttachChildControls()
        {
            int.TryParse(this.Page.Request.QueryString["categoryId"], out this.categoryId);
            int num = Globals.RequestQueryNum("isLimitedTimeDiscountId");

            this.keyWord = this.Page.Request.QueryString["keyWord"];
            this.pIds    = this.Page.Request.QueryString["pIds"];
            if (!string.IsNullOrWhiteSpace(this.keyWord))
            {
                this.keyWord = this.keyWord.Trim();
            }
            this.hdfKeyword       = (System.Web.UI.HtmlControls.HtmlInputHidden) this.FindControl("hdfKeyword");
            this.hdfKeyword.Value = this.keyWord;
            this.imgUrl           = (HiImage)this.FindControl("imgUrl");
            this.litContent       = (System.Web.UI.WebControls.Literal) this.FindControl("litContent");
            this.rptProducts      = (VshopTemplatedRepeater)this.FindControl("rptProducts");
            this.rptCategories    = (VshopTemplatedRepeater)this.FindControl("rptCategories");
            this.rptCategoryList  = (VshopTemplatedRepeater)this.FindControl("rptCategoryList");
            this.txtTotalPages    = (System.Web.UI.HtmlControls.HtmlInputHidden) this.FindControl("txtTotal");
            string text = this.Page.Request.QueryString["sort"];

            if (string.IsNullOrWhiteSpace(text))
            {
                text = "DisplaySequence";
            }
            string text2 = this.Page.Request.QueryString["order"];

            if (string.IsNullOrWhiteSpace(text2))
            {
                text2 = "desc";
            }
            int pageNumber;

            if (!int.TryParse(this.Page.Request.QueryString["page"], out pageNumber))
            {
                pageNumber = 1;
            }
            int maxNum;

            if (!int.TryParse(this.Page.Request.QueryString["size"], out maxNum))
            {
                maxNum = 20;
            }
            System.Collections.Generic.IList <CategoryInfo> maxSubCategories = CategoryBrowser.GetMaxSubCategories(this.categoryId, 1000);
            this.rptCategories.DataSource = maxSubCategories;
            this.rptCategories.DataBind();
            DataSet categoryList = CategoryBrowser.GetCategoryList();

            this.rptCategoryList.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.rptCategoryList_ItemDataBound);
            this.rptCategoryList.DataSource     = categoryList;
            this.rptCategoryList.DataBind();
            int num2;

            this.rptProducts.DataSource = ProductBrowser.GetProducts(MemberProcessor.GetCurrentMember(), null, new int?(this.categoryId), this.keyWord, pageNumber, maxNum, out num2, text, text2, this.pIds, num == 1);
            this.rptProducts.DataBind();
            this.txtTotalPages.SetWhenIsNotNull(num2.ToString());
            string title = "商品列表";

            if (this.categoryId > 0)
            {
                CategoryInfo category = CategoryBrowser.GetCategory(this.categoryId);
                if (category != null)
                {
                    title = category.Name;
                }
            }
            PageTitle.AddSiteNameTitle(title);
        }
Example #59
0
 /// <summary>
 /// Preselects category in the tree.
 /// </summary>
 /// <param name="categoryObj">Category to be selected.</param>
 /// <param name="expandLast">Indicates, if selected ategori is to be expanded.</param>
 private void PreselectCategory(CategoryInfo categoryObj, bool expandLast)
 {
     if (categoryObj != null)
     {
         // Decide which tree will be affected
         if (categoryObj.CategoryIsPersonal)
         {
             treeElemP.SelectPath = categoryObj.CategoryIDPath;
             treeElemP.SelectedItem = categoryObj.CategoryName;
             treeElemP.ExpandPath = categoryObj.CategoryIDPath + (expandLast ? "/" : "");
         }
         else
         {
             treeElemG.SelectPath = categoryObj.CategoryIDPath;
             treeElemG.SelectedItem = categoryObj.CategoryName;
             treeElemG.ExpandPath = categoryObj.CategoryIDPath + (expandLast ? "/" : "");
         }
     }
 }
Example #60
0
        private void btnSaveCategory_Click(object sender, System.EventArgs e)
        {
            CategoryInfo category = CatalogHelper.GetCategory(this.categoryId);

            if (category == null)
            {
                this.ShowMsg("编缉商品分类错误,未知", false);
                return;
            }
            if (this.fileUpload.HasFile)
            {
                try
                {
                    ResourcesHelper.DeleteImage(category.Icon);
                    category.IconUrl = CatalogHelper.UploadCategoryIcon(this.fileUpload.PostedFile);
                }
                catch
                {
                    this.ShowMsg("图片上传失败,您选择的不是图片类型的文件,或者网站的虚拟目录没有写入文件的权限", false);
                    return;
                }
            }
            else
            {
                category.IconUrl = category.Icon;
            }
            category.Name                  = this.txtCategoryName.Text;
            category.SKUPrefix             = this.txtSKUPrefix.Text;
            category.RewriteName           = this.txtRewriteName.Text;
            category.MetaTitle             = this.txtPageKeyTitle.Text;
            category.MetaKeywords          = this.txtPageKeyWords.Text;
            category.MetaDescription       = this.txtPageDesc.Text;
            category.AssociatedProductType = this.dropProductTypes.SelectedValue;
            category.Notes1                = this.fckNotes1.Text;
            //category.TaxRateId = this.dropTaxRate.SelectedValue;
            category.CategoryType = (CategoryType)System.Enum.Parse(typeof(CategoryType), this.ddlType.SelectedValue);
            int isIdsadble = 0;

            int.TryParse(this.radioButton.SelectedValue, out isIdsadble);
            category.IsDisable = isIdsadble;

            category.Notes2 = this.fckNotes2.Text;
            category.Notes3 = this.fckNotes3.Text;
            if (category.Depth > 1)
            {
                CategoryInfo category2 = CatalogHelper.GetCategory(category.ParentCategoryId.Value);
                if (string.IsNullOrEmpty(category.Notes1))
                {
                    category.Notes1 = category2.Notes1;
                }
                if (string.IsNullOrEmpty(category.Notes2))
                {
                    category.Notes2 = category2.Notes2;
                }
                if (string.IsNullOrEmpty(category.Notes3))
                {
                    category.Notes3 = category2.Notes3;
                }
            }
            ValidationResults validationResults = Validation.Validate <CategoryInfo>(category, new string[]
            {
                "ValCategory"
            });
            string text = string.Empty;

            if (!validationResults.IsValid)
            {
                foreach (ValidationResult current in (System.Collections.Generic.IEnumerable <ValidationResult>)validationResults)
                {
                    text += Formatter.FormatErrorMessage(current.Message);
                }
                this.ShowMsg(text, false);
            }
            else
            {
                CategoryActionStatus categoryActionStatus = CatalogHelper.UpdateCategory(category);
                if (categoryActionStatus == CategoryActionStatus.Success)
                {
                    base.Response.Redirect(Globals.GetAdminAbsolutePath("/product/ManageCategories.aspx"), true);
                    return;
                }
                if (categoryActionStatus == CategoryActionStatus.UpdateParentError)
                {
                    this.ShowMsg("不能自己成为自己的上级分类", false);
                    return;
                }
                this.ShowMsg("编缉商品分类错误,未知", false);
                return;
            }
        }