Esempio n. 1
0
        public string AddDiscussionAjax(int topicid = 0, string addtitle = "", string post = "", string name = "", string email = "", string company = "", bool notify = false, string recaptcha_challenge_field = "", string recaptcha_response_field = "")
        {
            CurtDevDataContext db = new CurtDevDataContext();
            JavaScriptSerializer js = new JavaScriptSerializer();
            #region trycatch
            try {
                string remoteip = (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) ? Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : Request.ServerVariables["REMOTE_ADDR"];
                if (!(Models.ReCaptcha.ValidateCaptcha(recaptcha_challenge_field, recaptcha_response_field, remoteip))) {
                    throw new Exception("The Captcha was incorrect. Try again please!");
                }
                if (topicid == 0) { throw new Exception("The topic was invalid."); }
                if (addtitle.Trim() == "") { throw new Exception("Title is required."); }
                if (post.Trim() == "") { throw new Exception("Post is required"); }
                if (email.Trim() != "" && (!IsValidEmail(email.Trim()))) { throw new Exception("Your email address was not a valid address."); }
                if (notify == true && email.Trim() == "") { throw new Exception("You cannot be notified by email without an email address."); }
                if(checkIPAddress(remoteip)) { throw new Exception("You cannot post because your IP Address is blocked by our server."); }

                bool moderation = Convert.ToBoolean(ConfigurationManager.AppSettings["ForumModeration"]);

                ForumThread t = new ForumThread {
                    topicID = topicid,
                    active = true,
                    closed = false,
                    createdDate = DateTime.Now,
                };

                db.ForumThreads.InsertOnSubmit(t);
                db.SubmitChanges();

                ForumPost p = new ForumPost {
                    threadID = t.threadID,
                    title = addtitle,
                    post = post,
                    name = name,
                    email = email,
                    notify = notify,
                    approved = !moderation,
                    company = company,
                    createdDate = DateTime.Now,
                    flag = false,
                    active = true,
                    IPAddress = remoteip,
                    parentID = 0,
                    sticky = false
                };

                db.ForumPosts.InsertOnSubmit(p);
                db.SubmitChanges();

                Post newpost = ForumModel.GetPost(p.postID);
                return js.Serialize(newpost);

            } catch (Exception e) {
                return "{\"error\": \"" + e.Message + "\"}";
            }
            #endregion
        }
Esempio n. 2
0
        public async Task <ThreadDetailsModel> GetById(int id)
        {
            // Get the thread and then retrieve the posts associated with it
            ForumThread thread = await _unitOfWork.ForumThreads.GetById(id);

            IReadOnlyCollection <PostDetailsModel> posts = await _postsService.GetByThread(id);

            // Combine the retrieved thread and the posts
            ThreadDetailsModel threadDetails = new ThreadDetailsModel(thread, posts);

            return(threadDetails);
        }
Esempio n. 3
0
        public bool DeleteThread(ForumThread thread)
        {
            var i = threads.Select(x => x.ID).ToList().IndexOf(thread.ThreadID.ToString());

            subForums.First(x => x.ID == thread.ParentID.ToString()).ThreadCount--;
            if (i == -1)
            {
                return(false);
            }
            threads.RemoveAt(i);
            return(true);
        }
        public ActionResult Details(ForumThread item)
        {
            this.ViewBag.ThreadTitle = item.Title;
            this.InitializeMetadataDetailsViewBag(item);  // Sitefinity SEO optimizations
            var posts = this.GetPosts(item).Select(x => new ItemViewModel(x));

            var viewModel = new ContentListViewModel()
            {
                Items = posts.ToList()
            };

            return(this.View("Detail.ForumThreadDetails", viewModel));
        }
Esempio n. 5
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            int published = 0;

            if (drpPublish.SelectedIndex == 0)
            {
                published = 1;
            }
            //Session["userid"] = 1;
            ForumThread thread = new ForumThread(txtTitle.Text, txtContent.Text, drpSection.SelectedItem.Text, published, Convert.ToInt32(Session["userid"]));

            thread.CreateThreadintoDb();
        }
