public void Audit(SendOptions sendOptions, TransportMessage transportMessage) { // Revert the original body if needed (if any mutators were applied, forward the original body as received) transportMessage.RevertToOriginalBodyIfNeeded(); // Create a new transport message which will contain the appropriate headers var messageToForward = new TransportMessage(transportMessage.Id, transportMessage.Headers) { Body = transportMessage.Body, Recoverable = transportMessage.Recoverable, TimeToBeReceived = sendOptions.TimeToBeReceived.HasValue ? sendOptions.TimeToBeReceived.Value : transportMessage.TimeToBeReceived }; messageToForward.Headers[Headers.ProcessingMachine] = RuntimeEnvironment.MachineName; messageToForward.Headers[Headers.ProcessingEndpoint] = EndpointName; if (transportMessage.ReplyToAddress != null) { messageToForward.Headers[Headers.OriginatingAddress] = transportMessage.ReplyToAddress.ToString(); } // Send the newly created transport message to the queue MessageSender.Send(messageToForward, new SendOptions(sendOptions.Destination) { ReplyToAddress = Configure.PublicReturnAddress }); }
public void Defer(TransportMessage message, SendOptions sendOptions) { message.Headers[TimeoutManagerHeaders.RouteExpiredTimeoutTo] = sendOptions.Destination.ToString(); DateTime deliverAt; if (sendOptions.DelayDeliveryWith.HasValue) { deliverAt = DateTime.UtcNow + sendOptions.DelayDeliveryWith.Value; } else { if (sendOptions.DeliverAt.HasValue) { deliverAt = sendOptions.DeliverAt.Value; } else { throw new ArgumentException("A delivery time needs to be specified for Deferred messages"); } } message.Headers[TimeoutManagerHeaders.Expire] = DateTimeExtensions.ToWireFormattedString(deliverAt); try { MessageSender.Send(message, new SendOptions(TimeoutManagerAddress)); } catch (Exception ex) { Log.Error("There was a problem deferring the message. Make sure that DisableTimeoutManager was not called for your endpoint.", ex); throw; } }
void SendMessage(TransportMessage message, SendOptions sendOptions, IModel channel) { var destination = sendOptions.Destination; string callbackAddress; if (sendOptions.GetType().FullName.EndsWith("ReplyOptions") && message.Headers.TryGetValue(CallbackHeaderKey, out callbackAddress)) { destination = Address.Parse(callbackAddress); } //set our callback address if (!string.IsNullOrEmpty(CallbackQueue)) { message.Headers[CallbackHeaderKey] = CallbackQueue; } var properties = channel.CreateBasicProperties(); RabbitMqTransportMessageExtensions.FillRabbitMqProperties(message, sendOptions, properties); RoutingTopology.Send(channel, destination, message, properties); }
public static DeliveryOptions ToDeliveryOptions(this Dictionary<string, string> options) { var operation = options["Operation"].ToLower(); switch (operation) { case "publish": return new PublishOptions(Type.GetType(options["EventType"])) { ReplyToAddress = Address.Parse(options["ReplyToAddress"]) }; case "send": case "audit": var sendOptions = new SendOptions(options["Destination"]); ApplySendOptionSettings(sendOptions, options); return sendOptions; case "reply": var replyOptions = new ReplyOptions(Address.Parse(options["Destination"]), options["CorrelationId"]) { ReplyToAddress = Address.Parse(options["ReplyToAddress"]) }; ApplySendOptionSettings(replyOptions, options); return replyOptions; default: throw new Exception("Unknown operation: " + operation); } }
public static BrokeredMessage ToBrokeredMessage(this TransportMessage message, SendOptions options, SettingsHolder settings, bool expectDelay, Configure config) { var brokeredMessage = BrokeredMessageBodyConversion.InjectBody(message.Body); SetHeaders(message, options, settings, config, brokeredMessage); var timeToSend = DelayIfNeeded(options, expectDelay); if (timeToSend.HasValue) brokeredMessage.ScheduledEnqueueTimeUtc = timeToSend.Value; TimeSpan? timeToLive = null; if (message.TimeToBeReceived < TimeSpan.MaxValue) { timeToLive = message.TimeToBeReceived; } else if (options.TimeToBeReceived.HasValue && options.TimeToBeReceived < TimeSpan.MaxValue) { timeToLive = options.TimeToBeReceived.Value; } if (timeToLive.HasValue) { if (timeToLive.Value <= TimeSpan.Zero) return null; brokeredMessage.TimeToLive = timeToLive.Value; } GuardMessageSize(brokeredMessage); return brokeredMessage; }
public void RequiresImmediateDispatch_Should_Return_True_When_Immediate_Dispatch_Requested() { var options = new SendOptions(); options.RequireImmediateDispatch(); Assert.IsTrue(options.RequiredImmediateDispatch()); }
public void Send(TransportMessage message, SendOptions sendOptions) { Address destination = null; try { destination = DetermineDestination(sendOptions); var connectionInfo = connectionStringProvider.GetForDestination(sendOptions.Destination); var queue = new TableBasedQueue(destination, connectionInfo.Schema); if (sendOptions.EnlistInReceiveTransaction) { SqlTransaction currentTransaction; if (connectionStore.TryGetTransaction(connectionInfo.ConnectionString, out currentTransaction)) { queue.Send(message, sendOptions, currentTransaction.Connection, currentTransaction); } else { SqlConnection currentConnection; if (connectionStore.TryGetConnection(connectionInfo.ConnectionString, out currentConnection)) { queue.Send(message, sendOptions, currentConnection); } else { using (var connection = sqlConnectionFactory.OpenNewConnection(connectionInfo.ConnectionString)) { queue.Send(message, sendOptions, connection); } } } } else { // Suppress so that even if DTC is on, we won't escalate using (var tx = new TransactionScope(TransactionScopeOption.Suppress)) { using (var connection = sqlConnectionFactory.OpenNewConnection(connectionInfo.ConnectionString)) { queue.Send(message, sendOptions, connection); } tx.Complete(); } } } catch (SqlException ex) { if (ex.Number == 208) { ThrowQueueNotFoundException(destination, ex); } ThrowFailedToSendException(destination, ex); } catch (Exception ex) { ThrowFailedToSendException(destination, ex); } }
public async Task<ActionResult> SendTestMessage(SendTestMessage sendTestMessage) { try { var sendOptions = new SendOptions { ContentType = sendTestMessage.ContentType, Importance = sendTestMessage.Importance }; var message = new TestMessage { Text = sendTestMessage.MessageText }; var bus = await _busManager.GetBus(); var sentMessage = await bus.Send(message, sendOptions); return View("Index", new SendTestMessage { MessageSent = true, SentMessageId = sentMessage.MessageId }); } catch (Exception ex) { sendTestMessage.ErrorsOccurred = true; sendTestMessage.ErrorMessage = ex.ToString(); } return View("Index", sendTestMessage); }
public void SendOptions_GetCorrelationId_Should_Return_Null_When_No_CorrelationId_Configured() { var options = new SendOptions(); var correlationId = options.GetCorrelationId(); Assert.IsNull(correlationId); }
async void Simple(IEndpointInstance endpoint, SendOptions sendOptions, ILog log) { #region EnumCallback Message message = new Message(); Status response = await endpoint.Request<Status>(message, sendOptions); log.Info("Callback received with response:" + response); #endregion }
public void GetDeliveryDate_Should_Return_The_Configured_Delivery_Date() { var options = new SendOptions(); DateTimeOffset deliveryDate = new DateTime(2012, 12, 12, 12, 12, 12); options.DoNotDeliverBefore(deliveryDate); Assert.AreEqual(deliveryDate, options.GetDeliveryDate()); }
public async Task<ActionResult> SendIntMessage() { IntMessage message = new IntMessage(); SendOptions sendOptions = new SendOptions(); sendOptions.SetDestination("Samples.Callbacks.Receiver"); Task<int> statusTask = MvcApplication.Endpoint.Request<int>(message, sendOptions); return View("SendIntMessage", await statusTask); }
public async Task<ActionResult> SendEnumMessage() { EnumMessage message = new EnumMessage(); SendOptions sendOptions = new SendOptions(); sendOptions.SetDestination("Samples.Callbacks.Receiver"); Task<Status> statusTask = MvcApplication.BusSession.Request<Status>(message, sendOptions); return View("SendEnumMessage", await statusTask); }
async Task RequestImmediateDispatch(IPipelineContext context) { #region RequestImmediateDispatch SendOptions options = new SendOptions(); options.RequireImmediateDispatch(); await context.Send(new MyMessage(), options); #endregion }
public async Task<ActionResult> SendEnumMessage() { var message = new EnumMessage(); var sendOptions = new SendOptions(); sendOptions.SetDestination("Samples.Callbacks.Receiver"); Task<Status> statusTask = MvcApplication.EndpointInstance.Request<Status>(message, sendOptions); return View("SendEnumMessage", await statusTask.ConfigureAwait(false)); }
public async Task<ActionResult> SendObjectMessage() { ObjectMessage message = new ObjectMessage(); SendOptions sendOptions = new SendOptions(); sendOptions.SetDestination("Samples.Callbacks.Receiver"); Task<ObjectResponseMessage> responseTask = MvcApplication.Endpoint.Request<ObjectResponseMessage>(message, sendOptions); return View("SendObjectMessage", await responseTask); }
public async Task<ActionResult> SendObjectMessage() { var message = new ObjectMessage(); var sendOptions = new SendOptions(); sendOptions.SetDestination("Samples.Callbacks.Receiver"); Task<ObjectResponseMessage> responseTask = MvcApplication.EndpointInstance.Request<ObjectResponseMessage>(message, sendOptions); return View("SendObjectMessage", await responseTask.ConfigureAwait(false)); }
public void SendOptions_GetDestination_Should_Return_Null_When_No_Destination_Configured() { var options = new SendOptions(); var destination = options.GetDestination(); Assert.IsNull(destination); }
public void IsRoutingToThisEndpoint_Should_Return_True_When_Routed_To_This_Endpoint() { var options = new SendOptions(); options.RouteToThisEndpoint(); Assert.IsTrue(options.IsRoutingToThisEndpoint()); }
public void GetDeliveryDelay_Should_Return_The_Configured_Delay_TimeSpan() { var options = new SendOptions(); var delay = TimeSpan.FromMinutes(42); options.DelayDeliveryWith(delay); Assert.AreEqual(delay, options.GetDeliveryDelay()); }
public void IsRoutingToThisInstance_Should_Return_True_When_Routed_To_This_Instance() { var options = new SendOptions(); options.RouteToThisInstance(); Assert.IsTrue(options.IsRoutingToThisInstance()); }
/// <summary> /// Sends the given <paramref name="message"/> /// </summary> public void Send(TransportMessage message, SendOptions sendOptions) { var address = sendOptions.Destination; var queuePath = NServiceBus.MsmqUtilities.GetFullPath(address); var transactionType = GetTransactionTypeForSend(); if (message.TimeToBeReceived < MessageQueue.InfiniteTimeout && WillUseTransactionThatSupportsMultipleOperations(sendOptions.EnlistInReceiveTransaction, transactionType)) { throw new Exception($"Failed to send message to address: {address.Queue}@{address.Machine}. Sending messages with a custom TimeToBeReceived is not supported on transactional MSMQ."); } try { using (var q = new MessageQueue(queuePath, false, Settings.UseConnectionCache, QueueAccessMode.Send)) { using (var toSend = NServiceBus.MsmqUtilities.Convert(message)) { toSend.UseDeadLetterQueue = Settings.UseDeadLetterQueue; toSend.UseJournalQueue = Settings.UseJournalQueue; toSend.TimeToReachQueue = Settings.TimeToReachQueue; var replyToAddress = sendOptions.ReplyToAddress ?? message.ReplyToAddress; if (replyToAddress != null) { toSend.ResponseQueue = new MessageQueue(NServiceBus.MsmqUtilities.GetReturnAddress(replyToAddress.ToString(), address.ToString())); } if (sendOptions.EnlistInReceiveTransaction && UnitOfWork.HasActiveTransaction()) { q.Send(toSend, UnitOfWork.Transaction); } else { q.Send(toSend, transactionType); } } } } catch (MessageQueueException ex) { if (ex.MessageQueueErrorCode == MessageQueueErrorCode.QueueNotFound) { var msg = address == null ? "Failed to send message. Target address is null." : string.Format("Failed to send message to address: [{0}]", address); throw new QueueNotFoundException(address, msg, ex); } ThrowFailedToSendException(address, ex); } catch (Exception ex) { ThrowFailedToSendException(address, ex); } }
void SendMessage(TransportMessage message, SendOptions sendOptions, dynamic channel) { var destination = DetermineDestination(sendOptions); var properties = channel.CreateBasicProperties(); KafkaTransportMessageExtensions.FillKafkaProperties(message, sendOptions, properties); routingTopology.Send(channel, destination, message, properties); }
Address RequestorProvidedCallbackAddress(SendOptions sendOptions) { string callbackAddress; if (IsReply(sendOptions) && context.TryGet(CallbackHeaderKey, out callbackAddress)) { return Address.Parse(callbackAddress); } return null; }
public async Task Should_use_public_return_address_if_specified() { var behavior = new ApplyReplyToAddressBehavior("MyEndpoint", "MyInstance", "PublicAddress", null); var options = new SendOptions(); var context = CreateContext(options); await behavior.Invoke(context, ctx => TaskEx.CompletedTask); Assert.AreEqual("PublicAddress", context.Headers[Headers.ReplyToAddress]); }
static IOutgoingSendContext CreateContext(SendOptions options, bool fromHandler) { var message = new MyMessage(); var context = new OutgoingSendContext(new OutgoingLogicalMessage(message.GetType(), message), options, new RootContext(null, null, null)); if (fromHandler) { context.Extensions.Set(new PendingTransportOperations()); } return context; }
async void Simple() { IEndpointInstance endpoint = null; SendOptions sendOptions = new SendOptions(); #region EnumCallback Message message = new Message(); Status response = await endpoint.Request<Status>(message, sendOptions); Console.WriteLine("Callback received with response:" + response); #endregion }
public void SendOptions_GetDestination_Should_Return_Configured_Destination() { const string expectedDestination = "custom send destination"; var options = new SendOptions(); options.SetDestination(expectedDestination); var destination = options.GetDestination(); Assert.AreEqual(expectedDestination, destination); }
public async Task Should_default_to_setting_the_reply_to_header_to_this_endpoint() { var behavior = new ApplyReplyToAddressBehavior("MyEndpoint", "MyInstance", null, null); var options = new SendOptions(); var context = CreateContext(options); await behavior.Invoke(context, ctx => TaskEx.CompletedTask); Assert.AreEqual("MyEndpoint", context.Headers[Headers.ReplyToAddress]); }
void ISendMessages.Send(TransportMessage message, SendOptions sendOptions) { details = new SendDetails { Destination = sendOptions.Destination, Message = message }; messageReceived.Set(); }
private static bool OpRaiseEvent(byte __0, Il2CppSystem.Object __1, Photon.Realtime.RaiseEventOptions __2, SendOptions __3) // events sent by you { // event code == 4 if (__0 == 4) // 4 is sending cached events { return(DataOKToSend(__1)); } return(true); }
/// <summary> /// Send data to all connected peers /// </summary> /// <param name="writer">DataWriter with data</param> /// <param name="options">Send options (reliable, unreliable, etc.)</param> /// <param name="excludePeer">Excluded peer</param> public void SendToAll(NetDataWriter writer, SendOptions options, NetPeer excludePeer) { SendToAll(writer.Data, 0, writer.Length, options, excludePeer); }
public void Send(TransportMessage message, SendOptions sendOptions) { }
/// <inheritdoc/> internal override async Task <bool> SendEventAndExecuteAsync(ActorId targetId, Event e, Actor sender, EventGroup group, SendOptions options) { this.Assert(sender is StateMachine, "Only an actor can call 'SendEventAndExecuteAsync': avoid " + "calling it directly from the test method; instead call it through a test driver actor."); this.Assert(e != null, "{0} is sending a null event.", sender.Id); this.Assert(targetId != null, "{0} is sending event {1} to a null actor.", sender.Id, e); this.AssertExpectedCallerActor(sender, "SendEventAndExecuteAsync"); EnqueueStatus enqueueStatus = this.EnqueueEvent(targetId, e, sender, group, options, out Actor target); if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning) { this.RunActorEventHandler(target, null, false, sender as StateMachine); // Wait until the actor reaches quiescence. await(sender as StateMachine).ReceiveEventAsync(typeof(QuiescentEvent), rev => (rev as QuiescentEvent).ActorId == targetId); return(true); } // EnqueueStatus.EventHandlerNotRunning is not returned by EnqueueEvent // (even when the actor was previously inactive) when the event e requires // no action by the actor (i.e., it implicitly handles the event). return(enqueueStatus is EnqueueStatus.Dropped || enqueueStatus is EnqueueStatus.NextEventUnavailable); }
private static IntPtr patch_method(IntPtr __self, IntPtr parameters, byte opCode, SendOptions sendParams, EgMessageType messageType = EgMessageType.Operation) { /* * if (UnityEngine.Input.GetKey(UnityEngine.KeyCode.P)) * { * VRC.UI.PageWorldInfo pageWorldInfo = UnityEngine.Object.FindObjectsOfType<VRC.UI.PageWorldInfo>()[0]; * Console.WriteLine(pageWorldInfo.apiWorld.id); * } */ /* * Console.WriteLine("------------------------------"); * Console.WriteLine("opCode: " + opCode.ToString()); * Console.WriteLine("sendParams [channel]: " + sendParams.Channel.ToString()); * Console.WriteLine("sendParams [DeliveryMode]: " + sendParams.DeliveryMode.ToString()); * Console.WriteLine("sendParams [Encrypt]: " + sendParams.Encrypt.ToString()); * Console.WriteLine("messageType: " + messageType.ToString()); */ if (BlazeManager.GetForPlayer <bool>("Photon Serilize")) { if (sendParams.DeliveryMode == DeliveryMode.UnreliableUnsequenced && sendParams.Channel != 1) { return(true.Cast()); } } return((pPhotonPeer.InvokeOriginal(__self, new IntPtr[] { parameters, new IntPtr(opCode), sendParams.Cast(), new IntPtr((int)messageType) }) != null).Cast()); }
public void ClientSendPacket <T>(SendOptions options, ushort msgType, T messageData) where T : INetSerializable { ClientSendPacket(options, msgType, messageData.Serialize); }
public void Send(byte[] data, SendOptions options) { Send(data, 0, data.Length, options); }
public int GetMaxSinglePacketSize(SendOptions options) { return(_mtu - NetPacket.GetHeaderSize(SendOptionsToProperty(options))); }
static async Task AsyncMain() { Console.Title = "Endpoint1"; var endpointConfiguration = new EndpointConfiguration("Endpoint1"); #region UseTransport endpointConfiguration.UseTransport <LearningTransport>(); #endregion endpointConfiguration.UseSerialization <JsonSerializer>(); var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); Console.WriteLine("Press S to send a message"); Console.WriteLine("Press D to send a delayed message"); Console.WriteLine("Press E to send a message that will throw an exception"); Console.WriteLine("Press any key to exit"); #region StartMessageInteraction while (true) { var key = Console.ReadKey(); Console.WriteLine(); if (key.Key == ConsoleKey.D) { var message = new TheMessage(); var sendOptions = new SendOptions(); sendOptions.DelayDeliveryWith(TimeSpan.FromSeconds(10)); sendOptions.SetDestination("Endpoint2"); await endpointInstance.Send(message, sendOptions) .ConfigureAwait(false); Console.WriteLine("Sent a delayed message"); continue; } if (key.Key == ConsoleKey.S) { var message = new TheMessage(); var sendOptions = new SendOptions(); sendOptions.SetDestination("Endpoint2"); await endpointInstance.Send(message, sendOptions) .ConfigureAwait(false); Console.WriteLine("Sent a message"); continue; } if (key.Key == ConsoleKey.E) { var message = new TheMessage { ThrowException = true }; var sendOptions = new SendOptions(); sendOptions.SetDestination("Endpoint2"); await endpointInstance.Send(message, sendOptions) .ConfigureAwait(false); Console.WriteLine("Sent a message that will throw"); continue; } break; } #endregion Console.WriteLine("Message sent. Press any key to exit"); Console.ReadKey(); await endpointInstance.Stop() .ConfigureAwait(false); }
public void Send(TransportMessage message, SendOptions sendOptions) { throw new Exception("Simulated"); }
/// <summary> /// Sends an asynchronous <see cref="Event"/> to a machine. /// </summary> internal override void SendEvent(MachineId target, Event e, AsyncMachine sender, Guid opGroupId, SendOptions options) { EnqueueStatus enqueueStatus = this.EnqueueEvent(target, e, sender, opGroupId, out Machine targetMachine); if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning) { this.RunMachineEventHandler(targetMachine, null, false); } }
public void ClientSendPacket(SendOptions options, ushort msgType, System.Action <NetDataWriter> serializer) { Client.ClientSendPacket(options, msgType, serializer); }
/// <summary> /// Sends an <see cref="Event"/> to a machine. Returns immediately if the target machine was already /// running. Otherwise blocks until the machine handles the event and reaches quiescense. /// </summary> public override Task <bool> SendEventAndExecute(MachineId target, Event e, Guid opGroupId = default, SendOptions options = null) => this.SendEventAndExecuteAsync(target, e, opGroupId, options);
/// <summary> /// Sends an asynchronous <see cref="Event"/> to a machine. /// </summary> public override void SendEvent(MachineId target, Event e, Guid opGroupId = default, SendOptions options = null) => this.SendEvent(target, e, null, opGroupId, options);
public void Audit(SendOptions sendOptions, TransportMessage message) { ((dynamic)builder.Build(AuditerImplType)).Audit(sendOptions, message); }
/// <summary> /// Send data to all connected peers /// </summary> /// <param name="data">Data</param> /// <param name="options">Send options (reliable, unreliable, etc.)</param> /// <param name="excludePeer">Excluded peer</param> public void SendToAll(byte[] data, SendOptions options, NetPeer excludePeer) { SendToAll(data, 0, data.Length, options, excludePeer); }
public async Task DistributeScheduledAsync(UserEventMessage userEvent, bool isLastAttempt) { var links = userEvent.Links(); var parentContext = Activity.Current?.Context ?? default; using (var activity = Telemetry.Activities.StartActivity("DistributeUserEventScheduled", ActivityKind.Internal, parentContext, links: links)) { await userNotificationsStore.TrackAttemptAsync(userEvent); try { var user = await userStore.GetCachedAsync(userEvent.AppId, userEvent.UserId); if (user == null) { throw new DomainException(Texts.Notification_NoApp); } var app = await appStore.GetCachedAsync(userEvent.AppId); if (app == null) { throw new DomainException(Texts.Notification_NoUser); } var options = new SendOptions { App = app, User = user }; var notification = await CreateUserNotificationAsync(userEvent, options); notification.NotificationActivity = activity?.Context ?? default; try { await userNotificationsStore.InsertAsync(notification); } catch (UniqueConstraintException) { throw new DomainException(Texts.Notification_AlreadyProcessed); } foreach (var channel in channels) { if (notification.Channels.TryGetValue(channel.Name, out var notificationChannel)) { foreach (var configuration in notificationChannel.Status.Keys) { await channel.SendAsync(notification, notificationChannel.Setting, configuration, options, default); } } } log.LogInformation("Processed user event for app {appId} with ID {id} to topic {topic}.", userEvent.AppId, userEvent.EventId, userEvent.Topic); } catch (Exception ex) { if (isLastAttempt) { await userNotificationsStore.TrackFailedAsync(userEvent); } if (ex is DomainException domainException) { await logStore.LogAsync(userEvent.AppId, domainException.Message); } else { log.LogError(ex, "Failed to process user event for app {appId} with ID {id} to topic {topic}.", userEvent.AppId, userEvent.EventId, userEvent.Topic); throw; } } } }
public void ServerSendPacket <T>(long connectionId, SendOptions options, ushort msgType, T messageData) where T : INetSerializable { ServerSendPacket(connectionId, options, msgType, messageData.Serialize); }
/// <summary> /// Enqueues an event to the actor with the specified id. /// </summary> private EnqueueStatus EnqueueEvent(Actor actor, Event e, Actor sender, EventGroup group, SendOptions options) { EventOriginInfo originInfo; string stateName = null; if (sender is StateMachine senderStateMachine) { originInfo = new EventOriginInfo(sender.Id, senderStateMachine.GetType().FullName, NameResolver.GetStateNameForLogging(senderStateMachine.CurrentState)); stateName = senderStateMachine.CurrentStateName; } else if (sender is Actor senderActor) { originInfo = new EventOriginInfo(sender.Id, senderActor.GetType().FullName, string.Empty); } else { // Message comes from the environment. originInfo = new EventOriginInfo(null, "Env", "Env"); } EventInfo eventInfo = new EventInfo(e, originInfo) { MustHandle = options?.MustHandle ?? false, Assert = options?.Assert ?? -1 }; Guid opId = group == null ? Guid.Empty : group.Id; this.LogWriter.LogSendEvent(actor.Id, sender?.Id.Name, sender?.Id.Type, stateName, e, opId, isTargetHalted: false); return(actor.Enqueue(e, group, eventInfo)); }
static async Task AsyncMain() { Console.Title = "Samples.ServiceControl.RabbitMQAdapter.Sales"; const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ"; var random = new Random(); #region SalesConfiguration var endpointConfiguration = new EndpointConfiguration("Samples.ServiceControl.RabbitMQAdapter.Sales"); var transport = endpointConfiguration.UseTransport <RabbitMQTransport>(); transport.ConnectionString("host=localhost"); transport.UseDirectRoutingTopology(); endpointConfiguration.SendFailedMessagesTo("adapter_error"); endpointConfiguration.AuditProcessedMessagesTo("adapter_audit"); #endregion var recoverability = endpointConfiguration.Recoverability(); endpointConfiguration.UsePersistence <InMemoryPersistence>(); var chaos = new ChaosGenerator(); endpointConfiguration.RegisterComponents( registration: components => { components.ConfigureComponent(() => chaos, DependencyLifecycle.SingleInstance); }); recoverability.Immediate( customizations: immediate => { immediate.NumberOfRetries(0); }); recoverability.Delayed(delayed => delayed.NumberOfRetries(0)); recoverability.DisableLegacyRetriesSatellite(); endpointConfiguration.EnableInstallers(); var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); Console.WriteLine("Press enter to exit"); Console.WriteLine("Press 'o' to generate order"); Console.WriteLine("Press 'f' to toggle simulating of message processing failure"); while (true) { var key = Console.ReadKey(); Console.WriteLine(); if (key.Key == ConsoleKey.Enter) { break; } var lowerInvariant = char.ToLowerInvariant(key.KeyChar); if (lowerInvariant == 'o') { var orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray()); var shipOrder = new ShipOrder { OrderId = orderId, Value = random.Next(100) }; var sendOptions = new SendOptions(); sendOptions.SetDestination("Samples.ServiceControl.RabbitMQAdapter.Shipping"); await endpointInstance.Send(shipOrder, sendOptions) .ConfigureAwait(false); } if (lowerInvariant == 'f') { chaos.IsFailing = !chaos.IsFailing; Console.WriteLine($"Failure simulation is now turned {(chaos.IsFailing ? "on" : "off")}"); ConsoleHelper.ToggleTitle(); } } await endpointInstance.Stop() .ConfigureAwait(false); }
/// <inheritdoc/> internal override void SendEvent(ActorId targetId, Event e, Actor sender, EventGroup group, SendOptions options) { if (e is null) { string message = sender != null? string.Format("{0} is sending a null event.", sender.Id.ToString()) : "Cannot send a null event."; this.Assert(false, message); } if (sender != null) { this.Assert(targetId != null, "{0} is sending event {1} to a null actor.", sender.Id, e); } else { this.Assert(targetId != null, "Cannot send event {1} to a null actor.", e); } this.AssertExpectedCallerActor(sender, "SendEvent"); EnqueueStatus enqueueStatus = this.EnqueueEvent(targetId, e, sender, group, options, out Actor target); if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning) { this.RunActorEventHandler(target, null, false, null); } }
public void ServerSendPacket(long connectionId, SendOptions options, ushort msgType, System.Action <NetDataWriter> serializer) { Server.ServerSendPacket(connectionId, options, msgType, serializer); }
/// <inheritdoc/> public override void SendEvent(ActorId targetId, Event e, EventGroup group = null, SendOptions options = null) { var senderOp = this.Scheduler.GetExecutingOperation <ActorOperation>(); this.SendEvent(targetId, e, senderOp?.Actor, group, options); }
public void ClientSendPacket(SendOptions options, ushort msgType) { ClientSendPacket(options, msgType, null); }
public void Send(NetDataWriter dataWriter, SendOptions options) { Send(dataWriter.Data, 0, dataWriter.Length, options); }
/// <summary> /// Send data to all connected peers /// </summary> /// <param name="writer">DataWriter with data</param> /// <param name="options">Send options (reliable, unreliable, etc.)</param> public void SendToAll(NetDataWriter writer, SendOptions options) { SendToAll(writer.Data, 0, writer.Length, options); }
public void Send(byte[] data, int start, int length, SendOptions options) { //Prepare PacketProperty property = SendOptionsToProperty(options); int headerSize = NetPacket.GetHeaderSize(property); //Check fragmentation if (length + headerSize > _mtu) { if (options == SendOptions.Sequenced || options == SendOptions.Unreliable) { throw new Exception("Unreliable packet size > allowed (" + (_mtu - headerSize) + ")"); } int packetFullSize = _mtu - headerSize; int packetDataSize = packetFullSize - NetConstants.FragmentHeaderSize; int fullPacketsCount = length / packetDataSize; int lastPacketSize = length % packetDataSize; int totalPackets = fullPacketsCount + (lastPacketSize == 0 ? 0 : 1); NetUtils.DebugWrite("FragmentSend:\n" + " MTU: {0}\n" + " headerSize: {1}\n" + " packetFullSize: {2}\n" + " packetDataSize: {3}\n" + " fullPacketsCount: {4}\n" + " lastPacketSize: {5}\n" + " totalPackets: {6}", _mtu, headerSize, packetFullSize, packetDataSize, fullPacketsCount, lastPacketSize, totalPackets); if (totalPackets > ushort.MaxValue) { throw new Exception("Too many fragments: " + totalPackets + " > " + ushort.MaxValue); } int dataOffset = headerSize + NetConstants.FragmentHeaderSize; for (ushort i = 0; i < fullPacketsCount; i++) { NetPacket p = _packetPool.Get(property, packetFullSize); p.FragmentId = _fragmentId; p.FragmentPart = i; p.FragmentsTotal = (ushort)totalPackets; p.IsFragmented = true; Buffer.BlockCopy(data, i * packetDataSize, p.RawData, dataOffset, packetDataSize); SendPacket(p); } if (lastPacketSize > 0) { NetPacket p = _packetPool.Get(property, lastPacketSize + NetConstants.FragmentHeaderSize); p.FragmentId = _fragmentId; p.FragmentPart = (ushort)fullPacketsCount; //last p.FragmentsTotal = (ushort)totalPackets; p.IsFragmented = true; Buffer.BlockCopy(data, fullPacketsCount * packetDataSize, p.RawData, dataOffset, lastPacketSize); SendPacket(p); } _fragmentId++; return; } //Else just send NetPacket packet = _packetPool.GetWithData(property, data, start, length); SendPacket(packet); }
private async Task <UserNotification> CreateUserNotificationAsync(UserEventMessage userEvent, SendOptions options) { using (Telemetry.Activities.StartActivity("CreateUserNotification")) { var notification = userNotificationFactory.Create(options.App, options.User, userEvent); if (notification == null) { throw new DomainException(Texts.Notification_NoSubject); } foreach (var channel in channels) { if (channel.IsSystem && !string.IsNullOrWhiteSpace(channel.Name)) { if (!notification.Channels.TryGetValue(channel.Name, out var channelInfo)) { channelInfo = new UserNotificationChannel { Setting = new ChannelSetting { Send = ChannelSend.Send } }; notification.Channels[channel.Name] = channelInfo; } } if (notification.Channels.TryGetValue(channel.Name, out var channelConfig) && channelConfig.Setting.Send == ChannelSend.Send) { var configurations = channel.GetConfigurations(notification, channelConfig.Setting, options); foreach (var configuration in configurations) { if (!string.IsNullOrWhiteSpace(configuration)) { channelConfig.Status[configuration] = new ChannelSendInfo(); await userNotificationsStore.CollectAsync(notification, channel.Name, ProcessStatus.Attempt); } } } } return(notification); } }
public void Send(TransportMessage message, SendOptions sendOptions) { Message = message; Options = sendOptions; }
public void ServerSendPacket(long connectionId, SendOptions options, ushort msgType) { ServerSendPacket(connectionId, options, msgType, null); }