示例#1
0
        public MessageWriter(string categoryName)
        {
            Category category = new CategoryController().GetCachedCategoryByLinkName(categoryName, true);

            if (category != null)
                this._categoryId = category.Id;
        }
示例#2
0
        protected override string ViewLookUp(string baseName, string defaultViewName)
        {
            Category category = new CategoryController().GetCachedCategory(CategoryID, false);

            // category-name.view
            if (category.ParentId <= 0 && ViewExists(CategoryName + baseName))
                return CategoryName + baseName;

            // Subcategories
            if (category.ParentId > 0)
            {
                // parent-name.child-name.view
                if (ViewExists(category.LinkName.Replace("/", ".") + baseName))
                    return category.LinkName.Replace("/", ".") + baseName;

                // childcategory.parent-name.view
                if (ViewExists("childcategory." + category.Parent.LinkName + baseName))
                    return "childcategory." + category.Parent.LinkName + baseName;

                // childcategory.view
                if (ViewExists("childcategory" + baseName))
                    return "childcategory" + baseName;

                // parent-name.view
                if (ViewExists(category.Parent.LinkName + baseName))
                    return category.Parent.LinkName + baseName;
            }

            // category.view
            if (ViewExists("category" + baseName))
                return "category" + baseName;

            // index.view
            return base.ViewLookUp(baseName, defaultViewName);
        }
示例#3
0
        public override string RenderData()
        {
            CategoryCollection cc = null;

            if (CategoryIds == null || CategoryIds.Length == 0)
                cc = new CategoryController().GetTopLevelCachedCategories();
            else
            {
                CategoryController controller = new CategoryController();
                cc = new CategoryCollection();
                foreach (int i in CategoryIds)
                {
                    Category c = controller.GetCachedCategory(i, true);
                    if(c != null)
                        cc.Add(c);
                }
            }

            StringBuilder sb = new StringBuilder("<ul>");
            foreach(Category c in cc)
            {
                sb.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", c.Url, c.Name);
            }

            sb.Append("</ul>");

            return sb.ToString();
        }
 public CategoryControllerTests()
 {
     _categoryAdminService = A.Fake<ICategoryAdminService>();
     //use the default of the container existing
     A.CallTo(() => _categoryAdminService.ProductContainerExists()).Returns(true);
     _categoryController = new CategoryController(_categoryAdminService);
 }
示例#5
0
        public ItemWriter(string parentCategory)
        {
            Category category = new CategoryController().GetCachedCategoryByLinkName(parentCategory, true);

            if (category != null)
                this._categoryId = category.Id;
        }
示例#6
0
 private IEnumerable GetCatalogCategories()
 {
     CategoryCollection categories = new CategoryController().GetTopLevelCachedCategories();
     foreach (Category c in categories)
     {
         if (c.Type > 0 && System.Enum.IsDefined(typeof(Graffiti.Core.Marketplace.CatalogType), c.Type))
             yield return c;
     }
 }
        public CategoryControllerTests()
        {
            _viewModelFactoryMock = new Mock<SearchViewModelFactory>(null, null);
            _httpRequestMock = new Mock<HttpRequestBase>();

            var context = new Mock<HttpContextBase>();
            context.SetupGet(x => x.Request).Returns(_httpRequestMock.Object);
            
            _subject = new CategoryController(_viewModelFactoryMock.Object);
            _subject.ControllerContext = new ControllerContext(context.Object, new RouteData(), _subject);
        }
示例#8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        LiHyperLink.SetNameToCompare(Context, "presentation");

        NavigationSettings settings = NavigationSettings.Get();
        CategoryCollection cc = new CategoryController().GetTopLevelCachedCategories();

        foreach(Category c in cc)
        {
            bool found = false;
            foreach(DynamicNavigationItem di in settings.SafeItems())
            {
                if(di.NavigationType == DynamicNavigationType.Category && di.CategoryId == c.Id)
                {
                    found = true;
                    break;
                }
            }

            if(!found)
                the_Categories.Items.Add(new ListItem(c.Name,"Category-" + c.UniqueId));
        }

        Query q = Post.CreateQuery();
        q.AndWhere(Post.Columns.CategoryId, CategoryController.UnCategorizedId);
        q.AndWhere(Post.Columns.IsDeleted, false);
        q.AndWhere(Post.Columns.Status, 1);

        PostCollection pc = new PostCollection();
        pc.LoadAndCloseReader(q.ExecuteReader());

        foreach (Post p in pc)
        {
            bool found = false;
            foreach (DynamicNavigationItem di in settings.SafeItems())
            {
                if (di.NavigationType == DynamicNavigationType.Post && di.PostId == p.Id)
                {
                    found = true;
                    break;
                }
            }

            if (!found)
                the_Posts.Items.Add(new ListItem(p.Title, "Post-" + p.UniqueId));
        }

        // 0 - Title, 1 - Type, 2 - LID
        string itemFormat = "<div style=\"border: solid 1px #999; padding: 4px;\"><strong>{0} ({1})</strong><div style=\"text-align:right;\"><a title=\"Delete Link\" href=\"javascript:void();\" onclick=\"remove_Link( &#39;{1}&#39;,&#39;{0}&#39;, &#39;{2}&#39;); return false;\">Delete</a></div></div>";
        foreach (DynamicNavigationItem dni in settings.SafeItems())
        {
            lbar.Items.Add(new Telligent.Glow.OrderedListItem(string.Format(itemFormat, dni.Name, dni.NavigationType.ToString(), dni.Id), dni.Name, dni.NavigationType.ToString() + "-" + dni.Id.ToString()));
        }
    }
示例#9
0
        private IEnumerable GetCategories()
        {
            Category parentCategory = new CategoryController().GetCachedCategory(_parentCategoryName, true);

            if (parentCategory != null && parentCategory.HasChildren)
            {
                foreach (Category c in parentCategory.Children)
                {
                    yield return c;
                }
            }
        }
示例#10
0
        public RSS GetFeed(string categoryName)
        {
            var feed = new RSS();

            if (!String.IsNullOrEmpty(categoryName))
            {
                var category = new CategoryController().GetCachedCategoryByLinkName(categoryName, false);

                feed.CategoryID = category.Id;
                feed.CategoryName = category.LinkName;
            }

            return feed;
        }
示例#11
0
        protected override string ViewLookUp(string baseName, string defaultViewName)
        {
            Category category = new CategoryController().GetCachedCategory(CategoryID, false);

            if (ViewExists(CategoryName + "." + PostName + baseName))
                return CategoryName + "." + PostName + baseName;
            else if (ViewExists(CategoryName.Replace("/", ".") + ".post" + baseName))
                return CategoryName.Replace("/", ".") + ".post" + baseName;
            else if (ViewExists(CategoryName + ".post" + baseName))
                return CategoryName + ".post" + baseName;
            else if (defaultViewName == "post.view" && ViewExists(PostName + ".view"))
                return PostName + ".view";
            else if (ViewExists(PostName + baseName))
                return PostName + baseName;

            // Subcategories
            if (category.ParentId > 0)
            {
                // parent-name.child-name.view
                if (ViewExists(category.LinkName.Replace("/", ".") + ".post" + baseName))
                    return category.LinkName.Replace("/", ".") + ".post" + baseName;

                // childcategory.parent-name.post.view
                if (ViewExists("childcategory." + category.Parent.LinkName + baseName))
                    return "childcategory." + category.Parent.LinkName + baseName;

                if (ViewExists(category.LinkName.Replace("/", ".") + baseName))
                    return category.LinkName.Replace("/", ".") + baseName;

                if (ViewExists(category.Parent.LinkName + ".post" + baseName))
                    return category.Parent.LinkName + ".post" + baseName;

                if (ViewExists(category.Parent.LinkName + baseName))
                    return category.Parent.LinkName + baseName;
            }
            /*
            else if (ViewExists(CategoryName + baseName))
                return CategoryName + baseName;
            */
            else if (CategoryID == CategoryController.UnCategorizedId && ViewExists("page" + baseName))
                return "page" + baseName;

            else if (ViewExists("post" + baseName))
                return "post" + baseName;

            else if (ViewExists(defaultViewName))
                return defaultViewName;

            return base.ViewLookUp(baseName, defaultViewName);
        }
        private Category AddNewsCategory()
        {
            CategoryController cc           = new CategoryController();
            Category           newsCategory = cc.GetCachedCategory(this.newsCategoryName, true);

            if (newsCategory == null)
            {
                newsCategory          = new Category();
                newsCategory.Name     = this.newsCategoryName;
                newsCategory.ParentId = -1;
                newsCategory.Save();
            }

            return(newsCategory);
        }