Esempio n. 6
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;
            }

            threadid = Convert.ToInt32(Request.QueryString["threadid"]);
            ForumThread thr = new ForumThread();

            thr.GetThread(threadid);
            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 = sec = Request.QueryString["sec"].ToString();
                }
                else
                {
                    drpSection.Items.Clear();
                    drpSection.Items.Add("Select a section");
                }
            }
            if (thr != null)
            {
                txtTitle.Text   = thr.ThreadTitle;
                txtContent.Text = thr.ThreadBody;
                if (thr.Published == 1)
                {
                    drpPublish.SelectedIndex = 0;
                }
                else
                {
                    drpPublish.SelectedIndex = 1;
                }
            }
        }
Esempio n. 7
0
        // GET: ForumThreads/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ForumThread forumThread = db.ForumThreads.Find(id);

            if (forumThread == null)
            {
                return(HttpNotFound());
            }
            return(View(forumThread));
        }
Esempio n. 8
0
        private void Page_Load(object sender, EventArgs e)
        {
            SecurityHelper.DisableBrowserCache();

            LoadParams();

            userCanEdit = UserCanEditModule(moduleId, Forum.FeatureGuid);
            if (!userCanEdit)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            forumThread = new ForumThread(threadId);
            if (forumThread.ModuleId != moduleId)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            if (SiteUtils.IsFishyPost(this))
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            ForumThreadIndexBuilderProvider indexBuilder
                = (ForumThreadIndexBuilderProvider)IndexBuilderManager.Providers["ForumThreadIndexBuilderProvider"];

            if (indexBuilder != null)
            {
                forumThread.ThreadMoved += new ForumThread.ThreadMovedEventHandler(indexBuilder.ThreadMovedHandler);
            }

            siteUser = SiteUtils.GetCurrentSiteUser();

            PopulateLabels();

            if (!IsPostBack)
            {
                PopulateControls();
                if ((Request.UrlReferrer != null) && (hdnReturnUrl.Value.Length == 0))
                {
                    hdnReturnUrl.Value    = Request.UrlReferrer.ToString();
                    lnkCancel.NavigateUrl = hdnReturnUrl.Value;
                }
            }

            AnalyticsSection = ConfigHelper.GetStringProperty("AnalyticsForumSection", "forums");
        }
        /// <summary>
        /// Update an existing thread by Id and forumThread object
        /// </summary>
        /// <param name="threadId"></param>
        /// <param name="forumThread"></param>
        /// <returns></returns>
        public async Task <ForumThread> UpdateThread(string threadId, ForumThread forumThread)
        {
            if (forumThread == null && threadId == null)
            {
                throw new ArgumentNullException(typeof(ForumThread).Name + "Object or may be threadId is Null");
            }
            var update = await _dbFCollection.FindOneAndUpdateAsync(Builders <ForumThread> .
                                                                    Filter.Eq("ThreadId", forumThread.ThreadId), Builders <ForumThread> .
                                                                    Update.Set("ThreadName", forumThread.ThreadName).Set("UserTypes", forumThread.UserTypes)
                                                                    .Set("Email", forumThread.Email).
                                                                    Set("Description", forumThread.Description).Set("IsApproved", forumThread.IsApproved));

            return(update);
        }
