public void Serialization() { // overflowing message var om = new MessageWrapper {ContainerName = "con", BlobName = "blo"}; var stream = new MemoryStream(); var serializer = new CloudFormatter(); serializer.Serialize(om, stream, om.GetType()); stream.Position = 0; var omBis = (MessageWrapper) serializer.Deserialize(stream, typeof (MessageWrapper)); Assert.AreEqual(om.ContainerName, omBis.ContainerName, "#A00"); Assert.AreEqual(om.BlobName, omBis.BlobName, "#A01"); }
public void Serialization() { // overflowing message var om = new MessageWrapper {ContainerName = "con", BlobName = "blo"}; var stream = new MemoryStream(); var serializer = GlobalSetup.Container.Resolve<IDataSerializer>(); serializer.Serialize(om, stream); stream.Position = 0; var omBis = (MessageWrapper) serializer.Deserialize(stream, typeof(MessageWrapper)); Assert.AreEqual(om.ContainerName, omBis.ContainerName, "#A00"); Assert.AreEqual(om.BlobName, omBis.BlobName, "#A01"); }
public virtual Task <IList <MarketDataVM> > SubMarketDataAsync(IEnumerable <ContractKeyVM> instrIDList, int timeout = 10000) { var tempList = AddToMarketDataMap(instrIDList); var tcs = new TimeoutTaskCompletionSource <IList <MarketDataVM> >(timeout); var serialId = NextSerialId; #region callback MessageWrapper.RegisterAction <PBMarketDataList, ExceptionMessage> (MSG_ID_SUB_MD, (resp) => { if (resp.Header?.SerialId == serialId) { tcs.TrySetResult(SubMDSuccessAction(resp)); } tempList.Clear(); }, (bizErr) => { if (bizErr.SerialId == serialId) { tcs.TrySetException(new MessageException(bizErr.MessageId, ErrorType.BIZ_ERROR, bizErr.Errorcode, bizErr.Description.ToStringUtf8())); } tempList.Clear(); } ); #endregion SendMessage(serialId, MSG_ID_SUB_MD, instrIDList); return(tcs.Task); }
/// <summary> /// Publishes the received message to all registered subscribers. /// </summary> /// <param name="message"></param> /// <returns></returns> public Task ReceiveMessageAsync(MessageWrapper message) { message.IsRelayed = true; return(PublishMessageAsync(message)); }
public async Task RouteToServerInstance(string key, MessageWrapper data) { var bs = this.messageSerializer.SerializeBytes(data); await this.redisDatabaseSelector.Database.ListLeftPushAsync(key, bs); }
public override async Task Receive(MessageRetrieved retrieved, MessageWrapper message) { var body = message.Body ?? new byte[0]; try { using (var tokenSource = new CancellationTokenSource()) { var pushContext = new MessageContext(message.Id, new Dictionary <string, string>(message.Headers), body, new TransportTransaction(), tokenSource, new ContextBag()); await pipeline(pushContext).ConfigureAwait(false); if (tokenSource.IsCancellationRequested) { // if the pipeline cancelled the execution, nack the message to go back to the queue await retrieved.Nack().ConfigureAwait(false); } else { // the pipeline hasn't been cancelled, the message should be acked await retrieved.Ack().ConfigureAwait(false); } } } catch (LeaseTimeoutException) { // The lease has expired and cannot be used any longer to Ack or Nack the message. // see original issue: https://github.com/Azure/azure-storage-net/issues/285 throw; } catch (Exception ex) { var context = CreateErrorContext(retrieved, message, ex, body); ErrorHandleResult immediateRetry; try { immediateRetry = await errorPipe(context).ConfigureAwait(false); } catch (Exception e) { criticalError.Raise($"Failed to execute recoverability policy for message with native ID: `{message.Id}`", e); await retrieved.Nack().ConfigureAwait(false); return; } if (immediateRetry == ErrorHandleResult.RetryRequired) { // For an immediate retry, the error is logged and the message is returned to the queue to preserve the DequeueCount. // There is no in memory retry as scale-out scenarios would be handled improperly. Logger.Warn("Azure Storage Queue transport failed pushing a message through pipeline. The message will be requeued", ex); await retrieved.Nack().ConfigureAwait(false); } else { // Just acknowledge the message as it's handled by the core retry. await retrieved.Ack().ConfigureAwait(false); } } }
public override bool Run(string[] arguments, MessageWrapper message) { if (arguments.Length >= 1) { arguments[0] = arguments[0].ToLower(); } if (arguments.Length >= 2) { arguments[1] = arguments[1].ToLower(); } switch (arguments[0]) { case "random": var rtag = TagsModule.database.tags.ElementAt(new Random().Next(0, TagsModule.database.tags.Count)); SendTag(rtag.Value, message.Channel, "Tag: " + rtag.Key + Environment.NewLine); //message.Channel.SendMessageAsync("Tag: " + rtag.Key+Environment.NewLine+rtag.Value.content); return(true); case "add": if (TagsModule.database.tags.ContainsKey(arguments[1])) { message.Channel.SendMessageAsync("That tag is already taken."); return(false); } if (message.headless) { if (arguments.Length <= 2) { message.Channel.SendMessageAsync("Can't add an empty tag."); } else { TagsModule.database.tags[arguments[1]] = new Tag(message.Author.Username, message.Author.Discriminator, message.Author.Id.ToString(), arguments[2]); } } else { var content = ""; var attachName = ""; var attachUrl = ""; if (message.message.Attachments.Count > 0) { attachName = message.message.Attachments.First().Filename; attachUrl = message.message.Attachments.First().Url; } if (arguments.Length <= 2 && attachUrl == "") { message.Channel.SendMessageAsync("Can't add an empty tag."); return(false); } else if (arguments.Length > 2) { content = arguments[2]; } TagsModule.database.tags[arguments[1]] = new Tag(message.message.Author.Username, message.message.Author.Discriminator, message.message.Author.Id.ToString(), content, attachName, attachUrl); } message.Channel.SendMessageAsync("Added tag " + arguments[1]); TagsModule.SaveTags(); return(true); case "edit": if (TagsModule.database.tags.ContainsKey(arguments[1])) { if (TagsModule.database.tags[arguments[1]].ownerID != message.Author.Id.ToString()) { message.Channel.SendMessageAsync("That tag is not yours."); return(false); } else { var content = ""; var attachName = ""; var attachUrl = ""; if (message.message.Attachments.Count > 0) { attachName = message.message.Attachments.First().Filename; attachUrl = message.message.Attachments.First().Url; } if (arguments.Length <= 2 && attachUrl == "") { message.Channel.SendMessageAsync("Can't add an empty tag."); return(false); } else if (arguments.Length > 2) { content = arguments[2]; } TagsModule.database.tags[arguments[1]].content = content; TagsModule.database.tags[arguments[1]].attachmentFilename = attachName; TagsModule.database.tags[arguments[1]].attachmentUrl = attachUrl; message.Channel.SendMessageAsync("Edited tag " + arguments[1]); TagsModule.SaveTags(); return(true); } } message.Channel.SendMessageAsync("That tag doesn't exist."); return(false); case "delete": if (TagsModule.database.tags.ContainsKey(arguments[1])) { if (TagsModule.database.tags[arguments[1]].ownerID != message.Author.Id.ToString()) { message.Channel.SendMessageAsync("That tag is not yours."); return(false); } else { TagsModule.database.tags.Remove(arguments[1]); message.Channel.SendMessageAsync("Removed tag " + arguments[1]); TagsModule.SaveTags(); return(true); } } message.Channel.SendMessageAsync("That tag doesn't exist."); return(false); case "owner": if (TagsModule.database.tags.ContainsKey(arguments[1])) { var tag = TagsModule.database.tags[arguments[1]]; message.Channel.SendMessageAsync("That tag is owned by " + tag.ownerName + "#" + tag.ownerTag + " (" + tag.ownerID + ")"); return(true); } message.Channel.SendMessageAsync("That tag doesn't exist."); return(false); case "list": IGuild guild = null; if (!message.headless && typeof(IGuildChannel).IsAssignableFrom(message.message.Channel.GetType())) { guild = (message.message.Channel as IGuildChannel).Guild; } var user = Utils.GetMention(arguments[1], guild); while (!user.IsCompleted) { //WAIT } if (user.Result.success) { var txt = "Tags owned by user id " + user.Result.id.ToString() + ":" + Environment.NewLine; foreach (var element in TagsModule.database.tags) { if (element.Value.ownerID == user.Result.id.ToString()) { txt += "**" + element.Key + "**" + Environment.NewLine; } } message.Channel.SendMessageAsync(txt); return(true); } return(false); } if (TagsModule.database.tags.ContainsKey(arguments[0])) { SendTag(TagsModule.database.tags[arguments[0]], message.Channel); return(true); } message.Channel.SendMessageAsync("That tag doesn't exist."); return(false); }
/// <summary> /// Deserializes the provided <paramref name="message"/> Payload into an intance of type <typeparam name="TResult"></typeparam> /// </summary> /// <typeparam name="TResult"></typeparam> /// <returns></returns> public static TResult Deserialize <TResult>(this StatefulServiceBase service, MessageWrapper message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } if (string.IsNullOrWhiteSpace(message.Payload)) { throw new ArgumentNullException(nameof(message.Payload)); } var payload = JsonConvert.DeserializeObject <TResult>(message.Payload); return(payload); }
public async Task OnMessageDeliveryFailedAsync(string queueName, ReferenceWrapper subscriber, MessageWrapper messageWrapper, Exception exception, int throttleFactor) { var onMessageDeliveryFailed = MessageDeliveryFailed; if (onMessageDeliveryFailed != null) { await onMessageDeliveryFailed.Invoke(queueName, subscriber, messageWrapper, exception); } subscriber.SkipCount = throttleFactor; if (_stats.TryGetValue(queueName, out var stats)) { stats.TotalDeliveryFailures++; } }
public Task ReceiveMessageAsync(MessageWrapper message) { return(InvokeWithRetryAsync( client => client.Channel.ReceiveMessageAsync(message))); }
protected abstract Task EnqueueMessageAsync(MessageWrapper message, Reference subscriber, ITransaction tx);
private void SendData(ScavengerServiceMessageType messageType, Guid scavengerId, Action <BinaryWriter> writeData = null) { var message = new MessageWrapper((int)messageType, scavengerId); _clientTerminal.SendMessage(message.WriteBuffer(writeData)); }
private void send(Socket socket, int type) { writeMessage(socket, MessageWrapper.wrapMessage(type)); }
private void send(Socket socket, int type, int content) { writeMessage(socket, MessageWrapper.wrapMessage(type, content)); }
private string DatabaseDownMitigation(MessageWrapper wrapper) { string returnMessage = "Audit Point Processed - Unsuccessful"; string messageThresholdString = ConfigurationManager.AppSettings["messageQueueThreshold"]; int messageThreshold = Convert.ToInt32((messageThresholdString == null) ? "1000" : messageThresholdString); string messageQueueSetting = ConfigurationManager.AppSettings["errorQueueName"]; string errorQueueName = messageQueueSetting == null ? "no message queue defined in config" : messageQueueSetting; //this is our last ditch effort to keep this audit , we put it on an error //Q which then should be processed when the database is back up. string queuePath = ConfigurationManager.AppSettings["dbWriterQueueName"]; MessageQueue q = null; try { if (!MessageQueue.Exists(errorQueueName)) { MessageQueue.Create(errorQueueName, true); } q = new MessageQueue(errorQueueName); } catch (Exception exQueueInstantiation) { _log.Fatal("Cannot Process Any Audit Messages At this time, All Mitigations Have Failed, Multiple Systems Failure has Occurred, Error Queue Name: " + errorQueueName, exQueueInstantiation); throw new ApplicationException("Cannot instantiate or create MSMQ " + errorQueueName, exQueueInstantiation); } finally { if (q != null) { q.Dispose(); } } try { if (IsMSMQOverThreshold(q, messageThreshold)) { _log.Fatal("Audit MSMQ Message Threshold Exceeded, Please Check MSMQ, still accepting Messages But Unfixed Could use up Maximum Memory on Machine" + q.QueueName); } try { WriteMessage(q, wrapper); } catch (Exception ex) { _log.Fatal("Cannot Process Any Audit Messages At this time, All Mitigations Have Failed, Multiple Systems Failure has Occurred, Error Queue Name: " + q.QueueName, ex); throw new ApplicationException("Cannot Accept Any Audit Messages At this time, All Mitigations Have Failed, Multiple Systems Failure has Occurred, Error Queue Name: " + q.QueueName, ex); } } finally { if (q != null) { q.Dispose(); } } returnMessage = "Audit Point Written to Error Q - Successful"; return(returnMessage); }
static void TestSerialization() { NGinnBPM.MessageBus.Impl.JsonMessageSerializer ser = new NGinnBPM.MessageBus.Impl.JsonMessageSerializer(); MessageWrapper mw = new MessageWrapper(); mw.Headers["Correlation-Id"] = "9389328492834.1"; mw.Headers["Deliver-At"] = DateTime.Now.AddDays(1).ToString(); mw.Body = new Ping { Id = "ala ma kota" }; StringWriter sw = new StringWriter(); ser.Serialize(mw, sw); log.Info("Serialized: {0}", sw.ToString()); MessageWrapper mw2 = (MessageWrapper) ser.Deserialize(new StringReader(sw.ToString())); log.Info("MW2: {0}", mw2); }
protected static ErrorContext CreateErrorContext(MessageRetrieved retrieved, MessageWrapper message, Exception ex, byte[] body) { var context = new ErrorContext(ex, message.Headers, message.Id, body, new TransportTransaction(), retrieved.DequeueCount); return(context); }
/// <summary> /// Receives a published message using the handler registered for the given type. /// </summary> /// <param name="messageWrapper"></param> /// <returns></returns> public virtual Task ReceiveMessageAsync(MessageWrapper messageWrapper) { return(_subscriberServiceHelper.ProccessMessageAsync(messageWrapper, Handlers)); }
public abstract Task Receive(MessageRetrieved retrieved, MessageWrapper message);
/// <summary> /// Receives a published message using the handler registered for the given type. /// </summary> /// <param name="messageWrapper"></param> /// <returns></returns> public virtual Task ReceiveMessageAsync(MessageWrapper messageWrapper) { return(_brokerClient.ProcessMessageAsync(messageWrapper)); }
public override void OnMessageWrapperRegistered(AbstractMessageWrapper messageWrapper) { base.OnMessageWrapperRegistered(messageWrapper); MessageWrapper.RegisterAction <PBTradingDeskOptionParams, ExceptionMessage> ((uint)BusinessMessageID.MSG_ID_RTN_TRADINGDESK_PRICING, OnTradingDeskOptionParams, OnErrorAction); }
public MessageReceivedEventArgs(MessageWrapper message) { Message = message; }
public Task ProccessMessageAsync(MessageWrapper messageWrapper, Dictionary <Type, Func <object, Task> > handlers) { return(_helper.ProccessMessageAsync(messageWrapper, handlers)); }
static void OnMessage(object sender, MessageEventArgs e) { var mWrapper = new MessageWrapper(e.Message); Handlers[0].Handle(mWrapper, _client); }
public void Listen() { while (true) { Byte[] data = new Byte[1024]; Stream.Read(data, 0, data.Length); MessageWrapper responseData = ByteArrayToObject(data); if (responseData.Phase == MessageWrapper.Phases.SENDIP) { ClientName = responseData.YourName; } if (responseData.Phase == MessageWrapper.Phases.ACKNOWLEDGE) { IsMyTurn = responseData.ActivePlayer == ClientName; } if (responseData.Phase == MessageWrapper.Phases.ATACK) { int[] points = new int[8]; points[0] = responseData.CellToHit; bool isPlaneHit = false; this.Dispatcher.Invoke((Action)(() => { foreach (var btn in SelfPlaneMap.Children) { var button = btn as CustomButton; if (button.Uid == responseData.CellToHit.ToString()) { if (button.IsHead == true) { button.Background = Brushes.Black; switch (button.HeadDirection) { case Direction.Up: points = GetHeadUpPlaneCoord(Convert.ToInt32(button.Uid)).GetPoints(); break; case Direction.Left: points = GetHeadLeftPlaneCoord(Convert.ToInt32(button.Uid)).GetPoints(); break; case Direction.Right: points = GetHeadRightPlaneCoord(Convert.ToInt32(button.Uid)).GetPoints(); break; case Direction.Down: points = GetHeadDownPlaneCoord(Convert.ToInt32(button.Uid)).GetPoints(); break; default: break; } isPlaneHit = true; DeadPlanes++; break; } else { button.Background = Brushes.Black; //isPlaneHit = true; break; } } } })); if (DeadPlanes == 3) { SendMessage(new MessageWrapper() { Phase = MessageWrapper.Phases.LOSE, Lost = true }, true); } else { SendMessage(new MessageWrapper() { Points = points, IsPlaneHit = isPlaneHit, Phase = MessageWrapper.Phases.HIT }, true); } ColorPoints(points, SelfPlaneMap, Brushes.Black); } if (responseData.Phase == MessageWrapper.Phases.HIT) { ColorPoints(responseData.Points, HitTargetMap, responseData.IsPlaneHit ? Brushes.Green : Brushes.Pink); SendMessage(new MessageWrapper() { Phase = MessageWrapper.Phases.LOSE, Lost = DeadPlanes == 3 ? true : false }); } if (responseData.Phase == MessageWrapper.Phases.END) { if (DeadPlanes < 3) { MessageBox.Show("You won the game! " + ClientName); } } } }
public async Task BroadCast(MessageWrapper data) { var bs = this.messageSerializer.SerializeBytes(data); await this.redisDatabaseSelector.Database.PublishAsync(BROAD_CAST_KEY, bs); }
async Task MovePoisonMessage(MessageWrapper message, string queue) { throw new Exception(); }
public void Serialize(MessageWrapper wrapper, Stream stream) { messageSerializer.Serialize(wrapper, stream); }
public ProtoBufPackageInfo(MessageWrapper msg) { Msg = msg; }
public void Send(MessageWrapper messageWrapper) { udpSendUtils.SendDeliveryConfirmationMessage(messageWrapper.MessageId); }
public async Task OnMessageQueuedToSubscriberAsync(string queueName, ReferenceWrapper subscriber, MessageWrapper messageWrapper) { var onMessageQueuedToSubscriber = MessageQueuedToSubscriber; if (onMessageQueuedToSubscriber != null) { await onMessageQueuedToSubscriber.Invoke(queueName, subscriber, messageWrapper); } if (_stats.TryGetValue(queueName, out var stats)) { stats.TotalReceived++; } }
public AuditMSMQProcessor(MessageWrapper Message) { _message = Message; }
public async Task OnMessageDeliveredAsync(string queueName, ReferenceWrapper subscriber, MessageWrapper messageWrapper) { var onMessageDelivered = MessageDelivered; if (onMessageDelivered != null) { await onMessageDelivered.Invoke(queueName, subscriber, messageWrapper); } if (_stats.TryGetValue(queueName, out var stats)) { stats.TotalDelivered++; } }