示例#13
0
        public async Task PostCategory_Success()
        {
            var category = new CategoryVm
            {
                Name = "Watch"
            };

            var controller = new CategoryController(_dbContext);
            var result     = await controller.CreateCategory(category);

            var createdAtActionResult = Assert.IsType <CreatedAtActionResult>(result.Result);
            var returnValue           = Assert.IsType <CategoryVm>(createdAtActionResult.Value);

            Assert.Equal("Watch", returnValue.Name);
        }
        public async Task Edit_ThrowsWebuiException_WithInnerServiceException()
        {
            _catService.Setup(x => x.GetItemAsync(It.IsAny <int>())).Throws <ServiceException>();
            _tofService.Setup(x => x.GetListAsync()).ReturnsAsync(new List <TypeOfFlow>());
            var target = new CategoryController(_tofService.Object, null, _catService.Object, null);

            try
            {
                await target.Edit(1);
            }
            catch (WebUiException e)
            {
                Assert.IsInstanceOfType(e.InnerException, typeof(ServiceException));
            }
        }
        public async Task Add_InputWebUser_ReturnsPartialView()
        {
            var target = new CategoryController(_tofService.Object, null, null, null);

            var result = await target.Add(new WebUser()
            {
                Id = "1"
            });

            var model = (result as PartialViewResult).ViewBag.TypesOfFlow;

            _tofService.Verify(m => m.GetListAsync(), Times.Exactly(1));
            Assert.IsInstanceOfType(model, typeof(IEnumerable <TypeOfFlow>));
            Assert.IsInstanceOfType(result, typeof(PartialViewResult));
        }
        public async Task GetListCategoriesTestAsync()
        {
            // Arrange
            mockCategoryService.Setup(service => service.ListCategories()).ReturnsAsync(await CategoryTestHelper.GetCategories());
            CategoryController controller = new CategoryController(mockCategoryService.Object);

            // Act
            var result = await controller.List();

            var okResult = Assert.IsType <OkObjectResult>(result);
            var model    = Assert.IsType <List <CategoryListDto> >(okResult.Value);

            // Assert
            Assert.Equal((await CategoryTestHelper.GetCategories()).Where(c => c.Id == 1).FirstOrDefault().Title, model.Where(c => c.Id == 1).FirstOrDefault().Title);
        }
        public async void SortDownOkCategoryAsync()
        {
            // Arrange
            CategoryController controller = new CategoryController(mockCategoryService.Object);

            // Act
            var result = await controller.Down(It.IsAny <int>());

            var okResult = Assert.IsType <OkObjectResult>(result);

            // Assert
            Assert.IsType <OkObjectResult>(result);
            mockCategoryService.Verify(
                mock => mock.DownCategory(It.IsAny <int>()));
        }
示例#18
0
        public void Index_ReturnsEmptyList()
        {
            // Arrange
            var dataService = new InMemoryDataService();
            var controller  = new CategoryController(dataService, _logger, _configuration, _fileService);

            // Act
            var result = controller.Index();
            var model  = result.ExtractModel <CategoryViewModel[]>();

            // Assert
            Assert.IsInstanceOf <ViewResult>(result);
            Assert.IsNotNull(model);
            Assert.AreEqual(model.Length, 0);
        }
示例#19
0
        public static async Task AddChildCategoryAsync(CategoryController categoryController)
        {
            DisplayCategoryTree(await categoryController.GetCategoriesAsync(), null, false);

            Console.Write("Ввидите (id) : ");
            await categoryController.WalkCategoriesAsync(Console.ReadLine()); //Выбираем категорию, в которую хотим добавить подкатегорию

            Console.WriteLine("Ввидите название подкатегории блюда (Украинская кухня): ");
            var newSubcategory = await categoryController.AddChildAsync(categoryController.CurrentCategory.Id, Console.ReadLine());//Создаем или добавляем подкатегорию

            if (newSubcategory == null)
            {
                Console.WriteLine("Такая подкатегория уже есть.");
            }
        }
        public void CreateCategory_ReturnsCorrectResourceType_WhenValidObjectSubmitted()
        {
            mockData.Add(new Category
            {
                Id   = 0,
                Name = "test"
            });
            mockRepo.Setup(repo => repo.GetById(x => x.Id == 1, null))
            .Returns(Task.FromResult(mockData[0]));
            var controller = new CategoryController(mockRepo.Object, mapper);

            var result = controller.CreateCategory(new CategoryCreateDto());

            Assert.IsType <ActionResult <CategoryDto> >(result);
        }
示例#21
0
        private Category AddEventCategory()
        {
            CategoryController cc            = new CategoryController();
            Category           eventCategory = cc.GetCachedCategory(this.eventCategoryName, true);

            if (eventCategory == null)
            {
                eventCategory          = new Category();
                eventCategory.Name     = this.eventCategoryName;
                eventCategory.ParentId = -1;
                eventCategory.Save();
            }

            return(eventCategory);
        }
示例#22
0
        public async Task GetCategory_Success()
        {
            _dbContext.Categories.Add(new Category
            {
                Name = "watch"
            });
            await _dbContext.SaveChangesAsync();

            var controller = new CategoryController(_dbContext);
            var result     = await controller.GetAllCategory();

            var actionResult = Assert.IsType <ActionResult <IEnumerable <CategoryVm> > >(result);

            Assert.NotEmpty(actionResult.Value);
        }
示例#23
0
        public void addItemCategory(int id, string h = "")
        {
            var categories = CategoryController.GetByParentID("", id);

            if (categories.Count > 0)
            {
                foreach (var c in categories)
                {
                    ListItem listitem = new ListItem(h + c.CategoryName, c.ID.ToString());
                    ddlCategory.Items.Add(listitem);

                    addItemCategory(c.ID, h + "---");
                }
            }
        }
示例#24
0
        public void Put_Invalid_ID_Should_ReturnsNotFoundResult()
        {
            // Arrange
            IDataRepository <Category> mockRepository = Substitute.For <IDataRepository <Category> >();
            CategoryController         categoryCont   = new CategoryController(mockRepository);
            // Act
            Category newCat = new Category()
            {
                IsValid = false, Name = "Changed"
            };
            var notFoundResult = categoryCont.Put(68, newCat);

            // Assert
            Assert.IsType <Microsoft.AspNetCore.Mvc.NotFoundObjectResult>(notFoundResult);
        }
示例#25
0
        public async Task Category_Update_Response()
        {
            //Arrange
            var dbContext = await GetDataContext();

            var categoryController = new CategoryController(dbContext);
            //Act
            var category = categoryController.GetCategory(2).Result;

            category.CategoryName = "Updated category";
            var categoryResponse = categoryController.UpdateCategory(category).Result;

            //Assert
            Assert.Equal(categoryResponse.CategoryName, "Updated category");
        }
示例#26
0
        public void TestCreateCategoryController()
        {
            CategoryRepository categoryRepo       = new CategoryRepository(DatabaseDummy.DatabaseDummyCreate("TestCreateCategoryController"));
            CategoryController categoryController = new CategoryController(categoryRepo);

            Category category = new Category
            {
                CategoryName = "History",
                NumberOfUses = 0
            };

            var actionResult = categoryController.CreateCategory(category);

            Assert.IsNotType <BadRequestObjectResult>(actionResult);
        }
        public async Task GetCategoryTestAsync()
        {
            // Arrange
            mockCategoryService.Setup(service => service.SingleCategory(It.IsAny <int>())).ReturnsAsync(await CategoryTestHelper.GetCategory());
            CategoryController controller = new CategoryController(mockCategoryService.Object);

            // Act
            var result = await controller.Single(It.IsAny <int>());

            var okResult = Assert.IsType <OkObjectResult>(result);
            var model    = Assert.IsType <CategoryViewDto>(okResult.Value);

            // Assert
            Assert.Equal((await CategoryTestHelper.GetCategory()).Title, model.Title);
        }
        public async Task GetListContainingAllCategories_WhenCalledReturnsAllCategories()
        {
            //Arrange
            var moq = new Mock <ICategoryService>();

            moq.Setup(i => i.GetAllCategories()).ReturnsAsync(DummyCategory());

            //Act
            var controller = new CategoryController(moq.Object);

            var all = await controller.GetListContainingAllCategories();

            //Assert
            Assert.NotNull(all);
        }
        public async Task CreateCategoryTestAsync()
        {
            // Arrange
            CategoryController controller = new CategoryController(mockCategoryService.Object);

            // Act
            var result = await controller.Create(await CategoryTestHelper.GetCategoryCreateNormal());

            var okResult = Assert.IsType <OkObjectResult>(result);

            // Assert
            Assert.IsType <OkObjectResult>(result);
            mockCategoryService.Verify(
                mock => mock.CreateCategory(It.IsAny <string>(), It.IsAny <int?>()));
        }
        public async Task PostACategory_WhenNullIsPassed_ReturnsNotFound()
        {
            //Arrange
            var moq = new Mock <ICategoryService>();

            moq.Setup(i => i.CreateCategory(null));

            //Act
            var controller = new CategoryController(moq.Object);

            var result = await controller.PostACategory(null);

            //Assert
            Assert.IsType <NotFoundResult>(result);
        }
示例#31
0
        public void GetAllTest()
        {
            // Arrange
            var mock = new Mock <ICategoryRepository>();

            mock.Setup(r => r.GetAll()).Returns(GetCategories());
            var controller = new CategoryController(mock.Object);
            //Act
            var result = controller.GetAll();

            // Assert
            Assert.AreEqual(mock.Object.GetAll().Result.Count, result.Result.Count());
            Assert.IsTrue(mock.Object.GetAll().Result.TrueForAll(m => result.Result.Any(r => r.Id == m.Id &&
                                                                                        r.Name == m.Name && r.Slug == m.Slug)));
        }
        public void GetCategoryById_WhenValidIdPassed_ReturnsCorrectCategory()
        {
            //Arrange
            var moq = new Mock <ICategoryService>();

            moq.Setup(i => i.GetOneCategory(1)).Returns(DummyCategory().FirstOrDefault(x => x.CategoryId == 1));

            //Act
            var controller = new CategoryController(moq.Object);

            var category = controller.GetCategoryById(1).Result as OkObjectResult;

            //Assert
            Assert.Equal("Fiction", (category.Value as CategoryDTO).CategoryName);
        }
        public async Task GetAllCategories_ReturnsPartialViewresult()
        {
            var target = new CategoryController(null, null, null, _categoryHelper.Object);

            _categoryHelper.Setup(m => m.GetCategoriesToShowOnPage(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <Func <Category, bool> >())).ReturnsAsync(new List <Category>());

            var result = await target.GetAllCategories(new WebUser(), 1);

            var viewName = (result as PartialViewResult).ViewName;
            var model    = (result as PartialViewResult).Model as IEnumerable <Category>;

            Assert.IsNotNull(model);
            Assert.AreEqual(viewName, "CategorySummaryPartial");
            Assert.IsInstanceOfType(result, typeof(PartialViewResult));
        }
