/// <summary>Adds a message to the in-game display</summary> /// <param name="message">The message to add</param> internal static void AddMessage(AbstractMessage message) { if (TrainManager.PlayerTrain.StationState == TrainStopState.Jumping) { //Ignore messages triggered during a jump return; } if (message is MarkerImage || message is TextureMessage) { for (int i = 0; i < ImageMessages.Count; i++) { if (ImageMessages[i] == message) { return; } } message.AddMessage(Game.SecondsSinceMidnight); ImageMessages.Add(message); return; } for (int i = 0; i < TextualMessages.Count; i++) { if (TextualMessages[i] == message) { //Other messages display one per message return; } } //Prep: May be needed to trigger text replacement etc. message.AddMessage(Game.SecondsSinceMidnight); //Add to the start of the list TextualMessages.Insert(0, message); }
public virtual void SendAsync(AbstractMessage message) { this.sendDone.WaitOne(); byte[] buffer = message.GetEnvelope(); Trace.WriteLine(string.Format("Sending asynch message {0} len {1}", message.MessageUID, message.MessageLength)); this.socket.BeginSend(buffer, this, SendCallback); }
private void C_OmemoSessionBuildError(XMPPClient client, OmemoSessionBuildErrorEventArgs args) { Task.Run(() => { ChatTable chat = ChatDBManager.INSTANCE.getChat(ChatTable.generateId(args.CHAT_JID, client.getXMPPAccount().getBareJid())); if (!(chat is null)) { // Add an error chat message: ChatMessageTable msg = new ChatMessageTable() { id = ChatMessageTable.generateErrorMessageId(AbstractMessage.getRandomId(), chat.id), chatId = chat.id, date = DateTime.Now, fromUser = args.CHAT_JID, isImage = false, message = "Failed to encrypt and send " + args.MESSAGES.Count + " OMEMO message(s) with:\n" + args.ERROR, state = MessageState.UNREAD, type = MessageMessage.TYPE_ERROR }; ChatDBManager.INSTANCE.setChatMessage(msg, true, false); // Set chat messages to encrypted failed: setOmemoChatMessagesSendFailed(args.MESSAGES, chat); } }); }
public void SendToAll(AbstractMessage message) { foreach (Player player in Controller.GetInstance().GetPlayers()) { SendData(player.IPAddress, message); } }
public void SendData(IPAddress address, AbstractMessage message) { try { byte[] data, len; message.Guid = guid; MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, message); memoryStream.Close(); len = new byte[Core.RECEIVE_BUFFER_SIZE]; data = memoryStream.ToArray(); Encoding.ASCII.GetBytes(data.Length.ToString()).CopyTo(len, 0); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(address, clientPort); sock.Send(len); sock.Send(data); sock.Close(); } catch { ConnectionLost(Controller.GetInstance().GetPlayer(address)); } }
//--------------------------------------------------------Events:---------------------------------------------------------------------\\ #region --Events-- private void OnOmemoSessionBuildError(XMPPClient xmppClient, OmemoSessionBuildErrorEventArgs args) { Task.Run(async() => { ChatModel chat; using (SemaLock semaLock = DataCache.INSTANCE.NewChatSemaLock()) { chat = DataCache.INSTANCE.GetChat(xmppClient.getXMPPAccount().getBareJid(), args.CHAT_JID, semaLock); } if (!(chat is null)) { // Add an error chat message: ChatMessageModel msg = new ChatMessageModel() { chatId = chat.id, date = DateTime.Now, fromBareJid = args.CHAT_JID, isCC = false, isDummyMessage = false, isEncrypted = false, isFavorite = false, isImage = false, message = "Failed to encrypt and send " + args.MESSAGES.Count + " OMEMO message(s) with:\n" + args.ERROR, stableId = AbstractMessage.getRandomId(), state = MessageState.UNREAD, type = MessageMessage.TYPE_ERROR }; await DataCache.INSTANCE.AddChatMessageAsync(msg, chat); // Set chat messages to encrypted failed: SetOmemoChatMessagesSendFailed(args.MESSAGES, chat); } }); }
/// <summary> /// Création d'un message vierge. /// </summary> /// <param name="eventType">Code de l'événement (A28, A01, ...).</param> /// <param name="eventOperator">Informations de la personne à l'origine de l'événement.</param> /// <returns></returns> public AbstractMessage CreateMessage(string eventType, object eventOperator) { AbstractMessage msgHL7 = null; if (string.IsNullOrWhiteSpace(eventType)) { throw new ArgumentNullException(nameof(eventType)); } if (!EventType.Description.ContainsKey(eventType)) { throw new EncodingException($"L'événement '{eventType}' n'est pas implémenté par '{TypeUtil.GetTypeName(this)}'."); } switch (eventType) { case EventType.A28: { msgHL7 = new ADT_A28(this._options.EncodingChars, eventOperator); break; } default: { throw new EncodingException($"L'événement '{eventType}' n'est pas implémenté par '{TypeUtil.GetTypeName(this)}'."); } } return(msgHL7); }
protected override async Task processMessageAsync(NewValidMessageEventArgs args) { if (!STREAM_MANAGEMENT_ENABLED) { return; } AbstractMessage msg = args.MESSAGE; switch (state) { case SMState.DISABLED: if (msg is StreamFeaturesMessage || msg is OpenStreamAnswerMessage) { StreamFeaturesMessage features = null; if (msg is OpenStreamAnswerMessage) { features = (msg as OpenStreamAnswerMessage).getStreamFeaturesMessage(); } else { features = msg as StreamFeaturesMessage; } if (features == null) { return; } if (features.containsFeature("sm")) { setMessageProcessed(args); SMEnableMessage enableMsg = new SMEnableMessage(); await XMPP_CONNECTION.sendAsync(enableMsg, false, true); serverSMEnabled = true; state = SMState.REQUESTED; } } break; case SMState.REQUESTED: if (msg is SMEnableMessage enableAnswMsg) { setMessageProcessed(args); // Update connection information: state = SMState.ENABLED; clientSMEnabled = true; stopListeningForMessages(); } else if (msg is SMFailedMessage failedMsg) { setMessageProcessed(args); // Handle errors: state = SMState.ERROR; stopListeningForMessages(); } break; } }
private bool updateDevicesIfNeededMsg(AbstractMessage msg) { if (msg is IQErrorMessage errMsg) { Logger.Error("[OMEMO HELPER](" + CONNECTION.account.getIdAndDomain() + ") Failed to set OMEMO device list to: " + CONNECTION.account.user.domain + "\n" + errMsg.ERROR_OBJ.ToString()); setState(OmemoHelperState.ERROR); return(true); } else if (msg is IQMessage) { Logger.Info("[OMEMO HELPER](" + CONNECTION.account.getIdAndDomain() + ") Device list updated."); if (CONNECTION.account.omemoDeviceId == 0) { CONNECTION.account.omemoDeviceId = tmpDeviceId; CONNECTION.account.onPropertyChanged(nameof(CONNECTION.account.omemoDeviceId)); } if (!CONNECTION.account.omemoBundleInfoAnnounced) { announceBundleInfo(); } else { setState(OmemoHelperState.ENABLED); } return(true); } return(false); }
public override void Print(AbstractMessage msg, bool showFullPath) { var line = 0; var column = 0; try { line = msg.Location.Row; column = msg.Location.Column; } catch { //Log (ex); } var m = new EvalMessage { MessageType = msg.MessageType, Text = msg.Text, Line = line, Column = column, }; Messages.Add(m); // // Print it to the console if there's an error // if (msg.MessageType == "error") { var tm = msg.Text; System.Threading.ThreadPool.QueueUserWorkItem(_ => Console.WriteLine("ERROR: {0}", tm)); } }
private async Task ParseAndShowNotificationAsync(string s, ToastNotification progressToast, BindableString statusText) { UpdateProgress(progressToast, statusText, "Started"); if (string.IsNullOrEmpty(s)) { Logger.Warn("Received an empty push notification..."); return; } Logger.Trace(s); AbstractMessage msg = MessageParser.Parse(s); if (msg is null) { Logger.Warn("Invalid push message received: " + s); return; } UpdateProgress(progressToast, statusText, "Parsed"); if (msg is TestPushMessage) { ToastHelper.ShowSimpleToast("Here is your test push message. It got successfully received from the push server!🎉"); Logger.Info("Test push message received."); return; } else if (msg is PushMessage pushMsg) { await HandelPushMessageAsync(pushMsg, progressToast, statusText); } else { Logger.Warn("Invalid push message action received: " + msg.action); return; } }
public MessageDecoderResult Decode(IoSession session, IoBuffer input, IProtocolDecoderOutput output) { // Try to skip header if not read. if (!_readHeader) { input.GetInt16(); // Skip 'type'. _sequence = input.GetInt32(); // Get 'sequence'. _readHeader = true; } // Try to decode body AbstractMessage m = DecodeBody(session, input); // Return NEED_DATA if the body is not fully read. if (m == null) { return(MessageDecoderResult.NeedData); } else { _readHeader = false; // reset readHeader for the next decode } m.Sequence = _sequence; output.Write(m); return(MessageDecoderResult.OK); }
public MarkerEndEvent(double TrackPositionDelta, AbstractMessage Message, HostInterface Host) { this.TrackPositionDelta = TrackPositionDelta; DontTriggerAnymore = false; message = Message; currentHost = Host; }
public void CheckKilledOtherRegex_KilledOtherMessageWithHeadshotPenetratedAsInput_ExpectedCorrectConstructionOfObject() { string input = "\"WeedMonkey<67><STEAM_1:1:84194999><TERRORIST>\" [341 -429 96] killed other \"chicken<194>\" [344 -451 96] with \"knife_t\" (headshot penetrated)"; var regex = new KilledOtherRegex(); AbstractMessage abstractMessage = regex.Parse(input); Assert.NotNull(abstractMessage); var killedOtherMessage = (KilledOtherMessage)abstractMessage; Assert.Equal("WeedMonkey", killedOtherMessage.UserName); Assert.Equal("67", killedOtherMessage.UserID); Assert.Equal("STEAM_1:1:84194999", killedOtherMessage.UserSteamID); Assert.Equal("TERRORIST", killedOtherMessage.UserTeam); Assert.Equal(341, killedOtherMessage.UserPosX); Assert.Equal(-429, killedOtherMessage.UserPosY); Assert.Equal(96, killedOtherMessage.UserPosZ); Assert.Equal("chicken", killedOtherMessage.KilledOtherName); Assert.Equal("194", killedOtherMessage.KilledOtherID); Assert.Equal(344, killedOtherMessage.KilledUserPosX); Assert.Equal(-451, killedOtherMessage.KilledUserPosY); Assert.Equal(96, killedOtherMessage.KilledUserPosZ); Assert.Equal("knife_t", killedOtherMessage.Weapon); Assert.True(killedOtherMessage.IsHeadshot); Assert.True(killedOtherMessage.IsPenetrated); }
public void DataArrival(String address, AbstractMessage message) { if (message is SelectServerMessage) { HandleSelectServerMessage(address, message); } else if (message is CharacterSelectionMessage) { HandleCharacterSelectionMessage(address, message); } else if (message is WaitingOponentMessage) { HandleWaitingOponentMessage(address, message); } else if (message is StartGameMessage) { HandleStartGameMessage(address, message); } else if (message is CharacterPositionMessage) { HandleCharacterPositionMessage(address, message); } else if (message is StartBattleMessage) { HandleStartBattleMessage(address, message); } else if (message is UpdateMessage) { HandleUpdateMessage(address, message); } else if (message is TurnMessage) { HandleTurnMessage(address, message); } else if (message is AffectsMessage) { HandleAffectsMessage(address, message); } else if (message is ChatMessage) { HandleChatMessage(address, message); } else if (message is EndGameMessage) { HandleEndGameMessage(address, message); } else if (message is PingMessage) { HandlePingMessage(address, message); } else if (message is InvalidGuidMessage) { HandleInvalidGuidMessage(address, message); } else if (message is LeaveMessage) { HandleLeaveMessage(address, message); } }
/// <summary> /// Send a message /// </summary> /// <param name="message">The message to send</param> /// <returns>True if the message has been sent, otherwise false</returns> public bool Send(AbstractMessage message) { if (handler == null) { return(false); } return(handler.Send(message)); }
/// <summary> /// Send a buffer. It's a synchronous operation. The previous send has to be completed. /// You can define a timeout on the previous send and skip this one in case of time out. /// </summary> /// <param name="message">The message to send</param> /// <param name="previousSendTimeout">Timeout on the previous send in ms</param> /// <returns>True if the message has been sent, otherwise false</returns> internal bool SendMessage(AbstractMessage message, int previousSendTimeout) { byte[] buffer = message.GetEnvelope(); Trace.WriteLine(string.Format("Sending message, len {0}", message.MessageLength)); bool r = SendBuffer(this, buffer, previousSendTimeout); return(r); }
public virtual void SendMessage(List <Guid> userList, AbstractMessage resp = null) { if (resp == null) { resp = this.response; } sender.SendMessage(userList, resp); }
private static string GetFormattedLogMessage(AbstractMessage message) { var path = GetSourcePath(message); var row = message.Location.Row; var column = message.Location.Column; return(string.Format("{0} ({1},{2}): {3}", path.FullPath, row, column, message.Text)); }
private void handleHCUpdate(AbstractMessage message) { HCMessage hcMessage = message as HCMessage; gameModel.User.HC += hcMessage.Amount; Messenger.Dispatch(HCMessage.UPDATED); updateView(); }
/// <summary> /// Send asynchronous message /// </summary> /// <param name="message">The message to send</param> public void SendAsync(AbstractMessage message) { if (handler == null) { return; } handler.SendAsync(message); }
public override void Print(AbstractMessage msg, bool showFullPath) { if (msg.MessageType != "error") { return; } AddMessage(msg.MessageType, msg.Text, msg.Location.Row, msg.Location.Column); }
/// <summary> /// Sends the given message to the server or stores it until there is a connection to the server. /// </summary> /// <param name="msg">The message to send.</param> /// <param name="cacheIfNotConnected">Cache the message if the connection state does not equals 'CONNECTED', to ensure the message doesn't get lost.</param> /// <param name="sendIfNotConnected">Sends the message if the underlaying TCP connection is connected to the server and ignores the connection state of the XMPPConnection.</param> public async Task sendAsync(AbstractMessage msg, bool cacheIfNotConnected, bool sendIfNotConnected) { if (state == ConnectionState.CONNECTING) { resetConnectionTimer(); } if (state != ConnectionState.CONNECTED && !sendIfNotConnected) { if (Logger.logLevel >= LogLevel.DEBUG) { Logger.Warn("Did not send message, due to connection state is " + state + "\n" + msg.toXmlString()); } else { Logger.Warn("Did not send message, due to connection state is " + state); } if ((cacheIfNotConnected || msg.shouldSaveUntilSend())) { MessageCacheDBManager.INSTANCE.addMessage(account.getIdAndDomain(), msg); } if (!sendIfNotConnected) { return; } } if (msg is IQMessage && msg.ID != null) { messageIdCache.addTimed(msg.ID); } try { if (await TCP_CONNECTION.sendAsync(msg.toXmlString())) { // Only trigger onMessageSend(...) for chat messages: if (msg is MessageMessage m) { onMessageSend(msg.ID, m.chatMessageId, false); return; } } else { Logger.Error("Error during sending message for account: " + account.getIdAndDomain()); } } catch (Exception e) { Logger.Error("Error during sending message for account: " + account.getIdAndDomain(), e); } if ((cacheIfNotConnected || msg.shouldSaveUntilSend())) { MessageCacheDBManager.INSTANCE.addMessage(account.getIdAndDomain(), msg); } }
protected override void OnReceive(AbstractMessage message) { TypeSwitch.On(message) .Case((ClearMessage clearMessage) => { // Reset partition and send sync message clear(); clearMessage.Sender.SendMe(new EstimateRefinedMessage(this)); }) .Case((RefineMessage refineMessage) => { // Perform local refine step refine(); refineMessage.Sender.SendMe(new EstimateRefinedMessage(this)); }) .Case((CountMessage countMessage) => { var blocks = new HashSet <int>(); foreach (var node in ownerInverted[this]) { if (!blocks.Contains(partition[node])) { blocks.Add(partition[node]); } } countMessage.Sender.SendMe(new CountedMessage(this, blocks)); }) .Case((ShareMessage shareMessage) => { // Share changes foreach (var worker in ownerInverted.Keys) { if (worker != this) { var changedNodesOfInterest = partition.Where(kvp => interestedIn[worker].Contains(kvp.Key) && changed[kvp.Key]); if (changedNodesOfInterest.Any()) { worker.SendMe(new UpdatePartitionMessage <TNode>(this, changedNodesOfInterest)); } } } shareMessage.Sender.SendMe(new SharedMessage(this)); }) .Case((UpdatePartitionMessage <TNode> updatePartitionMessage) => { foreach (var change in updatePartitionMessage.Changes) { partition[change.Key] = change.Value; } }) .Case((SegmentRequestMessage segmentRequestMessage) => { segmentRequestMessage.Sender.SendMe(new SegmentResponseMessage <TNode>(this, partition.Where(kvp => owner[kvp.Key] == this))); }); }
public static void Dispatch(string type, AbstractMessage message = null) { ObjUnityEvent thisEvent = null; if (instance.eventDictionary.TryGetValue(type, out thisEvent)) { thisEvent.Invoke(message); } }
/// <summary> /// Build an acknowledge message. /// </summary> /// <param name="message">Incoming message.</param> static public AcknowledgeMessage BuildAcknowledgeMessage(AbstractMessage message) { return(new AcknowledgeMessage { MessageId = GenerateUuid(), CorrelationId = message.MessageId, Timestamp = GenerateTimestamp() }); }
void OnMessage(AbstractMessage msg) { var m = _printer; if (m != null) { m(msg); } }
private void HandlePingMessage(String address, AbstractMessage message) { if (controller.Client.LastPing == default(DateTime)) { Controller.GetInstance().Client.StartPing(); } controller.Client.LastPing = DateTime.Now; controller.Client.SendData(message); }
/// <summary> /// Build an error message. /// </summary> /// <param name="message">Incoming message.</param> static public ErrorMessage BuildErrorMessage(AbstractMessage message) { return(new ErrorMessage { MessageId = GenerateUuid(), CorrelationId = message.MessageId, Timestamp = GenerateTimestamp() }); }
/// <inheritdoc/> public Task MarkMessageAsPublishedAsync(string id, AbstractMessage message) { var entity = new DynamicTableEntity(id, message.Id, "*", new Dictionary <string, EntityProperty> { { IsPublishedColumnName, new EntityProperty(true) }, }); return(tableProxy.ExecuteAsync(TableOperation.Merge(entity))); }
public void Receive(AbstractMessage message) { Console.WriteLine(this.GetType().ToString() + " => Sending Push Notification with content: " + message.GetBody()); }