Exemplo n.º 1
0
        public void Forum_SearchController_Index_ShouldReturnCorrectResultsCaseInsensitive(string searchTerm)
        {
            // Arrange
            var data         = new Mock <IUowData>();
            var pagerFactory = new Mock <IPagerViewModelFactory>();

            data.Setup(d => d.Threads.All()).Returns(SearchTestCollection().AsQueryable());

            Mapper.Initialize(cfg => cfg.CreateMap <Thread, ThreadViewModel>());

            SearchController controller = new SearchController(data.Object, pagerFactory.Object);

            var expected = new ThreadViewModel[]
            {
                new ThreadViewModel()
                {
                    Id = 2, Published = new DateTime(2017, 01, 02), Title = "test", Content = "SomeContent", AnswersCount = 0, SectionName = "testSectionName", UserId = "id"
                },
                new ThreadViewModel()
                {
                    Id = 1, Published = new DateTime(2017, 01, 03), Title = string.Empty, Content = "Test", AnswersCount = 0, SectionName = "testSectionName", UserId = "id"
                },
                new ThreadViewModel()
                {
                    Id = 4, Published = new DateTime(2017, 01, 04), Title = "Important topic", Content = "Unit testing has helped me alot!", AnswersCount = 0, SectionName = "testSectionName", UserId = "id"
                }
            };

            // Act
            var result      = controller.Index(searchTerm, 1) as ViewResult;
            var resultModel = result.Model as Tuple <IEnumerable <ThreadViewModel>, IPagerViewModel>;

            // Assert
            CollectionAssert.AreEqual(expected, resultModel.Item1, new ThreadViewModelComparer());
        }