Esempio n. 10
0
        public ActionResult AddPost(int id = 0, string titlestr = "", string post = "", bool sticky = false)
        {
            string remoteip = (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) ? Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : Request.ServerVariables["REMOTE_ADDR"];
            try {
                if (id == 0) throw new Exception("Topic is required.");
                if (titlestr.Trim().Length == 0) throw new Exception("Title is required.");
                if (post.Trim().Length == 0) throw new Exception("Post content is required.");
                CurtDevDataContext db = new CurtDevDataContext();

                ForumThread t = new ForumThread {
                    topicID = id,
                    active = true,
                    closed = false,
                    createdDate = DateTime.Now
                };
                db.ForumThreads.InsertOnSubmit(t);
                db.SubmitChanges();
                user u = Users.GetUser(Convert.ToInt32(Session["userID"]));

                ForumPost p = new ForumPost {
                    threadID = t.threadID,
                    title = titlestr,
                    post = post,
                    IPAddress = remoteip,
                    createdDate = DateTime.Now,
                    approved = true,
                    active = true,
                    flag = false,
                    notify = false,
                    parentID = 0,
                    name = u.fname + " " + u.lname,
                    company = "CURT Manufacturing",
                    email = u.email,
                    sticky = sticky
                };
                db.ForumPosts.InsertOnSubmit(p);
                db.SubmitChanges();

                return RedirectToAction("threads", new { id = id });

            } catch (Exception e) {
                FullTopic topic = ForumModel.GetTopic(id);
                ViewBag.topic = topic;
                ViewBag.error = e.Message;
                ViewBag.titlestr = titlestr;
                ViewBag.post = post;
                ViewBag.sticky = sticky;
                return View();
            }
        }
Esempio n. 11
0
        public ActionResult Create([Bind(Include = "ID,ForumSectionID,Title,Text")] ForumThread forumThread)
        {
            if (ModelState.IsValid)
            {
                //forumThread.ForumSectionID = forumThread.ForumSectionID;
                forumThread.Author      = User.Identity.Name;
                forumThread.PublishDate = DateTime.Now;
                db.ForumThreads.Add(forumThread);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(forumThread));
        }
 public static ForumThreadModel ConvertToForumThreadModel(this ForumThread thread, bool includeContent)
 {
     return(new ForumThreadModel()
     {
         CreatedBy = thread.UserProfile.UserName,
         CreatedById = thread.UserProfile.UserId,
         IsSticky = thread.IsSticky,
         CreatedOn = thread.CreatedOn.ToShortDateString() + thread.CreatedOn.ToShortTimeString(),
         ModifiedOn = thread.ModifiedOn.HasValue ? thread.ModifiedOn.Value.ToShortDateString() + thread.ModifiedOn.Value.ToShortTimeString() : "",
         ThreadId = thread.ThreadId,
         ThreadTitle = thread.ThreadTitle,
         ThreadContent = includeContent ? thread.ThreadContent : ""
     });
 }
Esempio n. 13
0
        public ActionResult ViewTopic(Guid topicId, string threadTitle, string threadContent, bool isSticky)
        {
            ViewTopicModel viewTopicModel = new ViewTopicModel()
            {
                Threads = new List <ForumThreadModel>()
            };

            using (CGWebEntities entities = new CGWebEntities())
            {
                UserProfile currentUserProfile = entities.UserProfiles.Where(P => P.UserName.Equals(User.Identity.Name)).Single();

                ForumThread newThread = new ForumThread()
                {
                    CreatedBy     = currentUserProfile.UserId,
                    CreatedOn     = DateTime.UtcNow,
                    ForumTopic    = topicId,
                    IsSticky      = isSticky,
                    ModifiedOn    = null,
                    ThreadContent = threadContent,
                    ThreadId      = Guid.NewGuid(),
                    ThreadTitle   = HtmlSanitizerUtility.SanitizeInputStringNoHTML(threadTitle)
                };

                entities.ForumThreads.Add(newThread);
                entities.SaveChanges();
                ModelState.Clear();

                ForumTopic currentTopic = entities.ForumTopics.Where(T => T.TopicId.Equals(topicId)).Single();
                viewTopicModel.CurrentTopic = currentTopic.ConvertToForumTopicModel();
                viewTopicModel.ParentForum  = currentTopic.Forum.ConvertToViewForumModel(false, false);

                if (!currentTopic.IsPublic && !Request.IsAuthenticated)
                {
                    return(RedirectToAction("Login", "Account"));
                }

                var currentTopicGroup = entities.ForumThreads.Where(FT => FT.ForumTopic.Equals(topicId));

                int currentTopicViewLimit = Convert.ToInt32(ConfigurationManager.AppSettings["ForumTopicPagingLimit"]);
                viewTopicModel.MaxPages    = (int)Math.Ceiling((double)currentTopicGroup.Count() / (double)currentTopicViewLimit);
                viewTopicModel.CurrentPage = viewTopicModel.MaxPages - 1;

                foreach (ForumThread thread in currentTopicGroup.OrderByDescending(FT => FT.CreatedOn).OrderByDescending(FT => FT.IsSticky).Skip(currentTopicViewLimit * viewTopicModel.CurrentPage).Take(currentTopicViewLimit))
                {
                    viewTopicModel.Threads.Add(thread.ConvertToForumThreadModel(false));
                }
            }

            return(View(viewTopicModel));
        }
        /// <summary>
        /// Redirects to a thread page given a specified <see cref="ForumPost"/> ID
        /// </summary>
        public ActionResult Post(int id)
        {
            var       db   = new ZkDataContext();
            ForumPost post = db.ForumPosts.FirstOrDefault(x => x.ForumPostID == id);
            int?      page = GetPostPage(post);

            if (page == 0)
            {
                page = null;
            }
            ForumThread thread = post.ForumThread;

            return(RedirectToAction("Thread", new { id = thread.ForumThreadID, page = page }));
        }
