Example #1
0
 public static void UpdateCategoryOrder(DataTable dtOrders)
 {
     for (int i = 0; i < dtOrders.Rows.Count; i++)
     {
         ForumCategory.UpdateCategoryOrder(int.Parse(dtOrders.Rows[i]["CategoryID"].ToString()), int.Parse(dtOrders.Rows[i]["Order"].ToString()));
     }
 }
        public async Task <IActionResult> Edit(Guid id, [Bind("Name,Id")] ForumCategory forumCategory)
        {
            if (id != forumCategory.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(forumCategory);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ForumCategoryExists(forumCategory.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(forumCategory));
        }
Example #3
0
        public static void InitializeForum(ForumContext context)
        {
            context.Database.EnsureCreated();

            if (context.ForumCategories.Any())
            {
                return;   // DB has been seeded
            }

            var category = new ForumCategory[]
            {
                new ForumCategory {
                    CategoryName = "General"
                },
                new ForumCategory {
                    CategoryName = "Crypto"
                }
            };

            foreach (ForumCategory c in category)
            {
                context.ForumCategories.Add(c);
            }
            context.SaveChanges();
        }
 public virtual List<ForumCategory> GetDropList(long boardId) {
     List<ForumCategory> results = this.GetByBoard( boardId );
     ForumCategory category = new ForumCategory();
     category.Name = alang.get( typeof( ForumApp ), "plsSelectCategory" );
     results.Insert( 0, category );
     return results;
 }
Example #5
0
        public static void DeleteCategory(int CategoryID)
        {
            ForumCategory mCategory = new ForumCategory();

            mCategory.CategoryID = CategoryID;
            mCategory.CustomDelete();
        }
        public async Task <IActionResult> Edit(int id, [Bind("Name,IsDeleted,DeletedOn,Id,CreatedOn,ModifiedOn")] ForumCategory forumCategory)
        {
            if (id != forumCategory.Id)
            {
                return(this.NotFound());
            }

            if (this.ModelState.IsValid)
            {
                try
                {
                    this.dataRepository.Update(forumCategory);
                    await this.dataRepository.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!this.ForumCategoryExists(forumCategory.Id))
                    {
                        return(this.NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }

                return(this.RedirectToAction(nameof(this.Index)));
            }

            return(this.View(forumCategory));
        }
Example #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //Session["userid"] = 1; Session["forumid"] = 1;
            if (!(Convert.ToInt32(Session["userid"]) > 0))
            {
                Response.Redirect("../Pages/Registration.aspx?error=1");
            }
            if (IsPostBack)
            {
                return;
            }
            List <string> categories = new List <string>();

            categories = ForumCategory.GetPublishedCategoryNames(Convert.ToInt32(Session["forumid"]));
            categories.Insert(0, "Select a category");
            drpCategory.DataSource = categories;
            drpCategory.DataBind();
            if (Request.QueryString["sec"] != null)
            {
                drpCategory.SelectedValue = Request.QueryString["cat"].ToString();
                if (drpCategory.SelectedIndex > 0)
                {
                    drpSection.DataSource = ForumSection.GetAllSectionNames(drpCategory.SelectedItem.Text);
                    drpSection.DataBind();
                    drpSection.SelectedValue = Request.QueryString["sec"].ToString();
                }
                else
                {
                    drpSection.Items.Clear();
                    drpSection.Items.Add("Select a section");
                }
            }
        }
        private void CreateCountryGroups(int parentCategory, Dictionary <int, ForumCategory> items)
        {
            //var items = new List<ForumCategory>();

            var curId = parentCategory;

            var context   = new _8a_oldContext();
            var countries = context.Set <Model.ForumThreads>().Where(f => f.CountryCode != "GLOBAL" && f.ObjectClass == "CLS_ForumGeneral").Select(f => f.CountryCode).Distinct().ToList();

            foreach (var countryISO3 in countries)
            {
                var country = SeedStore.GetCountryByCountryISO3(countryISO3);
                if (country == null)
                {
                    Console.Write(Environment.NewLine);
                    Console.WriteLine("countrycode: '" + countryISO3 + "' not found. Skipped creating this country");
                    continue;
                }
                var now      = DateTime.Now;
                var newGroup = new ForumCategory
                {
                    Id           = ++curId,
                    Slug         = country.Slug,
                    Name         = country.Name,
                    UserId       = SeedStore.GetZeroUserId(),
                    DateCreated  = now,
                    DateModified = now,
                    ParentId     = parentCategory
                };
                items.Add(newGroup.Id.Value, newGroup);
            }

            //return items;
        }
            public async Task <Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                ForumCategory forumCategory = await _context.ForumCategories.SingleOrDefaultAsync(x => x.Id == request.ForumCategoryId);

                if (forumCategory == null)
                {
                    throw new RestException(HttpStatusCode.BadRequest, "Invalid forum category.");
                }

                var newForum = new Forum
                {
                    Title           = request.Title,
                    Description     = request.Description ?? string.Empty,
                    Icon            = request.Icon ?? string.Empty,
                    ForumCategoryFK = forumCategory.Id,
                    ForumCategory   = forumCategory
                };

                _context.Add(newForum);

                if (await _context.SaveChangesAsync() > 0)
                {
                    return(Unit.Value);
                }
                else
                {
                    throw new Exception("Problem saving changes");
                }
            }