Exemplo n.º 2
0
        public IActionResult Delete(ThreadViewModel vm)
        {
            var thread = _threadService.GetThreadById(vm.Id);

            _threadService.DeleteThread(thread);
            return(RedirectToAction("List", "Thread"));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Index()
        {
            var posts = (await _postDataService.GetAll(true)).ToArray();
            var model = new ThreadViewModel(posts);

            return(View(model));
        }
        public ActionResult UpdatePost(int postId, int threadId, FormCollection form)
        {
            Post thePost = db.Posts.Single(p => p.PostId == postId);

            try
            {
                UpdateModel(thePost, "Post");
                db.SaveChanges();
                //Success: return uneditable post.
                return(PartialView("SinglePost", thePost));
            }
            catch
            {
                //Fail: return editable post.
                Thread          theThread = db.Threads.Single(t => t.ThreadId == threadId);
                ThreadViewModel tvm       = new ThreadViewModel
                {
                    Thread     = theThread,
                    Post       = thePost,
                    PageNumber = this.pageNumber,
                    PageSize   = Preferences.PAGE_SIZE
                };
                return(PartialView("PostEditor", tvm));
            }
        }
Exemplo n.º 5
0
        public async Task <Thread> CreateThread(ThreadViewModel model)
        {
            if (string.IsNullOrEmpty(model.Name))
            {
                return(null);
            }
            if (string.IsNullOrEmpty(model.ThreadCreator))
            {
                return(null);
            }
            if (string.IsNullOrEmpty(model.Type))
            {
                return(null);
            }
            using (var http = new HttpClient())
            {
                var content = new StringContent(JsonConvert.SerializeObject(model));
                var result  = await http.PostAsync(URL, content);

                if (result.IsSuccessStatusCode)
                {
                    var response = await result.Content.ReadAsStringAsync();

                    var thread = JsonConvert.DeserializeObject <Thread>(response);
                    return(thread);
                }
                else
                {
                    return(null);
                }
            }
        }
Exemplo n.º 6
0
        public void Forum_HomeController_Index_ShouldReturnOnlyVisibleThreadsAtPage3()
        {
            // Arrange
            var data         = new Mock <IUowData>();
            var pagerFactory = new Mock <IPagerViewModelFactory>();

            data.Setup(d => d.Threads.All()).Returns(ThreadsCollection().AsQueryable());
            Mapper.Initialize(cfg => cfg.CreateMap <Thread, ThreadViewModel>());

            HomeController controller = new HomeController(data.Object, pagerFactory.Object);

            var expected = new ThreadViewModel[]
            {
                new ThreadViewModel()
                {
                    Id = 7, Published = new DateTime(2017, 01, 07), Title = string.Empty, Content = string.Empty, AnswersCount = 0, SectionName = "testSectionName", UserId = "id"
                },
                new ThreadViewModel()
                {
                    Id = 8, Published = new DateTime(2017, 01, 08), Title = string.Empty, Content = string.Empty, AnswersCount = 0, SectionName = "testSectionName", UserId = "id"
                }
            };

            // Act
            var result      = controller.Index(3) as ViewResult;
            var resultModel = result.Model as Tuple <IEnumerable <ThreadViewModel>, IPagerViewModel>;

            // Assert
            CollectionAssert.AreEqual(expected, resultModel.Item1, new ThreadViewModelComparer());
        }
Exemplo n.º 7
0
        public async Task <List <ThreadViewModel> > GetForumThreads(string forumId)
        {
            List <ThreadViewModel> threadViewModels = new List <ThreadViewModel>();

            var q = await forumDbContext.Threads
                    .Where(t => t.ForumId == forumId)
                    .ToListAsync();

            foreach (var thread in q)
            {
                ThreadViewModel threadViewModel = new ThreadViewModel
                {
                    ThreadId    = thread.ThreadId,
                    ThreadTitle = thread.ThreadTitle,
                    ForumId     = thread.ForumId,
                    PostedOn    = thread.PostedOn,
                    Subject     = thread.Subject,
                    AuthorName  = thread.AuthorName,
                    UserId      = thread.UserId
                };

                threadViewModels.Add(threadViewModel);
            }

            return(threadViewModels);
        }
Exemplo n.º 8
0
        //  [ActionName("GetNewThread")]
        public ActionResult GetThread(int threadId)
        {
            var model  = new InsideThreadViewModel();
            var thread = repository.GetThread(threadId);

            if (thread == null)
            {
                return(HttpNotFound());
            }
            var threadViewModel = new ThreadViewModel();

            threadViewModel.Date      = thread.Date;
            threadViewModel.Name      = thread.Name;
            threadViewModel.SubId     = thread.SubId;
            threadViewModel.Text      = thread.Text;
            threadViewModel.ThreadId  = thread.ThreadId;
            threadViewModel.PostCount = 0;
            threadViewModel.UserId    = thread.UserId;
            if (thread.UserId is null)
            {
                threadViewModel.Username = "******";
            }
            else
            {
                var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(new ApplicationDbContext()));
                var user    = manager.FindById(thread.UserId);
                threadViewModel.Username = user is null ? "Неизвестный" : user.UserName;
            }
            model.thread = threadViewModel;

            model.posts = (List <Post>)repository.GetPosts(threadId);

            return(View(model));
        }
Exemplo n.º 9
0
        public void AddThread(ThreadViewModel thread)
        {
            var threadModel = this.mappingService.MapThreadViewModelToThreadModel(thread);

            ctx.Thread.Add(threadModel);
            ctx.SaveChanges();
        }