Esempio n. 15
0
        public static ForumThread GetDefaultForumThread()
        {
            var thread = new ForumThread
            {
                Id             = "t123123",
                CurrentPage    = 5,
                MaxPages       = 78,
                ShowNavigation = true,
                ParentId       = "/f3432",
                Title          = "Den stora tråden om allsvenskan 2017"
            };

            return(thread);
        }
Esempio n. 16
0
 public ForumThreadGet(ForumThread thread)
 {
     ID           = thread.ThreadID.ToString();
     Title        = thread.Title;
     Text         = thread.Text;
     PostTime     = thread.PostTime;
     LastPostTime = thread.LastPostTime;
     if (thread.User != null)
     {
         UserName = thread.User.UserName;
     }
     Comments      = thread.NumberOfComments;
     ParentForumID = thread.ParentID.ToString();
 }
        public static void RemoveForumIndexItem(object oForumThread)
        {
            if (WebConfigSettings.DisableSearchIndex)
            {
                return;
            }

            if (!(oForumThread is ForumThread))
            {
                return;
            }

            ForumThread forumThread = oForumThread as ForumThread;

            // get list of pages where this module is published
            List <PageModule> pageModules
                = PageModule.GetPageModulesByModule(forumThread.ModuleId);

            // must update index for all pages containing
            // this module
            foreach (PageModule pageModule in pageModules)
            {
                mojoPortal.SearchIndex.IndexItem indexItem = new mojoPortal.SearchIndex.IndexItem();
                // note we are just assigning the properties
                // needed to derive the key so it can be found and
                // deleted from the index
                indexItem.SiteId   = forumThread.SiteId;
                indexItem.PageId   = pageModule.PageId;
                indexItem.ModuleId = forumThread.ModuleId;
                indexItem.ItemId   = forumThread.ForumId;

                if (ForumConfiguration.AggregateSearchIndexPerThread)
                {
                    indexItem.QueryStringAddendum = "&thread=" + forumThread.ThreadId.ToInvariantString();
                }
                else
                {
                    indexItem.QueryStringAddendum = "&thread="
                                                    + forumThread.ThreadId.ToInvariantString()
                                                    + "&postid=" + forumThread.PostId.ToInvariantString();
                }

                mojoPortal.SearchIndex.IndexHelper.RemoveIndex(indexItem);
            }

            if (debugLog)
            {
                log.Debug("Removed Index ");
            }
        }
Esempio n. 18
0
        private void SearchExistingPosts(List <string> keywords, ForumThread forumThread, List <Post> posts)
        {
            for (int i = 0; i < posts.Count; ++i)
            {
                if (posts[i].PageNo < forumThread.NbPage)
                {
                    //var matches = SearchEngine.Search(keywords, new List<string>() { posts[i].Content });

                    //if (matches.Any()) {
                    //    OnPostsFound(posts[i], matches);
                    //}
                }
            }
        }