示例#34
0
        private static int GetNumberCategory(CategoryController categoryController)
        {
            int numberSelectedCategory;

            do
            {
                Console.Write("Выберете категорию: ");
                while (!int.TryParse(Console.ReadLine(), out numberSelectedCategory))
                {
                    Console.WriteLine("Не корректный выбор (введите число)");
                    Console.Write("Повторите выбор: ");
                }
            } while (numberSelectedCategory > categoryController.GetCategories().Count);
            return(numberSelectedCategory);
        }
示例#35
0
        public void GetCategoryByCorrectIdTest()
        {
            var category = new Category
            {
                Id   = 1,
                Name = "Test Category"
            };
            var repository = new Mock <ICategoryRepository>();

            repository.Setup(r => r.GetCategory(1)).Returns(category);
            var categoryController = new CategoryController(repository.Object);
            var category2          = categoryController.GetCategory(1);

            Assert.IsType <OkObjectResult>(category2);
        }
示例#36
0
        public ActionResult SiteMap()
        {
            var objCategory = new CategoryController().GetCategoryBySlug("site-map", _isClearCache);

            if (objCategory == null || objCategory.CategoryId == -1)
            {
                Response.Redirect("/404/");
            }

            var categories = new CategoryController().ListCategoryByGroup();

            ViewBag.BreadCrumb  = LoadBreadCrumb(objCategory);
            ViewBag.ObjCategory = objCategory;
            return(PartialView(categories));
        }
        public void GetCategoryById_WhenValidIdIsPassed_ReturnsOkResult()
        {
            //Arrange
            var moq = new Mock <ICategoryService>();

            moq.Setup(x => x.GetOneCategory(2)).Returns(DummyCategory().FirstOrDefault(i => i.CategoryId == 2));

            //Act
            var controller = new CategoryController(moq.Object);

            var myResult = controller.GetCategoryById(2);//Id 2 is a valid id

            //Assert
            Assert.IsType <OkObjectResult>(myResult.Result);
        }
        public async Task DeleteCategory_WhenValidIdIsPassed_ReturnsOkResult()
        {
            //Arrange
            var moq = new Mock <ICategoryService>();

            moq.Setup(r => r.RemoveCategory(1));

            //Act
            var controller = new CategoryController(moq.Object);

            var result = await controller.DeleteCategory(1);

            //Assert
            Assert.IsType <OkResult>(result);
        }
示例#39
0
        public async Task ReturnBadRequest_WhenModelIsInvalid()
        {
            var categoryServiceMocked   = new Mock <ICategoryService>();
            var mapperMocked            = new Mock <IMappingProvider>();
            var createCategoryViewModel = new CreateCategoryViewModel();

            var categoryController = new CategoryController(categoryServiceMocked.Object,
                                                            mapperMocked.Object);

            categoryController.ModelState.AddModelError("error", "error");

            var result = await categoryController.CreateCategory(createCategoryViewModel);

            Assert.AreEqual(result.GetType(), typeof(BadRequestObjectResult));
        }
示例#40
0
 private void FillCategoryNodes()
 {
     categoryController = new CategoryController(currentUser);
     treeView1.Nodes.Clear();
     foreach (var category in categoryController.categories)
     {
         TreeNode categoryNode = new TreeNode(Text = category.Name);
         if (category.Parent != null)
         {
             continue;
         }
         FillTreeNode(categoryNode);
         treeView1.Nodes.Add(categoryNode);
     }
 }
        public async Task Index_ShouldReturn_CategoryViewModel_WithAllProducts()
        {
            // Arrange
            var mockCategoryService = new Mock <ICategoryService>();
            var CategoryController  = new CategoryController(mockCategoryService.Object);
            var id = 1; // category

            // Act
            var result = await CategoryController.Index(id);

            // Assert
            var viewResult = Assert.IsType <ViewResult>(result);

            Assert.IsType <CategoryViewModel>(viewResult.Model);
        }
示例#42
0
 private IEnumerable GetMessages()
 {
     CategoryCollection categories = new CategoryController().GetTopLevelCachedCategories();
     foreach (Category c in categories)
     {
         if (c.Type == 1 && (_categoryId == 0 || _categoryId == c.Id))
         {
             Category messagesCategory = c.Children.FirstOrDefault(cat => Util.AreEqualIgnoreCase(cat.Name, MarketplacePlugin.MessagesCategoryName));
             if (messagesCategory != null)
             {
                 foreach (Post p in new Data().PostsByCategory(messagesCategory, 15))
                 {
                     yield return p;
                 }
             }
         }
     }
 }
        public CategoryPage GetCategory(string param)
        {
            var category = new CategoryController().GetCachedCategoryByLinkName(param, true);

            if (category != null)
            {
                var categoryPage = new CategoryPage();

                categoryPage.CategoryID = category.Id;
                categoryPage.CategoryName = category.LinkName;
                categoryPage.MetaDescription = category.MetaDescription;
                categoryPage.MetaKeywords = category.MetaKeywords;

                return categoryPage;
            }

            return null;
        }
示例#44
0
        protected override void LoadContent(GraffitiContext graffitiContext)
        {
            IsIndexable = false;

            graffitiContext["where"] = "category";

            Category category = new CategoryController().GetCachedCategory(CategoryID, false);

            if(CategoryName != null && !Util.AreEqualIgnoreCase(CategoryName,category.LinkName))
            {
                RedirectTo(category.Url);
            }

            graffitiContext["title"] = category.Name + " : " + SiteSettings.Get().Title;
            graffitiContext["category"] = category;

            graffitiContext.RegisterOnRequestDelegate("posts", GetCategoryPosts);

            // GetCategoryPosts needs to be called so the pager works
            GetCategoryPosts("posts", graffitiContext);
        }
示例#45
0
        protected virtual object GetCategoryPosts(string key, GraffitiContext graffitiContext)
        {
            Category category = new CategoryController().GetCachedCategory(CategoryID, false);
            int pageSize = SiteSettings.Get().PageSize;
            PostCollection pc = ZCache.Get<PostCollection>(string.Format(CacheKey, PageIndex, CategoryID, category.SortOrder, pageSize));
            if (pc == null)
            {
                pc = new PostCollection();
                Query q = PostCollection.DefaultQuery(PageIndex, pageSize, category.SortOrder);

                if (Category.IncludeChildPosts)
                {
                    if (category.ParentId > 0)
                        q.AndWhere(Post.Columns.CategoryId, CategoryID);
                    else
                    {
                        List<int> ids = new List<int>(category.Children.Count + 1);
                        foreach (Category child in category.Children)
                            ids.Add(child.Id);

                        ids.Add(category.Id);

                        q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                    }
                }
                else
                {
                    q.AndWhere(Post.Columns.CategoryId, CategoryID);
                }
                pc.LoadAndCloseReader(q.ExecuteReader());
                ZCache.InsertCache(string.Format(CacheKey, PageIndex, CategoryID, category.SortOrder, pageSize), pc, 60);
            }

            graffitiContext.TotalRecords = category.PostCount;
            graffitiContext.PageIndex = PageIndex;
            graffitiContext.PageSize = SiteSettings.Get().PageSize;

            return pc;
        }
    private void BindData(CategoryWidget widget)
    {
        txtTitle.Text = widget.Title;

        CategoryCollection cc = new CategoryController().GetTopLevelCachedCategories();

        CategoryCollection InUse = new CategoryCollection();
        CategoryCollection NotInUse = new CategoryCollection();

        NotInUse.AddRange(cc);

        foreach(int i in widget.CategoryIds)
        {
            bool found = false;
            foreach(Category c in NotInUse)
            {
                if(i == c.Id)
                {
                    InUse.Add(c);
                    found = true;
                }
            }

            if(found)
            {
                NotInUse.Remove(InUse[InUse.Count - 1]);
            }
        }

        the_Categories.DataSource = NotInUse;
        the_Categories.DataBind();

        existing_items.Items.Clear();
        foreach (Category c in InUse)
        {
            existing_items.Items.Add(new Telligent.Glow.OrderedListItem(string.Format(this.ItemFormat, c.Name, c.Id), c.Name, c.Id.ToString()));
        }
    }
示例#47
0
        /// <summary>
        /// Gets the last x amount of comments from the specified category Id
        /// </summary>
        /// <param name="numberOfComments"></param>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public CommentCollection RecentComments(int numberOfComments, int categoryId)
        {
            CommentCollection cc = ZCache.Get<CommentCollection>("Comments-Recent-" + numberOfComments + "c:" + categoryId);
            if (cc == null)
            {
                cc = new CommentCollection();
                Query q = Comment.CreateQuery();
                q.AndWhere(Comment.Columns.IsDeleted, false);
                q.AndWhere(Comment.Columns.IsPublished, true);
                if (categoryId > 0)
                {
                    Category category = new CategoryController().GetCachedCategory(categoryId, true);
                    if (category != null)
                    {
                        if (category.ParentId > 0)
                            q.AndWhere(Post.Columns.CategoryId, categoryId);
                        else
                        {
                            List<int> ids = new List<int>(category.Children.Count + 1);
                            foreach (Category child in category.Children)
                                ids.Add(child.Id);

                            ids.Add(category.Id);

                            q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                        }
                    }
                    else
                    {
                        //this should result in no data, but it will signal to
                        //the end user to edit/remove this widget
                        q.AndWhere(Post.Columns.CategoryId, categoryId);
                    }
                }
                q.Top = numberOfComments.ToString();
                q.OrderByDesc(Comment.Columns.Id);

                cc.LoadAndCloseReader(q.ExecuteReader());

                ZCache.InsertCache("Comments-Recent-" + numberOfComments + "c:" + categoryId, cc, 60);
            }

            return cc;
        }