Exemplo n.º 10
0
        public async Task <ActionResult <ThreadViewModel[]> > GetForum(int forumId)
        {
            List <ThreadViewModel> forumThreadEntries = new List <ThreadViewModel>();

            Forum currentForum = await _context.Fora.Include(i => i.ForumThreadEntries).ThenInclude(i => i.Author).FirstOrDefaultAsync(cf => cf.Id == forumId);

            // Create the view model
            foreach (ThreadEntry threadEntry in currentForum.ForumThreadEntries)
            {
                ThreadViewModel forumThreadEntryViewModel = new ThreadViewModel();

                forumThreadEntryViewModel.InjectFrom(threadEntry);

                forumThreadEntryViewModel.Author = new ApplicationUserViewModel();
                forumThreadEntryViewModel.Author.InjectFrom(threadEntry);

                forumThreadEntryViewModel.Replies = currentForum.ForumThreadEntries.Where(forumThreadEntry => forumThreadEntry.Root?.Id == threadEntry.Id && forumThreadEntry.Parent != null).Count();
                IOrderedEnumerable <ThreadEntry> interim = currentForum.ForumThreadEntries.Where(m => m.Root?.Id == threadEntry.Id).OrderBy(m => m.UpdatedAt.ToFileTime());
                if (interim.Count() > 0)
                {
                    forumThreadEntryViewModel.LastReply = interim.FirstOrDefault().UpdatedAt.ToString();
                }
                else
                {
                    forumThreadEntryViewModel.LastReply = DateTime.Now.ToString();
                }

                forumThreadEntries.Add(forumThreadEntryViewModel);
            }

            return(forumThreadEntries.ToArray());
        }
Exemplo n.º 11
0
        public async Task <IActionResult> EditThread(ThreadViewModel model)
        {
            try
            {
                var thread = forumService.GetThreadModel(model.ThreadId);

                if (userManager.GetUserId(User) == thread.UserId || User.IsInRole("Admin"))
                {
                    thread.ThreadTitle = model.ThreadTitle;
                    thread.Subject     = model.Subject;

                    await forumService.EditThread(thread);
                }
                else
                {
                    throw new Exception();
                }
            }
            catch
            {
                ViewBag.ErrorTitle   = "Editing Error";
                ViewBag.ErrorMessage = "There was an issue editing your thread. Please contact us for support.";
                return(View("Error"));
            }
            return(RedirectToAction("ThreadPosts", new { threadId = model.ThreadId }));
        }
Exemplo n.º 12
0
        private ThreadDetailsViewModel GetModel(IReadOnlyCollection <Section> sections, IReadOnlyCollection <Commentary> comments, Thread thread, int likesAmount, int likeStatus)
        {
            var sectionModels = sections.Select(s => new SectionViewModel
            {
                SectionName = s.Name
            }).ToList();
            var commentsModels = comments.OrderByDescending(c => c.CommentTime).Select(c => new CommentThreadViewModel
            {
                AuthorNickname = c.Author.Username,
                CommentTime    = c.CommentTime,
                Content        = c.Content
            }).ToList();
            var threadModel = new ThreadViewModel
            {
                ThreadId       = thread.Id,
                AuthorNickname = thread.Author.Username,
                Content        = thread.Content,
                Title          = thread.Title
            };

            var isAuthor = User.Identity.IsAuthenticated ? thread.Author.Username == User.Identity.Name : false;
            var model    = new ThreadDetailsViewModel
            {
                LikesAmount = likesAmount,
                LikeStatus  = likeStatus,
                IsAuthor    = isAuthor,
                Sections    = sectionModels,
                Comments    = commentsModels,
                Thread      = threadModel
            };

            return(model);
        }