Esempio n. 19
0
 public void AddThread(ForumThread thread)
 {
     if (thread.ThreadID == null ||
         thread.Title == null ||
         thread.Text == null)
     {
         throw new NullReferenceException();
     }
     subForums.First(x => x.ID == thread.ParentID.ToString()).ThreadCount++;
     if (threads.Count == maxThreads)
     {
         threads.RemoveAt(maxThreads - 1);
     }
     threads.Insert(0, thread);
 }
Esempio n. 20
0
        public static HashSet <ForumThread> GetThread(string cmdText)
        {
            HashSet <ForumThread> thread = new HashSet <ForumThread>();

            using (IDataReader reader = DataHelper.ExecuteReader(CommandType.Text, cmdText, null))
            {
                while (reader.Read())
                {
                    ForumThread tmp = ForumThread.CreateFromReader(reader);
                    tmp.RootMessage = builder.BuildRootMessage(reader);
                    thread.Add(tmp);
                }
            }
            return(thread);
        }
Esempio n. 21
0
        public async Task GetById_CallsRepositoryWithCorrectId_WhenProvidedValidId()
        {
            // Arrange
            ForumThread thread = new ForumThread {
                Id = 11
            };

            _threadsRepositoryMock.Setup(x => x.GetById(It.IsAny <int>())).ReturnsAsync(thread);

            // Act
            ThreadDetailsModel result = await _threadsService.GetById(thread.Id);

            // Assert
            _threadsRepositoryMock.Verify(x => x.GetById(thread.Id));
        }
Esempio n. 22
0
        public async Task GetById_ReturnsCorrectPost_WhenProvidedValidId()
        {
            // Arrange
            ForumThread thread = new ForumThread {
                Id = 11
            };

            _threadsRepositoryMock.Setup(x => x.GetById(It.IsAny <int>())).ReturnsAsync(thread);

            // Act
            ThreadDetailsModel result = await _threadsService.GetById(thread.Id);

            // Assert
            Assert.That(result.Id, Is.EqualTo(thread.Id));
        }
Esempio n. 23
0
        // GET: Forum
        public ActionResult Index(int id)
        {
            ForumThread forum = null;

            try
            {
                forum = _forumThreadFacade.GetById(id);
            }
            catch (Exception ex)
            {
                log.Error("Exception ", ex);
            }
            ViewBag.UserId = User.Identity.GetUserId();
            return(View(forum));
        }
Esempio n. 24
0
        public bool AddNewDiscussionThreadNotification(ForumThread thread)
        {
            var notification = new Notification
            {
                Description        = thread.AddedByUser.FirstName + " " + thread.AddedByUser.LastName,
                Link               = string.Format(DiscussionPostLink, thread.AddedFor, thread.PostId),
                TypeOfNotification = NotificationType.NewDiscussionThreadNotification,
                AddedBy            = thread.AddedBy,
                Title              = "New Comment on Discussion Post",
                AddedOn            = DateTime.Now,
            };

            new MailerBl().AddNewDiscussionThreadMail(notification, thread.PostId);
            return(AddNotification(notification, UserDataAccesor.GetUserId(notification, thread.AddedFor)));
        }
Esempio n. 25
0
        public Dictionary <string, object> getDataTableFromThread(ForumThread Thread)
        {
            Dictionary <string, object> newThread = new Dictionary <string, object>();

            newThread.Add("title", Thread.title);
            newThread.Add("categoryid", Thread.threadCategory.getID());
            newThread.Add("replies", Thread.replies);
            newThread.Add("authorid", Thread.author.getID());
            newThread.Add("creationdate", SharedLibrary.Utilities.DateTimeSQLite(Thread.creationDate));
            newThread.Add("updateddate", SharedLibrary.Utilities.DateTimeSQLite(Thread.updatedDate));
            newThread.Add("content", Thread.content);
            newThread.Add("visible", Convert.ToInt32(Thread.visible));

            return(newThread);
        }