Example #10
0
        public static ForumCategory ValidateCategory( ForumCategory category, MvcContext ctx )
        {
            if (category == null) category = new ForumCategory();

            String name = ctx.Post( "Name" );
            if (strUtil.IsNullOrEmpty( name ))
                ctx.errors.Add( lang.get( "exName" ) );

            String nameColor = ctx.Post( "NameColor" );
            if (strUtil.HasText( nameColor )) {
                String errorInfo = alang( ctx, "exColorFormat" );
                if (nameColor.Length != 7) ctx.errors.Add( errorInfo );
                if (nameColor.StartsWith( "#" ) == false) ctx.errors.Add( errorInfo );
            }

            int boardId = ctx.PostInt( "BoardId" );

            category.Name = name;
            category.NameColor = nameColor;
            category.BoardId = boardId;
            category.OwnerId = ctx.owner.Id;
            category.OwnerType = ctx.owner.obj.GetType().FullName;
            category.Creator = (User)ctx.viewer.obj;

            return category;
        }
        public void Create()
        {
            ForumCategory category = ForumValidator.ValidateCategory(ctx);

            if (errors.HasErrors)
            {
                run(Admin, category.BoardId);
                return;
            }

            ForumBoard board = boardService.GetById(category.BoardId, ctx.owner.obj);

            if (board == null)
            {
                run(Admin, category.BoardId);
                return;
            }

            category.AppId = board.AppId;
            Result result = categoryService.Insert(category);

            if (result.HasErrors)
            {
                errors.Join(result);
                run(Admin, category.BoardId);
                return;
            }

            logService.Add((User)ctx.viewer.obj, ctx.app.Id, string.Format(alang("logAddCategory"), category.Name, board.Name), ctx.Ip);
            redirect(Admin, board.Id);
        }
Example #12
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            ForumCategory category;
            int           published;

            if (drpPublish1.SelectedIndex == 0)
            {
                published = 1;
            }
            else
            {
                published = 0;
            }
            //Session["userid"] = 1;
            //Session["forumid"] = 1;
            if (!string.IsNullOrEmpty(txtDesc1.Text))
            {
                category = new ForumCategory(txtTitle1.Text, Convert.ToInt32(Session["userid"]), published, Convert.ToInt32(Session["forumid"]), txtDesc1.Text);
            }
            else
            {
                category = new ForumCategory(txtTitle1.Text, Convert.ToInt32(Session["userid"]), published, Convert.ToInt32(Session["forumid"]));
            }
            category.CreateCategoryintoDb();
        }