Exemplo n.º 13
0
        public void SearchController_Index_ShouldReturnCorrectResultsCaseInsensitiveSecondPage(string searchTerm)
        {
            // Arrange
            var data         = new Mock <IUowData>();
            var pagerFactory = new Mock <IPagerViewModelFactory>();

            data.Setup(d => d.Threads.All()).Returns(SearchTestCollection().AsQueryable());

            Mapper.Initialize(cfg => cfg.CreateMap <Thread, ThreadViewModel>());

            SearchController controller = new SearchController(data.Object, pagerFactory.Object);

            var expected = new ThreadViewModel[]
            {
                new ThreadViewModel()
                {
                    Id = 7, Published = new DateTime(2017, 01, 07), Title = "How to test it!", Content = "Need some help here!", AnswersCount = 0, SectionName = "testSectionName", UserId = "id"
                }
            };

            // Act
            var result      = controller.Index(searchTerm, 2) as ViewResult;
            var resultModel = result.Model as Tuple <IEnumerable <ThreadViewModel>, IPagerViewModel>;

            // Assert
            CollectionAssert.AreEqual(expected, resultModel.Item1, new ThreadViewModelComparer());
        }
        public IActionResult Thread(int id)
        {
            var thread = this.threadService.GetById(id);

            var currentUserId = this.userManager.GetUserId(this.User);

            var replies = thread.Replies.Select(r => new ReplyModel
            {
                Id                   = r.Id,
                PostedByName         = r.PostedBy.DisplayName,
                PostedByAvatarUrl    = r.PostedBy.ImageUrl,
                RepliedOn            = r.CreatedOn,
                InputContent         = r.Content,
                ThreadId             = r.ThreadId,
                CurrentUserIsCreator = this.replyService.UserIsCreator(currentUserId, r.Id),
            });

            var model = new ThreadViewModel
            {
                Id                = thread.Id,
                Title             = thread.Title,
                PostedByName      = thread.PostedBy.UserName,
                PostedByAvatarUrl = thread.PostedBy.ImageUrl,
                CreatedOn         = thread.CreatedOn,
                InputContent      = thread.Content,
                Replies           = replies.OrderByDescending(r => r.RepliedOn),
            };

            return(this.View(model));
        }
Exemplo n.º 15
0
        public ThreadViewModel GetDataRecord(int threadID)
        {
            ThreadViewModel vm = null;

            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("GetThreadDetails", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@ThreadID", SqlDbType.Int).Value = threadID;

                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        vm = new ThreadViewModel
                        {
                            ThreadID    = (int)reader["ThreadID"],
                            TopicID     = (int)reader["TopicID"],
                            UserID      = (int)reader["UserID"],
                            Name        = reader["Name"].ToString(),
                            Description = reader["Description"].ToString(),
                            CreatedDate = (reader.IsDBNull(reader.GetOrdinal("CreatedDate")) ? null : (DateTime?)reader["CreatedDate"])
                        };
                    }

                    reader.Close();
                    con.Close();
                }
            }

            return(vm);
        }
Exemplo n.º 16
0
        private async void ThreadSelected(object sender, SelectedItemChangedEventArgs e)
        {
            //var webHandler = new WebHandler();
            ThreadsList.SelectedItem = null;
            ThreadViewModel thread = await e.SelectedItem.ToString().GetThreadByName();

            await Navigation.PushAsync(new ThreadPage(thread));
        }
Exemplo n.º 17
0
 public async Task <IActionResult> UpdateThreadAsync(ThreadViewModel thread, int pageIndex)
 {
     if (ModelState.IsValid)
     {
         await _threadService.UpdateAsync(_mapper.Map <ThreadDto>(thread));
     }
     return(RedirectToAction("ViewCategory", "Category", new { categoryId = thread.CategoryId, pageIndex }));
 }
Exemplo n.º 18
0
        public void UpdateThread(ThreadViewModel entity)
        {
            Thread thread = _mapper.Map <Thread>(_threadRepository.GetById(entity.Id));

            thread.Title = entity.Title;

            _threadRepository.Update(thread);
        }
Exemplo n.º 19
0
        public IActionResult AddThread(ThreadViewModel thread, string id)
        {
            var category = _categoryService.GetCategoryById(int.Parse(id));

            thread.Category = category;
            _threadService.CreateThread(thread);
            return(RedirectToAction("Category", "Category", new { category.Id }));
        }
Exemplo n.º 20
0
        public ActionResult Thread(Guid id)
        {
            ThreadViewModel vm = new ThreadViewModel();

            vm.ForumThread = Repository.Instance.Get <ForumThread>(id);
            vm.Posts       = Repository.Instance.GetPostsByThreadID(id);
            return(View(vm));
        }
Exemplo n.º 21
0
 public async Task <IActionResult> CreateThreadAsync(ThreadViewModel thread, Guid categoryId, int pageIndex, int pageSize)
 {
     if (ModelState.IsValid && categoryId != Guid.Empty)
     {
         await _threadService.CreateAsync(thread);
     }
     return(RedirectToAction("ViewCategory", "Category", new { categoryId, pageIndex, pageSize }));
 }
