コード例 #1
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            parameters = (Dictionary <string, ViewModelBase>)e.Parameter;

            TopicViewModel topicVm = (TopicViewModel)parameters["topicVm"];

            TopicTitle = topicVm.TopicTitle;

            //TopicViewModel topicVm = (TopicViewModel) e.Parameter;

            MessageViewModel messageVM = new MessageViewModel();

            DataContext = messageVM;

            SystemNavigationManager.GetForCurrentView().BackRequested += MainPage_BackRequested;

            //ObservableCollection<ViewModelBase> ret = await ((MessageViewModel)DataContext).GetListMessage(topicVm.TopicId);

            messageVM.GetListMessage(topicVm.TopicId);
        }
コード例 #2
0
ファイル: TopicService.cs プロジェクト: ngocnt1801/QBCS
 public bool AddTopic(TopicViewModel model)
 {
     try
     {
         var topic = new Topic()
         {
             Code      = model.Code,
             Name      = model.Name,
             CourseId  = model.CourseId,
             IsDisable = false
         };
         unitOfWork.Repository <Topic>().Insert(topic);
         unitOfWork.SaveChanges();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
コード例 #3
0
        public async Task <IActionResult> CreateNewTopic(TopicViewModel topicView)
        {
            if (Request.Form.Files.Count != 1)
            {
                ModelState.AddModelError("Image", "image cannot be empty");
            }
            else
            {
                topicView.TopicPicture = ImageConvertor.ConvertImageToBytes(Request.Form.Files[0]);
            }

            if (ModelState.IsValid)
            {
                var mappedTopic = mapper.Map <TopicDTO>(topicView);
                await topicService.CreateTopic(mappedTopic);

                return(RedirectToAction(nameof(Panel)));
            }
            return(View(topicView));
        }
コード例 #4
0
        public IActionResult Insert(TopicViewModel topic)
        {
            if (topic == null)
            {
                return(BadRequest("Topic info must not be null"));
            }

            int result = _topic.Insert(topic);

            if (result == 0)
            {
                return(BadRequest("Faulthy topic info."));
            }
            if (result == 1)
            {
                return(BadRequest("This topic is already in the system"));
            }

            return(Ok("Inserted topic " + topic.TopicName));
        }
コード例 #5
0
        public IActionResult Update(TopicViewModel topic)
        {
            if (topic == null)
            {
                return(BadRequest("Topic info must not be null"));
            }

            int result = _topic.Update(topic);

            if (result == 0)
            {
                return(BadRequest("Faulthy topic info."));
            }
            if (result == 1)
            {
                return(NotFound("Topic not found"));
            }

            return(Ok("Updated topic " + topic.TopicName));
        }
コード例 #6
0
        // GET: Topics/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Topic topic = db.GetFromDatabase<Topic>(id);

            if (topic == null)
            {
                return HttpNotFound();
            }

            TopicViewModel tvm = new TopicViewModel();
            tvm.Topic = topic;
            FillTopicViewModelLists(tvm);

            return View(tvm);
        }
コード例 #7
0
ファイル: HomeController.cs プロジェクト: darkbuivn/newBlog
        public ActionResult Index()
        {
            ViewBag.Title = Common.Contant.PageTitle.HOME_PAGE;

            TopicViewModel model;
            Topic          topic = _topicService.GetNewest();

            if (topic != null)
            {
                model              = Mapper.Map <Topic, TopicViewModel>(topic);
                model.Category     = Mapper.Map <Category, CategoryViewModel>(_categoryService.GetById(model.CategoryId));
                ViewBag.MoreTopics = _topicService.GetMore(model.Id);
            }
            else
            {
                model          = new TopicViewModel();
                model.Category = new CategoryViewModel();
            }
            return(View(model));
        }
コード例 #8
0
        /// <summary>
        /// Create a new topic/thread for a class/module
        /// </summary>
        /// <param name="discussionViewModel">Topic View Model</param>
        /// <returns>TopicViewModel if created successfully otherwise null</returns>
        public TopicViewModel AddTopic(TopicViewModel topicViewModel)
        {
            Topic _topic = new Topic();

            try
            {
                _topic             = ObjectMapper.Map <TopicViewModel, Topic>(topicViewModel);
                _topic.PublishFrom = DateTime.Now;
                _topic.PublishTo   = DateTime.Now;
                Topic newTopicPost = TopicManager.Add(_topic);
            }
            catch (Exception ex)
            {
                ExceptionManager.HandleException(ex, PolicyNameType.ExceptionReplacing);
                return(null);
            }
            TopicViewModel _topicViewModel = ObjectMapper.Map <Topic, TopicViewModel>(_topic);

            return(_topicViewModel);
        }
コード例 #9
0
        public async Task Post([FromBody] TopicViewModel model)
        {
            // MySql
            this.mysqlContext.Topics.Add(new Topic()
            {
                Content    = model.Content,
                CreateTime = DateTime.Now,
                Title      = model.Title
            });
            await this.mysqlContext.SaveChangesAsync();

            // PgSql
            this.pgsqlContext.Topics.Add(new Topic()
            {
                Content    = model.Content,
                CreateTime = DateTime.Now,
                Title      = model.Title
            });
            await this.pgsqlContext.SaveChangesAsync();
        }
コード例 #10
0
        public async Task <IActionResult> Edit(int?ID)
        {
            var topic = await _context.Topics.SingleOrDefaultAsync(s => s.ID == ID);

            if (topic == null)
            {
                throw new ApplicationException($"Unable to load topic with ID '{ID}'.");
            }
            var model = new TopicViewModel
            {
                ID          = topic.ID,
                TopicName   = topic.TopicName,
                Description = topic.Description,
                isFeatured  = topic.isFeatured,
                Rules       = topic.Rules
            };

            ViewData["Action"] = "Edit";
            return(PartialView("_TopicData", model));
        }
コード例 #11
0
        public async Task <IActionResult> Put(int id, [FromBody] TopicViewModel topicViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var topicDto = await _topicService.GetByIdAsync(id);

            if (topicDto == null)
            {
                return(BadRequest());
            }

            topicDto = _mapper.Map <TopicViewModel, TopicDto>(topicViewModel);

            await _topicService.UpdateAsync(topicDto);

            return(Ok());
        }
コード例 #12
0
ファイル: DMaster.cs プロジェクト: vilasholkar/AVV
        public TopicViewModel GetTopicByID(int TopicID)
        {
            var topicViewModelData = new TopicViewModel();
            List <SqlParameter> sqlParameterList = new List <SqlParameter>();

            sqlParameterList.Add(new SqlParameter("@TopicID", TopicID));
            IList <DataTableMapping> dataTableMappingList = new List <DataTableMapping>();

            dataTableMappingList.Add(new DataTableMapping("Table", "Topic"));
            dataTableMappingList.Add(new DataTableMapping("Table1", "Course"));
            dataTableMappingList.Add(new DataTableMapping("Table2", "Batch"));
            DataSet ds = DGeneric.RunSP_ReturnDataSet("sp_GetTopicByID", sqlParameterList, dataTableMappingList);

            if (ds.Tables.Count > 0)
            {
                foreach (DataTable dt in ds.Tables)
                {
                    if (dt.Rows.Count > 0)
                    {
                        switch (dt.TableName)
                        {
                        case "Topic":
                            topicViewModelData          = DGeneric.BindDataList <TopicViewModel>(dt).FirstOrDefault();
                            topicViewModelData.StreamID = dt.Rows[0]["StreamID"].ToString().Split(',').Select(int.Parse).ToArray();
                            topicViewModelData.CourseID = dt.Rows[0]["CourseID"].ToString() != string.Empty ? dt.Rows[0]["CourseID"].ToString().Split(',').Select(int.Parse).ToArray() : null;
                            topicViewModelData.BatchID  = dt.Rows[0]["BatchID"].ToString() != string.Empty ? dt.Rows[0]["BatchID"].ToString().Split(',').Select(int.Parse).ToArray() : null;
                            break;

                        case "Course":
                            topicViewModelData.Course = DGeneric.BindDataList <CourseViewModel>(dt);
                            break;

                        case "Batch":
                            topicViewModelData.Batch = DGeneric.BindDataList <BatchViewModel>(dt);
                            break;
                        }
                    }
                }
            }
            return(topicViewModelData);
        }
コード例 #13
0
        public async Task <IActionResult> Edit(TopicViewModel model)
        {
            model.Title   = model.Title?.Trim();
            model.Content = model.Content?.Trim();

            ViewData["Error"] = true;
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var loginUserName = User.Identity.Name;
            var loginUser     = await this._userRepo.FindAsync(p => p.Name == loginUserName);

            if (loginUser == null)
            {
                ModelState.AddModelError("", "用户找不到");
                return(View(model));
            }
            var topicOrign = await this._topicRepo.FindAsync(p => p.TopicId == model.TopicId);

            if (topicOrign == null)
            {
                throw new Exception("找不到话题,或已被删除");
            }
            topicOrign.Title          = model.Title;
            topicOrign.Content        = model.Content;
            topicOrign.Type           = model.Tab;
            topicOrign.UpdateDateTime = DateTime.Now;

            var result = await this._topicRepo.UpdateAsync(topicOrign);

            if (result)
            {
                return(new RedirectResult(Url.Content($"/Topic/Index/{topicOrign.TopicId}")));
            }
            else
            {
                ModelState.AddModelError("", "出现未知错误,编辑失败,请稍后再试");
                return(View(model));
            }
        }
コード例 #14
0
        public async Task <IActionResult> Add(TopicViewModel model)
        {
            ViewData["Action"] = "Add";
            ViewData["Error"]  = true;
            model.Title        = model.Title?.Trim();
            model.Content      = model.Content?.Trim();
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var loginUser = await this._userRepo.FindAsync(p => p.Name == User.Identity.Name);

            if (loginUser == null)
            {
                ModelState.AddModelError("", "用户找不到");
                return(View(model));
            }
            var topic = new Topic()
            {
                Title          = model.Title,
                Content        = model.Content,
                AuthorId       = loginUser.UserId,
                CreateDateTime = DateTime.Now,
                Type           = model.Tab
            };
            var result = await this._topicRepo.AddAsync(topic, false);

            loginUser.Topic_Count += 1;
            loginUser.Score       += 5;
            result = await this._userRepo.UpdateAsync(loginUser);

            if (result)
            {
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ModelState.AddModelError("", "出现未知错误,发布失败,请稍后再试");
                return(View(model));
            }
        }
コード例 #15
0
        public async Task <IActionResult> CreateDiscussion(TopicViewModel model)
        {
            var tags = new List <Tag>();

            if (!string.IsNullOrEmpty(model.SelectedTags))
            {
                tags = (await tagsService.ParseTags(model.SelectedTags)).ToList();
            }

            model.Topic = await topicsRepository.FindByIdAsync(model.TopicId);

            if (string.IsNullOrWhiteSpace(model.Discussion.Title))
            {
                ModelState.AddModelError <TopicViewModel>(m => m.Discussion.Title, "Zadejte název diskuse.");
                return(View("Topic", model));
            }

            if (string.IsNullOrWhiteSpace(model.Contribution.Content))
            {
            }

            var user = await userManager.GetUserAsync(User);

            model.Discussion.Created        = DateTime.Now;
            model.Discussion.User           = user;
            model.Discussion.Topic          = model.Topic;
            model.Discussion.DiscussionTags = tags.Select(t => new DiscussionTag
            {
                Tag = t
            }).ToList();

            await discussionsRepository.CreateAsync(model.Discussion);

            model.Contribution.Created    = DateTime.Now;
            model.Contribution.User       = user;
            model.Contribution.Discussion = model.Discussion;

            await contributionsRepository.CreateAsync(model.Contribution);

            return(RedirectToAction("Discussion", new { id = model.Discussion.Id }));
        }
コード例 #16
0
        public async Task <ActionResult> Topic(Guid topicId)
        {
            var topic = await _service.GetTopic(topicId, 1, 10);

            var model = new TopicViewModel
            {
                Id    = topic.Id,
                Title = topic.Title,
                Posts = topic.Posts.Select(t => new PostViewModel
                {
                    Content       = t.Content,
                    CreationDate  = t.CreationDate,
                    Author        = t.Author,
                    AttachedFiles = t.AttachedFiles
                }).ToList(),
                Author       = topic.Author,
                CreationDate = topic.CreationDate
            };

            return(View(model));
        }
コード例 #17
0
ファイル: TopicsController.cs プロジェクト: sachinp290/TS
        public ActionResult Create(TopicViewModel item)
        {
            try
            {
                if (item.SubjectID != 0)
                {
                    var result = APIHelper <TopicViewModel> .Post("topic", item);

                    if (result)
                    {
                        return(RedirectToAction("Index"));
                    }
                    return(View(item));
                }
                return(RedirectToAction("Create"));
            }
            catch (Exception ea)
            {
                throw ea;
            }
        }
コード例 #18
0
        private async Task <TopicViewModel> GetTopicViewModel(long idTopic, int?page)
        {
            TopicViewModel tvm = new TopicViewModel();

            tvm.topic = GetTopic(idTopic);
            var posting = from p in dbContext.Posting where p.idTopic == idTopic select p;

            tvm.postings = await PaginatedList <Posting> .CreateAsync(posting, page ?? 1, 10);

            tvm.postingsViewModel = new List <PostingViewModel>();
            string          photo = "../images/blank-profile-picture.png";
            ApplicationUser user  = new ApplicationUser();

            user = dbContext.ApplicationUser.SingleOrDefault(u => u.Id == tvm.topic.idUser);
            if (user.UserPhoto != null)
            {
                var base64 = Convert.ToBase64String(user.UserPhoto);
                photo = String.Format("data:image/jpg;base64,{0}", base64);
            }
            ViewData["imgUserTopic"] = photo;
            foreach (var post in tvm.postings)
            {
                photo = "../images/blank-profile-picture.png";
                user  = dbContext.ApplicationUser.SingleOrDefault(u => u.Id == post.idUser);
                if (user.UserPhoto != null)
                {
                    var base64 = Convert.ToBase64String(user.UserPhoto);
                    photo = String.Format("data:image/jpg;base64,{0}", base64);
                }
                PostingViewModel postingTarget = new PostingViewModel {
                    idTopic   = post.idTopic,
                    idPosting = post.idPosting,
                    idUser    = post.idUser,
                    Message   = post.Message,
                    imgSrc    = photo
                };
                tvm.postingsViewModel.Add(postingTarget);
            }
            return(tvm);
        }
コード例 #19
0
        public ActionResult AddTopic(TopicViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            Topic add = ModelConverter.ViewToTopic(model);
            ApplicationDbContext context = new ApplicationDbContext();

            add.ParentId = model.ParentId == -1 ? null : model.ParentId;
            if (add.ParentId == null)
            {
                add.Level = 0;
            }
            else
            {
                add.Level = context.Topics.First(x => x.Id == add.ParentId).Level + 1;
            }
            context.Topics.Add(add);
            context.SaveChanges();
            return(RedirectToAction("Topics"));
        }
コード例 #20
0
        public async Task <IActionResult> Index(int id)
        {
            var topic = await this._topicRepo.FindAsync(p => p.TopicId == id && !p.Deleted);

            if (topic == null)
            {
                throw new Exception("找不到此话题,或已被删除");
            }
            topic.VisitCount += 1;
            await this._topicRepo.UpdateAsync(topic);

            var author = await this._userRepo.FindAsync(p => p.UserId == topic.AuthorId);

            if (author == null)
            {
                throw new Exception("作者未找到");
            }

            var topicViewModel = new TopicViewModel()
            {
                Tab     = topic.Type,
                Title   = topic.Title,
                Content = topic.Content,

                Topic  = topic,
                Author = author,
                Html   = topic.Html
            };

            if (User.Claims.Any(p => p.Type == ClaimTypes.Name))
            {
                var loginUser = await this._userRepo.FindAsync(p => p.Name == User.Identity.Name);

                topicViewModel.LoginUser = loginUser;
                topicViewModel.Collected = await this._topicCollectRepo.IsExistAsync(p => p.TopicId == topic.TopicId && p.UserId == loginUser.UserId);
            }

            return(View(topicViewModel));
        }
コード例 #21
0
 public async Task <IActionResult> Create([Bind("TopicName,Description,StartDate,EndDate, isFeatured, Rules")] TopicViewModel model, string returnUrl = null)
 {
     ViewData["ReturnUrl"] = returnUrl;
     if (ModelState.IsValid)
     {
         var rules   = model.Rules;
         var request = new SearchRequest
         {
             Query = ElasticsearchQueryBuilder.QueryBuilder(JObject.Parse(rules)),
             Size  = 50
         };
         var topic = new Topics
         {
             TopicName   = model.TopicName,
             Description = model.Description,
             DateCreated = DateTime.Now,
             StartDate   = model.StartDate,
             EndDate     = model.EndDate,
             Rules       = model.Rules,
             ESRequest   = _client.RequestResponseSerializer.SerializeToString(request),
             isFeatured  = model.isFeatured
         };
         try
         {
             _context.Add(topic);
             var result = await _context.SaveChangesAsync();
         }
         catch (DbUpdateException /* ex */)
         {
             //Log the error (uncomment ex variable name and write a log.)
             ModelState.AddModelError("", "Unable to save changes. " +
                                      "Try again, and if the problem persists, " +
                                      "see your system administrator.");
         }
     }
     StatusMessage = "Thêm mới chủ đề thành công!";
     return(RedirectToAction(nameof(Index)));
     //return View("Index", model);
 }
コード例 #22
0
ファイル: TopicController.cs プロジェクト: DevilOfFire/Forum
        public async Task <IActionResult> Index(int id, int page, int option)
        {
            switch (option)
            {
            case 0:
                ViewBag.Page = 0;
                break;

            case 1:
                ViewBag.Page = DecPage(page);
                break;

            case 2:
                ViewBag.Page = IncPage(page);
                break;

            case 3:
                ViewBag.Page = await LastPage(id);

                break;
            }
            ViewBag.MaxPosts = maxPosts;
            // Leniwe ładowanie - dopasuj posty do tematu o konkretnym Id
            var model = new TopicViewModel();

            model.Topic = await _context.Topic
                          .Where(m => m.TopicId == id)
                          .Include(p => p.Posts)
                          .FirstOrDefaultAsync();

            if (model.Topic == null)
            {
                return(NotFound());
            }
            model.Post = new Post();

            return(View(model));
        }
コード例 #23
0
        public async void CreateTopic_Returns_Ok()
        {
            var request = new SaveTopicViewModel
            {
                Title   = "Test topic",
                ThemeId = Guid.NewGuid()
            };

            var viewModel = new TopicViewModel
            {
                Id = Guid.NewGuid()
            };

            var topicService = new Mock <ITopicService>();

            topicService.Setup(s => s.CreateTopic(request)).ReturnsAsync(viewModel);

            var controller = new TopicController(topicService.Object);

            var result = await controller.CreateTopic(request);

            Assert.Equal(viewModel, result.Value);
        }
コード例 #24
0
        public ActionResult Index(int id)
        {
            var topic = _topicRepo.All()
                        .Where(t => t.Id == id)
                        .Include(t => t.Author)
                        .SingleOrDefault();

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

            var replies = _replyRepo.All()
                          .Where(c => c.TopicId == id)
                          .OrderBy(c => c.CreatedAtUtc)
                          .Include(r => r.Author)
                          .ToList();
            var showModel = TopicViewModel.CreateFrom(topic, replies);

            topic.ViewCount++;
            _topicRepo.Update(topic);
            return(View(showModel));
        }
コード例 #25
0
        public async Task <IActionResult> Post([FromBody] TopicViewModel topic)
        {
            if (ModelState.IsValid)
            {
                var isTokenValid = await _tokenValidator.IsTokenValid(Request.Headers, HttpContext);

                if (isTokenValid)
                {
                    var topicToAdd = new Topic()
                    {
                        Body = topic.Body, Name = topic.Name
                    };
                    var user = await GetCurrentUserAsync();

                    topicToAdd.CreatorId = user.Id;
                    await _topicRepository.AddTopic(topicToAdd);

                    return(Ok(topicToAdd));
                }
            }

            return(BadRequest(ModelState));
        }
コード例 #26
0
ファイル: ChatController.cs プロジェクト: zelinskiy/AspCourse
        public IActionResult AddNewTopic(TopicViewModel model)
        {
            var user = userManager.Users.First(u => u.UserName == User.Identity.Name);

            if (user.IsMuted)
            {
                return(Json("YOU ARE MUTED"));
            }

            Topic newTopic = new Topic()
            {
                Title    = model.NewTopicTitle,
                Author   = user,
                IsClosed = false,
                IsSticky = false,
            };

            _context.Topics.Add(newTopic);
            _context.SaveChanges();

            Message opMessage = new Message()
            {
                Text       = model.NewMessageText,
                CreatedAt  = DateTime.UtcNow,
                Author     = user,
                Topic      = _context.Topics.First(t => t.Id == newTopic.Id),
                PictureUrl = model.NewMessagePictureUrl
            };


            _context.Messages.Add(opMessage);
            _context.SaveChanges();



            return(Content($"Topic #{newTopic.Id} added!"));
        }
コード例 #27
0
        //public async Task<IActionResult> Topic(string fragment1 = null, string fragment2 = null, string fragment3 = null, string fragment4 = null, string fragment5 = null, string fragment6 = null, string fragment7 = null, string fragment8 = null, string fragment9 = null, string fragment10 = null)
        public async Task <IActionResult> Topic()
        {
            var routeCollection = HttpContext.GetRouteData();
            var topic           = routeCollection.Values.Values.FirstOrDefault()?.ToString();

            var vm = new TopicViewModel(topic, HttpContext);


            if (SqlDataAccess.CanUseSql)
            {
                var prefix   = ControllerHelper.GetCurrentDomainPrefix(HttpContext.Request);
                var settings = await SqlDataAccess.GetSqlRepositorySettings(prefix);

                if (settings == null)
                {
                    return(NotFound($"Document repository {prefix} does not exist."));
                }
                vm.SetRootSettingsForRequest(settings);
                vm.UseSqlServer  = true;
                vm.CurrentPrefix = prefix;
            }

            // TODO: How do we get the repository Auth Requirement from the db or local settings?
            if (vm.GetSetting <bool>(SettingsEnum.RequireAuthentication))
            {
                CheckAuthentication();
            }

            var appUser = User.GetAppUser();

            vm.AppUser = appUser;


            await vm.LoadData();

            return(View(vm.ThemeFolder + "/" + vm.TemplateName + ".cshtml", vm));
        }
コード例 #28
0
        public JsonResult AddTopic(TopicViewModel vm)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("InsertTopic", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@UserID", SqlDbType.Int).Value    = (int)System.Web.HttpContext.Current.Session["UserID"];
                        cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = vm.Name;

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

                        reader.Close();
                        con.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HttpException("You don't have access. Please login to continue", ex);
            }

            return(this.Json(vm));
        }