Example #13
0
 private void OK_Click(object sender, RoutedEventArgs e)
 {
     if (CheckFields())
     {
         var category = db.ForumCategories.Where(e => e.Name.Equals(Category.SelectedItem)).FirstOrDefault();
         if (SelectedId == 0)
         {
             if (category != null)
             {
                 db.ForumCategories.Add(new ForumCategory
                 {
                     Name     = Name.Text,
                     Category = category.Id
                 });
             }
             else
             {
                 db.ForumCategories.Add(new ForumCategory {
                     Name = Name.Text
                 });
             }
         }
         else
         {
             ForumCategory item = db.ForumCategories.Where(e => e.Id == SelectedId).Single();
             item.Name = Name.Text;
             if (category != null)
             {
                 item.Category = category.Id;
             }
         }
         db.SaveChanges();
         Exit();
     }
 }
        public void SaveSort(int boardId)
        {
            int    id  = ctx.PostInt("id");
            String cmd = ctx.Post("cmd");

            ForumCategory category = categoryService.GetById(id, ctx.owner.obj);

            if (category == null)
            {
                echoRedirect(lang("exDataNotFound"));
                return;
            }

            List <ForumCategory> list = categoryService.GetByBoard(boardId);

            if (cmd == "up")
            {
                new SortUtil <ForumCategory>(category, list).MoveUp();
                echoRedirect("ok");
            }
            else if (cmd == "down")
            {
                new SortUtil <ForumCategory>(category, list).MoveDown();
                echoRedirect("ok");
            }
            else
            {
                echoError(lang("exUnknowCmd"));
            }
        }
 public ForumCategory SelectForumCategoryByURLToken(string urlToken)
 {
     using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
     {
         using (SqlConnection conn = new SqlConnection(DatabaseManager.DatabaseEngine.ConnectionString))
         {
             conn.Open();
             SqlCommand cmd = new SqlCommand("ForumCategory_SelectByURLToken", conn);
             cmd.CommandType = CommandType.StoredProcedure;
             cmd.Parameters.Add(new SqlParameter("@URLToken", urlToken));
             SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
             ForumCategory entity;
             if (!reader.Read())
             {
                 entity = null;
             }
             else
             {
                 entity = new ForumCategory(reader);
             }
             reader.Close();
             return(entity);
         }
     }
 }
 public ForumTopic()
 {
     Messages = new List<ForumMessage>();
     Category = new ForumCategory();
     TopicInbox = new List<ForumTopicInbox>();
     Watchers = new List<ForumTopicWatchers>();
 }
        public async Task <IActionResult> Edit(Int32?id, ForumCategory model)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var forumCategory = await _context.ForumCategorys
                                .SingleOrDefaultAsync(m => m.Id == id);

            if (forumCategory == null)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                forumCategory.Name = model.Name;

                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(model));
        }
        public void Add(ForumCategory category)
        {
            DbCommand comm = this.GetCommand("SPForumsCategoriesInsert");
            comm.AddParameter<string>(this.Factory, "CategoryName", category.Name);
            comm.AddParameter<int>(this.Factory, "CategoryOrder", category.Order);

            comm.SafeExecuteNonQuery();
        }
Example #19
0
        public async Task <bool> CreateCategoryAsync(ForumCategory newCategory)
        {
            var categories = _context.ForumCategories;
            await categories.AddAsync(newCategory);

            await _context.SaveChangesAsync();

            return(true);
        }
 private void LoadCategories()
 {
     foreach (Category c in admin.Categories)
     {
         ForumCategory forumCategory = (ForumCategory)LoadControl("UserControls/ForumCategory.ascx");
         forumCategory.Category = c;
         category.Controls.Add(forumCategory);
     }
 }
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            ForumCategory forumCategory = await db.ForumCategories.FindAsync(id);

            db.ForumCategories.Remove(forumCategory);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
        public virtual List <ForumCategory> GetDropList(int boardId)
        {
            List <ForumCategory> results  = this.GetByBoard(boardId);
            ForumCategory        category = new ForumCategory();

            category.Name = alang.get(typeof(ForumApp), "plsSelectCategory");
            results.Insert(0, category);
            return(results);
        }