Exemplo n.º 22
0
        private ThreadViewModel GenerateThreadViewModel(int forumID, EditorType editorType, int? postID = null)
        {
            if (editorType == EditorType.Edit && !postID.HasValue)
                throw new InvalidOperationException("postID is required to generate an edit ThreadViewModel");

            Forum forum = _forumServices.GetForum(forumID);

            var permittedThreadTypes = _permissionServices.GetAllowedThreadTypes(forumID, _currentUser.UserID).ToList();
            var model = new ThreadViewModel()
            {
                EditorType = editorType,
                Forum = forum,
                ForumID = forum.ForumID,
                ThreadEditor = new ThreadEditorViewModel()
                {
                    AllowThreadImages = SiteConfig.AllowThreadImage.ToBool(),
                    PermittedThreadTypes = permittedThreadTypes,
                    ThreadImages = _threadServices.GetThreadImages(),
                },
                CanUploadAttachments = _permissionServices.CanCreateAttachment(forumID, _currentUser.UserID),
                CanCreatePoll = _permissionServices.CanCreatePoll(forumID, _currentUser.UserID)
            };

            if (editorType == EditorType.Edit)
            {
                var post = _postServices.GetPost(postID.Value);
                var thread = post.Thread;
                model.ThreadEditor.ThreadType = thread.Type;
                model.ThreadEditor.Image = thread.Image;
                model.ThreadEditor.ThreadID = post.ThreadID;
                model.ThreadEditor.Title = thread.Title;
                model.PostEditor = GeneratePostEditorViewModel(thread.ThreadID, EditorType.Edit, post);

                if (post.Thread.Poll != null)
                {
                    Poll poll = post.Thread.Poll;
                    IEnumerable<PollOption> options = poll.PollOptions;
                    bool hasVotes = options.Any(item => item.PollVotes.Count > 0);
                    model.PollEditor = new PollEditorViewModel()
                    {
                        HasVotes = hasVotes,
                        Options = poll.PollOptionsAsString(),
                        Text = poll.Question,
                        PollID = poll.PollID
                    };
                }
            }

            if (TempData.ContainsKey("Preview_Text"))
            {
                string previewText = (string)TempData["Preview_Text"];
                model.PreviewText = _parseServices.ParseBBCodeText(previewText);
                model.Preview = true;
                model.PreviewTitle = (string)TempData["Preview_Title"];
            }

            return model;
        }
Exemplo n.º 23
0
        public IActionResult AddThread(string forumId)
        {
            ThreadViewModel threadViewModel = new ThreadViewModel()
            {
                ForumId = forumId
            };

            return(View(threadViewModel));
        }
        public ThreadPage(ThreadViewModel model)
        {
            _model = model;
            InitializeComponent();

            BindingContext = _model;

            var cell = new TextCell();
        }