コード例 #29
0
        public TopicViewModel ViewTopic(int topicId)
        {
            var topic = _topicRepo.All()
                        .Where(t => t.Id == topicId)
                        .Include(t => t.Author)
                        .SingleOrDefault();

            if (topic == null)
            {
                return(null);
            }

            var replies = _replyRepo.All()
                          .Where(c => c.TopicId == topicId)
                          .OrderBy(c => c.CreatedAtUtc)
                          .Include(r => r.Author)
                          .ToList();

            // todo:   _eventBus.Publish(new TopicViewedEvent{ TopicId = topicId });
            topic.ViewCount += 1;
            _topicRepo.Update(topic);

            return(TopicViewModel.CreateFrom(topic, replies));
        }
コード例 #30
0
        public IActionResult <HashSet <TopicViewModel> > Topics(HttpResponse response, HttpSession session)
        {
            IEnumerable <Topic>      topics = this.data.Topics.GetAll();
            HashSet <TopicViewModel> tvms   = new HashSet <TopicViewModel>();

            var authenticationTvm = new TopicViewModel();

            authenticationTvm.UserLoggedIn = this.signInManager.IsAuthenticated(session);
            tvms.Add(authenticationTvm);

            foreach (var topic in topics)
            {
                TopicViewModel tvm = new TopicViewModel()
                {
                    Author       = topic.Author.Username,
                    Category     = topic.Category.Name,
                    PostedOn     = topic.PublishDate.ToString(),
                    RepliesCount = topic.Replies.Count,
                    Title        = topic.Title,
                };
                tvms.Add(tvm);
            }
            return(this.View(tvms));
        }