Example #23
0
        public Boolean CanEditForumCategory(ForumCategory forumCategory)
        {
            if (this.HttpContext.User.IsInRole(ApplicationRoles.Administrators))
            {
                return(true);
            }

            return(false);
        }
        public async Task CreateNewThreadShouldAddCorrectly()
        {
            var store = new Mock <IUserStore <ApplicationUser> >();

            var userManager = new UserManager <ApplicationUser>(store.Object, null, null, null, null, null, null, null, null);

            var catRepo    = new Mock <IDeletableEntityRepository <ForumCategory> >();
            var catService = new ForumCategoryService(catRepo.Object);

            var replyRepo = new Mock <IDeletableEntityRepository <ForumReply> >();

            var threadList = new List <ForumThread>();

            var newForumCategory = new ForumCategory()
            {
                Id = 1, Title = "title1"
            };
            var newForumCategory2 = new ForumCategory()
            {
                Id = 2, Title = "title2"
            };

            threadList.Add(new ForumThread()
            {
                Id = 1, Title = "thread1", Category = newForumCategory
            });
            threadList.Add(new ForumThread()
            {
                Id = 2, Title = "thread2", Category = newForumCategory
            });
            threadList.Add(new ForumThread()
            {
                Id = 3, Title = "thread3", Category = newForumCategory
            });
            threadList.Add(new ForumThread()
            {
                Id = 4, Title = "thread4", Category = newForumCategory2
            });
            threadList.Add(new ForumThread()
            {
                Id = 5, Title = "thread5"
            });

            var threadRepo = new Mock <IDeletableEntityRepository <ForumThread> >();

            threadRepo.Setup(x => x.All()).Returns(threadList.AsQueryable());
            threadRepo.Setup(x => x.AddAsync(It.IsAny <ForumThread>()))
            .Callback((ForumThread t) => threadList.Add(t));

            var threadService = new ForumThreadService(threadRepo.Object, replyRepo.Object, catService, userManager);

            await threadService.CreateNewThread("13456", 2, "title1", "111");

            Assert.True(threadRepo.Object.All().Any(x => x.Title == "title1"));
            Assert.False(threadRepo.Object.All().Any(x => x.Title == "title123"));
        }
Example #25
0
        public async Task <bool> CreateCategoryAsync(ForumCategory newCategory)
        {
            using var context = _dbFactory.CreateDbContext();
            var categories = context.ForumCategories;
            await categories.AddAsync(newCategory);

            await context.SaveChangesAsync();

            return(true);
        }
 protected virtual ForumCategory ParseBasicPageContentRow(DataRow dr)
 {
     var category = new ForumCategory()
     {
         Id = dr.Get<int>("CategoryId"),
         Name = dr.GetString("CategoryName"),
         Order = dr.Get<int>("CategoryOrder")
     };
     return category;
 }
Example #27
0
 public ActionResult Edit([Bind(Include = "ForumCategoryId,Name")] ForumCategory forumCategory)
 {
     if (ModelState.IsValid)
     {
         db.Entry(forumCategory).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(forumCategory));
 }
        public static string GetForumCategory(RestCommand command, int categoryID)
        {
            ForumCategory forumCategory = ForumCategories.GetForumCategory(command.LoginUser, categoryID);

            if (forumCategory.OrganizationID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            return(forumCategory.GetXml("ForumCategory", true));
        }
Example #29
0
        public async Task <IActionResult> AddCategory(ForumCategory category)
        {
            await _forumRepository.AddCategory(category);

            if (await _forumRepository.SaveChanges() == true)
            {
                return(new OkObjectResult(category));
            }
            return(new BadRequestObjectResult(category));
        }
Example #30
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (IsPostBack)
     {
         return;
     }
     //Session["forumid"] = 1;
     drpCategories.DataSource = ForumCategory.GetPublishedCategoryNames(Convert.ToInt32(Session["forumid"]));
     drpCategories.DataBind();
 }
Example #31
0
        public ActionResult Create([Bind(Include = "ForumCategoryId,Name")] ForumCategory forumCategory)
        {
            if (ModelState.IsValid)
            {
                db.ForumCategorys.Add(forumCategory);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(forumCategory));
        }
        public async Task <ActionResult> Edit([Bind(Include = "Id,Category,CategoryDescription")] ForumCategory forumCategory)
        {
            if (ModelState.IsValid)
            {
                db.Entry(forumCategory).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(forumCategory));
        }