Exemplo n.º 25
0
        //
        // GET: Forum/Thread/ThreadId&GroupId
        public async Task <ActionResult> Thread(int threadId, int groupId, int?page)
        {
            const int messagesPerPage = 20;

            // Filling in the viewbags
            ViewBag.GroupName = await GroupManager.GetGroupNameByIdAsync(groupId);

            ViewBag.GroupId  = groupId;
            ViewBag.ThreadId = threadId;

            // Creating a list of messages
            ThreadViewModel model  = new ThreadViewModel();
            Thread          thread = await ThreadManager.FindByIdAsync(threadId);

            ICollection <MessagesViewModel> messagesViewModels = new List <MessagesViewModel>();

            model.ThreadName = thread.Name;

            // TODO: make this so this is only if the user is loged in
            model.Subscribed = ThreadManager.IsUserSubscribedToThreac(thread);

            // Creating the messages
            foreach (Message message in thread.Messages)
            {
                messagesViewModels.Add(new MessagesViewModel
                {
                    Id            = message.Id,
                    UserName      = UserManager.FindById(message.User.UserId).UserName,
                    JoinDate      = message.User.JoinDate,
                    Posts         = message.User.PostsCount,
                    Signiture     = message.User.Signature,
                    Reputation    = message.Reputation,
                    ThreadId      = threadId,
                    GroupId       = groupId,
                    Image         = ProfilePictureSystem.GetProfilePicture(message.User.UserId),
                    Country       = (await UserManager.FindByIdAsync(message.User.UserId)).Country,
                    VotingEnabled = ReputationSystem.CanUserVote(message),
                    IsCreator     = (message.User.UserId == User.Identity.GetUserId()),

                    Body          = message.Body,
                    MessagePost   = message.TimeStamp,
                    MessageNumber = message.MessagePlacementInThread
                });
            }

            // Sorts the list by date
            messagesViewModels = messagesViewModels.OrderByDescending(m => m.MessagePost).ToList();

            // Changing to it a page list
            model.Messages = messagesViewModels.ToPagedList(page ?? 1, messagesPerPage);

            // Increase the view count
            await ThreadManager.AddThreadViewwCountAsync(thread.Id);

            return(View(model));
        }
Exemplo n.º 26
0
        public IActionResult RemoveThread2(string threadId)
        {
            ThreadViewModel thread = _threadService.GetThreadById(threadId);

            string categoryTitle = _categoryService.GetCategoryById(thread.CategoryId).Title;

            _threadService.DeleteThread(threadId);

            return(RedirectToAction("ShowAllThreads", new { categoryId = thread.CategoryId, categoryTitle }));
        }
Exemplo n.º 27
0
        public ActionResult AddThread(ThreadViewModel thread)
        {
            if (ModelState.IsValid)
            {
                _repo.AddThread(ThreadHelper.Transform(thread));

                return(PartialView("Index", ThreadHelper.Transform(_repo.GetThreads())));
            }
            return(PartialView("AddThread", thread));
        }
Exemplo n.º 28
0
 public ThreadPage(ThreadViewModel viewModel)
 {
     BindingContext = viewModel;
     InitializeComponent();
     viewModel.LoadCommentsCommand.Execute(null);
     MessagingCenter.Subscribe <ThreadViewModel, string>(viewModel, "Error", (sender, data) =>
     {
         DisplayAlert("Error", data, "Ok");
     });
 }
Exemplo n.º 29
0
        public IActionResult EditThread(string threadId, string title)
        {
            ThreadViewModel thread = _threadService.GetThreadById(threadId);

            thread.Title = title;

            _threadService.UpdateThread(thread);

            return(RedirectToAction("ShowAllCategories"));
        }
Exemplo n.º 30
0
        public Thread MapThreadViewModelToThreadModel(ThreadViewModel model)
        {
            var threadModel = new Thread()
            {
                Id        = model.Id,
                OwnerId   = model.Owner,
                OponentId = model.OponentVM.Id
            };

            return(threadModel);
        }
Exemplo n.º 31
0
 protected override async void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     var linkTransform = ServiceLocator.Current.GetServiceOrThrow<ILinkTransformService>();
     var link = NavigationHelper.GetLinkFromParameter(e.Parameter);
     navigatedLink = linkTransform.GetThreadLinkFromAnyLink(link);
     navigatePostLink = null;
     if (link != null)
     {
         if ((link.LinkKind & BoardLinkKind.Post) != 0 && e.NavigationMode != NavigationMode.Back)
         {
             navigatePostLink = link;
         }
     }
     if (navigatedLink == null)
     {
         await AppHelpers.ShowError(new InvalidOperationException("Неправильный тип параметра навигации"));
         BootStrapper.Current.NavigationService.GoBack();
         return;
     }
     savedTopPostHash = await GetStoredCurrentPostHash(navigatedLink);
     isTopPostSet = true;
     var vm = new ThreadViewModel(navigatedLink);
     ViewModel = vm;
     vm.PostsUpdated += LiteWeakEventHelper.CreateHandler(new WeakReference<ThreadPage>(this), (root, esender, ee) => root.OnPostsUpdated(esender, ee));
     isBackNavigated = e.NavigationMode == NavigationMode.Back;
     vm.IsBackNavigatedToViewModel = isBackNavigated;
     vm.PropertyChanged += ViewModelOnPropertyChanged;
     ViewModelOnPropertyChanged(vm, new PropertyChangedEventArgs(null));
     NavigatedTo?.Invoke(this, e);
 }
