//api/topic public void Delete(int id) { var c = TopicService.GetById(id); if (c == null) { throw new Exception("Topic not found"); } if (!Library.Utils.IsModerator() && c.MemberId != Members.GetCurrentMemberId()) { throw new Exception("You cannot delete this topic"); } TopicService.Delete(c); }
void CommentVote(object sender, ActionEventArgs e) { Action a = (Action)sender; var ts = new TopicService(ApplicationContext.Current.DatabaseContext); var cs = new CommentService(ApplicationContext.Current.DatabaseContext, ts); if (a.Alias == "LikeComment" || a.Alias == "DisLikeComment") { var c = cs.GetById(e.ItemId); if (c != null) { e.ReceiverId = c.MemberId; } } }
public void GetLatest_ShouldReturnCorrectData() { var user = UserCreator.Create("test"); var list = new List <Topic>() { TopicCreator.Create(user), TopicCreator.Create(user), }; var topicRepo = DeletableEntityRepositoryMock.Get <Topic>(list); var service = new TopicService(topicRepo.Object); var result = service.GetLatest <TopicViewModel>(); Assert.Equal(2, result.Count); }
public ActionResult Authorise(DialoguePage page) { if (User.IsInRole(AppConstants.AdminRoleName)) { var viewModel = new AuthoriseViewModel { PageTitle = Lang("Authorise.PageTitle"), Members = MemberService.GetUnAuthorisedMembers(), Posts = PostService.GetAllPendingPosts(), Topics = TopicService.GetAllPendingTopics() }; return(View(PathHelper.GetThemeViewPath("Authorise"), viewModel)); } return(ErrorToHomePage(Lang("Errors.GenericMessage"))); }
public void GetById_ShouldReturnCorrectData() { var user = UserCreator.Create("test"); var topic = TopicCreator.Create(user); var topicRepo = DeletableEntityRepositoryMock.Get <Topic>(new List <Topic>() { topic }); var service = new TopicService(topicRepo.Object); var result = service.GetById <TopicViewModel>(topic.Id); Assert.NotNull(result); Assert.Equal(topic.Id, result.Id); }
private void HandleCreateTopic(TopicDto newTopic) { var topic = new Topic { Title = newTopic.Title, Description = newTopic.Description }; if (TopicService.AddTopic(topic)) { Log.Information($"Topic {topic.Title} created"); Communication.SendSuccess(_webSocket); } else { Communication.SendError(_webSocket, "Wrong username or password"); } }
public ActionResult Create(SearchProfileModel model) { if (model.IsValid) { try { string userName = this.Session["USERNAME"].ToString(); if (model.SearchProfileCheckBoxs.Where(x => x.Check).Count() == 0) { ModelState.AddModelError("", "Must choose a topic, at least!"); return(View(model)); } model.SearchProfileTopics = new List <TopicModel>(); model.Utilizador = new UserService().GetUser(userName); model.IsActive = true; foreach (TopicsViewModel item in model.SearchProfileCheckBoxs.Where(x => x.Check)) { model.SearchProfileTopics.Add(new TopicService().GetTopic(item.Id)); } service.InsertSearchProfile(model); return(RedirectToAction("Profile", "Account", new { id = userName })); } catch (Exception e) { ModelState.AddModelError("", e.Message); } } IList <ThemeModel> temas = new ThemeService().GetActiveThemes(); IList <TopicsViewModel> _topics = new List <TopicsViewModel>(); IList <TopicModel> topics = new TopicService().GetActiveTopics().OrderBy(x => x.Theme.Name).ToList(); topics.ToList().ForEach(x => _topics.Add(new TopicsViewModel { Name = x.Name, Check = false, Id = x.Id, ThemeId = x.Theme.Id, ThemeName = x.Theme.Name })); model = new SearchProfileModel { SearchProfileCheckBoxs = _topics }; ModelState.AddModelError("", model.Error); return(View(model)); }
public void BeforeMarkedAsSolutionAllow() { var topicRepository = Substitute.For <ITopicRepository>(); var postRepository = Substitute.For <IPostRepository>(); var membershipUserPointsService = Substitute.For <IMembershipUserPointsService>(); var settingsService = Substitute.For <ISettingsService>(); settingsService.GetSettings().Returns(new Settings { PointsAddedForSolution = 20 }); var topicService = new TopicService(membershipUserPointsService, settingsService, topicRepository, postRepository, _api, _topicNotificationService); var marker = new MembershipUser { UserName = "******", Id = Guid.NewGuid() }; var topic = new Topic { Name = "something", Tags = new List <TopicTag> { new TopicTag { Tag = "tagone" }, new TopicTag { Tag = "tagtwo" } }, User = marker }; var post = new Post { PostContent = "Test content" }; var solutionWriter = new MembershipUser { UserName = "******" }; EventManager.Instance.BeforeMarkedAsSolution += eventsService_BeforeMarkedAsSolutionAllow; topicService.SolveTopic(topic, post, marker, solutionWriter); Assert.IsTrue(topic.Solved); EventManager.Instance.BeforeMarkedAsSolution -= eventsService_BeforeMarkedAsSolutionAllow; }
protected void Page_Load(object sender, EventArgs e) { if (Session["userInfo"] == null) { string url = Request.Url.ToString(); Response.Redirect("/Login.aspx?url=" + url); } else { SectionService sectionService = new SectionService(); //板块信息列表 sectionList = sectionService.GetModelList(""); sectionId = Int32.Parse(Request["sectionId"]); TopicService topicService = new TopicService(); Topic topicInfo = new Topic(); if (IsPostBack) { sectionId = Int32.Parse(Request["sectionId"]); topicInfo.t_u_id = ((bbs.Model.User)Session["userInfo"]).id; topicInfo.t_s_id = Int32.Parse(Request.Form["topic.section.id"]); topicInfo.content = Request.Form["topic.content"]; topicInfo.title = Request.Form["topic.title"]; topicInfo.publishtime = DateTime.Now; topicInfo.good = "0"; topicInfo.top = "0"; int i = topicService.Add(topicInfo); //topic表的id值 if (i > 0) { topicInfo.id = i; //板块主键ID Session["topicInfo"] = topicInfo; Response.Redirect("/topic/TopicList.aspx?sectionId=" + topicInfo.t_s_id); } else { ErrorMsg = "发布失败,请重新发布!"; } } } }
public static void SendSlackSpamReport(string postBody, int topicId, string commentType, int memberId) { var ts = new TopicService(ApplicationContext.Current.DatabaseContext); using (var client = new WebClient()) { var topic = ts.GetById(topicId); var post = string.Format("Topic title: *{0}*\n\n Link to topic: http://our.umbraco.org{1}\n\n", topic.Title, topic.GetUrl()); post = post + string.Format("{0} text: {1}\n\n", commentType, postBody); post = post + string.Format("Go to member http://our.umbraco.org/member/{0}\n\n", memberId); var body = string.Format("The following forum post was marked as spam by the spam system, if this is incorrect make sure to mark it as ham.\n\n{0}", post); if (memberId != 0) { var member = ApplicationContext.Current.Services.MemberService.GetById(memberId); if (member != null) { var querystring = string.Format("api?ip={0}&email={1}&f=json", Utils.GetIpAddress(), HttpUtility.UrlEncode(member.Email)); body = body + string.Format("Check the StopForumSpam rating: http://api.stopforumspam.org/{0}", querystring); } } body = body.Replace("&", "&").Replace("<", "<").Replace(">", ">"); var values = new NameValueCollection { { "channel", ConfigurationManager.AppSettings["SlackChannel"] }, { "token", ConfigurationManager.AppSettings["SlackToken"] }, { "username", ConfigurationManager.AppSettings["SlackUsername"] }, { "icon_url", ConfigurationManager.AppSettings["SlackIconUrl"] }, { "text", body } }; try { var data = client.UploadValues("https://slack.com/api/chat.postMessage", "POST", values); var response = client.Encoding.GetString(data); } catch (Exception ex) { Log.Add(LogTypes.Error, new User(0), -1, string.Format("Posting update to Slack failed {0} {1}", ex.Message, ex.StackTrace)); } } }
public ActionResult TopicCategoryList(string MasterName = "Topic") { ViewBag.MasterName = MasterName; List <TopicCategory> allCategory = new List <Smoke.Entity.TopicCategory>(); List <TopicCategory> result = new List <Smoke.Entity.TopicCategory>(); if (!string.IsNullOrEmpty(MasterName) && !string.IsNullOrWhiteSpace(MasterName)) { allCategory = TopicService.QueryAllTopicCategoryListByMasterName(MasterName) ?? new List <Smoke.Entity.TopicCategory>(); if (allCategory == null) { allCategory = new List <TopicCategory>(); } result = allCategory.Where(p => p.CommonStatus == CommonStatus.Actived).ToList(); } return(View(result)); }
private void HandleTopicMessage(TopicMessageDto topicMessageDto) { if (!AuthService.IsLoggedIn(_user)) { Communication.SendError(_webSocket, "You must be logged in to send direct message"); Log.Warning("Not logged in user tried to send topic message"); return; } var topic = TopicService.GetTopics(topicMessageDto.TopicTitle); if (topic != null) { var newTopicMessage = new TopicMessage { CreatedAt = DateTimeOffset.Now, Text = topicMessageDto.Text, UserId = _user.UserId, TopicsId = topic.TopicsId }; var topicMessage = MessageService.SaveTopicMessage(newTopicMessage); if (topicMessage != null) { var userList = TopicService.GetUserForTopic(topic); foreach (var user in userList.Where(user => _connectedClient.ContainsKey(user))) { MessageService.SendTopicMessage( topicMessage, _connectedClient[user] ); } } else { Communication.SendError(_webSocket, $"Could not save message to topic {topicMessageDto.TopicTitle}"); Log.Error("Error while saving topic message"); } } else { Communication.SendError(_webSocket, $"Could not send message to topic {topicMessageDto.TopicTitle}"); Log.Warning($"Topic {topicMessageDto.TopicTitle} do not exist"); } }
/// <summary> /// 根据话题 ID 获取对应话题信息 /// </summary> /// <returns>数据表或 null</returns> protected DataTable GetDataOfTopic() { DataTable data = null; Int64 topicId = GetTopicId(); if (topicId > 0) { data = TopicService.GetTopicById(topicId); } else { throw new Exception("传递 URL 参数错误,话题 ID 格式不正确, 获取动态数据失败 -> GetDataOfTopic()"); } return(data); }
/// <summary> /// 展示所有的话题 /// </summary> protected void DisplayTopicList() { try { List <Topic> list = TopicService.GetAllTopic(); if (list != null) { LvTopicGroupCard.DataSource = list; LvTopicGroupCard.DataBind(); } } catch (Exception ex) { PromptInfo.Text = ex.Message; } }
public void AddPost_ValidTopicAlias_PostAdded(string topicAlias, string content) { var testDatabaseContext = DbContextFactory.Create(); var post = new NewPostDTO { Content = content, AuthorID = 1 }; var service = new TopicService(testDatabaseContext); service.AddPost(topicAlias, post); var topicData = service.GetTopicWithPosts(topicAlias); Assert.Contains(topicData.Posts, p => p.AuthorID == post.AuthorID && p.Content == post.Content); }
private void SetupTopicList() { TopicService topicService = new TopicService(Ioc.GetInstance <ITopicRepository>()); var topics = topicService.GetAllTopics().OrderByDescending(x => x.CreatedDate); foreach (var topic in topics) { ddlTopics.Items.Add(new ListItem(topic.TopicName, topic.TopicId.ToString())); } ListItem item = new ListItem("Please select a Topic", "-1"); ddlTopics.Items.Insert(0, item); item.Selected = true; }
/// <summary> /// 设置/取消管理员通知处理程序 /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void SetManagerNoticeEventModule_After(TopicMember sender, CommonEventArgs eventArgs) { if (eventArgs.EventOperationType != EventOperationType.Instance().SetTopicManager() && eventArgs.EventOperationType != EventOperationType.Instance().CancelTopicManager()) { return; } TopicService groupService = new TopicService(); TopicEntity entity = groupService.Get(sender.TopicId); if (entity == null) { return; } User senderUser = DIContainer.Resolve <IUserService>().GetFullUser(sender.UserId); if (senderUser == null) { return; } NoticeService noticeService = DIContainer.Resolve <NoticeService>(); Notice notice = Notice.New(); notice.UserId = sender.UserId; notice.ApplicationId = TopicConfig.Instance().ApplicationId; notice.TypeId = NoticeTypeIds.Instance().Hint(); notice.LeadingActorUserId = 0; notice.LeadingActor = string.Empty; notice.LeadingActorUrl = string.Empty; notice.RelativeObjectId = sender.TopicId; notice.RelativeObjectName = StringUtility.Trim(entity.TopicName, 64); notice.RelativeObjectUrl = SiteUrls.FullUrl(SiteUrls.Instance().TopicHome(entity.TopicKey)); if (eventArgs.EventOperationType == EventOperationType.Instance().SetTopicManager()) { notice.TemplateName = NoticeTemplateNames.Instance().SetTopicManager(); } else { notice.TemplateName = NoticeTemplateNames.Instance().CannelTopicManager(); } noticeService.Create(notice); }
/// <summary> /// 显示前 7 条话题 /// </summary> /// <param name="number">话题数</param> protected void DisplayHotTopic() { try { List <Topic> listTopic = TopicService.GetTopicByTop(10); // 显示前 6 条热门话题 if (listTopic != null) { ListHotTopic.DataSource = listTopic; ListHotTopic.DataBind(); } } catch (Exception ex) { PromptInfo.Text = ex.Message; } }
public void Put(int id, TopicSaveModel model) { var c = TopicService.GetById(id); if (c == null) { throw new Exception("Topic not found"); } if (c.MemberId != Members.GetCurrentMemberId()) { throw new Exception("You cannot edit this topic"); } c.Body = model.Body; TopicService.Save(c); }
protected object GetPosts(int topicId) { try { var result = TopicService.Get(topicId, x => x.Posts.Select(y => y.CreatedBy))?.Posts .Select(x => new { Id = x.Id, CreatedAt = x.CreatedAt, CreatedById = x.CreatedBy?.Id, CreatedByName = x.CreatedBy?.FullName, CreatedByProfileImage = x.CreatedBy?.ProfileImage64Url, Text = x.Text, CanEdit = SecurityContext.IsAuthenticated && x.CreatedBy == SecurityContext.User, CanDelete = SecurityContext.IsManager || SecurityContext.IsAdmin }).ToList(); var order = CustomConvert.ToInt32(this.sortByDropDownList.SelectedValue); switch (order) { case 1: result = result.OrderBy(x => x.CreatedAt).ToList(); break; case 2: result = result.OrderByDescending(x => x.CreatedByName).ToList(); break; case 3: result = result.OrderBy(x => x.CreatedByName).ToList(); break; default: result = result.OrderByDescending(x => x.CreatedAt).ToList(); break; } return(result.ToList <object>()); } catch (Exception exception) { //handle exception return(null); } }
public void Update_ShouldThrowExceptionWhenUserIsNotOwner() { var user = UserCreator.Create("test"); var visitor = UserCreator.Create("visitor"); var topic = TopicCreator.Create(user); var list = new List <Topic>() { topic }; var topicRepo = DeletableEntityRepositoryMock.Get <Topic>(list); var service = new TopicService(topicRepo.Object); Exception ex = Assert.Throws <AggregateException>(() => service.UpdateAsync(topic.Id, visitor.Id, string.Empty, string.Empty).Wait()); Assert.Contains("Topic does not exist", ex.Message); }
public void Should_not_duplicate_subscribers() { //Setup. const int userId = 10; const string topicKey = "News"; var topicService = new TopicService(); //Execute. topicService.Subscribe(userId, topicKey); topicService.Subscribe(userId, topicKey); var topic = topicService.Get(topicKey); //Verify. topic.Subscribers.Count.Should().Be(1); //Teardown. }
protected void Page_Load(object sender, EventArgs e) { int pageNumber = 1; if (!Int32.TryParse(Request["page"], out pageNumber)) { pageNumber = 1; } TopicService topicService = new TopicService(); //根据pageNumber查询出topicList topicList = topicService.FindAllTopic(pageNumber); //生成分页链接 pageCode = PageUtil.genPagination("/admin/TopiclistAdmin.aspx", topicService.GetRecordCount(""), pageNumber, topicService.pageSize, ""); }
public static void SendSlackSpamReport(string postBody, int topicId, string commentType, int memberId) { var ts = new TopicService(ApplicationContext.Current.DatabaseContext); var topic = ts.GetById(topicId); var post = string.Format("Topic title: *{0}*\n\n Link to topic: https://our.umbraco.com{1}\n\n", topic.Title, topic.GetUrl()); post = post + string.Format("{0} text: {1}\n\n", commentType, postBody); post = post + string.Format("Go to member https://our.umbraco.com/member/{0}\n\n", memberId); var body = string.Format("The following forum post was marked as spam by the spam system, if this is incorrect make sure to mark it as ham.\n\n{0}", post); body = body.Replace("&", "&").Replace("<", "<").Replace(">", ">"); var slack = new Slack(); slack.PostSlackMessage(body); }
public void TestGetAll() { IEnumerable <Topic> topics = new List <Topic>() { new Topic() { Id = "ads6safasf5f5asf4asf5", Name = "Thien nhien", ImgUrl = "https://storage.googleapis.com/trip-sharing-final-image-bucket/image-201907201619337977-3i9uvrioa3noa7c3.jpg" } }; mockTopicRepository.Setup(x => x.GetAll()).Returns(topics); var topicService = new TopicService(mockTopicRepository.Object); IEnumerable <Topic> list_topics = topicService.GetAll(); Assert.IsNotNull(list_topics); }
public async Task <IActionResult> Add([FromBody] AddTopicModel model) { if (model == null) { return(InvalidRequest()); } var result = await TopicService.Add(model); if (result.Success) { return(Success(result.Data)); } else { return(Error(result.ErrorMessage)); } }
public async Task <IActionResult> Query([FromQuery] QueryTopicModel model) { if (model == null) { return(InvalidRequest()); } var result = await TopicService.QueryNotTrash(model.PageIndex, model.PageSize, model.Status, model.Keywords); if (result.Success) { return(PagedData(result.Data, result.Total)); } else { return(Error(result.ErrorMessage)); } }
public ActionResult TopicCategoryInfo(int sysNo, string MasterName) { TopicCategory info = new TopicCategory(); if (sysNo > 0) { info = TopicService.LoadTopicCategory(sysNo) ?? new Smoke.Entity.TopicCategory(); if (info.SysNo <= 0) { info.MasterName = MasterName; } } else { info.MasterName = MasterName; } return(PartialView("~/Views/Topic/_TopicCategoryInfo.cshtml", info)); }
public void TopicAsSpam(int id) { var t = TopicService.GetById(id); if (Members.IsAdmin() == false) { throw new Exception("You cannot mark this topic as spam"); } if (t == null) { throw new Exception("Topic not found"); } t.IsSpam = true; TopicService.Save(t); }
public async Task <ServiceResult <ICollection <ReplyDetail> > > RepliesOfTopic(int topicid) { var topic = await TopicService.TopicFromId(topicid); if (topic.State != ServiceResultEnum.Exist) { return(Result <ICollection <ReplyDetail> >(topic.State, null, topic.Detail)); } ICollection <ReplyDetail> replyDetails = new List <ReplyDetail>(); foreach (var reply in topic.ExtraData.Replies) { var detailedReply = await TopicService.ReplyFromId(reply.Id); replyDetails.Add(detailedReply.ExtraData.ToDetail()); } return(Exist(replyDetails, "查询成功")); }