示例#48
0
        public IEnumerable Query(IDictionary paramaters)
        {
            string type = paramaters["type"] as string;
            if (type != null)
                paramaters.Remove("type");
            else
                type = "post";

            switch(type)
            {
                case "post":

                    Query postQuery = Post.CreateQuery();
                    SetLimits(postQuery,paramaters);

                    string categoryName = paramaters["category"] as string;
                    if (categoryName != null)
                        paramaters.Remove("category");

                        if(categoryName == "none")
                            categoryName = CategoryController.UncategorizedName;

                    if (categoryName != null)
                        paramaters["categoryid"] = new CategoryController().GetCachedCategory(categoryName, false).Id;

                    if(paramaters["isDeleted"] == null)
                        paramaters["isDeleted"] = false;

                    if (paramaters["isPublished"] == null)
                    {
                        paramaters["isPublished"] = true;
                    }

                    string orderBy = paramaters["orderby"] as string;
                    if (orderBy != null)
                        paramaters.Remove("orderBy");
                    else
                        orderBy = "Published DESC";

                    postQuery.Orders.Add(orderBy);

                    string cacheKey = "Posts-";
                    foreach (string key in paramaters.Keys)
                    {
                        Column col = GetPostColumn(key);
                        postQuery.AndWhere(col, paramaters[key]);
                        cacheKey += "|" + col.Name + "|" + paramaters[key];
                    }

                    PostCollection pc = ZCache.Get<PostCollection>(cacheKey);
                    if (pc == null)
                    {
                        pc = new PostCollection();
                        pc.LoadAndCloseReader(postQuery.ExecuteReader());
                        ZCache.InsertCache(cacheKey, pc, 90);
                    }
                    return pc;

                case "comment":

                    break;

                case "category":

                    break;
            }

            return null;
        }
示例#49
0
        /// <summary>
        /// Gets a Category by the specified name
        /// </summary>
        /// <param name="categoryName"></param>
        /// <returns></returns>
        public Category GetCategory(string categoryName)
        {
            if (string.IsNullOrEmpty(categoryName))
                return null;

            if (categoryName.StartsWith("/"))
                categoryName = categoryName.Substring(1);

            if (categoryName.EndsWith("/"))
                categoryName = categoryName.Substring(0, categoryName.Length - 1);

            if (string.IsNullOrEmpty(categoryName))
                return null;

            string[] parts = categoryName.Split(new char[] { '/' });
            Category category = null;
            Category parent_Category = new CategoryController().GetCachedCategory(parts[0], true);

            if (parent_Category == null)
                return null;

            if (parts.Length > 1)
            {
                if (parent_Category.HasChildren)
                {
                    foreach (Category child_Category in parent_Category.Children)
                    {
                        if (Util.AreEqualIgnoreCase(child_Category.Name, parts[1]))
                        {
                            category = child_Category;
                            break;
                        }
                    }
                }
            }
            else
                category = parent_Category;

            return category;
        }
示例#50
0
    private void ProcessCategoryDropdownList(CategoryController cc, bool isAdmin, Category uncategorized)
    {
        if (!IsPostBack || Request.Form[CategoryList.UniqueID] != CategoryList.SelectedValue)
        {

            CategoryCollection categories = cc.GetTopLevelCachedCategories();

            CategoryList.Items.Clear();
            foreach (Category parent in categories)
            {
                if (RolePermissionManager.GetPermissions(parent.Id, GraffitiUsers.Current).Edit)
                    CategoryList.Items.Add(new ListItem(Server.HtmlDecode(parent.Name), parent.Id.ToString()));

                foreach (Category child in parent.Children)
                {
                    if (RolePermissionManager.GetPermissions(child.Id, GraffitiUsers.Current).Edit)
                        CategoryList.Items.Add(new ListItem("--" + Server.HtmlDecode(child.Name), child.Id.ToString()));
                }
            }

            if (RolePermissionManager.GetPermissions(uncategorized.Id, GraffitiUsers.Current).Edit)
                CategoryList.Items.Add(new ListItem(uncategorized.Name, uncategorized.Id.ToString()));

            if (isAdmin)
                CategoryList.Items.Add(new ListItem("[Add New Category]", "-1"));

            if (IsPostBack)
                CategoryList.SelectedValue = Request.Form[CategoryList.UniqueID];
        }
    }
示例#51
0
    protected void publish_return_click(object sender, EventArgs e)
    {
        try
        {
            if (!IsValid)
                return;

            IGraffitiUser user = GraffitiUsers.Current;

            ListItem catItem = CategoryList.SelectedItem;
            if (catItem.Value == "-1" && String.IsNullOrEmpty(newCategory.Text))
            {
                SetMessage("Please enter a name for the new Category.", StatusType.Error);
                return;
            }

            string extenedBody = txtContent_extend.Text;
            string postBody = txtContent.Text;

            if (string.IsNullOrEmpty(postBody))
            {
                SetMessage("Please enter a post body.", StatusType.Warning);
                return;
            }

            Category c = new Category();

            if (catItem.Value == "-1")
            {
                try
                {
                    Category temp = new Category();
                    temp.Name = newCategory.Text;
                    temp.Save();

                    c = temp;

                    CategoryController.Reset();
                }
                catch (Exception ex)
                {
                    SetMessage("The category could not be created. Reason: " + ex.Message, StatusType.Error);
                }
            }
            else
            {
                c = new CategoryController().GetCachedCategory(Int32.Parse(catItem.Value), false);
            }

            string pid = Request.QueryString["id"];
            Post p = pid == null ? new Post() : new Post(pid);

            if (p.IsNew)
            {
                p["where"] = "web";

                p.UserName = user.Name;

                if (Request.Form["dateChangeFlag"] == "true")
                    p.Published = PublishDate.DateTime;
                else
                    p.Published = DateTime.Now.AddHours(SiteSettings.Get().TimeZoneOffSet);
            }
            else
            {
                p.Published = PublishDate.DateTime;
            }

            p.ModifiedOn = DateTime.Now.AddHours(SiteSettings.Get().TimeZoneOffSet);

            p.PostBody = postBody;
            if (string.IsNullOrEmpty(extenedBody) || extenedBody == "<p></p>" || extenedBody == "<p>&nbsp;</p>" || extenedBody == "<br />\r\n")
            {
                p.ExtendedBody = null;
            }
            else
            {
                p.ExtendedBody = extenedBody;
            }

            p.Title = Server.HtmlEncode(txtTitle.Text);
            p.EnableComments = EnableComments.Checked;
            p.Name = txtName.Text;
            p.TagList = txtTags.Text.Trim();
            p.ContentType = "text/html";
            p.CategoryId = c.Id;
            p.Notes = txtNotes.Text;
            p.ImageUrl = postImage.Text;
            p.MetaKeywords = Server.HtmlEncode(txtKeywords.Text.Trim());
            p.MetaDescription = Server.HtmlEncode(txtMetaScription.Text.Trim());
            p.IsHome = HomeSortOverride.Checked;
            p.PostStatus = (PostStatus)Enum.Parse(typeof(PostStatus), Request.Form[PublishStatus.UniqueID]);

            CustomFormSettings cfs = CustomFormSettings.Get(c);
            if (cfs.HasFields)
            {
                foreach (CustomField cf in cfs.Fields)
                {
                    if (cf.FieldType == FieldType.CheckBox && Request.Form[cf.Id.ToString()] == null)
                        p[cf.Name] = null; // false.ToString();
                    else if (cf.FieldType == FieldType.DateTime && Request.Form[cf.Id.ToString()].IndexOf("_") > -1)
                        p[cf.Name] = null;
                    else
                        p[cf.Name] = Request.Form[cf.Id.ToString()];
                }
            }

            if (HasDuplicateName(p))
            {
                SetMessage("A post in the selected category already exists with the same name.", StatusType.Error);
                return;
            }

            PostRevisionManager.CommitPost(p, user, FeaturedSite.Checked, FeaturedCategory.Checked);

            string CatQuery = (Request.QueryString["category"] == null) ? null : (p.Status == 1) ? "&category=" + p.CategoryId : "&category=" + Request.QueryString["category"];
            string AuthQuery = (Request.QueryString["author"] == null) ? null : "&author=" + Request.QueryString["author"];
            Response.Redirect("~/graffiti-admin/posts/" + "?id=" + p.Id + "&status=" + p.Status + CatQuery + AuthQuery);
        }
        catch (Exception ex)
        {
            SetMessage("Your post could not be saved. Reason: " + ex.Message, StatusType.Error);
        }
    }
