public List <MessageGroup> ListMessageGroup(int pIdGame, int pIdPlayer) { List <MessageGroup> list_message_group = new List <MessageGroup> (); string conn = "URI=file:" + Application.streamingAssetsPath + "/AdvScrabble.db"; //Path to database. IDbConnection dbconn; dbconn = (IDbConnection) new SqliteConnection(conn); dbconn.Open(); //Open connection to the database. IDbCommand dbcmd = dbconn.CreateCommand(); string sqlQuery = String.Format("SELECT * FROM message_group where id_game = \"{0}\" and id_player = \"{1}\"", pIdGame, pIdPlayer); dbcmd.CommandText = sqlQuery; IDataReader reader = dbcmd.ExecuteReader(); while (reader.Read()) { MessageGroup mg = new MessageGroup(); mg.Id_message_group = reader.GetInt32(2); mg.Name = reader.GetString(3); mg.MessageList = this.ListMessages(pIdGame, pIdPlayer, reader.GetInt32(2)); list_message_group.Add(mg); } reader.Close(); reader = null; dbcmd.Dispose(); dbcmd = null; dbconn.Close(); dbconn = null; return(list_message_group); }
public JRTrimPageData() { Message = new MessageGroup("https://forum.solidworks.com/thread/237287"); Panel = new PanelGroup(); Beam = new BeamGroup(); Fit = new FitGroup(); }
public async Task SendMessageGroup(string Message, int UserID, int GroupID) { Group g = await api.GetGroupAsync(GroupID); if (g == null) { return; } Player p = await api.GetPlayerAsync(UserID); if (p == null) { return; } MessageGroup mg = new MessageGroup() { Content = Message, ID_Destination = GroupID, ID_Sender = UserID, Status = MessageStatus.None, Send_Time = DateTime.Now, Destination = g, Sender = p }; g.Messages.Add(mg); await Clients.Group("group_" + GroupID).ReceiveMessageGroup(mg); await api.db.SaveChangesAsync(); }
public async Task <IHttpActionResult> PutMessageGroup(int id, MessageGroup messageGroup) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != messageGroup.ID) { return(BadRequest()); } db.Entry(messageGroup).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!MessageGroupExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
private static ConsoleColor ColorOf(MessageGroup group) { switch (group) { case MessageGroup.Attack: case MessageGroup.Captcha: case MessageGroup.PixelFail: case MessageGroup.Error: return(ConsoleColor.Red); case MessageGroup.Assist: case MessageGroup.Pixel: return(ConsoleColor.Green); case MessageGroup.Info: return(ConsoleColor.Magenta); case MessageGroup.TechInfo: case MessageGroup.Update: return(ConsoleColor.Cyan); case MessageGroup.TechState: return(ConsoleColor.Yellow); case MessageGroup.PixelInfo: case MessageGroup.Debug: default: return(ConsoleColor.Gray); } }
public Message GetLastMessageForGivenGroup(MessageGroup messageGroup) { _dbContext.Entry(messageGroup) .Reference(p => p.Messages) .Load(); return(messageGroup.Messages.OrderBy(x => x.MessageDate).Last()); }
public async Task <MessageGroup> CreateNewGroup(MessageGroup messageGroup) { messageGroup.TextMessages.Clear(); await _bSChatDBContext.MessageGroup.AddAsync(messageGroup); await _bSChatDBContext.SaveChangesAsync(); return(messageGroup); }
public JsonResult Get(int id) { MessageGroupBL messageGroupBL = new MessageGroupBL(); MessageDetailBL messageDetailBL = new MessageDetailBL(); MessageGroup messageGroupInfo = messageGroupBL.GetById(id); IEnumerable <object> messageInfo = messageDetailBL.GetByGroupID(id); return(Json(new { messageGroupID = messageGroupInfo.MessageGroupID, studentID = messageGroupInfo.StudentID, content = messageGroupInfo.Content, childMessages = messageInfo })); }
private async ValueTask WriteCurrentMessageGroupAsync() { var templateContext = CreateTemplateContext(new Dictionary <string, object> { ["MessageGroup"] = MessageGroup.Join(_messageGroupBuffer) }); await templateContext.EvaluateAsync(_messageGroupTemplate.Page); }
private async ValueTask WriteMessageGroupAsync(MessageGroup messageGroup) { var templateContext = new MessageGroupTemplateContext(Context, messageGroup); var templateBundle = await TemplateBundle.ResolveAsync(); await _writer.WriteLineAsync( await templateBundle.MessageGroupTemplate.RenderAsync(templateContext) ); }
public static void LogPixel(this Logger logger, string msg, DateTime time, MessageGroup group, int x, int y, string color) { string text = string.Format("{0} {1} at ({2};{3})", msg.PadRight(maxPixelMsgLength), color, x.ToString().PadLeft(MaxCoordXYLength), y.ToString().PadLeft(MaxCoordXYLength)); logger.Log(text, group, time); }
public void I_should_only_be_allowed_to_add_valid_message_types() { Assert.Throws <ArgumentException>(() => { SpecialGroup group = MessageGroup.Build <SpecialGroup>() .Add(new PingMessage()) .Add(new PongMessage()) .Add(new UpdateMessage()); }); }
public async Task <MessageGroup> asMessageGroup(int messagesPagination = 1) { MessageGroup model = new MessageGroup() { GroupId = MessageGroup.GroupId, }; model.GroupMembers.AddRange(MessageGroup.GroupMembers); model.Messages.AddRange(await GetMessages(messagesPagination)); return(model); }
public async Task <IHttpActionResult> GetMessageGroup(int id) { MessageGroup messageGroup = await db.MessageGroups.FindAsync(id); if (messageGroup == null) { return(NotFound()); } return(Ok(messageGroup)); }
public void I_should_be_able_to_retrieve_a_single_message_by_position() { PingMessage ping = new PingMessage(); PongMessage pong = new PongMessage(); MessageGroup group = MessageGroup.Build <MessageGroup>() .Add(ping) .Add(pong); PingMessage thePing = group.Get <PingMessage>(0); }
public void I_should_be_able_to_join_a_bunch_of_messages_into_a_group() { object[] items = new object[] { new PingMessage(), new PongMessage() }; MessageGroup group = MessageGroup.Join(items); Assert.That(group.Count, Is.EqualTo(2)); Assert.That(group[0], Is.TypeOf(typeof(PingMessage))); Assert.That(group[1], Is.TypeOf(typeof(PongMessage))); }
public async Task <IHttpActionResult> PostMessageGroup(MessageGroup messageGroup) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.MessageGroups.Add(messageGroup); await db.SaveChangesAsync(); return(CreatedAtRoute("DefaultApi", new { id = messageGroup.ID }, messageGroup)); }
public static IMessageGroup GetGrouping(object group) { object groupKey = new object(); var grouping = new MessageGroup(); if (group.TryGetPropertyValue("groupkey", out groupKey)) { grouping.GroupKey = groupKey.ToString(); } return(grouping); }
public static void LogPixel(this Logger logger, string msg, DateTime time, MessageGroup group, int x, int y, EarthPixelColor color) { const int maxMsgLength = 22; const int maxCoordLength = 6; string text = string.Format("{0} {1} at ({2};{3})", msg.PadRight(maxMsgLength), color.ToString().PadRight(colorPadLength), x.ToString().PadLeft(maxCoordLength), y.ToString().PadLeft(maxCoordLength)); logger.Log(text, group, time); }
public static void ExcludeUnnecessaryLogGroups(MessageGroup messageGroup, EventLogEntryType ReportInformationLevel = EventLogEntryType.Error) { using (var connection = Connection) { if (messageGroup.EntryType <= ReportInformationLevel) { return; } messageGroup.MessageSent = true; connection.GetCollection <MessageGroup>(nameof(MessageGroup)).Update(messageGroup); } }
public void I_should_be_able_to_split_a_bunch_of_messages_from_a_group() { PingMessage ping = new PingMessage(); PongMessage pong = new PongMessage(); MessageGroup group = MessageGroup.Build <MessageGroup>() .Add(ping) .Add(pong); object[] items = group.ToArray(); Assert.That(items.Length, Is.EqualTo(2)); }
public async Task <IHttpActionResult> DeleteMessageGroup(int id) { MessageGroup messageGroup = await db.MessageGroups.FindAsync(id); if (messageGroup == null) { return(NotFound()); } db.MessageGroups.Remove(messageGroup); await db.SaveChangesAsync(); return(Ok(messageGroup)); }
public void I_Should_be_able_to_subscribe() { Consumer c = new Consumer(LocalBus); LocalBus.Subscribe(c); SpecialGroup group = MessageGroup.Build <SpecialGroup>() .Add(new PingMessage()) .Add(new PongMessage()); LocalBus.Publish(group); Assert.That(c.Received.WaitOne(TimeSpan.FromSeconds(5), true), Is.True, "No message received by consumer"); }
public void I_should_get_an_exception_when_I_try_to_get_an_unmatched_type() { PingMessage ping = new PingMessage(); PongMessage pong = new PongMessage(); MessageGroup group = MessageGroup.Build <MessageGroup>() .Add(ping) .Add(pong); Assert.Throws <ArgumentException>(() => { PingMessage thePing = group.Get <PingMessage>(1); }); }
public void One() { PingMessage ping = new PingMessage(); PongMessage pong = new PongMessage(); MessageGroup group = MessageGroup.Build <MessageGroup>() .Add(ping) .Add(pong); Assert.That(group.Count, Is.EqualTo(2)); Assert.That(group[0], Is.TypeOf(typeof(PingMessage))); Assert.That(group[1], Is.TypeOf(typeof(PongMessage))); }
public void Create(string senderId, int groupId, string text) { var messageGroup = new MessageGroup { SenderId = senderId, GroupId = groupId, DateSent = DateTime.UtcNow, IsSeen = false, MessageText = text }; this.db.MessageGroups.Add(messageGroup); this.db.SaveChanges(); }
public override async ValueTask WritePostambleAsync() { // Flush current message group if (_messageGroupBuffer.Any()) { await WriteMessageGroupAsync(MessageGroup.Join(_messageGroupBuffer)); } var templateContext = new LayoutTemplateContext(Context, _themeName, _messageCount); var templateBundle = await TemplateBundle.ResolveAsync(); await _writer.WriteLineAsync( await templateBundle.PostambleTemplate.RenderAsync(templateContext) ); }
private static string FormatLine(string msg, MessageGroup group, DateTime time) { if (group == MessageGroup.Debug) { return(string.Concat(time.ToString("HH:mm:ss.fff"), space, $"[{group.ToString().ToUpper()}]", space, msg)); } else { return(string.Concat(time.ToString("HH:mm:ss.fff"), space, $"[{group.ToString().ToUpper()}]".PadRight(msgGroupPadLength), largeSpace, msg)); } }
private static MessageGroup ReadMessageGroup(BinaryReader BR, Encoding E) { MessageGroup MG = new MessageGroup(); MG.Category = BR.ReadByte(); MG.Language = BR.ReadByte(); MG.ID = BR.ReadByte(); MG.ParentGroup = BR.ReadByte(); MG.Title = E.GetString(BR.ReadBytes(32)).TrimEnd('\0'); MG.Description = E.GetString(BR.ReadBytes(32)).TrimEnd('\0'); uint MessageCount = BR.ReadUInt32(); /* MessageBytes */ BR.ReadUInt32(); for (int i = 0; i < MessageCount; ++i) MG.Messages.Add(AutoTranslator.ReadMessage(BR, E)); return MG; }
private static MessageGroup AddLogGroup(LiteDatabase connection, TaskLogging taskLogging, Task task) { var messageGroups = connection.GetCollection <MessageGroup>(nameof(MessageGroup)); var messageGroup = new MessageGroup() { Task = task, DateTime = DateTime.Now, IsErrorLog = taskLogging.ErrorAccured(), MessageSent = false, EntryType = EventLogEntryType.Information }; messageGroups.Insert(messageGroup); messageGroups.EnsureIndex(t => t.DateTime); return(messageGroup); }
private void ExportMessageID(string outputDir, MessageGroup group, StringContext context) { context.Add(CONTEXT_MESSAGE_GROUP_KEY, group); string outputFilePath = $"{outputDir}/{group.Name}_ID{GetExtension()}"; string outputContent = TemplateEngine.Execute(context, exportData.idTemplateContent, new string[] { typeof(MessageGroup).Assembly.Location }); if (!string.IsNullOrEmpty(outputContent)) { File.WriteAllText(outputFilePath, outputContent); } context.Remove(CONTEXT_MESSAGE_GROUP_KEY); }
/// <summary> /// Finds the chat corresponding to the message group. If no such chat exists it will be created. The corresponding handle will also be created. /// </summary> /// <param name="group">The message group.</param> /// <returns>The ID of the chat.</returns> private long GetOrCreateChat(MessageGroup group) { // Check for existing chat string checkChat = String.Format("SELECT ROWID FROM {0} WHERE chat_identifier = '{1}' AND service_name = '{2}'", ChatTable, group.Address, MessageService); object existingChatId = Scalar(checkChat); if (existingChatId != null) return (long)existingChatId; // Insert new chat string insertChat = String.Format("INSERT INTO {0} (guid, style, state, chat_identifier, service_name) VALUES ('{1}', {2}, {3}, '{4}', '{5}')", ChatTable, string.Format("{0};-;{1}", MessageService, group.Address), 45, 2, group.Address, MessageService); Query(insertChat); long chatId = LastInsertId; // Get or create handle long handleId = GetOrCreateHandle(group); // Insert join string insertJoin = String.Format("INSERT INTO {0} (chat_id, handle_id) VALUES ({1}, {2})", ChatHandleJoinTable, chatId, handleId); Query(insertJoin); return chatId; }
/// <summary> /// Writes a group of messages to the database. /// </summary> /// <param name="group">The group of messages.</param> public void SaveMessageGroup(MessageGroup group) { using (SQLiteTransaction transaction = _connection.BeginTransaction()) { // Get or create handle and chat long handleId = GetOrCreateHandle(group); long chatId = GetOrCreateChat(group); // Insert messages using a prepared statement using (var command = new SQLiteCommand(_connection)) { // Build query command.CommandText = String.Format("INSERT INTO {0} " + "(guid, text, handle_id, country, version, service, date, date_read, date_delivered, is_finished, is_from_me, is_prepared, is_read, is_sent) " + "VALUES (?, ?, {1}, '{2}', {3}, '{4}', ?, ?, ?, {5}, ?, {6}, ?, ?)", MessageTable, handleId, group.CountryCode.ToString().ToLower(), 1, MessageService, 1, 1); // Create and setup statement parameters var guid = new SQLiteParameter(); var text = new SQLiteParameter(); var date = new SQLiteParameter(); var dateRead = new SQLiteParameter(); var dateDelivered = new SQLiteParameter(); var isFromMe = new SQLiteParameter(); var isRead = new SQLiteParameter(); var isSent = new SQLiteParameter(); command.Parameters.Add(guid); command.Parameters.Add(text); command.Parameters.Add(date); command.Parameters.Add(dateRead); command.Parameters.Add(dateDelivered); command.Parameters.Add(isFromMe); command.Parameters.Add(isRead); command.Parameters.Add(isSent); // Execute the statement for each message foreach (var message in group) { // Fill prepared statement guid.Value = Guid.NewGuid().ToString().ToUpper(); text.Value = message.Text; date.Value = message.AppleTimestamp; dateRead.Value = message.AppleTimestamp; dateDelivered.Value = message.AppleTimestamp; isFromMe.Value = (message.Type == MessageType.Outgoing) ? 1 : 0; isRead.Value = (message.Type == MessageType.Incoming) ? 1 : 0; isSent.Value = (message.Type == MessageType.Outgoing) ? 1 : 0; command.ExecuteNonQuery(); // Insert join long messageId = LastInsertId; string insertJoin = String.Format("INSERT INTO {0} (chat_id, message_id) VALUES ({1}, {2})", ChatMessageJoinTable, chatId, messageId); Query(insertJoin); } } // Commit changes transaction.Commit(); } }
/// <summary> /// Finds the handle corresponding to the message group. If no such handle exists it will be created. /// </summary> /// <param name="group">The message group.</param> /// <returns>The ID of the handle.</returns> private long GetOrCreateHandle(MessageGroup group) { // Check for existing handle string checkHandle = String.Format("SELECT ROWID FROM {0} WHERE id = '{1}' AND service = '{2}'", HandleTable, group.Address, MessageService); object existingHandleId = Scalar(checkHandle); if (existingHandleId != null) return (long)existingHandleId; // Insert new handle string insertHandle = String.Format("INSERT INTO {0} (id, country, service, uncanonicalized_id) VALUES ('{1}', '{2}', '{3}', '{1}')", HandleTable, group.Address, group.CountryCode, MessageService); Query(insertHandle); return LastInsertId; }
/// <summary>组合组消息</summary> /// <param name="message">消息</param> /// <param name="remoteIdentity">远程标识</param> /// <returns></returns> protected virtual Message JoinGroup(GroupMessage message, Object remoteIdentity = null) { var key = String.Format("{0}#{1}", remoteIdentity, message.Identity); MessageGroup mg = null; if (!groups.TryGetValue(key, out mg)) { mg = new MessageGroup(); mg.Identity = message.Identity; groups.Add(key, mg); } // 加入到组,如果返回false,表示未收到所有消息 if (!mg.Add(message)) { WriteLog("接收分组 Identity={0} {1}/{2} [{3}] 已完成:{4}/{5}", message.Identity, message.Index, message.Count, message.Data == null ? 0 : message.Data.Length, mg.Count, mg.Total); return null; } WriteLog("接收分组 Identity={0} {1}/{2} [{3}] 已完成:{4}/{5}", message.Identity, message.Index, message.Count, message.Data == null ? 0 : message.Data.Length, mg.Count, mg.Total); // 否则,表示收到所有消息 groups.Remove(key); // 读取真正的消息 return mg.GetMessage(); }
/// <summary>发送消息。如果有响应,可在消息到达事件<see cref="OnReceived"/>中获得。这里会实现大消息分包。</summary> /// <param name="message"></param> public virtual void Send(Message message) { var ms = message.GetStream(); WriteLog("发送消息 [{0}] {1}", ms.Length, message); if (MaxMessageSize <= 0 || ms.Length < MaxMessageSize) OnSend(ms); else { var mg = new MessageGroup(); mg.Split(ms, MaxMessageSize, message.Header); var count = 0; foreach (var item in mg) { if (item.Index == 1) count = item.Count; ms = item.GetStream(); WriteLog("发送分组 Identity={0} {1}/{2} [{3}] [{4}]", item.Identity, item.Index, count, item.Data == null ? 0 : item.Data.Length, ms.Length); Debug.Assert(item.Index == count || ms.Length == MaxMessageSize, "分拆的组消息大小不合适!"); OnSend(ms); } } }