Esempio n. 26
0
        public ActionResult Edit(int Id)
        {
            LinkedList <rrForumThread> llForumThread = rrForumThreadDB.GetForumThread(ForumId: rrForumThreadDB.ForumId, ThreadId: Id);

            if (llForumThread.Count == 0)
            {
                ViewData["ErrorMessage"] = string.Format("Тема не найдена");
                return(View("Error"));
            }
            var Thread = llForumThread.First.Value;

            ForumThread Model = new ForumThread(Thread);

            return(View(Model));
        }
Esempio n. 27
0
        public ActionResult Edit(int id, ForumThread Model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            LinkedList <rrForumThread> llThread = rrForumThreadDB.GetForumThread(
                ForumId: rrForumThreadDB.ForumId,
                ThreadId: id);

            if (llThread.Count == 0)
            {
                ViewData["ErrorMessage"] = string.Format("Тема не найдена");
                return(View("Error"));
            }
            rrForumThread ForumThread = llThread.First.Value;

            string FileName = ForumThread.FileName;

            if (!string.IsNullOrEmpty(FileName) && (Model.DeleteFile || Model.File != null))
            {
                string FilePath = Server.MapPath(string.Format("~/Files/{0}", FileName));
                System.IO.File.Delete(FilePath);
                FileName = null;
            }
            if (Model.File != null && !Model.DeleteFile)
            {
                FileName = string.Format("{0}_{1}", Guid.NewGuid().ToString(), Model.File.FileName);
                var FilePath = Server.MapPath(Path.Combine("~/Files", FileName));
                Model.File.SaveAs(FilePath);
            }
            if (ForumThread.CreatedBy != CurrentUser.UserId)
            {
                ViewData["ErrorMessage"] = "Нельзя редактировать сообщения созданные другими пользователями";
                return(View("Error"));
            }

            string Title       = CurrentUser.UserId != ForumThread.CreatedBy ? ForumThread.Title : Model.Title;
            string Description = Uri.UnescapeDataString(Model.Description);


            rrForumThreadDB.UpdateForumThread(ForumId: rrForumThreadDB.ForumId,
                                              UserId: CurrentUser.UserId, ThreadId: ForumThread.ThreadId, Title: Model.Title,
                                              Description: Description, FileName: FileName);

            return(ForumRedirect(ForumThread.ThreadParentId));
        }
Esempio n. 28
0
        public ActionResult ViewThread(ForumReplyModel model)
        {
            ViewThreadModel viewThreadModel = new ViewThreadModel()
            {
                Replies = new List <ForumReplyModel>()
            };

            using (CGWebEntities entities = new CGWebEntities())
            {
                UserProfile currentUserProfile = entities.UserProfiles.Where(P => P.UserName.Equals(User.Identity.Name)).Single();

                ForumReply newReply = new ForumReply()
                {
                    CreatedBy      = currentUserProfile.UserId,
                    CreatedOn      = DateTime.UtcNow,
                    ModifiedOn     = null,
                    ParentThreadId = model.ThreadId,
                    ReplyContent   = model.ReplyContent,
                    ReplyId        = Guid.NewGuid()
                };

                entities.ForumReplies.Add(newReply);
                entities.SaveChanges();
                ModelState.Clear();

                ForumThread currentThread = entities.ForumThreads.Where(FT => FT.ThreadId.Equals(model.ThreadId)).Single();

                viewThreadModel.ParentTopic = currentThread.ParentForumTopic.ConvertToForumTopicModel();

                if (!currentThread.ParentForumTopic.IsPublic && !Request.IsAuthenticated)
                {
                    return(RedirectToAction("Login", "Account"));
                }

                int currentPagingLimit = Convert.ToInt32(ConfigurationManager.AppSettings["ForumReplyPagingLimit"]);
                viewThreadModel.MaxPages    = (int)Math.Ceiling((double)currentThread.ForumReplies.Count / (double)currentPagingLimit);
                viewThreadModel.CurrentPage = viewThreadModel.MaxPages - 1;

                viewThreadModel.CurrentThread = currentThread.ConvertToForumThreadModel(true);

                foreach (ForumReply reply in currentThread.ForumReplies.OrderBy(FR => FR.CreatedOn).Skip(viewThreadModel.CurrentPage * currentPagingLimit).Take(currentPagingLimit))
                {
                    viewThreadModel.Replies.Add(reply.ConvertToThreadReplyModel(true));
                }
            }

            return(View(viewThreadModel));
        }