示例#52
0
    protected void Page_Load(object sender, EventArgs e)
    {
        NameValueCollection nvcCustomFields = null;
        IGraffitiUser user = GraffitiUsers.Current;
        bool isAdmin = GraffitiUsers.IsAdmin(user);
        CategoryController cc = new CategoryController();
        Category uncategorized = cc.GetCachedCategory(CategoryController.UncategorizedName, false);
        Post post = null;

        if (Request.QueryString["id"] != null)
            post = new Post(Request.QueryString["id"]);

        ProcessCategoryDropdownList(cc, isAdmin, uncategorized);

        if (!IsPostBack)
        {
            Telligent.Glow.ClientScripts.RegisterScriptsForDateTimeSelector(this);
            Util.CanWriteRedirect(Context);

            SetDefaultFormValues(isAdmin);

            if (Request.QueryString["nid"] != null)
            {
                post = new Post(Request.QueryString["nid"]);
                if (post.IsLoaded)
                {
                    if (isAdmin)
                    {
                        SetMessage("Your post was saved. View: <a href=\"" + post.Url + "\">" + post.Title + "</a>.", StatusType.Success);
                    }
                    else
                    {
                        SetMessage("Your post was saved. However, since you do not have permission to publish new content, it will need to be approved before it is viewable.", StatusType.Success);
                    }
                    FormWrapper.Visible = false;
                }
            }

            if (post != null)
            {
                bool isOriginalPublished = post.IsPublished;
                int currentVersionNumber = post.Version;

                VersionStoreCollection vsc = VersionStore.GetVersionHistory(post.Id);

                if (vsc.Count > 0)
                {
                    List<Post> the_Posts = new List<Post>();
                    foreach (VersionStore vs in vsc)
                    {
                        the_Posts.Add(ObjectManager.ConvertToObject<Post>(vs.Data));
                    }

                    the_Posts.Add(post);

                    the_Posts.Sort(delegate(Post p1, Post p2) { return Comparer<int>.Default.Compare(p2.Version, p1.Version); });

                    string versionHtml =
                         "<div style=\"width: 280px; overflow: hidden; padding: 6px 0; border-bottom: 1px solid #ccc;\"><b>Revision {0}</b> ({1})<div>by {2}</div><div style=\"font-style: italic;\">{3}</div></div>";
                    string versionText = "Revision {0}";
                    foreach (Post px in the_Posts)
                    {
                        VersionHistory.Items.Add(
                             new DropDownListItem(
                                  string.Format(versionHtml, px.Version, px.ModifiedOn.ToString("dd-MMM-yyyy"), GraffitiUsers.GetUser(px.ModifiedBy).ProperName, px.Notes),
                                  string.Format(versionText, px.Version), px.Version.ToString()));
                    }

                    int versionToEdit = Int32.Parse(Request.QueryString["v"] ?? "-1");
                    if (versionToEdit > -1)
                    {
                        foreach (Post px in the_Posts)
                        {
                            if (px.Version == versionToEdit)
                            {
                                post = px;

                                // add logic to change category if it was deleted here
                                CategoryCollection cats = new CategoryController().GetCachedCategories();
                                Category temp = cats.Find(
                                                                delegate(Category c)
                                                                {
                                                                    return c.Id == post.CategoryId;
                                                                });

                                if (temp == null && post.CategoryId != 1)
                                {
                                    post.CategoryId = uncategorized.Id;
                                    SetMessage("The category ID on this post revision could not be located. It has been marked as Uncategorized. ", StatusType.Warning);
                                }

                                break;
                            }
                        }
                    }
                    else
                    {
                        post = the_Posts[0];
                    }

                    VersionHistoryArea.Visible = true;
                    VersionHistory.SelectedValue = post.Version.ToString();
                    VersionHistory.Attributes["onchange"] = "window.location = '" +
                                                                         VirtualPathUtility.ToAbsolute("~/graffiti-admin/posts/write/") +
                                                                         "?id=" + Request.QueryString["id"] +
                                                                         "&v=' + this.options[this.selectedIndex].value;";
                }

                if (post.Id > 0)
                {
                    nvcCustomFields = post.CustomFields();

                    txtTitle.Text = Server.HtmlDecode(post.Title);
                    txtContent.Text = post.PostBody;
                    txtContent_extend.Text = post.ExtendedBody;
                    txtTags.Text = post.TagList;
                    txtName.Text = Util.UnCleanForUrl(post.Name);
                    EnableComments.Checked = post.EnableComments;
                    PublishDate.DateTime = post.Published;
                    txtNotes.Text = post.Notes;
                    postImage.Text = post.ImageUrl;
                    FeaturedSite.Checked = (post.Id == SiteSettings.Get().FeaturedId);
                    FeaturedCategory.Checked = (post.Id == post.Category.FeaturedId);
                    txtKeywords.Text = Server.HtmlDecode(post.MetaKeywords ?? string.Empty);
                    txtMetaScription.Text = Server.HtmlDecode(post.MetaDescription ?? string.Empty);
                    HomeSortOverride.Checked = post.IsHome;

                    ListItem li = CategoryList.Items.FindByValue(post.CategoryId.ToString());
                    if (li != null)
                        CategoryList.SelectedIndex = CategoryList.Items.IndexOf(li);
                    else
                        CategoryList.SelectedIndex = CategoryList.Items.IndexOf(CategoryList.Items.FindByValue(uncategorized.Id.ToString()));

                    li = PublishStatus.Items.FindByValue(post.Status.ToString());
                    if (li != null && post.Status != (int)PostStatus.PendingApproval && post.Status != (int)PostStatus.RequiresChanges)
                        PublishStatus.SelectedIndex = PublishStatus.Items.IndexOf(li);
                    else if (post.Status == (int)PostStatus.PendingApproval || post.Status == (int)PostStatus.RequiresChanges)
                    {
                        // turn published on if it is in req changes
                        ListItem li2 = PublishStatus.Items.FindByValue(Convert.ToString((int)PostStatus.Publish));
                        if (li2 != null)
                            PublishStatus.SelectedIndex = PublishStatus.Items.IndexOf(li2);
                    }

                    if (post.Version != currentVersionNumber && !isOriginalPublished)
                    {
                        SetMessage("You are editing an unpublished revision of this post.", StatusType.Warning);
                    }
                    else if (post.Version != currentVersionNumber && isOriginalPublished)
                    {
                        SetMessage("The post your are editing has been published. However, the revision you are editing has not been published.", StatusType.Warning);
                    }
                    else if (!isOriginalPublished)
                    {
                        SetMessage("You are editing an unpublished revision of this post.", StatusType.Warning);
                    }

                }
                else
                {
                    FormWrapper.Visible = false;
                    SetMessage("The post with the id " + Request.QueryString["id"] + " could not be found.", StatusType.Warning);
                }
            }
            else
            {
                ListItem liUncat = CategoryList.Items.FindByText(CategoryController.UncategorizedName);
                if (liUncat != null)
                    CategoryList.SelectedIndex = CategoryList.Items.IndexOf(liUncat);
            }
        }

        if (FormWrapper.Visible)
        {
            NavigationConfirmation.RegisterPage(this);
            NavigationConfirmation.RegisterControlForCancel(Publish_Button);

            Page.ClientScript.RegisterStartupScript(GetType(),
                 "Writer-Page-StartUp",
                 "$(document).ready(function() { var eBody = $('#extended_body')[0]; " + (!string.IsNullOrEmpty(txtContent_extend.Text) ? "eBody.style.position = 'static'; eBody.style.visibility = 'visible';" : "eBody.style.position = 'absolute'; eBody.style.visibility = 'hidden';") + "categoryChanged($('#" + CategoryList.ClientID + "')[0]); Publish_Status_Change();});", true);

            Page.ClientScript.RegisterHiddenField("dateChangeFlag", "false");
        }

        CustomFormSettings cfs = CustomFormSettings.Get(int.Parse(CategoryList.SelectedItem.Value));
        if (cfs.HasFields)
        {
            if (nvcCustomFields == null)
            {
                nvcCustomFields = new NameValueCollection();
                foreach (CustomField cf in cfs.Fields)
                {
                    if (Request.Form[cf.Id.ToString()] != null)
                        nvcCustomFields[cf.Name] = Request.Form[cf.Id.ToString()];
                }
            }

            bool isNewPost = (post != null) && (post.Id < 1);
            the_CustomFields.Text = cfs.GetHtmlForm(nvcCustomFields, isNewPost);
        }
        else
        {
            CustomFieldsTab.Tab.Enabled = false;
            the_CustomFields.Text = "";
        }

        PublishStatus.Attributes.Add("onchange", "Publish_Status_Change();");
    }
