protected override BaseResponse <EmptyViewModel> ExecuteCore(CreateDiscussionMessageRequestViewModel request) { var validationResult = ValidateProjectAccess(projectService, request.ProjectId); if (!validationResult.Response.Success) { return(validationResult.Response); } var project = validationResult.Project; var discussionMessage = new DiscussionMessage { CreatedBy = CurrentApplicationUser, CreatedOn = DateTime.UtcNow, Project = project, Content = request.Content }; repository.Create(discussionMessage, CurrentApplicationUser); repository.SaveChanges(); discussionHub.Clients.Group(project.Id.ToString()) .SendAsync("NewDiscussionMessage", discussionMessage.Id.ToString()); return(GetGenericResponseSuccess(null)); }
public static bool Update(DiscussionMessage message) { bool res = false; try { string query = "MessageUpdateById"; using (SqlConnection cnn = new SqlConnection(Configurations.ConnectionString)) { using (SqlCommand cmd = new SqlCommand(query, cnn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MessageId", message.Id)); cmd.Parameters.Add(new SqlParameter("@MessageType", message.Type)); cmd.Parameters.Add(new SqlParameter("@UpdateTime", DateTime.UtcNow)); cmd.Parameters.Add(new SqlParameter("@UserId", message.UserId)); cmd.Parameters.Add(new SqlParameter("@UserIp", message.UserIp)); cmd.Parameters.Add(new SqlParameter("@MessageSubject", message.Subject)); cmd.Parameters.Add(new SqlParameter("@MessageBody", message.Body)); foreach (SqlParameter Parameter in cmd.Parameters) { if (Parameter.Value == null) { Parameter.Value = DBNull.Value; } } cnn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader != null && reader.HasRows) { if (reader.Read()) { message.Id = Repository.Utils.Convert.ToInt32(reader["MessageId"]); if (message.Id > 0) { res = true; } // If MessageId <= 0 ERROR } } cnn.Close(); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("Exception:{0}", ex.ToString())); } return(res); }
public static bool LoadMessageById(DiscussionMessage message) { bool res = false; try { string query = "MessageGetById"; using (SqlConnection cnn = new SqlConnection(Configurations.ConnectionString)) { using (SqlCommand cmd = new SqlCommand(query, cnn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MessageId", message.Id)); cnn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader != null && reader.HasRows) { if (reader.Read()) { // load message message.IsVisible = Repository.Utils.Convert.ToBool(reader["IsVisible"]); message.IsAbuse = Repository.Utils.Convert.ToInt16(reader["IsAbuse"]); message.Type = (Repository.Memory.Forums.MessageTypes)Repository.Utils.Convert.ToInt16(reader["MessageType"]); message.InsertTime = Repository.Utils.Convert.ToDateTime(reader["InsertTime"]); message.UpdateTime = Repository.Utils.Convert.ToDateTime(reader["UpdateTime"]); message.UserId = Repository.Utils.Convert.ToInt64(reader["UserId"]); //message.UserName = Repository.Utils.Convert.ToString(reader["UserName"]); message.UserIp = Repository.Utils.Convert.ToString(reader["UserIp"]); message.Subject = Repository.Utils.Convert.ToString(reader["MessageSubject"]); message.Body = Repository.Utils.Convert.ToString(reader["MessageBody"]); message.Discussion.Id = Repository.Utils.Convert.ToInt32(reader["DiscussionId"]); message.Parent.Id = Repository.Utils.Convert.ToInt32(reader["ParentId"]); message.IsParent = (message.Discussion.Id == message.Id); } } cnn.Close(); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("Exception:{0}", ex.ToString())); } return(res); }
public DiscussionMessage CreateMessage(Int16?forumGroup, Int64?forum, Int32 discussion, Int32 message, bool isParent) { DiscussionMessage msg = new DiscussionMessage(); msg.Id = message; msg.IsParent = isParent; msg.Discussion = new Discussion(discussion, new Forum()); msg.Discussion.Forum.UrlName = string.Empty; msg.Discussion.Forum.PageId = forum.Value; msg.Discussion.Forum.ForumId = forumGroup.Value; msg.Parent = new DiscussionMessage(); return(msg); }
/** * 自定义api地址 * */ //private static readonly String api = "http://api.cn.ronghub.com"; static void Main(String[] args) { RongCloud rongCloud = RongCloud.GetInstance(appKey, appSecret); //自定义 api 地址方式 //RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api); Private Private = rongCloud.message.msgPrivate; // TODO MsgSystem system = rongCloud.message.system; methods.messages.group.Group group = rongCloud.message.group; Chatroom chatroom = rongCloud.message.chatroom; Discussion discussion = rongCloud.message.discussion; History history = rongCloud.message.history; /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/system.html#send * * 发送系统消息 * */ String[] targetIds = { "uPj70HUrRSUk-ixtt7iIGc" }; SystemMessage systemMessage = new SystemMessage() { SenderId = "Vu-oC0_LQ6kgPqltm_zYtI", TargetId = targetIds, ObjectName = txtMessage.GetType(), Content = txtMessage, PushContent = ".NET this is a push system", PushData = "{'pushData':'.NET hello'}", IsPersisted = 0, IsCounted = 0, ContentAvailable = 0 }; ResponseResult result = rongCloud.message.system.Send(systemMessage); Console.WriteLine("send system message: " + result.ToString()); /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/system.html#sendTemplate * * 发送系统模板消息方法 * */ StreamReader file = null; try { file = System.IO.File.OpenText("jsonsource/message/TemplateMessage.json"); TemplateMessage template = JsonConvert.DeserializeObject <TemplateMessage>(file.ReadToEnd()); ResponseResult messagePublishTemplateResult = system.SendTemplate(template); Console.WriteLine("send systemTemplate message: " + messagePublishTemplateResult.ToString()); } catch (Exception e) { Console.WriteLine(e.Message); } finally { file.Close(); } /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/system.html#sendTemplate * * 发送系统模板消息方法 * */ BroadcastMessage message = new BroadcastMessage() { SenderId = "Vu-oC0_LQ6kgPqltm_zYtI", ObjectName = txtMessage.GetType(), Content = txtMessage, Os = "Android" }; ResponseResult broadcastResult = rongCloud.message.system.Broadcast(message); Console.WriteLine("send broadcast: " + broadcastResult.ToString()); /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/private.html#send * * 发送单聊消息 * */ PrivateMessage privateMessage = new PrivateMessage() { SenderId = "Vu-oC0_LQ6kgPqltm_zYtI", TargetId = targetIds, ObjectName = txtMessage.GetType(), Content = txtMessage, PushContent = ".NET this is a push private", PushData = "{\"pushData\":\".NET hello\"}", VerifyBlacklist = 0, IsPersisted = 0, IsCounted = 0, ContentAvailable = 0, IsIncludeSender = 0 }; ResponseResult privateResult = Private.Send(privateMessage); Console.WriteLine("send private message: " + privateResult.ToString()); /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/private.html#sendTemplate * * 发送单聊模板消息方法 */ try { file = System.IO.File.OpenText("jsonsource/message/TemplateMessage.json"); TemplateMessage template = JsonConvert.DeserializeObject <TemplateMessage>(file.ReadToEnd()); ResponseResult messagePublishTemplateResult = Private.SendTemplate(template); Console.WriteLine("send privateTemplate message: " + messagePublishTemplateResult.ToString()); } catch (Exception e) { Console.WriteLine(e.Message); } finally { file.Close(); } /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/private.html#recall * * 撤回单聊消息 * */ RecallMessage recallMessage = new RecallMessage() { SenderId = "0fn8TiuHTUgjrZ1QJ8o50M", TargetId = "qHPBAoUS6DmEBtJH72RSDi", UId = "5H6P-CGC6-44QR-VB3R", SentTime = "1519444243981" }; ResponseResult recallPrivateResult = (ResponseResult)Private.Recall(recallMessage); Console.WriteLine("recall private: " + recallPrivateResult.ToString()); /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/group.html#send * * 群组消息 * */ GroupMessage groupMessage = new GroupMessage() { SenderId = "Vu-oC0_LQ6kgPqltm_zYtI", TargetId = new string[] { "STRe0shISpQlSOBvek1FfU" }, ObjectName = txtMessage.GetType(), Content = txtMessage, PushContent = "this is a push", PushData = "{\"pushData\":\"hello\"}", IsPersisted = 0, IsCounted = 0, IsIncludeSender = 0, ContentAvailable = 0 }; ResponseResult groupResult = group.Send(groupMessage); Console.WriteLine("send Group message: " + groupResult.ToString()); /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/group.html#recall * * 群组撤回消息 * */ recallMessage = new RecallMessage() { SenderId = "sea9901", TargetId = "markoiwm", UId = "5GSB-RPM1-KP8H-9JHF", SentTime = "1507778882124" }; ResponseResult recallMessageResult = (ResponseResult)group.Recall(recallMessage); Console.WriteLine("send recall group message: " + recallMessageResult.ToString()); /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/group.html#sendMention * * 群组@消息 * */ //要@的人 String[] mentionIds = { "uPj70HUrRSUk-ixtt7iIGc", "Vu-oC0_LQ6kgPqltm_zYtI" }; MentionedInfo mentionedInfo = new MentionedInfo(1, mentionIds, ""); //@内容 MentionMessageContent content = new MentionMessageContent(txtMessage, mentionedInfo); MentionMessage mentionMessage = new MentionMessage() { SenderId = "Vu-oC0_LQ6kgPqltm_zYtI", TargetId = new string[] { "STRe0shISpQlSOBvek1FfU" }, ObjectName = txtMessage.GetType(), Content = content, PushContent = "this is a push", PushData = "{\"pushData\":\"hello\"}", IsPersisted = 0, IsCounted = 0, IsIncludeSender = 0, ContentAvailable = 0 }; ResponseResult mentionResult = rongCloud.message.group.SendMention(mentionMessage); Console.WriteLine("group mention result: " + mentionResult.ToString()); /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/discussion.html#send * * 发送讨论组消息 * */ String[] discussionIds = { "lijhGk87", "lijhGk88" }; DiscussionMessage discussionMessage = new DiscussionMessage() { SenderId = "JuikH78ko", TargetId = discussionIds, ObjectName = txtMessage.GetType(), Content = txtMessage, PushContent = "this is a push", PushData = "{\"pushData\":\"hello\"}", IsPersisted = 0, IsCounted = 0, IsIncludeSender = 0, ContentAvailable = 0 }; ResponseResult discussionResult = discussion.Send(discussionMessage); Console.WriteLine("send discussion message: " + discussionResult.ToString()); /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/discussion.html#recall * * 撤回讨论组消息 * */ recallMessage = new RecallMessage() { SenderId = "sea9901", TargetId = "IXQhMs3ny", UId = "5GSB-RPM1-KP8H-9JHF", SentTime = "1519444243981" }; ResponseResult recallDiscussionResult = (ResponseResult)discussion.Recall(recallMessage); Console.WriteLine("recall discussion message: " + recallDiscussionResult.ToString()); /** * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/chatroom.html#send * * 聊天室消息 * */ String[] chatroomIds = { "OIBbeKlkx" }; CustomTxtMessage ctm = new CustomTxtMessage("hello world"); ChatroomMessage chatroomMessage = new ChatroomMessage() { SenderId = "aP9uvganV", TargetId = chatroomIds, Content = ctm, ObjectName = ctm.GetType() }; ResponseResult chatroomResult = chatroom.Send(chatroomMessage); Console.WriteLine("send chatroom message: " + chatroomResult.ToString()); /** * * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/chatroom.html#broadcast * * 聊天室广播消息 * * 此功能需开通专有服务: http://www.rongcloud.cn/deployment#overseas-cloud * * */ chatroomMessage = new ChatroomMessage() { SenderId = "aP9uvganV", Content = txtMessage, ObjectName = txtMessage.GetType() }; ResponseResult chatroomBroadcastresult = chatroom.Broadcast(chatroomMessage); Console.WriteLine("send chatroom broadcast message: " + chatroomBroadcastresult.ToString()); /** * * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/history.html#get * * 获取历史消息日志文件 * * */ HistoryMessageResult historyMessageResult = history.Get("2019011711"); Console.WriteLine("get history message: " + historyMessageResult.ToString()); /** * * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/history.html#get * * 删除历史消息日志文件 * * */ ResponseResult removeHistoryMessageResult = history.Remove("2018030210"); Console.WriteLine("remove history message: " + removeHistoryMessageResult.ToString()); Console.ReadLine(); }
private static string ForumMessage(DiscussionMessage message) { StringBuilder ret = new StringBuilder(); ret.AppendFormat("<div class=\"forum_message\" style=\"margin-{0}: {1}px;\">", UiResources.UiTexts.float_left, message.IsParent ? 2 : 20); ret.AppendFormat( "<a name=\"{0}\" class=\"hidden\"></a>" + "<div class=\"forum_message_subject_normal\" id=\"msg_hd_{0}\" " + "onclick=\"return ToggleForumMessage('msg_bd_{0}');\" " + ">" + "<img alt=\"{5} message\" src=\"/Content/Forums/Images/{5}.gif\" style=\"float:{6};\" /> " + "<span class=\"forum_message_caption\" style=\"float:{6};\">{1}</span>" + "<span class=\"forum_message_time\" style=\"float:{2}; text-align:{2};\">{3}</span>" + "<span class=\"forum_message_user\" style=\"float:{2}; text-align:{2};\">{4}</span>" + "</div>", message.Id, message.Subject, UiResources.UiTexts.float_right, DomainModel.Tools.DateTime.Convert.ToCulture( message.UpdateTime, WebUi.Models.AppCulture.CurrentCulture), message.UserName, message.Type.ToString(), UiResources.UiTexts.float_left ); ret.AppendFormat("<div class=\"forum_message_body\" style=\"display: none;\" id=\"msg_bd_{0}\">", message.Id); ret.AppendFormat("<span>{0}</span>", message.Body); ret.AppendFormat(" <div class=\"message_control_panel\">"); if (Models.Security.CurrentUser == null || Models.Security.CurrentUser.Id <= 0) { ret.AppendFormat("<span>{0}</span>", UiResources.UiTexts.login_to_manage_comments); } else { ret.AppendFormat("<ul>"); ret.AppendFormat("<li><a href=\"/Discussions/Reply/{0}/{1}/{2}/{3}?returnUrl={5}\">{4}</a></li>", message.Discussion.Forum.ForumId, message.Discussion.Forum.PageId, message.Discussion.Id, message.Id, UiResources.UiTexts.reply, message.Discussion.Forum.ForumPageUrl); if (Models.Security.CurrentUser.Id == message.UserId.Value) { ret.AppendFormat("<li><a href=\"/Discussions/Edit/{0}/{1}/{2}/{3}?returnUrl={5}\">{4}</a></li>", message.Discussion.Forum.ForumId, message.Discussion.Forum.PageId, message.Discussion.Id, message.Id, UiResources.UiTexts.edit_message, message.Discussion.Forum.ForumPageUrl); ret.AppendFormat("<li><a href=\"/Discussions/Delete/{0}/{1}/{2}/{3}?returnUrl={5}\">{4}</a></li>", message.Discussion.Forum.ForumId, message.Discussion.Forum.PageId, message.Discussion.Id, message.Id, UiResources.UiTexts.delete_message, message.Discussion.Forum.ForumPageUrl); } else { ret.AppendFormat("<li><a href=\"/Discussions/Report/{0}/{1}/{2}/{3}?returnUrl={5}\" onclick=\"return ConfirmMessageReport();\">{4}</a></li>", message.Discussion.Forum.ForumId, message.Discussion.Forum.PageId, message.Discussion.Id, message.Id, UiResources.UiTexts.report_abuse, message.Discussion.Forum.ForumPageUrl); } ret.AppendFormat("</ul>"); } ret.AppendFormat(" </div>"); ret.AppendFormat("</div>"); foreach (DiscussionMessage msg in message.Replies) { ret.Append(ForumMessage(msg)); } ret.Append("</div>"); return(ret.ToString()); }
/// <summary> /// 取得留言內頁資訊 /// </summary> /// <param name="token">使用者代碼</param> /// <param name="outerKey">留言/回覆代碼</param> /// <param name="maxResult">顯示回覆列表筆數 - 預設10筆</param> /// <returns></returns> public DiscussionCommentDetail GetCommentDetail(Guid token, string outerKey, int?maxResult = 10) { var db = _uow.DbContext; var result = new DiscussionCommentDetail(); result.Replys = new List <DiscussionMessage>(); discussionLikeService = new DiscussionFuncLike(); var msgEventId = Service.Utility.OuterKeyHelper.CheckOuterKey(outerKey); //用於取得msgEventId的留言資訊 var msgInfo = db.ActModuleMessage.FirstOrDefault(t => t.OuterKey == msgEventId); //如果是回覆則取得該回覆的留言資訊 | 若是留言則直接存取留言資訊 var commentInfo = (db.ActModuleMessage.FirstOrDefault(t => t.OuterKey == msgEventId && t.Parent != null)) != null?db.ActModuleMessage.Find(db.ActModuleMessage.FirstOrDefault(t => t.OuterKey == msgEventId).Parent) : msgInfo; if (commentInfo != null) { var commentCreatorInfo = new MemberService().UserIdToAccount(commentInfo.CreateUser.Value); // var commentCreatorInfo = new Service.MemberService().GetPhotoMember(db.Members.Find(commentInfo.CreateUser).Account); result.Comment = new DiscussionMessage() { CreateTime = commentInfo.Created.Utc.Value.ToLocalTime(), CreatorAccount = commentCreatorInfo.Account, CreatorName = commentCreatorInfo.Name, CreatorPhoto = commentCreatorInfo.Photo, Message = commentInfo.Content, EventId = commentInfo.OuterKey, Parent = commentInfo.Parent }; var commentPhoto = GetDiscussionMessageFileByMessageId(commentInfo.Id); result.Comment.Photos = commentPhoto != null ? commentPhoto : new List <FileStorageViewModel>(); var commentLikeArray = discussionLikeService.GetLikeArrayByEventId(commentInfo.OuterKey); result.Comment.LikeArray = commentLikeArray != null?commentLikeArray.ToArray() : null; var replys = db.ActModuleMessage.Where(t => t.Parent == commentInfo.Id).OrderByDescending(t => t.Created.Utc).ToList(); result.Comment.ReplyCount = replys.FirstOrDefault() != null?replys.Count() : 0; result.CommentCount = replys.FirstOrDefault() != null?replys.Count() : 0; //判斷現在是否要查留言內頁的資訊 if (msgInfo.Parent.HasValue) { //篩選該msg以後的留言[包含] replys = replys.Where(t => t.Id >= msgInfo.Id).ToList(); replys.Reverse(); result.OlderCount = result.CommentCount - replys.Count(); replys = replys.Take(maxResult.Value).ToList(); } else { result.OlderCount = replys.Count() > maxResult.Value ? replys.Count() - maxResult.Value : 0; replys = replys.Take(maxResult.Value).ToList(); replys.Reverse(); } foreach (var reply in replys) { var replyCreatorInfo = new MemberService().UserIdToAccount(reply.CreateUser.Value); // var replyCreatorInfo = new Service.MemberService().GetPhotoMember(db.Members.Find(reply.CreateUser).Account); var tempReply = new DiscussionMessage() { CreateTime = reply.Created.Utc.Value.ToLocalTime(), CreatorAccount = replyCreatorInfo.Account, CreatorName = replyCreatorInfo.Name, CreatorPhoto = replyCreatorInfo.Photo, Message = reply.Content, EventId = reply.OuterKey, Parent = reply.Parent }; var replyPhoto = GetDiscussionMessageFileByMessageId(reply.Id); tempReply.Photos = replyPhoto != null ? replyPhoto : new List <FileStorageViewModel>(); var likeArray = discussionLikeService.GetLikeArrayByEventId(reply.OuterKey); tempReply.LikeArray = likeArray != null?likeArray.ToArray() : null; if (reply.TagActModuleMessageId != null && reply.TagActModuleMessageId != 0) { var replyInfo = db.ActModuleMessage.Find(reply.TagActModuleMessageId); if (replyInfo != null) { var replyMemberInfo = db.Members.Find(replyInfo.CreateUser); tempReply.ReplyOuterKey = reply.OuterKey.ToString(); tempReply.ReplyName = replyMemberInfo.Name; } } tempReply.ReplyCount = db.ActModuleMessage.FirstOrDefault(t => t.Parent == reply.Id) != null?db.ActModuleMessage.Where(t => t.Parent == reply.Id).Count() : 0; result.Replys.Add(tempReply); } } return(result); }
/// <summary> /// 取得主題討論底下的留言列表 /// </summary> /// <param name="eventId"></param> /// <param name="msgEventId"></param> /// <param name="isLoadNewer"></param> /// <returns></returns> public List <DiscussionMessage> GetDiscussionMsgList(Guid eventId, Guid msgEventId, bool?isLoadNewer = true) { var result = new List <DiscussionMessage>(); var db = _uow.DbContext; //預設查詢主題討論的留言列表 var sqlData = from amm in db.ActModuleMessage join a in db.Activitys on amm.ActivityId equals a.Id where a.OuterKey == eventId orderby amm.Created.Utc select amm; if (sqlData.FirstOrDefault() != null) { discussionLikeService = new DiscussionFuncLike(); //查出該msg的資訊 var setMsgInfo = (sqlData.FirstOrDefault(t => t.OuterKey == msgEventId && t.Parent != null)) != null?sqlData.FirstOrDefault(t => t.Id == (sqlData.FirstOrDefault(tt => tt.OuterKey == msgEventId)).Parent) : sqlData.FirstOrDefault(t => t.OuterKey == msgEventId); if (setMsgInfo != null) { sqlData = sqlData.Where(t => t.Parent == null || t.Parent == 0); //查新的 if (isLoadNewer.Value) { //篩選該msg以後的留言[包含] sqlData = sqlData.Where(t => t.Id >= setMsgInfo.Id); } //查舊的 else { sqlData = sqlData.Where(t => t.Id < setMsgInfo.Id); } } //塞資料 foreach (var msg in sqlData) { //取得留言者資訊 var memberInfo = new MemberService().UserIdToAccount(msg.CreateUser.Value); // var memberInfo = new iThink.Service.Service.MemberService().GetPhotoMember(db.Members.Find(msg.CreateUser.Value).Account); //取得留言檔案資訊 var msgFile = GetDiscussionMessageFileByMessageId(msg.Id); var tempMsg = new DiscussionMessage(); tempMsg.Id = msg.Id; tempMsg.CreateTime = msg.Created.Local.Value; tempMsg.LikeArray = discussionLikeService.GetLikeArrayByEventId(msg.OuterKey).ToArray(); if (msgFile != null) { tempMsg.Photos = msgFile; } else { tempMsg.Photos = new List <FileStorageViewModel>(); } tempMsg.Message = msg.Content; tempMsg.EventId = msg.OuterKey; tempMsg.Parent = msg.Parent; if (memberInfo != null) { tempMsg.CreatorAccount = memberInfo.Account; tempMsg.CreatorName = memberInfo.Name; tempMsg.CreatorPhoto = memberInfo.Photo; } //是否有tag某篇留言 if (msg.TagActModuleMessageId != null && msg.TagActModuleMessageId != 0) { var replyInfo = db.ActModuleMessage.Find(msg.TagActModuleMessageId); if (replyInfo != null) { var replyMemberInfo = db.Members.Find(replyInfo.CreateUser); tempMsg.ReplyOuterKey = replyInfo.OuterKey.ToString(); tempMsg.ReplyName = replyMemberInfo.Name; } } //查詢回覆數量 tempMsg.ReplyCount = db.ActModuleMessage.FirstOrDefault(t => t.Parent == msg.Id) != null?db.ActModuleMessage.Where(t => t.Parent == msg.Id).Count() : 0; result.Add(tempMsg); } } return(result); }
private static bool LoadDiscussions(Forum forum, int startRow, int endRow) { bool res = false; try { forum.Clear(); string query = "MessagesList"; using (SqlConnection cnn = new SqlConnection(Configurations.ConnectionString)) { using (SqlCommand cmd = new SqlCommand(query, cnn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@ForumId", SqlDbType.SmallInt, 2, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Default, forum.ForumId)); cmd.Parameters.Add(new SqlParameter("@PageId", forum.PageId)); cmd.Parameters.Add(new SqlParameter("@StartRow", startRow)); cmd.Parameters.Add(new SqlParameter("@EndRow", endRow)); foreach (SqlParameter Parameter in cmd.Parameters) { if (Parameter.Value == null) { Parameter.Value = DBNull.Value; } } cnn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader != null && reader.HasRows) { // Every message belongs to a discussion in a forum Discussion discussion = null; DiscussionMessage message = null; DiscussionMessage parent = null; Int32 parentId = 0; Int32 discussionId = 0; Int32 messageId = 0; while (reader.Read()) { message = null; discussionId = Repository.Utils.Convert.ToInt32(reader["DiscussionId"]); parentId = Repository.Utils.Convert.ToInt32(reader["ParentId"]); messageId = Repository.Utils.Convert.ToInt32(reader["MessageId"]); // Update current discussion if (discussion != null) { // This message is in current discussion if (discussionId == discussion.Id) { // Do nothing. Current discussion is OK! } else { // This is a message inside a discussion // Or a root (a discussion) record so // Let's find discussion by it's id discussion = forum.FindDiscussion(discussionId); } } // If discussion not found, create and add it if (discussion == null) { discussion = new Discussion(discussionId, forum); forum.Add(discussion); if (messageId == discussionId) { // If this record is a discussion message message = discussion; } else { // This is a message inside a discussion that does not exist?! // An empty discussion created. Maybe filled later on // Let next step handle message related stuff } } // This is a message with an unknown parent inside a known discussion if (parentId <= 0 && message == null) { // Add it to the root of the discussion message = new DiscussionMessage(); discussion.Replies.Add(message); message.Parent = discussion; } else if (parentId > 0)// A new message { message = new DiscussionMessage(); // Find parent if (parent == null || parent.Id != parentId) { parent = discussion.FindMessage(parentId); } // Parent not found? Add it to the root of discussion if (parent == null) { parent = discussion; } parent.Replies.Add(message); message.Parent = parent; } message.Discussion = discussion; // At this point message must be at the right position // Try load it's data. // load message message.Id = messageId; message.IsVisible = Repository.Utils.Convert.ToBool(reader["IsVisible"]); message.IsAbuse = Repository.Utils.Convert.ToInt16(reader["IsAbuse"]); message.Type = (Repository.Memory.Forums.MessageTypes)Repository.Utils.Convert.ToInt16(reader["MessageType"]); message.InsertTime = Repository.Utils.Convert.ToDateTime(reader["InsertTime"]); message.UpdateTime = Repository.Utils.Convert.ToDateTime(reader["UpdateTime"]); message.UserId = Repository.Utils.Convert.ToInt64(reader["UserId"]); message.UserName = Repository.Utils.Convert.ToString(reader["UserName"]); message.UserIp = Repository.Utils.Convert.ToString(reader["UserIp"]); message.Subject = Repository.Utils.Convert.ToString(reader["MessageSubject"]); message.Body = Repository.Utils.Convert.ToString(reader["MessageBody"]); } reader.NextResult(); if (reader.Read()) { forum.TotalMessageCount = Repository.Utils.Convert.ToInt32(reader["TotalRows"]); } res = true; } cnn.Close(); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("Exception:{0}", ex.ToString())); } return(res); }
/** * 发送讨论组消息方法(以一个用户身份向讨论组发送消息,单条消息最大 128k,每秒钟最多发送 20 条消息.) * * * @param message:发送消息内容,参考融云消息类型表.示例说明;如果 objectName 为自定义消息类型,该参数可自定义格式。(必传) * * @return ResponseResult * @throws Exception **/ public async Task <ResponseResult> Send(DiscussionMessage message) { string code = CommonUtil.CheckFiled(message, PATH, CheckMethod.PUBLISH); if (null != code) { return(RongJsonUtil.JsonStringToObj <ResponseResult>(code)); } StringBuilder sb = new StringBuilder(); sb.Append("&fromUserId=").Append(HttpUtility.UrlEncode(message.SenderId, UTF8)); for (int i = 0; i < message.TargetId.Length; i++) { string child = message.TargetId[i]; if (null != child) { sb.Append("&toDiscussionId=").Append(HttpUtility.UrlEncode(child, UTF8)); } } sb.Append("&objectName=").Append(HttpUtility.UrlEncode(message.Content.GetType(), UTF8)); sb.Append("&content=").Append(HttpUtility.UrlEncode(message.Content.ToString(), UTF8)); if (message.PushContent != null) { sb.Append("&pushContent=").Append(HttpUtility.UrlEncode(message.PushContent, UTF8)); } if (message.PushData != null) { sb.Append("&pushData=").Append(HttpUtility.UrlEncode(message.PushData, UTF8)); } if (0 == message.IsPersisted) { sb.Append("&isPersisted=").Append(HttpUtility.UrlEncode(message.IsPersisted.ToString(), UTF8)); } if (0 == message.IsCounted) { sb.Append("&isCounted=").Append(HttpUtility.UrlEncode(message.IsCounted.ToString(), UTF8)); } if (0 == message.IsIncludeSender) { sb.Append("&isIncludeSender=").Append(HttpUtility.UrlEncode(message.IsIncludeSender.ToString(), UTF8)); } string body = sb.ToString(); if (body.IndexOf("&", StringComparison.Ordinal) == 0) { body = body.Substring(1, body.Length - 1); } string result = await RongHttpClient.ExecutePost(AppKey, AppSecret, body, RongCloud.ApiHostType.Type + "/message/discussion/publish.json", "application/x-www-form-urlencoded"); return(RongJsonUtil.JsonStringToObj <ResponseResult>( CommonUtil.GetResponseByCode(PATH, CheckMethod.PUBLISH, result))); }
public static void SeedDatabase(this Repository repository) { if (!repository.Database.EnsureCreated()) { return; } var shirley = new ApplicationUser { Email = "*****@*****.**", FirstName = "Shirley", LastName = "R. Williams", UserName = "******", PasswordHash = "AQAAAAEAACcQAAAAEAEcVubuaDLzBYYNu7aCOvJZjP5r696jOWZMUS7NY0FLj22g5opgFhLukAfti+CtjA==" }; var stephen = new ApplicationUser { Email = "*****@*****.**", FirstName = "Stephen", LastName = "Bryant", UserName = "******", PasswordHash = "AQAAAAEAACcQAAAAEKZxLV3C2lNtOU9J4f+bT3AUAnIGF3P2Ghlyp2b85KCKFW8pYH5L07SW6QBmP//Odw==" }; var reginald = new ApplicationUser { Email = "*****@*****.**", FirstName = "Reginald", LastName = "Ottinger", UserName = "******", PasswordHash = "AQAAAAEAACcQAAAAEDWoMxKTx2rllIJ5qXh8HwiZEpKAWvHcRTWblWDOia3PeOKADScHeLUoL05/M9n8UQ==" }; var aubrey = new ApplicationUser { Email = "*****@*****.**", FirstName = "Aubrey", LastName = "Fitzgerald", UserName = "******", PasswordHash = "AQAAAAEAACcQAAAAEAdKDbzyGhsrb9P7XbBYJzUqCBI4KAomwynQAs73kpgc45Z1Xy7oedZCNvOnBoIg1A==" }; var project = new Project { Name = "SmartShirt", Description = "Utilising modern sensors and fabrics, this product will enable users to track their body vitals with unparalleled accuracy" + " and precision, while not inhibiting their movement or constraining their bodies while exercising.", CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(15)) }; var marketResearchEpic = new Epic { Name = "Market Research", Description = "Conduct in depth market research, align product features and customer expectations, assert the viability of our product.", CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(15)), Project = project }; var marketResearchAssignment1 = new Assignment { Name = "[MR] Create 3 hypotheses on client needs in body sensor technology.", Description = "These hypotheses will be used in further market research and viability assertions.", Deadline = DateTime.Now.Subtract(TimeSpan.FromDays(10)), Assignee = shirley, Status = AssignmentStatus.Complete, CreatedBy = shirley, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(14)), Epic = marketResearchEpic }; var marketResearchAssignment2 = new Assignment { Name = "[MR] Assert hypotheses by conducting client interviews", Deadline = DateTime.Now.Subtract(TimeSpan.FromDays(3)), Assignee = shirley, Status = AssignmentStatus.InProgress, CreatedBy = shirley, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(12)), ModifiedBy = shirley, ModifiedOn = DateTime.Now.Subtract(TimeSpan.FromDays(10)), Epic = marketResearchEpic }; var marketResearchAssignment3 = new Assignment { Name = "[MR] Investigate competitor products", Description = "We should look into other similar products and come up with unique features with which we could attract a customer base.", Status = AssignmentStatus.Todo, CreatedBy = shirley, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(14)), Epic = marketResearchEpic }; var productDevelopmentEpic = new Epic { Name = "Product Development", Description = "Everything related to product production needs.", CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(15)), Project = project }; var productDevelopmentAssignment1 = new Assignment { Name = "[PD] Find contractors for production line services", Assignee = reginald, Status = AssignmentStatus.InProgress, CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(15)), ModifiedBy = stephen, ModifiedOn = DateTime.Now.Subtract(TimeSpan.FromDays(6)), Epic = productDevelopmentEpic }; var productDevelopmentAssignment2 = new Assignment { Name = "[PD] Design schematics for first prototype", Assignee = stephen, Status = AssignmentStatus.Todo, CreatedBy = reginald, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(15)), ModifiedBy = stephen, ModifiedOn = DateTime.Now.Subtract(TimeSpan.FromDays(8)), Epic = productDevelopmentEpic }; var intellectualPropertyEpic = new Epic { Name = "Intellectual Property", Description = "Everything related to intellectual property rights.", CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(14)), Project = project }; var intellectualPropertyAssignment1 = new Assignment { Name = "[IP] Investigate requirements for patent registration", Description = "We should make sure we meet the criteria for a patent ASAP to make sure we can start promoting our product without fear of " + "intellectual theft", Assignee = stephen, Status = AssignmentStatus.InProgress, CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(15)), Epic = intellectualPropertyEpic }; var shirleyJunction = new ProjectToUserJunction { Collaborator = shirley, Project = project, CreatedBy = shirley, CreatedOn = DateTime.Now }; var stephenJunction = new ProjectToUserJunction { Collaborator = stephen, Project = project, CreatedBy = stephen, CreatedOn = DateTime.Now }; var reginaldJunction = new ProjectToUserJunction { Collaborator = reginald, Project = project, CreatedBy = reginald, CreatedOn = DateTime.Now }; var comment1 = new Comment { CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(7)), Content = "{\"blocks\":[{\"key\":\"9o9oo\",\"text\":\"Perhaps it would be a good idea to collect information on the interviewees\' workout habits? That way we would be able to more accurately assess the opinions of people who have a more active lifestyle.\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}", Assignment = marketResearchAssignment2 }; var notification1 = new Notification { IsRead = false, Type = NotificationType.NewComment, Content = "A new comment on assignment [ [MR] Assert hypotheses by conducting client interviews ] has been left by: Stephen Bryant", User = shirley, Project = project, CreatedBy = shirley, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(7)) }; var comment2 = new Comment { CreatedBy = shirley, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(6)), Content = "{\"blocks\":[{\"key\":\"42eev\",\"text\":\"Good idea, I will make sure to inquire about it!\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}", Assignment = marketResearchAssignment2 }; var discussionMessage1 = new DiscussionMessage { Project = project, CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(6).Subtract(TimeSpan.FromHours(15).Subtract(TimeSpan.FromMinutes(30)))), Content = "{\"blocks\":[{\"key\":\"2jfo2\",\"text\":\"Hey guys, welcome to our project board! Don\'t hesitate to use this chat to discuss anything, it will be useful to have everything in one place whenever!\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}" }; var discussionMessage2 = new DiscussionMessage { Project = project, CreatedBy = shirley, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(6).Subtract(TimeSpan.FromHours(15).Subtract(TimeSpan.FromMinutes(29)))), Content = "{\"blocks\":[{\"key\":\"c63tm\",\"text\":\"Hey Stephen! Actually I had a question already: have we decided on our initial steps yet? I propose focusing on market research before we commit to anything. For this kind of product, a prototype will be quite expensive, we should make sure our first one is as close to the real one as we can!\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}" }; var discussionMessage3 = new DiscussionMessage { Project = project, CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(6).Subtract(TimeSpan.FromHours(15).Subtract(TimeSpan.FromMinutes(27)))), Content = "{\"blocks\":[{\"key\":\"a0shc\",\"text\":\"Good point. I will create some assignments for that right away. I suspect you\'ll want to volunteer for this one?\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}" }; var discussionMessage4 = new DiscussionMessage { Project = project, CreatedBy = shirley, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(6).Subtract(TimeSpan.FromHours(15).Subtract(TimeSpan.FromMinutes(26)))), Content = "{\"blocks\":[{\"key\":\"des4c\",\"text\":\"Yes, you can assign me right away!\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}" }; var discussionMessage5 = new DiscussionMessage { Project = project, CreatedBy = reginald, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(6).Subtract(TimeSpan.FromHours(16).Subtract(TimeSpan.FromMinutes(30)))), Content = "{\"blocks\":[{\"key\":\"b88bn\",\"text\":\"Hey guys, good to hear from you! I see everyone\'s eager to start working haha. Stephen, I think we should also prioritise intellectual property asap, considering we will want to start showing this product off at demos, we need to make sure we have a patent process underway. Don\'t want anyone snatching this from under our noses haha!\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}" }; var discussionMessage6 = new DiscussionMessage { Project = project, CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(6).Subtract(TimeSpan.FromHours(16).Subtract(TimeSpan.FromMinutes(25)))), Content = "{\"blocks\":[{\"key\":\"17gb\",\"text\":\"Hey Reginald, good idea! I\'ll start looking into it as soon as I have time!\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}" }; var discussionMessage7 = new DiscussionMessage { Project = project, CreatedBy = shirley, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(3).Subtract(TimeSpan.FromHours(16).Subtract(TimeSpan.FromMinutes(30)))), Content = "{\"blocks\":[{\"key\":\"4o5dv\",\"text\":\"Hey, anyone up for some lunch? I know a good place 15min away!!\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}" }; var discussionMessage8 = new DiscussionMessage { Project = project, CreatedBy = stephen, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(3).Subtract(TimeSpan.FromHours(16).Subtract(TimeSpan.FromMinutes(29)))), Content = "{\"blocks\":[{\"key\":\"fmi0o\",\"text\":\"I\'d join! Didn\'t realise how hungry I was \'till you mentioned it :D\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}" }; var discussionMessage9 = new DiscussionMessage { Project = project, CreatedBy = reginald, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(3).Subtract(TimeSpan.FromHours(16).Subtract(TimeSpan.FromMinutes(28)))), Content = "{\"blocks\":[{\"key\":\"6v9h6\",\"text\":\"Same here! See ya by the exit in 10?\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}" }; var discussionMessage10 = new DiscussionMessage { Project = project, CreatedBy = shirley, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(3).Subtract(TimeSpan.FromHours(16).Subtract(TimeSpan.FromMinutes(27)))), Content = "{\"blocks\":[{\"key\":\"6m7rc\",\"text\":\"Deal!\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}" }; var invitation = new Invitation { Email = aubrey.Email, Project = project, Token = Guid.NewGuid().ToString(), CreatedBy = shirley, CreatedOn = DateTime.Now.Subtract(TimeSpan.FromDays(6)) }; repository.Add(shirley); repository.Add(reginald); repository.Add(stephen); repository.Add(aubrey); project.Collaborators.Add(shirleyJunction); project.Collaborators.Add(stephenJunction); project.Collaborators.Add(reginaldJunction); repository.Add(project); repository.Add(marketResearchEpic); repository.Add(marketResearchAssignment1); repository.Add(marketResearchAssignment2); repository.Add(marketResearchAssignment3); repository.Add(productDevelopmentEpic); repository.Add(productDevelopmentAssignment1); repository.Add(productDevelopmentAssignment2); repository.Add(intellectualPropertyEpic); repository.Add(intellectualPropertyAssignment1); repository.Add(comment1); repository.Add(comment2); repository.Add(notification1); repository.Add(discussionMessage1); repository.Add(discussionMessage2); repository.Add(discussionMessage3); repository.Add(discussionMessage4); repository.Add(discussionMessage5); repository.Add(discussionMessage6); repository.Add(discussionMessage7); repository.Add(discussionMessage8); repository.Add(discussionMessage9); repository.Add(discussionMessage10); repository.Add(invitation); repository.SaveChanges(); }