Example #33
0
        public static int InsertArticleItem(int CategoryID, int ArticleID, string Subject, string Reply, ArticleItemStatus status, int UserID, string NickName)
        {
            SqlConnection conn = CARETTA.DBI.DBHelper.getConnection();

            conn.Open();

            SqlTransaction Tran = conn.BeginTransaction(IsolationLevel.Serializable);

            int ArticleItemID;

            try
            {
                DateTime CreateDate = DateTime.Now;
                string   LastPost   = LastPostTemplate.Replace("||MemberID||", UserID.ToString()).Replace("||NickName||", NickName).Replace("||Date||", CreateDate.ToShortDateString() + " " + CreateDate.ToShortTimeString());

                ForumArticleItems mArticleItem = new ForumArticleItems();
                mArticleItem.ArticleID  = ArticleID;
                mArticleItem.CreateDate = CreateDate;
                mArticleItem.CreatedBy  = UserID;
                mArticleItem.Reply      = Reply;
                mArticleItem.Score      = 0;
                mArticleItem.ScoreCount = 0;
                mArticleItem.Status     = (int)status;
                mArticleItem.Subject    = Subject;
                mArticleItem.Save();
                ArticleItemID = mArticleItem.ArticleItemID;

                ForumArticle mArticle = new ForumArticle();
                mArticle.Load(ArticleID);
                mArticle.LastPost     = LastPost;
                mArticle.LastPostDate = CreateDate;
                mArticle.Replies     += 1;
                mArticle.Save();

                ForumCategory mCategory = new ForumCategory();
                mCategory.Load(CategoryID);
                mCategory.LastPost     = LastPost;
                mCategory.LastPostDate = CreateDate;
                mCategory.Save();

                Tran.Commit();
            }
            catch (Exception ex)
            {
                Tran.Rollback();
                throw;
            }
            finally
            {
                conn.Close();
            }

            return(ArticleItemID);
        }
        public string Generate(int maxRows, string staticFileName = "")
        {
            var now = DateTime.Now;

            var items = new Dictionary <int, ForumCategory>();

            var zeroUserId = SeedStore.GetZeroUserId();

            var general = new ForumCategory
            {
                Id           = 1,
                Slug         = "general",
                Name         = "Open forum",
                UserId       = zeroUserId,
                DateCreated  = now,
                DateModified = now
            };

            items.Add(general.Id.Value, general);

            var dr8a = new ForumCategory
            {
                Id           = 2,
                Slug         = "dr8a",
                Name         = "Dr 8a",
                UserId       = zeroUserId,
                DateCreated  = now,
                DateModified = now
            };

            items.Add(dr8a.Id.Value, dr8a);


            var countryGroup = new ForumCategory
            {
                Id           = 3,
                Slug         = "country",
                Name         = "Country specific forums",
                UserId       = zeroUserId,
                DateCreated  = now,
                DateModified = now
            };

            items.Add(countryGroup.Id.Value, countryGroup);

            CreateCountryGroups(3, items);
            //items.AddRange(CreateCountryGroups(3));

            SeedStore.ForumCategories = items;

            var json = JsonConvert.SerializeObject(items.Values);

            return(json);
        }
Example #35
0
 private void Update_Click(object sender, RoutedEventArgs e)
 {
     if (ForumCategoryTable.SelectedIndex >= 0)
     {
         ForumCategory Item = (dynamic)ForumCategoryTable.SelectedItem;
         ForumCategoryEditView.IsEnabled  = true;
         ForumCategoryEditView.Visibility = Visibility.Visible;
         ForumCategoryEditView.Initialize(Item);
         EditHeight.Height = new GridLength(120);
     }
 }
 public ActionResult Edit(ForumCategory category)
 {
     try
     {
         _service.Edit(category);
     }
     catch (ValidationException ex)
     {
         this.AddErrors(this.ModelState, ex);
     }
     if (ModelState.IsValid)
     {
         return RedirectToAction("List");
     }
     return View("Edit", category);
 }
 public ActionResult Add()
 {
     int count = _service.GetAll().Count();
     var forumCategoryModel = new ForumCategory() { Order = ++count };
     return View("Edit", forumCategoryModel);
 }
		public ForumCategory SelectForumCategoryByURLToken(string urlToken)
		{
			using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
			{
				using (SqlConnection conn = new SqlConnection(DatabaseManager.DatabaseEngine.ConnectionString))
				{
					conn.Open();
					SqlCommand cmd = new SqlCommand("ForumCategory_SelectByURLToken", conn);
					cmd.CommandType = CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@URLToken", urlToken));
					SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
					ForumCategory entity;
					if (!reader.Read())
						entity = null;
					else
						entity = new ForumCategory(reader);
					reader.Close();
					return entity;
				}
			}
		}