Esempio n. 29
0
        public void MultipleThreadSingleForum()
        {
            var SearchDataMock = new Mock <ISearchResults>();

            string query = "test";

            List <Forum> forumList = new List <Forum>();
            Forum        forum1    = new Forum()
            {
                Title = "testForum1", Url = "testUrl"
            };

            forumList.Add(forum1);


            List <ForumThread> threadList = new List <ForumThread>();
            ForumThread        thread1    = new ForumThread()
            {
                Id = 1, Title = "testThread1", ViewCount = 5
            };
            ForumThread thread2 = new ForumThread()
            {
                Id = 2, Title = "testThread2", ViewCount = 7
            };

            threadList.Add(thread1);
            threadList.Add(thread2);

            SearchDataMock.Setup(_sresults => _sresults.GetSearchResultsByQuorum(query)).
            Returns(Task.FromResult(forumList));
            SearchDataMock.Setup(_sresults => _sresults.GetSearchResultsByPost(query)).
            Returns(Task.FromResult(threadList));

            Services.AddSingleton <ISearchResults>(SearchDataMock.Object);


            var cut = RenderComponent <SearchResultsPage>(Parameter("query", query), Parameter("forumPage", 1), Parameter("threadPage", 1));

            cut.MarkupMatches("<h3>Quorum Search Results</h3><div class='panel panel-default'><div class='row'><div class='column'><table class='table'>" +
                              "<thead><tr><th>Sub-Quorums</th></tr></thead><tbody><tr><td><a href='testUrl'>testForum1</a></td></tr></tbody></table>" +
                              "<ul class='list-group list-group-horizontal'><li id='forumsearchpagination' class='list-group-item'><b>1</b></li>" +
                              "</ul><table class='table'><thead><tr><th>Threads</th></tr></thead><tbody><tr><td><a href='/p/1'>testThread1</a>" +
                              "<div class='float-right'><span class='oi oi-eye'></span> 5</div></td>" +
                              "</tr><tr><td><a href='/p/2'>testThread2</a>" +
                              "<div class='float-right'><span class='oi oi-eye'></span> 7</div></td>" +
                              "</tr></tbody></table><ul class='list-group list-group-horizontal'><li id='threadsearchpagination' class='list-group-item'><b>1</b></li>" +
                              "</ul></div></div></div>");
        }
        private void UnsubscribeUser(int threadId)
        {
            SiteUser siteUser = SiteUtils.GetCurrentSiteUser();

            if (siteUser == null)
            {
                return;
            }
            if (!ForumThread.Unsubscribe(threadId, siteUser.UserId))
            {
                log.ErrorFormat("ForumThread.UnSubscribe({0}, {1}) failed", threadId, siteUser.UserId);
                lblUnsubscribe.Text = ForumResources.ForumThreadUnsubscribeFailed;
                return;
            }
            lblUnsubscribe.Text = ForumResources.ForumThreadUnsubscribeCompleted;
        }