Exemplo n.º 32
0
        public ActionResult ViewThread(ThreadViewModel model)
        {
            using (ForumRespository db = new ForumRespository())
            {
                Forum_Thread Thread = db.GetThreadByID(model.Id);

                if (Thread == null)
                {
                    return NotFoundView("Thread");
                }

                if (model.Page < 1) return RedirectToAction("ViewThread", new { id = model.Id, page = 1}); // page less than 0 for existing thread equals redirect to valid page.

                model.AddNavigation(Thread);

                Forum_User ThreadViewUser = GetCurrentUser(db);

                if (!db.CheckCategoryPermissions(Thread.Forum_Category, ThreadViewUser, P => P.AllowView))
                    return AuthenticationHelper.AccessDeniedView(model);

                model.AllowEditThread = db.CheckCategoryPermissions(Thread.Forum_Category, ThreadViewUser, P => (P.AllowDeleteOwnThread && Thread.Forum_Posts[0].PosterID == ThreadViewUser.UserID && Thread.Forum_Posts[0].PosterID != (int)BuildInUser.Guest) || P.AllowDeleteAllThread || P.AllowMoveThread || P.AllowLockThread);
                model.Locked = Thread.Locked;
                model.ThreadTitle = Thread.Title;

                int UserID = 0;
                Forum_User U = GetCurrentUser(db);
                if (U != null)
                {
                    UserID = U.UserID;
                    db.SetLastPost(Thread, U, Math.Min(model.Page * POSTS_PER_PAGE, Thread.Posts));
                    db.Save();
                }

                model.LastPage = (Thread.Posts - 1) / POSTS_PER_PAGE + 1;
                if (model.Page > model.LastPage) return RedirectToAction("ViewThread", new { id = model.Id, page = model.LastPage }); // page greater than what exists equals redirect to last page.
                IEnumerable<Forum_Post> Posts = Thread.Forum_Posts.Skip((model.Page - 1)* POSTS_PER_PAGE).Take(POSTS_PER_PAGE);

                int PostNumber = 0;

                foreach (Forum_Post Post in Posts)
                {
                    PostViewModel PostModel = new PostViewModel();
                    PostModel.Locked = model.Locked;
                    PostModel.PostNumber = ++PostNumber;
                    PostModel.ThreadID = model.Id;
                    PostModel.PostText = PostParser.Parse(Post.PostText);
                    PostModel.PostTime = Post.TimeStamp;
                    PostModel.Poster = new UserViewModel();
                    PostModel.PostID = Post.PostID;
                    PostModel.Poster.Name = Post.Forum_User.Username;
                    PostModel.Poster.UserID = Post.PosterID;
                    PostModel.AllowDelete = (PostNumber > 1 || model.Page > 1) && db.CheckCategoryPermissions(Thread.Forum_Category, ThreadViewUser,
                        P => (P.AllowDeleteOwnPost && Post.PosterID == ThreadViewUser.UserID && Post.PosterID != (int)BuildInUser.Guest) || P.AllowDeleteAllPosts);
                    PostModel.AllowEdit = db.CheckCategoryPermissions(Thread.Forum_Category, ThreadViewUser, P => (P.AllowEditOwnPost && Post.PosterID == ThreadViewUser.UserID && Post.PosterID != (int)BuildInUser.Guest) || P.AllowEditAllPosts);
                    model.PostList.Add(PostModel);
                }
                return View(model);
            }
        }