Example #39
0
 private ICommonDataGroup CreateCategory(ForumCategory category)
 {
     var group = new CommonDataGroup();
     group.Title = category.ToString().ToLower();
     return group;
 }
Example #40
0
 public virtual void Delete( ForumCategory category )
 {
     db.delete( category );
 }
Example #41
0
 public virtual Result Update( ForumCategory category )
 {
     return db.update( category );
 }
Example #42
0
        /// <summary>
        /// Get all categories (without the forums in it).
        /// </summary>
        /// <returns></returns>
        public List<ForumCategory> GetCategories()
        {
            DbCommand comm = GetCommand("SPForumsCategoriesGetAll");
            DataTable dt = GetTable(comm);

            List<ForumCategory> categoryList = new List<ForumCategory>();
            foreach (DataRow dr in dt.Rows)
            {
                ForumCategory category = new ForumCategory(dr.Get<int>("CategoryId"), dr.GetString("CategoryName"));
                category.Forums = new List<Forum>();
                categoryList.Add(category);
            }

            return categoryList;
        }
		public Result Store(ForumCategory forumCategory)
		{
			SqlConnection conn = null;
			try
			{
				using (TransactionScope scope = new TransactionScope())
				{
					conn = (SqlConnection)DatabaseManager.DatabaseEngine.GetConnection();
					SqlCommand cmd = new SqlCommand("ForumCategory_Store", conn);
					cmd.CommandType = CommandType.StoredProcedure;
					SqlParameter prm = new SqlParameter("@ForumCategoryID", forumCategory.ForumCategoryID);
					prm.Direction = ParameterDirection.InputOutput;
					cmd.Parameters.Add(prm);
					cmd.Parameters.Add(NewSqlParameter("@ClientSpaceID", forumCategory.ClientSpaceID, SqlDbType.BigInt));
					cmd.Parameters.Add(NewSqlParameter("@CategoryCode", forumCategory.CategoryCode, SqlDbType.NVarChar));
					cmd.Parameters.Add(NewSqlParameter("@Name", forumCategory.Name, SqlDbType.NVarChar));
					cmd.Parameters.Add(NewSqlParameter("@URLToken", forumCategory.URLToken, SqlDbType.NVarChar));
					cmd.Parameters.Add(NewSqlParameter("@DateCreated", forumCategory.DateCreated, SqlDbType.DateTime));
					cmd.Parameters.Add(NewSqlParameter("@Rank", forumCategory.Rank, SqlDbType.Int));
					cmd.Parameters.Add(NewSqlParameter("@InternalUseOnly", forumCategory.InternalUseOnly, SqlDbType.Bit));
					cmd.ExecuteNonQuery();
					forumCategory.ForumCategoryID = (long)prm.Value;
					scope.Complete();
				}
			}
			catch (Exception ex)
			{
				return new Result(ex.Message);
			}
			finally
			{
				DatabaseManager.DatabaseEngine.ReleaseConnection(conn);
			}
			return new Result();
		}
Example #44
0
 /// <summary>
 /// counts the number of threads in a given category
 /// </summary>
 /// <param name="category">is used to identify what category you want</param>
 /// <returns>The number of posts that belong to the given category</returns>
 public static int NumberofThreadsPerCategory(ForumCategory category)
 {
     return Threads.FindAll(x => x.Category.ID == category.ID).Count;
 }