Esempio n. 31
0
        /// <summary>
        /// 获取帖子
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>帖子</returns>
        public ForumThread GetByKey(Guid id)
        {
            ForumThread tmp = null;

            try
            {
                var list = ForumThreadPersist.GetThread("select * from fbs_ForumThread inner join fbs_Message on fbs_ForumThread.RootMessageID=fbs_Message.MessageID where fbs_ForumThread.ThreadID='" + id.ToString() + "'");
                if (list != null && list.Count == 1)
                {
                    tmp = list.SingleOrDefault();
                }
            }
            catch (InvalidOperationException error)
            { }
            return(tmp);
        }
 /// <summary>
 /// Add new forum thread in MongoDb collection
 /// </summary>
 /// <param name="forumThread"></param>
 /// <returns></returns>
 public async Task <ForumThread> NewForumThread(ForumThread forumThread)
 {
     try
     {
         if (forumThread == null)
         {
             throw new ArgumentNullException(typeof(ForumThread).Name + "Object is Null");
         }
         _dbFCollection = _mongoContext.GetCollection <ForumThread>(typeof(ForumThread).Name);
         await _dbFCollection.InsertOneAsync(forumThread);
     }
     catch (Exception ex)
     {
         throw (ex);
     }
     return(forumThread);
 }
Esempio n. 33
0
        /// <summary>
        /// Gives the most recent version of the given thread
        /// </summary>
        /// <param name="id">id is used to identify the thread</param>
        /// <returns>the most recent version of the thread</returns>
        public static ForumThread UpdateThread(int id)
        {
            OracleConnection conn = MakeConnection();
            conn.Open();

            string mainQuery = "SELECT * FROM THREAD WHERE THREADID = :THREADID";

            OracleCommand command = new OracleCommand(mainQuery, conn);
            command.Parameters.Add(new OracleParameter("THREADID", id));
            OracleDataReader dataReaderThread;
            OracleDataReader dataReaderPosts;

            ForumThread thread = null;

            try
            {
                dataReaderThread = command.ExecuteReader();
                while (dataReaderThread.Read())
                {
                    List<Post> posts = new List<Post>();
                    string postQuery = "SELECT * FROM POST WHERE THREADID =" + dataReaderThread["threadID"];
                    OracleCommand threadCommand = new OracleCommand(postQuery, conn);

                    dataReaderPosts = threadCommand.ExecuteReader();
                    while (dataReaderPosts.Read())
                    {
                        posts.Add(new Post(Convert.ToInt32(dataReaderPosts["postID"].ToString()), dataReaderPosts["inhoud"].ToString(), dataReaderPosts["USERNAME"].ToString()));
                    }

                    ForumCategory category = MainAdministration.Categorys.Find(x => x.ID == Convert.ToInt32(dataReaderThread["FORUMCATEGORIEID"].ToString()));

                    thread = new ForumThread(Convert.ToInt32(dataReaderThread["threadID"].ToString()), posts, category, dataReaderThread["THREADNAME"].ToString(), dataReaderThread["USERNAME"].ToString());
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                conn.Close();
            }

            return thread;
        }
Esempio n. 34
0
 partial void InsertForumThread(ForumThread instance);
 public void addThread(ForumThread thread)
 {
     threadList.Add(thread);
 }
Esempio n. 36
0
 partial void UpdateForumThread(ForumThread instance);
Esempio n. 37
0
	private void attach_ForumThreads(ForumThread entity)
	{
		this.SendPropertyChanging();
		entity.Forum = this;
	}
Esempio n. 38
0
 /// <summary>
 /// Deletes a thread
 /// </summary>
 /// <param name="thread">thread that needs to be deleted</param>
 public static void DeleteThread(ForumThread thread)
 {
     DatabaseManager.DeleteThread(thread.ID);
 }
Esempio n. 39
0
	private void detach_ForumThreads(ForumThread entity)
	{
		this.SendPropertyChanging();
		entity.Comment = null;
	}
Esempio n. 40
0
 /// <summary>
 /// create a new post
 /// </summary>
 /// <param name="user">User that posted this post</param>
 /// <param name="content">Content of this post</param>
 /// <param name="thread">thread this post belongs to</param>
 public static void CreateNewPost(User user, string content, ForumThread thread)
 {
     DatabaseManager.CreateNewPost(thread.ID, content, user.Username);
 }
Esempio n. 41
0
 partial void DeleteForumThread(ForumThread instance);