/// <summary> /// /// </summary> /// <param name="conversations"></param> /// <param name="userId"></param> /// <returns></returns> public static List <ConversationPreviewViewModel> ConversationsToConversationViewModels(List <Conversation> conversations, int userId, bool isShortcut = false) { using (RealTimeService rSercive = new RealTimeService(new CPMathHubModelContainer(), userId)) { List <ConversationPreviewViewModel> models = new List <ConversationPreviewViewModel>(); foreach (Conversation conversation in conversations) { ConversationPreviewViewModel model = new ConversationPreviewViewModel(); model.Id = conversation.Id; model.Avatar = rSercive.GetConversationAvatar(conversation); model.Name = rSercive.GetConversationName(conversation); if (!isShortcut) { model.LastMessage = conversation.Attendances .Where(m => m.UserId != userId) .FirstOrDefault() .Messages .OrderByDescending(m => m.CreatedDate) .FirstOrDefault(); if (model.LastMessage == default(Message)) { model.LastMessage = new Message(); model.LastMessage.Content = ""; } model.NewMessageNum = conversation.Attendances .Where(m => m.UserId != userId) .FirstOrDefault() .Messages.Count(m => m.Attendance.SeenDate <= m.CreatedDate); } model.IsOnline = true; models.Add(model); } return(models); } }
public async Task Handle(PaperInvestmentStartedIntegrationEvent @event) { try { var trace = await this._traceRepository.GetByTraceIdAsync(@event.TraceId); if (trace == null) { return; } var timeService = new RealTimeService(); trace.StartTracing(timeService); this._traceRepository.Update(trace); await _traceRepository.UnitOfWork .SaveChangesAsync(); } catch (Exception ex) { Console.WriteLine("Handle Integration Event: PaperInvestmentStartedIntegrationEvent."); Console.WriteLine("Result: Failure."); Console.WriteLine("Error Message: " + ex.Message); } }
public void RefreshActivityNum() { using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), Context.User.Identity.GetUserId <int>())) { rService.UpdateLastSeenNotification(); } }
public void RefreshMessageNum() { using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), Context.User.Identity.GetUserId <int>())) { rService.UpdateLastSeenMessage(); } }
public void GetNewMessageNum() { using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), Context.User.Identity.GetUserId <int>())) { Clients.Caller.notifyNewMessage(rService.CountNewMessageNotification()); } }
public bool Accept(int answerId) { bool result = qService.Accept(answerId); Answer answer = qService.GetAnswer(answerId); if (result && answer.UserId != _currentUserId) { //new Thread(() => //{ Question question = answer.Question; Notification notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = question.Title; notification.Seen = false; notification.Type = NotificationSettingEnum.AcceptedAnswer; notification.UserId = answer.UserId; notification.Link = Url.Action("Detail", "Question", new { id = question.Id }); cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } // } //).Start(); } return(result); }
public bool SetRoleUser(SetRoleViewModel model) { aService.ClearRolesUser(model.UserId); foreach (int id in model.RoleId) { Accessment assess = new Accessment(); assess.UserId = model.UserId; assess.RoleId = id; assess.AccessedDate = DateTime.Now; assess.ExpireDate = DateTime.Now.AddYears(1); aService.SetRoleUser(assess); } User user = cService.GetUser(model.UserId); Notification notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = string.Join(",", user.Assessments.Select(u => u.Role.Name)); notification.Seen = false; notification.Type = NotificationSettingEnum.Banned; notification.UserId = model.UserId; notification.Link = Url.Action("BannedPage", "Account"); cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } return(true); }
public ActionResult PostComment(int postId, string content = "") { Comment comment = new Comment(); comment.Content = content.Trim(); comment.UserId = Int32.Parse(User.Identity.GetUserId()); comment.CreatedDate = DateTime.Now; comment.LastEditedDate = comment.CreatedDate; comment.PostId = postId; comment.Status = PostStatusEnum.Active; comment.VoteDown = 0; comment.VoteUp = 0; cService.CommentPost(comment); comment.Author = cService.GetUser(comment.UserId); Post post = cService.GetPost(comment.PostId); if (post.UserId != _currentUserId) { Question question; if (post is Question) { question = qService.GetQuestion(comment.PostId); } else { question = qService.GetQuestion(((Answer)post).QuestionId); } //new Thread(() => //{ Notification notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = question.Title; notification.Seen = false; notification.Type = NotificationSettingEnum.UserComment; notification.UserId = question.UserId; notification.Link = Url.Action("Detail", "Question", new { id = question.Id }); cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } } //).Start(); //} List <Comment> comments = cService.GetComments(postId); ViewData["Status"] = PostStatusEnum.Active; ViewData["PostId"] = postId; return(PartialView("Partials/_CommentListPartialView", comments)); }
public void CheckOnline(int id) { using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), Context.User.Identity.GetUserId <int>())) { Conversation conversation = rService.GetConversation(id); List <int> users = conversation.Attendances.Select(c => c.User.Id).ToList(); int count = users.Count(u => _connections.TrackOnlineUser(u)); string cssClass = count > 1 ? "fa fa-circle mh-chat-status-icon-on conversation-status-" + id : "fa fa-circle mh-chat-status-icon-off conversation-status-" + id; Clients.Group(id + "").checkOnlineTrigger(id, cssClass); } }
public async Task Handle(RoundtripTargetPriceHitIntegrationEvent @event) { try { var trace = await this._traceRepository.GetByInvestmentId(@event.InvestmentId); if (trace == null) { return; } var idealPeriod = trace.IdealCandlePeriod; int minAmounts = 0; foreach (var strategy in trace.TradeStrategies) { if (strategy.GetIdealPeriod().Name == idealPeriod) { if (strategy.Strategy.MinimumAmountOfCandles > minAmounts) { minAmounts = strategy.Strategy.MinimumAmountOfCandles; } } } var period = CandlePeriod.FromName(idealPeriod); DateTime fromWithWarmingPeriod = (DateTime)trace.DateStarted; var oneCandleMinutes = CandlePeriodService.GetOneCandleMinutesByPeriod(period); var currentTime = new RealTimeService().GetCurrentDateTime(); var to = currentTime.AddMinutes(-oneCandleMinutes); fromWithWarmingPeriod = fromWithWarmingPeriod.AddMinutes(-oneCandleMinutes * (minAmounts + 1)); await this._trendAnalysisIntegrationEventService .PublishThroughEventBusAsync(new TargetPriceCandleDataRequestedIntegrationEvent( trace.TraceId, @event.RoundtripId, trace.Market.ExchangeId, trace.Market.BaseCurrency, trace.Market.QuoteCurrency, idealPeriod, @event.HitPrice, fromWithWarmingPeriod, to )); } catch (Exception ex) { Console.WriteLine("Handle Integration Event: RoundtripTargetPriceHitIntegrationEvent."); Console.WriteLine("Result: Failure."); Console.WriteLine("Error Message: " + ex.Message); } }
public ActionResult SendFriendRequest(int targetUserId, int friendId = 0, string tab = "allfriend", string returnPage = "UserProfile") { aService.SendFriendRequest(User.Identity.GetUserId <int>(), targetUserId); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), targetUserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(targetUserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewFriendRequest(rService.CountNewFriendRequestNotification()); } } return(RedirectToAction(returnPage, new { @userId = targetUserId, @tab = tab, @friendId = friendId })); }
public async Task Handle(InvestmentCandleDataRequestedIntegrationEvent @event) { try { var runningTraces = await _traceRepository.GetByStatus(TraceStatus.Started); foreach (var trace in runningTraces) { var market = new Market(@event.ExchangeId, @event.BaseCurrency.ToUpper(), @event.QuoteCurrency.ToUpper()); if (trace.Market.ExchangeId == @event.ExchangeId && trace.Market.BaseCurrency == @event.BaseCurrency && trace.Market.QuoteCurrency == @event.QuoteCurrency) { foreach (var strategy in trace.TradeStrategies) { if (strategy.GetIdealPeriod().Name == @event.CandlePeriod) { var minAmounts = strategy.Strategy.MinimumAmountOfCandles; var period = strategy.GetIdealPeriod(); DateTime fromWithWarmingPeriod = (DateTime)trace.DateStarted; var oneCandleMinutes = CandlePeriodService.GetOneCandleMinutesByPeriod(period); var currentTime = new RealTimeService().GetCurrentDateTime(); var to = currentTime.AddMinutes(-oneCandleMinutes); fromWithWarmingPeriod = fromWithWarmingPeriod.AddMinutes(-oneCandleMinutes * (minAmounts + 1)); await this._trendAnalysisIntegrationEventService .PublishThroughEventBusAsync(new TraceDataRequestedIntegrationEvent( trace.TraceId, strategy.StrategyId, trace.Market.ExchangeId, trace.Market.BaseCurrency, trace.Market.QuoteCurrency, strategy.GetIdealPeriod().Name, fromWithWarmingPeriod, to )); } } } } } catch (Exception ex) { Console.WriteLine("Handle Integration Event: CandleChartUpdatedIntegrationEvent."); Console.WriteLine("Result: Failure."); Console.WriteLine("Error Message: " + ex.Message); } }
public override Task OnDisconnected(bool stopCalled) { using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), Context.User.Identity.GetUserId <int>())) { _connections.Remove(Context.User.Identity.GetUserId <int>(), Context.ConnectionId); List <Conversation> conversations = rService.GetConversations(Context.User.Identity.GetUserId <int>()); foreach (Conversation conversation in conversations) { _connections.RemoveUserFromConversation(conversation.Id, Context.User.Identity.GetUserId <int>()); CheckOnline(conversation.Id); //Show all online users Clients.OthersInGroup(conversation.Id + "").getOnlineFriends(); } } return(base.OnDisconnected(stopCalled)); }
public ActionResult AnswerQuestion(int questionId, string content = "", AnswerEnum type = AnswerEnum.Answer) { Answer answer = new Answer(); answer.Content = content; answer.UserId = Int32.Parse(User.Identity.GetUserId()); answer.CreatedDate = DateTime.Now; answer.LastEditedDate = answer.CreatedDate; answer.QuestionId = questionId; answer.Type = type; answer.VoteDown = 0; answer.VoteUp = 0; answer.Accepted = false; answer.Status = PostStatusEnum.Active; qService.AnswerQuestion(answer); //new Thread(() => //{ Question question = qService.GetQuestion(questionId); if (question.UserId != _currentUserId) { Notification notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = question.Title; notification.Seen = false; notification.Type = answer.Type == AnswerEnum.Answer ? NotificationSettingEnum.UserAnswerQuestion : NotificationSettingEnum.UserHintQuestion; notification.UserId = question.UserId; notification.Link = Url.Action("Detail", "Question", new { id = question.Id }); cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } //} //).Start(); } return(RedirectToAction("Detail", new { id = questionId })); }
public void SendToConversation(string content, int conversationId) { //profileUrl, avatarUrl, username, content, time using (AccountService aService = new AccountService(new CPMathHubModelContainer(), Context.User.Identity.GetUserId <int>())) using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), Context.User.Identity.GetUserId <int>())) { User user = aService.GetUser(Context.User.Identity.GetUserId <int>()); string profileUrl = user.Id == Context.User.Identity.GetUserId <int>() ? "/Account/MyProfile" : "/Account/UserProfile?userId=" + user.Id; string avatarUrl = user.Avatar.Url.Replace("~", ""); string username = user.UserName; string time = DateTime.Now.ToShortTimeString(); Conversation conversation = rService.GetConversation(conversationId); Message message = new Message(); message.AttendanceId = conversation.Attendances.First(a => a.UserId == user.Id).Id; message.Content = content; message.CreatedDate = DateTime.Now; rService.AddMessage(message); Clients.Group(conversationId + "").addChatMessage(profileUrl, avatarUrl, username, content, time); Clients.OthersInGroup(conversationId + "").notifyNewMessage(rService.CountNewMessageNotification()); } }
public override Task OnReconnected() { using (AccountService aSercive = new AccountService(new CPMathHubModelContainer(), Context.User.Identity.GetUserId <int>())) using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), Context.User.Identity.GetUserId <int>())) { #region Notification Clients.Caller.notifyNewActivity(rService.CountNewActivityNotification()); Clients.Caller.notifyNewMessage(rService.CountNewMessageNotification()); Clients.Caller.notifyNewFriendRequest(rService.CountNewFriendRequestNotification()); #endregion #region Message User user = aSercive.GetUser(Context.User.Identity.GetUserId <int>()); if (user.Avatar == default(Image)) { user.Avatar.Url = "~/Content/img/user.jpg"; } if (!_connections.GetConnections(Context.User.Identity.GetUserId <int>()).Contains(Context.ConnectionId)) { _connections.Add(Context.User.Identity.GetUserId <int>(), Context.ConnectionId, user.Id + "", user.Avatar.Url); } List <Conversation> conversations = rService.GetConversations(user.Id); foreach (Conversation conversation in conversations) { _connections.AddUserToConversation(conversation.Id, Context.User.Identity.GetUserId <int>()); JoinConversation(conversation.Id + ""); CheckOnline(conversation.Id); Clients.OthersInGroup(conversation.Id + "").getOnlineFriends(); } //Show all online users Clients.Caller.showOnlineFriends(JsonConvert.SerializeObject(_connections.GetOnlineFriendConversationIds( Context.User.Identity.GetUserId <int>() ), Formatting.Indented)); #endregion } return(base.OnReconnected()); }
public void Setup() { IFileSystem fileSystem = new WindowsFileSystem(); IApplicationInfo applicationInfo = new ApplicationInfo(); ITimeService timeService = new RealTimeService(); ISignal serverStopSignal = new ManualResetSignal(false); IWebServerConfiguration configuration = new WebServerConfiguration(); IRazorCompiler razorCompiler = new InMemoryRazorCompiler(); IRazorViewRenderingEngine viewRenderingEngine = new RazorViewRenderingEngine(fileSystem, razorCompiler); IWebServerController webServerController = new WebServerController(serverStopSignal); IFileMimeTypesMap fileMimeTypesMap = new FileMimeTypesMap(); IFileCache fileCache = new FileCache(); List <IWebRequestRoute> routes = new List <IWebRequestRoute>(); string contentRootDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "sample-content"); ContentCommand contentCommand = new ContentCommand(contentRootDirectory, fileSystem, fileCache); routes.Add(new RegexWebRequestRoute("^content/(?<path>.+)$", HttpMethod.GET, contentCommand)); // ReSharper disable once CollectionNeverUpdated.Local List <IWebPolicy> policies = new List <IWebPolicy>(); const string ExternalUrl = "http://localhost"; const int Port = 12345; testServiceUrl = "{0}:{1}/".Fmt(ExternalUrl, Port); host = new TestHost( configuration, ExternalUrl, Port, null, fileSystem, applicationInfo, timeService, viewRenderingEngine, fileMimeTypesMap, webServerController, routes, policies); host.Start(); IWebConfiguration webConfiguration = new WebConfiguration("Syborg.Tests"); restClientFactory = new RestClientFactory(webConfiguration); }
public SyborgTestHttpModuleAppHost() { IFileSystem fileSystem = new WindowsFileSystem(); IApplicationInfo applicationInfo = new ApplicationInfo(); ITimeService timeService = new RealTimeService(); IRazorCompiler razorCompiler = new InMemoryRazorCompiler(); IRazorViewRenderingEngine viewRenderingEngine = new RazorViewRenderingEngine(fileSystem, razorCompiler); IWebServerConfiguration config = new WebServerConfiguration(); FileMimeTypesMap fileMimeTypesMap = new FileMimeTypesMap().RegisterStandardMimeTypes(); Initialize(config, fileSystem, applicationInfo, timeService, fileMimeTypesMap, viewRenderingEngine); IFileCache fileCache = new FileCache(); string webAppRootDir; if (!WebServerConfiguration.WebServerDevelopmentMode) { #if NCRUNCH webAppRootDir = @"D:\hg\ScalableMaps\WebApp\ScalableMaps\ScalableMaps.Web2"; #else webAppRootDir = ApplicationInfo.GetAppDirectoryPath(".."); #endif } else { webAppRootDir = ApplicationInfo.GetAppDirectoryPath(".."); } ContentCommand contentCommand = RegisterWebContent(webAppRootDir, fileCache, config); TestStreamCommand streamCommand = new TestStreamCommand(); AddRoute(new RegexWebRequestRoute("^Content/(?<path>.+)$", HttpMethod.GET, contentCommand)); AddRoute(new RegexWebRequestRoute("^stream/(?<path>.+)$", HttpMethod.GET, streamCommand)); AddPolicies(new IWebPolicy[] { new SecureResponseHeadersPolicy() }); }
public ActionResult BlockUser(BlockUserViewModel model) { BanAccount banAccount = new BanAccount(); banAccount.BannedDate = DateTime.Now; banAccount.Duration = model.Duration; banAccount.UnBanedDate = DateTime.Now.AddDays(banAccount.Duration); banAccount.BannedUser = cService.GetUser(model.BannedUserId); banAccount.BannedUser.Status = UserStatusEnum.Banned; banAccount.BanUser = cService.GetUser(User.Identity.GetUserId <int>()); banAccount.Description = model.Description; banAccount.BanReasons = aService.GetListBanReason(model.Reasons); aService.BlockUser(banAccount); Notification notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = banAccount.Duration + " ngày. Bắt đầu từ ngày " + banAccount.BannedDate.ToShortDateString(); notification.Seen = false; notification.Type = NotificationSettingEnum.Banned; notification.UserId = model.BannedUserId; notification.Link = Url.Action("BannedPage", "Account"); cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } return(PartialView("Partials/_HistoryBlockUserPartialView", banAccount.BannedUser)); }
public ActionResult PostComment(int postId, string content, string type = "comment") { PostStatusEnum status = PostStatusEnum.Active; if (type == "comment") { status = dService.GetDiscussion(postId).Status.Value; } else { status = cService.GetComment(postId, "Post").Post.Status.Value; } if (status != PostStatusEnum.Closed) { Comment comment = new Comment(); comment.Content = content; comment.UserId = User.Identity.GetUserId <int>(); comment.CreatedDate = DateTime.Now; comment.LastEditedDate = comment.CreatedDate; comment.PostId = postId; comment.Status = PostStatusEnum.Active; comment.VoteDown = 0; comment.VoteUp = 0; cService.CommentPost(comment); List <Comment> comments = cService.GetComments(postId); ICollection <CommentViewModel> commentsVM; Discussion discussion; Notification notification; switch (type) { //case "comment": // dService.IncludeUserForComments(comments); // dService.IncludeReplyForComments(comments); // commentsVM = comments.Select(Mapper.Map<Comment, CommentViewModel>).ToList(); // return PartialView("../CommonWidget/_CommentListPartialView", commentsVM); case "reply": dService.IncludeUserForComments(comments); commentsVM = comments.Select(Mapper.Map <Comment, CommentViewModel>).ToList(); Comment cm = cService.GetComment(comment.PostId); if (cm.UserId != _currentUserId) { discussion = dService.GetDiscussion(cm.PostId); notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = discussion.Title; notification.Seen = false; notification.Type = NotificationSettingEnum.UserComment; notification.UserId = cm.UserId; notification.Link = Url.Action("Detail", "Discussion", new { id = discussion.Id }); cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } } return(PartialView("../CommonWidget/_ReplyListPartialView", commentsVM)); default: dService.IncludeUserForComments(comments); dService.IncludeReplyForComments(comments); commentsVM = comments.Select(Mapper.Map <Comment, CommentViewModel>).ToList(); discussion = dService.GetDiscussion(comment.PostId); if (discussion.UserId != _currentUserId) { notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = discussion.Title; notification.Seen = false; notification.Type = NotificationSettingEnum.UserCommentMainPost; notification.UserId = discussion.UserId; notification.Link = Url.Action("Detail", "Discussion", new { id = discussion.Id }); cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } } return(PartialView("../CommonWidget/_CommentListPartialView", commentsVM)); } } return(null); }
public bool Like(int id) { //User user = cService.GetUser(User.Identity.GetUserId<int>()); Constant.Enum.LikeResult result = cService.Like(id, _currentUserId); Post post = cService.GetPost(id); if (post.UserId != _currentUserId && result != Constant.Enum.LikeResult.Fail && result != Constant.Enum.LikeResult.Unlike) { //new Thread(() => //{ NotificationSettingEnum notiType = default(NotificationSettingEnum); int userId = 0; int mainPostId = 0; string content = default(string); string mainPostType = default(string); string url = default(string); switch (result) { case Constant.Enum.LikeResult.Fail: break; case Constant.Enum.LikeResult.Article: notiType = NotificationSettingEnum.UserLikeMainPost; userId = post.UserId; content = ((Article)post).Title; mainPostId = id; url = Url.Action("Detail", "Blog", new { id = mainPostId }); break; case Constant.Enum.LikeResult.Discussion: notiType = NotificationSettingEnum.UserLikeMainPost; userId = post.UserId; content = ((Discussion)post).Title; mainPostId = id; url = Url.Action("Detail", "Discussion", new { id = mainPostId }); break; case Constant.Enum.LikeResult.Comment: notiType = NotificationSettingEnum.UserLikeComment; userId = post.UserId; content = ((MainPost)((Comment)post).Post).Title; mainPostId = ((MainPost)((Comment)post).Post).Id; mainPostType = EntityHelper.GetMainPostTypeNameOfNormalPost(post); url = Url.Action("Detail", mainPostType, new { id = mainPostId }); break; case Constant.Enum.LikeResult.Reply: notiType = NotificationSettingEnum.UserLikeComment; userId = post.UserId; content = ((MainPost)((Comment)((Comment)post).Post).Post).Title; mainPostId = ((MainPost)((Comment)((Comment)post).Post).Post).Id; mainPostType = EntityHelper.GetMainPostTypeNameOfNormalPost(post); url = Url.Action("Detail", mainPostType, new { id = mainPostId }); break; case Constant.Enum.LikeResult.Unlike: break; default: break; } //if (vote.Post.GetType().BaseType == typeof(Question)) //{ // question = qService.GetQuestion(vote.PostId); // notiType = NotificationSettingEnum.VotedQuestion; // userId = question.UserId; //} //else //{ // question = qService.GetQuestion(((Answer)vote.Post).QuestionId); // notiType = NotificationSettingEnum.VotedAnswer; // userId = vote.Post.UserId; //} Notification notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = content; notification.Seen = false; notification.Type = notiType; notification.UserId = userId; notification.Link = url; cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } //} //).Start(); } return(result != Constant.Enum.LikeResult.Fail); }
public ActionResult Create(QuestionCreateViewModel questionVM) { if (!ModelState.IsValid) { return(View("Views/QuestionCreateView", questionVM)); } Question question = new Question(); question = Mapper.Map <QuestionCreateViewModel, Question>(questionVM); question.CreatedDate = DateTime.Now; question.LastEditedDate = question.CreatedDate; question.UserId = User.Identity.GetUserId <int>(); question.Tags = cService.GetTags(questionVM.TagIds); question.Invitations = cService.GetInvitations(questionVM.InviteIds, User.Identity.GetUserId <int>()); question.Status = PostStatusEnum.Active; qService.InsertQuestion(question); EditedLog editedlog = new EditedLog(); editedlog.Content = question.Content; editedlog.CreatedDate = question.LastEditedDate; editedlog.PostId = question.Id; editedlog.UserId = question.UserId; editedlog.Title = question.Title; question.EditedContents.Add(editedlog); qService.EditQuestion(question); //Console.WriteLine(questionVM.Tags[0]); if (question.Id != 0) { //new Thread(() => //{ foreach (int inviteeId in question.Invitations.Select(i => i.InviteeId)) { Notification notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = question.Title; notification.Seen = false; notification.Type = NotificationSettingEnum.Invited; notification.UserId = inviteeId; notification.Link = Url.Action("Detail", "Question", new { id = question.Id }); cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } } // } //).Start(); return(RedirectToAction("Detail", new { id = question.Id })); } else { return(new HttpStatusCodeResult(500)); } }
public ActionResult Vote(int postId, VoteEnum type) { if (cService.GetPost(postId).UserId == _currentUserId) { return(Json(new { result = "", message = "Bạn không thể tự bình chọn cho chính mình." })); } Vote vote = new Vote(); vote.PostId = postId; vote.VotedDate = DateTime.Now; vote.Type = type; vote.UserId = _currentUserId; bool check = qService.Vote(vote); if (check && type == VoteEnum.VoteUp) { if (vote.Post.UserId != _currentUserId) { //new Thread(() => //{ Question question; NotificationSettingEnum notiType; int userId; if (vote.Post is Question) { question = qService.GetQuestion(vote.PostId); notiType = NotificationSettingEnum.VotedQuestion; userId = question.UserId; } else { question = qService.GetQuestion(((Answer)vote.Post).QuestionId); notiType = NotificationSettingEnum.VotedAnswer; userId = vote.Post.UserId; } Notification notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = question.Title; notification.Seen = false; notification.Type = notiType; notification.UserId = userId; notification.Link = Url.Action("Detail", "Question", new { id = question.Id }); cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } //} //).Start(); } return(Json(new { result = "up" })); } else if (check && type == VoteEnum.VoteDown) { return(Json(new { result = "down" })); } else { return(Json(new { result = "", message = "Bạn không thể bình chọn nhiều hơn 1 lần." })); } }
public bool BlockPost(int id) { Post post = aService.GetPost(id); post.Status = PostStatusEnum.Hidden; bool check = aService.UpdatePost(post); if (check) { Notification notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Seen = false; notification.UserId = post.UserId; #region Track Post Type if (post is MainPost) { notification.Type = NotificationSettingEnum.BlockedMainPost; notification.Content = ((MainPost)post).Title; if (post is Question) { notification.Link = Url.Action("Detail", "Question", new { id = id }); } else if (post is Discussion) { notification.Link = Url.Action("Detail", "Discussion", new { id = id }); } else { notification.Link = Url.Action("Detail", "Blog", new { id = id }); } } else if (post is Answer) { notification.Type = NotificationSettingEnum.BlockedAnswer; notification.Content = ((Answer)post).Question.Title; notification.Link = Url.Action("Detail", "Question", new { id = ((Answer)post).Question.Id }); } else if (post is Comment) { notification.Type = NotificationSettingEnum.BlockedComment; Comment comment = (Comment)post; if (comment.Post is Answer) { notification.Content = ((Answer)comment.Post).Question.Title; notification.Link = Url.Action("Detail", "Question", new { id = ((Answer)comment.Post).Question.Id }); } else if (comment.Post is Comment) { Comment c = (Comment)comment.Post; if (c.Post is Discussion) { notification.Content = ((Discussion)c.Post).Title; notification.Link = Url.Action("Detail", "Discussion", new { id = ((Discussion)c.Post).Id }); } else { notification.Content = ((Article)c.Post).Title; notification.Link = Url.Action("Detail", "Blog", new { id = ((Article)c.Post).Id }); } } else { if (comment.Post is Discussion) { notification.Content = ((Discussion)comment.Post).Title; notification.Link = Url.Action("Detail", "Discussion", new { id = ((Discussion)comment.Post).Id }); } else if (comment.Post is Question) { notification.Content = ((Question)comment.Post).Title; notification.Link = Url.Action("Detail", "Question", new { id = ((Question)comment.Post).Id }); } else { notification.Content = ((Article)comment.Post).Title; notification.Link = Url.Action("Detail", "Blog", new { id = ((Article)comment.Post).Id }); } } } #endregion cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } } return(check); }
public ActionResult Create(ArticleCreateViewModel model) { if (!ModelState.IsValid) { return(View("Views/BlogCreateView", model)); } Article article = new Article(); article = Mapper.Map <ArticleCreateViewModel, Article>(model); article.UserId = User.Identity.GetUserId <int>(); article.Tags = cService.GetTags(model.TagIds); article.Invitations = cService.GetInvitations(model.InviteIds, User.Identity.GetUserId <int>()); if (article.PublicDate.Value.Date == DateTime.Now.Date) { article.PublicDate = DateTime.Now; } bService.InsertArticle(article); EditedLog editedlog = new EditedLog(); editedlog.Content = article.Content; editedlog.CreatedDate = article.LastEditedDate; editedlog.PostId = article.Id; editedlog.UserId = article.UserId; editedlog.Title = article.Title; article.EditedContents.Add(editedlog); bService.UpdateArticle(article); //Console.WriteLine(questionVM.Tags[0]); if (article.Id != 0) { //new Thread(() => //{ foreach (int inviteeId in article.Invitations.Select(i => i.InviteeId)) { Notification notification = new Notification(); notification.AuthorId = _currentUserId; notification.CreatedDate = DateTime.Now; notification.Content = article.Title; notification.Seen = false; notification.Type = NotificationSettingEnum.Invited; notification.UserId = inviteeId; notification.Link = Url.Action("Detail", "Article", new { id = article.Id }); cService.AddNotification(notification); using (RealTimeService rService = new RealTimeService(new CPMathHubModelContainer(), notification.UserId)) { IEnumerable <string> connectionIds = RealTimeHub.Connections.GetConnections(notification.UserId); foreach (string conId in connectionIds) { _hub.Clients.Client(conId).notifyNewActivity(rService.CountNewActivityNotification()); } } } // } //).Start(); return(RedirectToAction("Detail", new { id = article.Id })); } else { return(new HttpStatusCodeResult(500)); } }