Example #45
0
        public static Forum GetForumTopicsForMain(Guid memberId, Guid forumId, long groupId, int count, int page, bool isArchived)
        {
            Forum forum = new Forum();
            try
            {
                var dc = new ManagementContext();

                var db = (from xx in dc.Forums.Include("Topics").Include("Topics.Messages").Include("Topics.TopicsInbox")
                          where xx.ForumId == forumId
                          select new
                          {
                              Created = xx.Created,
                              ForumId = xx.ForumId,
                              ForumName = xx.ForumName,
                              LeagueId = xx.LeagueOwner,
                              FederationId = xx.FederationOwner,
                              Categories = xx.Categories.OrderBy(x => x.NameOfCategory)
                          }).FirstOrDefault();
                forum.Created = db.Created;
                forum.ForumId = db.ForumId;
                forum.ForumName = db.ForumName;

                bool isManager = RDN.Library.Cache.MemberCache.IsAdministrator(memberId);
                //need to add the default forum.
                List<LeagueGroup> groups = new List<LeagueGroup>();
                groups.Insert(0, new LeagueGroup { Id = 0, GroupName = "RDNation" });

                foreach (var g in groups)
                {
                    ForumGroup gff = new ForumGroup();
                    gff.GroupId = g.Id;
                    gff.GroupName = g.GroupName;

                    //if nt league manager and group id > 0
                    if (gff.GroupId > 0 && !isManager)
                        isManager = MemberCache.IsModeratorOrBetterOfLeagueGroup(memberId, gff.GroupId);
                    //this is making sure its the actual starting group.
                    if (g.Id == groupId)
                    {
                        var topics = dc.ForumTopics.Where(x => gff.GroupId == x.GroupId && x.IsRemoved == false && x.IsArchived == isArchived && x.Forum.ForumId == forumId).OrderByDescending(x => x.LastPostDateTime).Skip(page * count).Take(count).AsParallel();

                        foreach (var topic in topics)
                        {
                            if (gff.Topics.Where(x => x.TopicId == topic.TopicId).FirstOrDefault() == null)
                            {
                                ForumTopic top = DisplayForumTopic(memberId, isManager, topic);
                                if (!top.IsPinned)
                                    gff.Topics.Add(top);
                                else
                                    gff.Topics.Insert(0, top);
                            }
                        }
                        var topicsSticky = dc.ForumTopics.Where(x => gff.GroupId == x.GroupId && x.IsRemoved == false && x.IsArchived == isArchived && x.IsSticky == true && x.Forum.ForumId == forumId).OrderByDescending(x => x.LastPostDateTime).Skip(page * count).Take(count).AsParallel();

                        foreach (var topic in topicsSticky)
                        {
                            if (gff.Topics.Where(x => x.TopicId == topic.TopicId).FirstOrDefault() == null)
                            {
                                ForumTopic top = DisplayForumTopic(memberId, isManager, topic);
                                if (!top.IsPinned)
                                    gff.Topics.Add(top);
                                else
                                    gff.Topics.Insert(0, top);
                            }
                        }

                        var topicsCount = dc.ForumTopics.Where(x => gff.GroupId == x.GroupId && x.IsRemoved == false && x.IsArchived == isArchived && x.Forum.ForumId == forumId).AsParallel().Count();
                        gff.PageSize = count;
                        gff.CurrentPage = page;
                        gff.NumberOfRecords = topicsCount;
                        gff.NumberOfPages = (int)Math.Ceiling((double)topicsCount / count);
                        forum.CurrentGroup = gff;
                    }

                    gff.UnreadTopics = dc.ForumInbox.Where(x => x.Topic.GroupId == gff.GroupId && x.Topic.IsRemoved == false && x.Topic.IsArchived == isArchived && x.Topic.Forum.ForumId == forumId && x.ToUser.MemberId == memberId).Count();

                    forum.GroupTopics.Add(gff);
                }

                //add the categories.
                //adds the unread category if there are unread messages
                ForumCategory unreadCat = new ForumCategory();
                unreadCat.CategoryId = -1;
                unreadCat.CategoryName = "Unread";
                unreadCat.GroupId = 0;
                var gro = forum.GroupTopics.Where(x => x.GroupId == groupId).FirstOrDefault();
                if (gro != null)
                    unreadCat.UnreadTopics = gro.UnreadTopics;

                if (unreadCat.UnreadTopics > 0)
                    forum.Categories.Add(unreadCat);

                ForumCategory latestCat = new ForumCategory();
                latestCat.CategoryId = 0;
                latestCat.CategoryName = "Latest";
                latestCat.GroupId = groupId;
                if (gro != null)
                    latestCat.UnreadTopics = gro.UnreadTopics;

                var cats = db.Categories.Where(x => x.IsRemoved == false && x.GroupId == latestCat.GroupId).OrderBy(x => x.NameOfCategory);

                if (cats.Count() > 0 || unreadCat.UnreadTopics > 0)
                    forum.Categories.Add(latestCat);

                foreach (var cat in cats)
                {
                    ForumCategory c = new ForumCategory();
                    c.CategoryId = cat.CategoryId;
                    c.CategoryName = cat.NameOfCategory;
                    c.GroupId = cat.GroupId;
                    c.UnreadTopics = dc.ForumInbox.Where(x => x.Topic.GroupId == cat.GroupId && x.Topic.Forum.ForumId == forumId && x.ToUser.MemberId == memberId && x.Topic.Category.CategoryId == cat.CategoryId).Count();
                    forum.Categories.Add(c);
                }


                forum.FederationId = forumId;
                forum.Type = ForumOwnerTypeEnum.main;


            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return forum;
        }
Example #46
0
 /// <summary>
 /// Creates a new thread
 /// </summary>
 /// <param name="user"> User that posted this thread</param>
 /// <param name="content">content of the first post</param>
 /// <param name="category">category this thread belongs to</param>
 /// <param name="threadName">name of this thread</param>
 public static void CreateNewThread(User user, string content, ForumCategory category, string threadName)
 {
     DatabaseManager.CreateNewThread(user.Username, category.ID, content, threadName);
 }
 public void Edit(ForumCategory category)
 {
     category.ValidateFields();
     _dataAccess.Edit(category);
 }
		public Result Delete(ForumCategory forumCategory)
		{
			Result result = new Result();
			if (OnBeforeDeleteForumCategory != null)
				OnBeforeDeleteForumCategory(forumCategory, result);
			SqlConnection conn = null;
			if (result.Succeeded)
			{
				try
				{
					using (TransactionScope scope = new TransactionScope())
					{
						conn = (SqlConnection)DatabaseManager.DatabaseEngine.GetConnection();
						SqlCommand cmd = new SqlCommand("ForumCategory_Delete", conn);
						cmd.CommandType = CommandType.StoredProcedure;
						cmd.Parameters.Add(new SqlParameter("@ForumCategoryID", forumCategory.ForumCategoryID));
						cmd.ExecuteNonQuery();
						scope.Complete();
					}
				}
				catch (Exception ex)
				{
					return new Result(ex.Message);
				}
				finally
				{
					DatabaseManager.DatabaseEngine.ReleaseConnection(conn);
				}
				if (OnForumCategoryDeleted != null)
					OnForumCategoryDeleted(forumCategory);
			}
			return result;
		}
Example #49
0
 public virtual Result Insert( ForumCategory category )
 {
     return db.insert( category );
 }
 public void Add(ForumCategory category)
 {
     category.ValidateFields();
     _dataAccess.Add(category);
 }
Example #51
0
        /// <summary>
        /// Gets a list of ForumCategories with the list forums, dependant of the user role.
        /// </summary>
        public List<ForumCategory> GetList(UserRole? role)
        {
            var comm = GetCommand("SPForumsGetByCategory");
            comm.AddParameter(Factory, "UserGroupId", DbType.Int16, (short?)role);
            var dt = GetTable(comm);

            var categoryList = new List<ForumCategory>();
            ForumCategory category = null;
            foreach (DataRow dr in dt.Rows)
            {
                if (category == null || category.Name != dr.GetString("CategoryName"))
                {
                    category = new ForumCategory(dr.Get<int>("CategoryId"), dr.GetString("CategoryName"));
                    category.Forums = new List<Forum>();
                    categoryList.Add(category);
                }
                Forum f = ParseForumDataRow(dr);
                f.Category = category;
                category.Forums.Add(f);
            }

            return categoryList;
        }