示例#53
0
        protected override void OnLoad(EventArgs e)
        {
            Initialize();

            SiteSettings settings = SiteSettings.Get();

            string baseUrl = SiteSettings.BaseUrl;

            if (string.IsNullOrEmpty(TagName))
            {
                Category category = null;
                if (CategoryID > -1)
                    category = new CategoryController().GetCachedCategory(CategoryID, false);

                if (category == null)
                {
                    if (!string.IsNullOrEmpty(settings.ExternalFeedUrl) &&
                        Request.UserAgent.IndexOf("FeedBurner", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        Context.Response.RedirectLocation = settings.ExternalFeedUrl;
                        Context.Response.StatusCode = 301;
                        Context.Response.End();
                    }
                }
                else if (!string.IsNullOrEmpty(category.FeedUrlOverride) &&
                         Request.UserAgent.IndexOf("FeedBurner", StringComparison.InvariantCultureIgnoreCase) == -1)
                {
                    Context.Response.RedirectLocation = category.FeedUrlOverride;
                    Context.Response.StatusCode = 301;
                    Context.Response.End();
                }
                else if (CategoryName != null && !Util.AreEqualIgnoreCase(CategoryName, category.LinkName))
                {
                    Context.Response.RedirectLocation = new Uri(Context.Request.Url, category.Url).ToString();
                    Context.Response.StatusCode = 301;
                    Context.Response.End();
                }

                string cacheKey = CategoryID > -1
                                      ? "Posts-Index-" + Util.PageSize + "-" + CategoryID.ToString()
                                      : string.Format("Posts-Categories-P:{0}-C:{1}-T:{2}-PS:{3}", 1, CategoryID,
                                                      SortOrderType.Descending, Util.PageSize);

                PostCollection pc = ZCache.Get<PostCollection>(cacheKey);

                if (pc == null)
                {
                    Query q = PostCollection.DefaultQuery();
                    q.Top = Util.PageSize.ToString();

                    if (SiteSettings.Get().IncludeChildPosts && macros.IsNotNull(category))
                    {
                        if (category.ParentId > 0)
                            q.AndWhere(Post.Columns.CategoryId, CategoryID);
                        else
                        {
                            List<int> ids = new List<int>(category.Children.Count + 1);
                            foreach (Category child in category.Children)
                                ids.Add(child.Id);

                            ids.Add(category.Id);

                            q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                        }
                    }
                    else
                    {
                        if (CategoryID > 0)
                            q.AndWhere(Post.Columns.CategoryId, CategoryID);
                    }

                    pc = new PostCollection();
                    pc.LoadAndCloseReader(q.ExecuteReader());

                    PostCollection permissionsFiltered = new PostCollection();

                    permissionsFiltered.AddRange(pc);

                    foreach (Post p in pc)
                    {
                        if (!RolePermissionManager.GetPermissions(p.CategoryId, GraffitiUsers.Current).Read)
                            permissionsFiltered.Remove(p);
                    }

                    ZCache.InsertCache(cacheKey, permissionsFiltered, 90);
                    pc = permissionsFiltered;
                }

                ValidateAndSetHeaders(pc, settings, Context);

                StringWriter sw = new StringWriter();
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
                XmlTextWriter writer = new XmlTextWriter(sw);

                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
                writer.WriteAttributeString("xmlns:slash", "http://purl.org/rss/1.0/modules/slash/");

                // Allow plugins to add additional xml namespaces
                Core.Events.Instance().ExecuteRssNamespace(writer);

                writer.WriteStartElement("channel");
                WriteChannel(writer, category, settings);

                // Allow plugins to add additional xml to the <channel>
                Core.Events.Instance().ExecuteRssChannel(writer);

                foreach (Post p in pc)
                {
                    writer.WriteStartElement("item");
                    WriteItem(writer, p, settings, baseUrl);

                    // Allow plugins to add additional xml to the <item>
                    Core.Events.Instance().ExecuteRssItem(writer, p);

                    writer.WriteEndElement(); // End Item
                }

                writer.WriteEndElement(); // End Channel
                writer.WriteEndElement(); // End Document

                // save XML into response
                Context.Response.ContentEncoding = System.Text.Encoding.UTF8;
                Context.Response.ContentType = "application/rss+xml";
                Context.Response.Write(sw.ToString());
            }
            else
            {
                PostCollection pc = GetTaggedPosts(TagName);

                ValidateAndSetHeaders(pc, settings, Context);

                StringWriter sw = new StringWriter();
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
                XmlTextWriter writer = new XmlTextWriter(sw);

                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
                writer.WriteAttributeString("xmlns:slash", "http://purl.org/rss/1.0/modules/slash/");

                Core.Events.Instance().ExecuteRssNamespace(writer);

                writer.WriteStartElement("channel");
                WriteChannel(writer, TagName, settings);

                // Allow plugins to add additional xml to the <channel>
                Core.Events.Instance().ExecuteRssChannel(writer);

                foreach (Post p in pc) {
                    writer.WriteStartElement("item");
                    WriteItem(writer, p, settings, baseUrl);

                    Core.Events.Instance().ExecuteRssItem(writer, p);

                    writer.WriteEndElement(); // End Item
                }

                writer.WriteEndElement(); // End Channel
                writer.WriteEndElement(); // End Document

                Context.Response.ContentEncoding = Encoding.UTF8;
                Context.Response.ContentType = "application/rss+xml";
                Context.Response.Write(sw.ToString());
            }
        }
        public void EditCategoryGoodInput()
        {
            //Arrange
            var controller = new CategoryController(Services);

            var expectedCategory = new Category { CategoryId = 1, Name = "test" };
            var allProducts = new List<Product> {
                new Product { Id = 1, Name = "tank", Price = 150, Stock = 5, Description = "blows things up", CategoryId = 1},
                new Product { Id = 1, Name = "tank", Price = 150, Stock = 5, Description = "blows things up", CategoryId = 1},
                new Product { Id = 1, Name = "tank", Price = 150, Stock = 5, Description = "blows things up", CategoryId = 1}
            };

            List<SelectListItem> expectedProductIDs = new List<SelectListItem>();
            foreach (Product p in allProducts)
            {
                string productId = Convert.ToString(p.Id);
                expectedProductIDs.Add(new SelectListItem { Text = productId, Value = productId });
            }

            //Act
            var viewResult = controller.EditCategory(1) as ViewResult;
            var actualCategory = controller.ViewBag.Category;
            var actualProductIDs = controller.ViewBag.ProductIDs;

            //Assert
            Assert.AreEqual(expectedCategory.CategoryId, actualCategory.CategoryId);
            Assert.AreEqual(expectedCategory.CategoryId, actualCategory.CategoryId);
            Assert.AreEqual(expectedCategory.CategoryId, actualCategory.CategoryId);

            Assert.AreEqual(expectedProductIDs.Count, actualProductIDs.Count);
            for (int i = 0; i < actualProductIDs.Count; i++)
            {
                Assert.AreEqual(expectedProductIDs[i].Text, actualProductIDs[i].Text);
                Assert.AreEqual(expectedProductIDs[i].Value, actualProductIDs[i].Value);
            }

            Assert.AreEqual("", viewResult.ViewName);
        }
示例#55
0
        protected override void HandleRequest(IGraffitiUser user, XmlTextWriter writer)
        {
            switch (Context.Request.HttpMethod.ToUpper())
            {
                case "GET":

                    CategoryController controller = new CategoryController();
                    CategoryCollection cc = null;
                    int count = 1;
                    if(Request.QueryString["id"] != null)
                    {
                        Category category = controller.GetCachedCategory(Int32.Parse(Request.QueryString["id"]), false);
                        cc = new CategoryCollection();
                        cc.Add(category);
                    }
                    else if (Request.QueryString["name"] != null)
                    {
                        Category category = controller.GetCachedCategory(Request.QueryString["name"], false);
                        cc = new CategoryCollection();
                        cc.Add(category);
                    }
                    else
                    {
                        cc = controller.GetAllTopLevelCachedCategories();
                        count = controller.GetAllCachedCategories().Count;
                    }
                    writer.WriteStartElement("categories");
                        writer.WriteAttributeString("pageIndex", "1");
                        writer.WriteAttributeString("pageSize", count.ToString() );
                        writer.WriteAttributeString("totalCategories", count.ToString());

                        foreach(Category category in cc)
                        {
                            WriteCategoryToXML(category, writer);
                        }
                    writer.WriteEndElement();
                    writer.Close();

                    break;

                case "POST":

                    XmlDocument doc = new XmlDocument();
                    doc.Load(Request.InputStream);

                    if (Request.Headers["Graffiti-Method"] != "DELETE")
                    {
                        if (GraffitiUsers.IsAdmin(user))
                        {
                            string xml = CreateUpdateCategory(doc);
                            writer.WriteRaw(xml);
                        }
                        else
                        {
                            UnuathorizedRequest();
                        }
                    }
                    else
                    {
                        XmlAttribute categoryIdAttribute = doc.SelectSingleNode("/category").Attributes["id"];

                        foreach (Post p in PostCollection.FetchAll())
                        {
                            if (p.CategoryId == Int32.Parse(categoryIdAttribute.Value))
                            {
                                if (p.IsDeleted)
                                {
                                    Post.DestroyDeletedPost(p.Id);
                                }
                                else
                                {
                                    Response.StatusCode = 500;
                                    writer.WriteRaw("<error>You can not delete a category that contains post.</error>");
                                    return;
                                }
                            }
                        }

                        Category.Destroy(Int32.Parse(categoryIdAttribute.Value));
                        CategoryController.Reset();

                        writer.WriteRaw("<result id=\"" + Int32.Parse(categoryIdAttribute.Value) + "\">deleted</result>");
                    }

                    break;

                default:

                    break;
            }
        }
示例#56
0
        protected string CreateUpdateCategory(XmlDocument doc)
        {
            Category category = null;
            XmlAttribute categoryIdAttribute = doc.SelectSingleNode("/category").Attributes["id"];
            if (categoryIdAttribute == null)
                category = new Category();
            else
            {
                int pid = Int32.Parse(categoryIdAttribute.Value);
                if (pid > 0)
                    category = new Category(pid);
                else
                    category = new Category();
            }

            XmlNode node = doc.SelectSingleNode("/category");

            if(category.IsNew)
            {
                category.ParentId = GetNodeValue(node.SelectSingleNode("parentId"), 0);

                if(category.ParentId > 0)
                {
                    Category parentCategory = new CategoryController().GetCachedCategory(category.ParentId, true);
                    if (parentCategory == null)
                        throw new RESTConflict("The parent category " + category.ParentId + " does not exist");

                    if (parentCategory.ParentId > 0)
                        throw new RESTConflict(
                            "Graffiti only supports two levels of categories. Please choose a root category as the parent");
                }
            }

            category.Name = GetNodeValue(node.SelectSingleNode("name"), null);
            if (string.IsNullOrEmpty(category.Name))
                throw new RESTConflict("No name was specified for the category");
            category.Name = Server.HtmlEncode(category.Name);

            category.LinkName = GetNodeValue(node.SelectSingleNode("linkName"), Util.CleanForUrl(category.Name));
            category.LinkName = Server.HtmlEncode(category.LinkName);
            category.FormattedName = category.LinkName;

            category.Body = GetNodeValue(node.SelectSingleNode("body"), null);
            category.MetaDescription = GetNodeValue(node.SelectSingleNode("metaDescription"), null);
            category.MetaKeywords = GetNodeValue(node.SelectSingleNode("metaKeywords"), null);
            category.FeedUrlOverride = GetNodeValue(node.SelectSingleNode("feedBurnerUrl"), null);

            category.SortOrderTypeId = (GetNodeValue(node.SelectSingleNode("sortOrderType"), category.SortOrderTypeId));

            if (!Enum.IsDefined(typeof(SortOrderType), category.SortOrderTypeId))
                category.SortOrderTypeId = 0;

            try
            {
                category.Save(GraffitiUsers.Current.Name);
                return "<result id = \"" + category.Id + "\">true</result>";
            }
            catch(Exception ex)
            {
                if (ex.Message.IndexOf("UNIQUE") > 0)
                    throw new RESTConflict("The suggested category name would lead to a duplicate category");

                throw;
            }
        }
示例#57
0
        /// <summary>
        /// Gets x amount of recent posts from the specified category Id
        /// </summary>
        /// <param name="numberOfPosts"></param>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public PostCollection RecentPosts(int numberOfPosts, int categoryId)
        {
            PostCollection pc = ZCache.Get<PostCollection>("Posts-Recent-" + numberOfPosts + "c:" + categoryId);
            if (pc == null)
            {
                Query q = PostCollection.DefaultQuery();

                if (categoryId > 0)
                {
                    Category category = new CategoryController().GetCachedCategory(categoryId, true);
                    if (category != null)
                    {
                        if (category.ParentId > 0)
                            q.AndWhere(Post.Columns.CategoryId, categoryId);
                        else
                        {
                            List<int> ids = new List<int>(category.Children.Count + 1);
                            foreach (Category child in category.Children)
                                ids.Add(child.Id);

                            ids.Add(category.Id);

                            q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                        }
                    }
                    else
                    {
                        //this should result in no data, but it will signal to
                        //the end user to edit/remove this widget
                        q.AndWhere(Post.Columns.CategoryId, categoryId);
                    }
                }

                q.Top = numberOfPosts.ToString();
                pc = PostCollection.FetchByQuery(q);
                ZCache.InsertCache("Posts-Recent-" + numberOfPosts + "c:" + categoryId, pc, 60);
            }
            return pc;
        }
 public new void Setup()
 {
     base.Setup();
     Services.Inject(new CategoryServiceStub(Categories));
     Services.Inject(new ProductServiceStub(Products));
     Controller = new CategoryController(Services);
 }
示例#59
0
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.RequestType != "POST" || !context.Request.IsAuthenticated)
                return;

            IGraffitiUser user = GraffitiUsers.Current;
            if (user == null)
                return;

            if (!RolePermissionManager.CanViewControlPanel(user))
                return;

            context.Response.ContentType = "text/plain";

            switch (context.Request.QueryString["command"])
            {
                case "deleteComment":

                    Comment c = new Comment(context.Request.Form["commentid"]);

                    if (RolePermissionManager.GetPermissions(c.Post.CategoryId, GraffitiUsers.Current).Publish)
                    {
                        Comment.Delete(context.Request.Form["commentid"]);
                        context.Response.Write("success");
                    }

                    break;

                case "deleteCommentWithStatus":

                    Comment c1 = new Comment(context.Request.Form["commentid"]);

                    if (RolePermissionManager.GetPermissions(c1.Post.CategoryId, GraffitiUsers.Current).Publish)
                    {
                        Comment.Delete(context.Request.Form["commentid"]);
                        context.Response.Write("The comment was deleted. <a href=\"javascript:void(0);\" onclick=\"Comments.unDelete('" + new Urls().AdminAjax + "'," + context.Request.Form["commentid"] + "); return false;\">Undo?</a>");
                    }
                    break;

                case "unDelete":
                    Comment c2 = new Comment(context.Request.Form["commentid"]);

                    if (RolePermissionManager.GetPermissions(c2.Post.CategoryId, GraffitiUsers.Current).Publish)
                    {
                        Comment comment = new Comment(context.Request.Form["commentid"]);
                        comment.IsDeleted = false;
                        comment.Save();
                        context.Response.Write("The comment was un-deleted. You may need to refresh the page to see it");
                    }
                    break;

                case "approve":
                    Comment c3 = new Comment(context.Request.Form["commentid"]);

                    if (RolePermissionManager.GetPermissions(c3.Post.CategoryId, GraffitiUsers.Current).Publish)
                    {
                        Comment cmt = new Comment(context.Request.Form["commentid"]);
                        cmt.IsDeleted = false;
                        cmt.IsPublished = true;
                        cmt.Save();
                        context.Response.Write("The comment was un-deleted and/or approved. You may need to refresh the page to see it");
                    }
                    break;

                case "deletePost":
                    try
                    {
                        Post postToDelete = new Post(context.Request.Form["postid"]);

                        Permission perm = RolePermissionManager.GetPermissions(postToDelete.CategoryId, user);

                        if (GraffitiUsers.IsAdmin(user) || perm.Publish)
                        {
                            postToDelete.IsDeleted = true;
                            postToDelete.Save(user.Name, DateTime.Now);

                            //Post.Delete(context.Request.Form["postid"]);
                            //ZCache.RemoveByPattern("Posts-");
                            //ZCache.RemoveCache("Post-" + context.Request.Form["postid"]);
                            context.Response.Write("The post was deleted. <a href=\"javascript:void(0);\" onclick=\"Posts.unDeletePost('" + new Urls().AdminAjax + "'," + context.Request.Form["postid"] + "); return false;\">Undo?</a>");
                        }
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "unDeletePost":
                    Post p = new Post(context.Request.Form["postid"]);
                    p.IsDeleted = false;
                    p.Save();
                    //ZCache.RemoveByPattern("Posts-");
                    //ZCache.RemoveCache("Post-" + context.Request.Form["postid"]);
                    //context.Response.Write("The post was un-deleted. You may need to fresh the page to see it");
                    break;

                case "permanentDeletePost":
                    Post tempPost = new Post(context.Request.Form["postid"]);
                    Post.DestroyDeletedPost(tempPost.Id);
                    context.Response.Write(tempPost.Title);
                    break;

                case "createdWidget":
                    string widgetID = context.Request.Form["id"];
                    List<WidgetDescription> the_widgets = Widgets.GetAvailableWidgets();
                    Widget widget = null;
                    foreach (WidgetDescription wia in the_widgets)
                    {
                        if (wia.UniqueId == widgetID)
                        {
                            widget = Widgets.Create(wia.WidgetType);
                            break;
                        }
                    }

                    context.Response.Write(widget.Id.ToString());

                    break;

                case "updateWidgetsOrder":

                    try
                    {
                        string listID = context.Request.Form["id"];
                        string list = "&" + context.Request.Form["list"];

                        Widgets.ReOrder(listID, list);

                        //StreamWriter sw = new StreamWriter(context.Server.MapPath("~/widgets.txt"), true);
                        //sw.WriteLine(DateTime.Now);
                        //sw.WriteLine();
                        //sw.WriteLine(context.Request.Form["left"]);
                        //sw.WriteLine(context.Request.Form["right"]);
                        //sw.WriteLine(context.Request.Form["queue"]);
                        //sw.WriteLine();
                        //sw.Close();

                        context.Response.Write("Saved!");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "deleteWidget":

                    string deleteID = context.Request.Form["id"];
                    Widgets.Delete(deleteID);
                    context.Response.Write("The widget was removed!");

                    break;

                case "createTextLink":
                    DynamicNavigationItem di = new DynamicNavigationItem();
                    di.NavigationType = DynamicNavigationType.Link;
                    di.Text = context.Request.Form["text"];
                    di.Href = context.Request.Form["href"];
                    di.Id = Guid.NewGuid();
                    NavigationSettings.Add(di);
                    context.Response.Write(di.Id);

                    break;

                case "deleteTextLink":
                    Guid g = new Guid(context.Request.Form["id"]);
                    NavigationSettings.Remove(g);
                    context.Response.Write("Success");
                    break;

                case "reOrderNavigation":
                    try
                    {
                        string navItems = "&" + context.Request.Form["navItems"];
                        NavigationSettings.ReOrder(navItems);
                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "addNavigationItem":

                    try
                    {
                        if (context.Request.Form["type"] == "Post")
                        {
                            Post navPost = Post.FetchByColumn(Post.Columns.UniqueId, new Guid(context.Request.Form["id"]));
                            DynamicNavigationItem item = new DynamicNavigationItem();
                            item.PostId = navPost.Id;
                            item.Id = navPost.UniqueId;
                            item.NavigationType = DynamicNavigationType.Post;
                            NavigationSettings.Add(item);
                            context.Response.Write("Success");
                        }
                        else if (context.Request.Form["type"] == "Category")
                        {
                            Category navCategory = Category.FetchByColumn(Category.Columns.UniqueId, new Guid(context.Request.Form["id"]));
                            DynamicNavigationItem item = new DynamicNavigationItem();
                            item.CategoryId = navCategory.Id;
                            item.Id = navCategory.UniqueId;
                            item.NavigationType = DynamicNavigationType.Category;
                            NavigationSettings.Add(item);
                            context.Response.Write("Success");
                        }

                    }
                    catch (Exception exp)
                    {
                        context.Response.Write(exp.Message);
                    }

                    break;

                case "reOrderPosts":
                    try
                    {
                        Dictionary<int, Post> posts = new Dictionary<int, Post>();
                        DataBuddy.Query query = Post.CreateQuery();
                        query.AndWhere(Post.Columns.CategoryId, int.Parse(context.Request.QueryString["id"]));
                        foreach (Post post in PostCollection.FetchByQuery(query))
                        {
                            posts[post.Id] = post;
                        }

                        string postOrder = context.Request.Form["posts"];
                        int orderNumber = 1;
                        foreach (string sId in postOrder.Split('&'))
                        {
                            Post post = null;
                            posts.TryGetValue(int.Parse(sId), out post);
                            if (post != null && post.SortOrder != orderNumber)
                            {
                                post.SortOrder = orderNumber;
                                post.Save();
                            }

                            orderNumber++;
                        }

                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "reOrderHomePosts":
                    try
                    {
                        Dictionary<int, Post> posts = new Dictionary<int, Post>();
                        DataBuddy.Query query = Post.CreateQuery();
                        query.AndWhere(Post.Columns.IsHome, true);
                        foreach (Post post in PostCollection.FetchByQuery(query))
                        {
                            posts[post.Id] = post;
                        }

                        string postOrder = context.Request.Form["posts"];
                        int orderNumber = 1;
                        foreach (string sId in postOrder.Split('&'))
                        {
                            Post post = null;
                            posts.TryGetValue(int.Parse(sId), out post);
                            if (post != null && post.HomeSortOrder != orderNumber)
                            {
                                post.HomeSortOrder = orderNumber;
                                post.Save();
                            }

                            orderNumber++;
                        }

                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "categoryForm":

                    int selectedCategory = int.Parse(context.Request.QueryString["category"] ?? "-1");
                    int postId = int.Parse(context.Request.QueryString["post"] ?? "-1");
                    NameValueCollection nvcCustomFields;
                    if (postId > 0)
                        nvcCustomFields = new Post(postId).CustomFields();
                    else
                        nvcCustomFields = new NameValueCollection();

                    CustomFormSettings cfs = CustomFormSettings.Get(selectedCategory);

                    if (cfs.HasFields)
                    {
                        foreach (CustomField cf in cfs.Fields)
                        {
                            if (context.Request.Form[cf.Id.ToString()] != null)
                                nvcCustomFields[cf.Name] = context.Request.Form[cf.Id.ToString()];
                        }

                        context.Response.Write(cfs.GetHtmlForm(nvcCustomFields, (postId < 1)));
                    }
                    else
                        context.Response.Write("");

                    break;

                case "toggleEventStatus":

                    try
                    {
                        EventDetails ed = Events.GetEvent(context.Request.QueryString["t"]);
                        ed.Enabled = !ed.Enabled;

                        if (ed.Enabled)
                            ed.Event.EventEnabled();
                        else
                            ed.Event.EventDisabled();

                        Events.Save(ed);

                        context.Response.Write(ed.Enabled ? "Enabled" : "Disabled");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "buildMainFeed":
                    try
                    {
                        FileInfo mainFeedFileInfo = new FileInfo(HttpContext.Current.Server.MapPath("~/Feed/Default.aspx"));

                        if (!mainFeedFileInfo.Directory.Exists)
                            mainFeedFileInfo.Directory.Create();

                        using (StreamWriter sw = new StreamWriter(mainFeedFileInfo.FullName, false))
                        {
                            sw.WriteLine("<%@ Page Language=\"C#\" Inherits=\"Graffiti.Core.RSS\" %>");
                            sw.Close();
                        }

                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                        return;
                    }

                    break;

                case "removeFeedData":
                    try
                    {
                        FeedManager.RemoveFeedData();
                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "buildCategoryPages":

                    try
                    {
                        CategoryCollection cc = new CategoryController().GetCachedCategories();
                        foreach (Category cat in cc)
                            cat.WritePages();

                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                        return;
                    }

                    break;

                case "buildPages":

                    try
                    {

                        Query q = Post.CreateQuery();
                        q.PageIndex = Int32.Parse(context.Request.Form["p"]);
                        q.PageSize = 20;
                        q.OrderByDesc(Post.Columns.Id);

                        PostCollection pc = PostCollection.FetchByQuery(q);
                        if (pc.Count > 0)
                        {

                            foreach (Post postToWrite in pc)
                            {
                                postToWrite.WritePages();
                                foreach (string tagName in Util.ConvertStringToList(postToWrite.TagList))
                                {
                                    if (!string.IsNullOrEmpty(tagName))
                                        Tag.WritePage(tagName);
                                }

                            }

                            context.Response.Write("Next");
                        }
                        else
                        {
                            context.Response.Write("Success");
                        }

                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                        return;
                    }

                    break;

                case "importPosts":

                    try
                    {
                        Post newPost = new Post();
                        newPost.Title = HttpContext.Current.Server.HtmlDecode(context.Request.Form["subject"].ToString());

                        string postName = HttpContext.Current.Server.HtmlDecode(context.Request.Form["name"].ToString());

                        PostCollection pc = new PostCollection();

                        if (!String.IsNullOrEmpty(postName))
                        {
                            Query q = Post.CreateQuery();
                            q.AndWhere(Post.Columns.Name, Util.CleanForUrl(postName));
                            pc.LoadAndCloseReader(q.ExecuteReader());
                        }

                        if (pc.Count > 0)
                        {
                            newPost.Name = "[RENAME ME - " + Guid.NewGuid().ToString().Substring(0, 7) + "]";
                            newPost.Status = (int)PostStatus.Draft;
                        }
                        else if (String.IsNullOrEmpty(postName))
                        {
                            newPost.Name = "[RENAME ME - " + Guid.NewGuid().ToString().Substring(0, 7) + "]";
                            newPost.Status = (int)PostStatus.Draft;
                        }
                        else
                        {
                            newPost.Name = postName;
                            newPost.Status = (int)PostStatus.Publish;
                        }

                        if (String.IsNullOrEmpty(newPost.Title))
                            newPost.Title = newPost.Name;

                        newPost.PostBody = HttpContext.Current.Server.HtmlDecode(context.Request.Form["body"].ToString());
                        newPost.CreatedOn = Convert.ToDateTime(context.Request.Form["createdon"]);
                        newPost.CreatedBy = context.Request.Form["author"];
                        newPost.ModifiedBy = context.Request.Form["author"];
                        newPost.TagList = context.Request.Form["tags"];
                        newPost.ContentType = "text/html";
                        newPost.CategoryId = Convert.ToInt32(context.Request.Form["category"]);
                        newPost.UserName = context.Request.Form["author"];
                        newPost.EnableComments = true;
                        newPost.Published = Convert.ToDateTime(context.Request.Form["createdon"]);
                        newPost.IsPublished = Convert.ToBoolean(context.Request.Form["published"]);

                        // this was causing too many posts to be in draft status.
                        // updated text on migrator to flag users to just move their content/binary directory
                        // into graffiti's root
                        //if (context.Request.Form["method"] == "dasBlog")
                        //{
                        //    if (newPost.Body.ToLower().Contains("/content/binary/"))
                        //        newPost.Status = (int)PostStatus.Draft;
                        //}

                        newPost.Save(GraffitiUsers.Current.Name);

                        int postid = Convert.ToInt32(context.Request.Form["postid"]);

                        IMigrateFrom temp = null;

                        switch (context.Request.Form["method"])
                        {
                            case "CS2007Database":

                                CS2007Database db = new CS2007Database();
                                temp = (IMigrateFrom)db;

                                break;
                            case "Wordpress":

                                Wordpress wp = new Wordpress();
                                temp = (IMigrateFrom)wp;

                                break;

                            case "BlogML":

                                BlogML bml = new BlogML();
                                temp = (IMigrateFrom)bml;

                                break;

                            case "CS21Database":
                                CS21Database csDb = new CS21Database();
                                temp = (IMigrateFrom)csDb;

                                break;

                            case "dasBlog":
                                dasBlog dasb = new dasBlog();
                                temp = (IMigrateFrom)dasb;

                                break;
                        }

                        List<MigratorComment> comments = temp.GetComments(postid);

                        foreach (MigratorComment cmnt in comments)
                        {
                            Comment ct = new Comment();
                            ct.PostId = newPost.Id;
                            ct.Body = cmnt.Body;
                            ct.Published = cmnt.PublishedOn;
                            ct.IPAddress = cmnt.IPAddress;
                            ct.WebSite = cmnt.WebSite;
                            ct.Email = string.IsNullOrEmpty(cmnt.Email) ? "" : cmnt.Email;
                            ct.Name = string.IsNullOrEmpty(cmnt.UserName) ? "" : cmnt.UserName;
                            ct.IsPublished = cmnt.IsPublished;
                            ct.IsTrackback = cmnt.IsTrackback;
                            ct.SpamScore = cmnt.SpamScore;
                            ct.DontSendEmail = true;
                            ct.DontChangeUser = true;

                            ct.Save();

                            Comment ctemp = new Comment(ct.Id);
                            ctemp.DontSendEmail = true;
                            ctemp.DontChangeUser = true;
                            ctemp.Body = HttpContext.Current.Server.HtmlDecode(ctemp.Body);
                            ctemp.Save();
                        }

                        if (newPost.Status == (int)PostStatus.Publish)
                            context.Response.Write("Success" + context.Request.Form["panel"]);
                        else
                            context.Response.Write("Warning" + context.Request.Form["panel"]);
                    }
                    catch (Exception ex)
                    {

                        context.Response.Write(context.Request.Form["panel"] + ":" + ex.Message);
                    }

                    break;

                case "saveHomeSortStatus":

                    SiteSettings siteSettings = SiteSettings.Get();
                    siteSettings.UseCustomHomeList = bool.Parse(context.Request.Form["ic"]);
                    siteSettings.Save();
                    context.Response.Write("Success");

                    break;

                case "checkCategoryPermission":

                    try
                    {
                        int catID = Int32.Parse(context.Request.QueryString["category"]);
                        string permissionName = context.Request.QueryString["permission"];
                        Permission perm = RolePermissionManager.GetPermissions(catID, user);

                        bool permissionResult = false;
                        switch (permissionName)
                        {
                            case "Publish":
                                permissionResult = perm.Publish;
                                break;
                            case "Read":
                                permissionResult = perm.Read;
                                break;
                            case "Edit":
                                permissionResult = perm.Edit;
                                break;
                        }

                        context.Response.Write(permissionResult.ToString().ToLower());
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

            }
        }
		public void Setup()
		{
			UnitOfWork = TestHelper.TestHelper.GetMockUnitOfWork();
			CategoryDbSet = TestHelper.TestHelper.GetMockCategoryDbSet();
			CategoryController = new CategoryController(UnitOfWork.Object, CategoryDbSet.Object);
		}