コード例 #31
0
        public static TopicViewModel CreateTopicViewModel(Topic topic,
                                                    PermissionSet permission,
                                                    List<Post> posts,
                                                    Post starterPost,
                                                    int? pageIndex,
                                                    int? totalCount,
                                                    int? totalPages,
                                                    MembershipUser loggedOnUser,
                                                    Settings settings,
                                                    bool getExtendedData = false)
        {

            var topicNotificationService = ServiceFactory.Get<ITopicNotificationService>();
            var pollAnswerService = ServiceFactory.Get<IPollAnswerService>();
            var voteService = ServiceFactory.Get<IVoteService>();
            var favouriteService = ServiceFactory.Get<IFavouriteService>();

            var userIsAuthenticated = loggedOnUser != null;

            // Check for online status
            var date = DateTime.UtcNow.AddMinutes(-AppConstants.TimeSpanInMinutesToShowMembers);

            var viewModel = new TopicViewModel
            {
                Permissions = permission,
                Topic = topic,
                Views = topic.Views,
                DisablePosting = loggedOnUser != null && (loggedOnUser.DisablePosting == true),
                PageIndex = pageIndex,
                TotalCount = totalCount,
                TotalPages = totalPages,
                LastPostPermaLink = string.Concat(topic.NiceUrl, "?", AppConstants.PostOrderBy, "=", AppConstants.AllPosts, "#comment-", topic.LastPost.Id),
                MemberIsOnline = topic.User.LastActivityDate > date,
            };
          
            if (starterPost == null)
            {
                starterPost = posts.FirstOrDefault(x => x.IsTopicStarter);
            }

            // Get votes for all posts
            var postIds = posts.Select(x => x.Id).ToList();
            postIds.Add(starterPost.Id);

            // Get all votes by post
            var votes = voteService.GetVotesByPosts(postIds);

            // Get all favourites for this user
            var allFavourites = favouriteService.GetByTopic(topic.Id);

            // Map the votes
            var startPostVotes = votes.Where(x => x.Post.Id == starterPost.Id).ToList();
            var startPostFavs = allFavourites.Where(x => x.Post.Id == starterPost.Id).ToList();

            // Create the starter post viewmodel
            viewModel.StarterPost = CreatePostViewModel(starterPost, startPostVotes, permission, topic, loggedOnUser, settings, startPostFavs);

            // Map data from the starter post viewmodel
            viewModel.VotesUp = startPostVotes.Count(x => x.Amount > 0);
            viewModel.VotesDown = startPostVotes.Count(x => x.Amount < 0);
            viewModel.Answers = totalCount != null ? (int)totalCount : posts.Count() - 1;

            // Create the ALL POSTS view models
            viewModel.Posts = CreatePostViewModels(posts, votes, permission, topic, loggedOnUser, settings, allFavourites);

            // ########### Full topic need everything   

            if (getExtendedData)
            {
                // See if the user has subscribed to this topic or not
                var isSubscribed = userIsAuthenticated && (topicNotificationService.GetByUserAndTopic(loggedOnUser, topic).Any());
                viewModel.IsSubscribed = isSubscribed;

                // See if the topic has a poll, and if so see if this user viewing has already voted
                if (topic.Poll != null)
                {
                    // There is a poll and a user
                    // see if the user has voted or not

                    viewModel.Poll = new PollViewModel
                    {
                        Poll = topic.Poll,
                        UserAllowedToVote = permission[SiteConstants.Instance.PermissionVoteInPolls].IsTicked
                    };

                    var answers = pollAnswerService.GetAllPollAnswersByPoll(topic.Poll);
                    if (answers.Any())
                    {
                        var pollvotes = answers.SelectMany(x => x.PollVotes).ToList();
                        if (userIsAuthenticated)
                        {
                            viewModel.Poll.UserHasAlreadyVoted = (pollvotes.Count(x => x.User.Id == loggedOnUser.Id) > 0);
                        }
                        viewModel.Poll.TotalVotesInPoll = pollvotes.Count();
                    }
                }
            }

            return viewModel;
        }