private async Task ProcessMessagesAsync(ProcessMessageEventArgs args) { var message = args.Message; var messageText = message.Body.ToString(); Console.WriteLine($"Received message: {messageText}, delivery count: {message.DeliveryCount}"); /* * Note: Un-commenting below line will cause message to be 'abandoned' immediately. * Message delivery will be retried if max delivery count has not been exceeded. */ // throw new Exception("thrown deliberately"); /* * Note: un-commenting below line will cause message to be 'abandoned' immediately. * Message delivery will be retried if max delivery count has not been exceeded. */ // await args.AbandonMessageAsync(message); /* * Note: un-commenting below line will cause message to be 'deadlettered' immediately. * Message delivery will NOT be retried (irrespective of whether the message delivery count * has been exceeded or not). */ // await args.DeadLetterMessageAsync(message); /* * Note: un-commenting below line will cause message to be marked 'completed' immediately. * Technically this is not required since MessageHandlerOptions's 'autoComplete' is set to true by default. */ await args.CompleteMessageAsync(message); }
/// <summary> /// Tries to process the unhandled <paramref name="message"/> through an potential registered <see cref="IAzureServiceBusFallbackMessageHandler"/> instance. /// </summary> /// <param name="messageReceiver"> /// The instance that can receive Azure Service Bus <see cref="ServiceBusReceivedMessage"/>; used within <see cref="IAzureServiceBusFallbackMessageHandler"/>s with Azure Service Bus specific operations. /// </param> /// <param name="message">The message that was received by the <paramref name="messageReceiver"/>.</param> /// <param name="messageContext">The context in which the <paramref name="message"/> should be processed.</param> /// <param name="correlationInfo">The information concerning correlation of telemetry and processes by using a variety of unique identifiers.</param> /// <param name="cancellationToken">The token to cancel the message processing.</param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="messageReceiver"/>, <paramref name="message"/>, <paramref name="messageContext"/>, or <paramref name="correlationInfo"/> is <c>null</c>. /// </exception> protected async Task TryServiceBusFallbackMessageAsync( ServiceBusReceiver messageReceiver, ServiceBusReceivedMessage message, AzureServiceBusMessageContext messageContext, MessageCorrelationInfo correlationInfo, CancellationToken cancellationToken) { Guard.NotNull(message, nameof(message), "Requires an Azure Service Bus message to be processed by the registered fallback message handler"); Guard.NotNull(messageContext, nameof(messageContext), "Requires an Azure Service Bus message context in which the incoming message can be processed"); Guard.NotNull(correlationInfo, nameof(correlationInfo), "Requires an correlation information to correlate between incoming Azure Service Bus messages"); if (HasAzureServiceBusFallbackHandler) { if (_fallbackMessageHandler.Value is AzureServiceBusMessageHandlerTemplate template) { if (messageReceiver is null) { Logger.LogWarning("Fallback message handler '{MessageHandlerType}' uses specific Azure Service Bus operations, but is unable to be configured during message routing because the message router didn't receive a Azure Service Bus message receiver; use other '{RouteMessageAsync}' method overload", _fallbackMessageHandler.Value.GetType().Name, nameof(RouteMessageAsync)); } else { var args = new ProcessMessageEventArgs(message, messageReceiver, cancellationToken); template.SetProcessMessageEventArgs(args); } } string fallbackMessageHandlerTypeName = _fallbackMessageHandler.Value.GetType().Name; Logger.LogTrace("Fallback on registered '{FallbackMessageHandlerType}' because none of the message handlers w ere able to process the message", fallbackMessageHandlerTypeName); await _fallbackMessageHandler.Value.ProcessMessageAsync(message, messageContext, correlationInfo, cancellationToken); Logger.LogTrace("Fallback message handler '{FallbackMessageHandlerType}' has processed the message", fallbackMessageHandlerTypeName); } }
private async Task ProcessMessageAsync(ProcessMessageEventArgs args) { var eventTypeName = args.Message.ApplicationProperties["event-type"].ToString(); var(eventType, eventHandlerTypes) = _eventHandlerTypesMap.FirstOrDefault(mapper => mapper.Key.FullName == eventTypeName); if (eventHandlerTypes != null && eventHandlerTypes.Count > 0) { var taskSelect = eventHandlerTypes.Select(eventHandlerType => { using var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME); var eventHandler = scope.ResolveOptional(eventHandlerType); if (eventHandler == null) { return(Task.CompletedTask); } var integrationEvent = JsonConvert.DeserializeObject(args.Message.Body.ToString(), eventType); var concreteType = typeof(IIntegrationEventHandler <>).MakeGenericType(eventType); return((Task)concreteType.GetMethod("HandleAsync") ?.Invoke(eventHandler, new object[] { integrationEvent })); }); await Task.WhenAll(taskSelect); } await args.CompleteMessageAsync(args.Message); }
public void ProcessMessageAsync_LogsWarning_Disposed() { try { _listener.Disposed = true; var message = ServiceBusModelFactory.ServiceBusReceivedMessage( messageId: Guid.NewGuid().ToString(), sequenceNumber: 1, deliveryCount: 55, enqueuedTime: DateTimeOffset.Now, lockedUntil: DateTimeOffset.Now); var receiver = new Mock <ServiceBusReceiver>().Object; var args = new ProcessMessageEventArgs(message, receiver, CancellationToken.None); Assert.That( async() => await _listener.ProcessMessageAsync(args), Throws.InstanceOf <InvalidOperationException>()); Assert.NotNull(_loggerProvider.GetAllLogMessages() .SingleOrDefault( x => x.FormattedMessage.StartsWith("Message received for a listener that is not in a running state. The message will not be delivered to the function, " + "and instead will be abandoned. (Listener started = True, Listener disposed = True") && x.Level == LogLevel.Warning)); } finally { _listener.Disposed = false; _loggerProvider.ClearAllLogMessages(); } }
private async Task HandleMessageAsync(ProcessMessageEventArgs processMessageEventArgs) { try { var rawMessageBody = Encoding.UTF8.GetString(processMessageEventArgs.Message.Body.ToBytes().ToArray()); Logger.LogInformation("Received message {MessageId} with body {MessageBody}", processMessageEventArgs.Message.MessageId, rawMessageBody); var order = JsonConvert.DeserializeObject <TMessage>(rawMessageBody); if (order != null) { await ProcessMessage(order, processMessageEventArgs.Message.MessageId, processMessageEventArgs.Message.ApplicationProperties, processMessageEventArgs.CancellationToken); } else { Logger.LogError( "Unable to deserialize to message contract {ContractName} for message {MessageBody}", typeof(TMessage), rawMessageBody); } Logger.LogInformation("Message {MessageId} processed", processMessageEventArgs.Message.MessageId); await processMessageEventArgs.CompleteMessageAsync(processMessageEventArgs.Message); } catch (Exception ex) { Logger.LogError(ex, "Unable to handle message"); } }
public async Task UserSettledPropertySetCorrectly() { var msg = new ServiceBusReceivedMessage(); var args = new ProcessMessageEventArgs( msg, new Mock <ServiceBusReceiver>().Object, CancellationToken.None); Assert.IsFalse(msg.IsSettled); msg.IsSettled = false; await args.AbandonMessageAsync(msg); Assert.IsTrue(msg.IsSettled); await args.CompleteMessageAsync(msg); Assert.IsTrue(msg.IsSettled); msg.IsSettled = false; await args.DeadLetterMessageAsync(msg); Assert.IsTrue(msg.IsSettled); msg.IsSettled = false; await args.DeadLetterMessageAsync(msg, "reason"); Assert.IsTrue(msg.IsSettled); msg.IsSettled = false; await args.DeferMessageAsync(msg); Assert.IsTrue(msg.IsSettled); }
public async Task ProcessMessageAsync_Success() { var message = ServiceBusModelFactory.ServiceBusReceivedMessage( messageId: Guid.NewGuid().ToString(), sequenceNumber: 1, deliveryCount: 55, enqueuedTime: DateTimeOffset.Now, lockedUntil: DateTimeOffset.Now); var receiver = new Mock <ServiceBusReceiver>().Object; var args = new ProcessMessageEventArgs(message, receiver, CancellationToken.None); _mockMessageProcessor.Setup(p => p.BeginProcessingMessageAsync(It.IsAny <ServiceBusMessageActions>(), message, It.IsAny <CancellationToken>())).ReturnsAsync(true); FunctionResult result = new FunctionResult(true); _mockExecutor.Setup(p => p.TryExecuteAsync(It.Is <TriggeredFunctionData>(q => ((ServiceBusTriggerInput)q.TriggerValue).Messages[0] == message), It.IsAny <CancellationToken>())).ReturnsAsync(result); _mockMessageProcessor.Setup(p => p.CompleteProcessingMessageAsync(It.IsAny <ServiceBusMessageActions>(), message, result, It.IsAny <CancellationToken>())).Returns(Task.FromResult(0)); await _listener.ProcessMessageAsync(args); _mockMessageProcessor.VerifyAll(); _mockExecutor.VerifyAll(); _mockMessageProcessor.VerifyAll(); }
static async Task MessageHandler(ProcessMessageEventArgs args) { string body = args.Message.Body.ToString(); Console.WriteLine($"Received: {body}"); await args.CompleteMessageAsync(args.Message); }
private async Task Processor_ProcessMessageAsync(ProcessMessageEventArgs arg) { try { var message = arg.Message.Body.ToObjectFromJson <AzureInvalidationMessage>(EntityJsonContext.FullJsonSerializerOptions); if (message.CreationDate < StartTime) { return; } if (message.OriginMachineName == Environment.MachineName && message.OriginApplicationName == Schema.Current.ApplicationName) { return; } Receive?.Invoke(message.MethodName, message.Argument); await arg.CompleteMessageAsync(arg.Message); }catch (Exception ex) { ex.LogException(ex => ex.ControllerName = nameof(AzureServiceBusBroadcast)); } }
private void WriteProcessLog(ProcessMessageEventArgs e) { lock (_processLogsLocker) { Application.Current.Dispatcher.Invoke(() => this.ProcessLogs.Insert(0, e)); } }
private async Task MessageHandler(ProcessMessageEventArgs arg) { var eventName = arg.Message.Subject; if (_subscriptionManager.HasSubscriptionsForEvent(eventName)) { var subscriptions = _subscriptionManager.GetHandlersForEvent(eventName); foreach (var subscription in subscriptions) { var handler = _serviceProvider.GetService(subscription.HandlerType); if (handler == null) { continue; } var eventType = _subscriptionManager.GetEventTypeByName(eventName); var messageData = Encoding.UTF8.GetString(arg.Message.Body); var integrationEvent = JsonSerializer.Deserialize(messageData, eventType); var concreteType = typeof(IIntegrationEventHandler <>).MakeGenericType(eventType); await(Task) concreteType.GetMethod("HandleAsync").Invoke(handler, new object[] { integrationEvent }); await arg.CompleteMessageAsync(arg.Message); } } }
private async Task MessageHandlerAsync(ProcessMessageEventArgs arg) { var message = arg.Message; var body = Encoding.UTF8.GetString(message.Body.ToArray()); var data = JsonSerializer.Deserialize <TEntity>(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (ValidateMessage(data)) { if (await ProcessDataAsync(data).ConfigureAwait(false)) { // Now that we're done with "processing" the message, we tell the broker about that being the // case. The MessageReceiver.CompleteAsync operation will settle the message transfer with // the broker and remove it from the broker. await arg.CompleteMessageAsync(message) .ConfigureAwait(false); } else { // If the message does not meet our processing criteria, we will dead letter it, meaning // it is put into a special queue for handling defective messages. The broker will automatically // dead letter the message, if delivery has been attempted too many times. await arg.DeadLetterMessageAsync(message) .ConfigureAwait(false); } } }
internal async Task ProcessMessageAsync(ProcessMessageEventArgs args) { EnsureIsRunning(); _concurrencyUpdateManager?.MessageProcessed(); using (CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(args.CancellationToken, _cancellationTokenSource.Token)) { var actions = new ServiceBusMessageActions(args); if (!await _messageProcessor.Value.BeginProcessingMessageAsync(actions, args.Message, linkedCts.Token).ConfigureAwait(false)) { return; } var receiveActions = new ServiceBusReceiveActions(args); ServiceBusTriggerInput input = ServiceBusTriggerInput.CreateSingle(args.Message, actions, receiveActions, _client.Value); TriggeredFunctionData data = input.GetTriggerFunctionData(); FunctionResult result = await _triggerExecutor.TryExecuteAsync(data, linkedCts.Token).ConfigureAwait(false); try { await _messageProcessor.Value.CompleteProcessingMessageAsync(actions, args.Message, result, linkedCts.Token) .ConfigureAwait(false); } finally { receiveActions.EndExecutionScope(); } } }
private async Task OnMessageReceivedAsync(ProcessMessageEventArgs args) { var message = args.Message; _logger.LogDebug("Message received with ID {MessageId}", message.MessageId); await TriggerWorkflowsAsync(new ServiceBusMessage(message), CancellationToken.None); }
public Task onMessage(ProcessMessageEventArgs arg) { string body = arg.Message.Body.ToString(); var message = JsonTool.Deserialize <PubSubMessage>(body); switch (message.ContentType) { case ContentType.NMS_UPDATE: { var obj = JsonTool.Deserialize <ModelUpdateEvent>(message.Content); Handle(obj, null); break; } case ContentType.SCADA_UPDATE: { var obj = JsonTool.Deserialize <ScadaUpdateEvent>(message.Content); Handle(obj, null); break; } case ContentType.SCADA_HISTORY: { var obj = JsonTool.Deserialize <HistoryUpdateEvent>(message.Content); Handle(obj, null); break; } case ContentType.SCADA_DOM: { var obj = JsonTool.Deserialize <DomUpdateEvent>(message.Content); Handle(obj, null); break; } case ContentType.SCADA_HISTORY_GRAPH: { var obj = JsonTool.Deserialize <HistoryGraphicalEvent>(message.Content); Handle(obj, null); break; } case ContentType.CE_UPDATE: { var obj = JsonTool.Deserialize <CeUpdateEvent>(message.Content); Handle(obj, null); break; } case ContentType.CE_HISTORY_GRAPH: { var obj = JsonTool.Deserialize <CeGraphicalEvent>(message.Content); Handle(obj, null); break; } default: break; } return(arg.CompleteMessageAsync(arg.Message)); }
private async Task MessageHandler(ProcessMessageEventArgs args) { try { _logger.LogInformation($"client '{_systemInfo.ClientId}' received message '{args.Message.MessageId}'. Processing..."); var message = await _messageParser.DeserializeAsync <TM>(args.Message.Body); await _messageProcessor.ProcessAsync((dynamic)message, args.CancellationToken); await args.CompleteMessageAsync(args.Message).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, $"an error has occurred while processing message '{args.Message.MessageId}': {ex.Message}"); if (args.Message.DeliveryCount > 3) { await args.DeadLetterMessageAsync(args.Message).ConfigureAwait(false); } else { await args.AbandonMessageAsync(args.Message).ConfigureAwait(false); } } }
private async Task ProcessPayments(ProcessMessageEventArgs args) { var message = args.Message; var body = Encoding.UTF8.GetString(message.Body); PaymentRequestMessage paymentRequestMessage = JsonConvert.DeserializeObject <PaymentRequestMessage>(body); var result = _processPayment.PaymentProcessor(); UpdatePaymentResultMessage updatePaymentResultMessage = new() { Status = result, OrderId = paymentRequestMessage.OrderId, Email = paymentRequestMessage.Email }; try { await _messageBus.PublishMessage(updatePaymentResultMessage, orderupdatepaymentresulttopic); await args.CompleteMessageAsync(args.Message); } catch (Exception e) { throw; } } }
private static async Task MessageHandler(ProcessMessageEventArgs args, string subscription) { var message = args.Message; Console.WriteLine($"Received: {message.Body}, id {message.MessageId}, subscription {subscription}"); await args.CompleteMessageAsync(message); }
/// <summary> /// Handle a new <paramref name="message"/> that was received by routing them through registered <see cref="IAzureServiceBusMessageHandler{TMessage}"/>s /// and optionally through an registered <see cref="IFallbackMessageHandler"/> or <see cref="IAzureServiceBusFallbackMessageHandler"/> if none of the message handlers were able to process the <paramref name="message"/>. /// </summary> /// <param name="messageReceiver"> /// The instance that can receive Azure Service Bus <see cref="ServiceBusReceivedMessage"/>; used within <see cref="IMessageHandler{TMessage,TMessageContext}"/>s with Azure Service Bus specific operations. /// </param> /// <param name="message">The message that was received by the <paramref name="messageReceiver"/>.</param> /// <param name="messageContext">The context in which the <paramref name="message"/> should be processed.</param> /// <param name="correlationInfo">The information concerning correlation of telemetry and processes by using a variety of unique identifiers.</param> /// <param name="cancellationToken">The token to cancel the message processing.</param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="messageReceiver"/>, <paramref name="message"/>, <paramref name="messageContext"/>, or <paramref name="correlationInfo"/> is <c>null</c>. /// </exception> /// <exception cref="InvalidOperationException">Thrown when no message handlers or none matching message handlers are found to process the message.</exception> protected async Task RouteMessageWithPotentialFallbackAsync( ServiceBusReceiver messageReceiver, ServiceBusReceivedMessage message, AzureServiceBusMessageContext messageContext, MessageCorrelationInfo correlationInfo, CancellationToken cancellationToken) { Guard.NotNull(message, nameof(message), "Requires an Azure Service Bus message to be processed by the registered message handlers"); Guard.NotNull(messageContext, nameof(messageContext), "Requires an Azure Service Bus message context in which the incoming message can be processed"); Guard.NotNull(correlationInfo, nameof(correlationInfo), "Requires an correlation information to correlate between incoming Azure Service Bus messages"); try { MessageHandler[] messageHandlers = GetRegisteredMessageHandlers().ToArray(); if (messageHandlers.Length <= 0 && !HasFallbackMessageHandler && !HasAzureServiceBusFallbackHandler) { throw new InvalidOperationException( $"Azure Service Bus message pump cannot correctly process the message in the '{nameof(AzureServiceBusMessageContext)}' " + "because no 'IAzureServiceBusMessageHandler<>' was registered in the dependency injection container. " + $"Make sure you call the correct 'WithServiceBusMessageHandler' extension on the {nameof(IServiceCollection)} " + "during the registration of the Azure Service Bus message pump or message router to register a message handler"); } Encoding encoding = messageContext.GetMessageEncodingProperty(Logger); string messageBody = encoding.GetString(message.Body.ToArray()); foreach (MessageHandler messageHandler in messageHandlers) { MessageResult result = await DeserializeMessageForHandlerAsync(messageBody, messageContext, messageHandler); if (result.IsSuccess) { var args = new ProcessMessageEventArgs(message, messageReceiver, cancellationToken); SetServiceBusPropertiesForSpecificOperations(messageHandler, args, messageContext); await messageHandler.ProcessMessageAsync(result.DeserializedMessage, messageContext, correlationInfo, cancellationToken); return; } } if (!HasFallbackMessageHandler && !HasAzureServiceBusFallbackHandler) { throw new InvalidOperationException( $"Message pump cannot correctly process the message in the '{nameof(AzureServiceBusMessageContext)}' " + "because none of the registered 'IAzureServiceBusMessageHandler<,>' implementations in the dependency injection container matches the incoming message type and context; " + $"and no '{nameof(IFallbackMessageHandler)}' or '{nameof(IAzureServiceBusFallbackMessageHandler)}' was registered to fall back to." + $"Make sure you call the correct '.WithServiceBusMessageHandler' extension on the {nameof(IServiceCollection)} during the registration of the message pump or message router to register a message handler"); } await TryFallbackProcessMessageAsync(messageBody, messageContext, correlationInfo, cancellationToken); await TryServiceBusFallbackMessageAsync(messageReceiver, message, messageContext, correlationInfo, cancellationToken); } catch (Exception exception) { Logger.LogCritical(exception, "Unable to process message with ID '{MessageId}'", message.MessageId); throw; } }
public ServiceBusMessageStateHandler(ProcessMessageEventArgs processMessage, IMessageSerializer serializer, int deadLetterDeliveryLimit, IDependencyInjection messageScope) { DeadLetterDeliveryLimit = deadLetterDeliveryLimit; MessageScope = messageScope; _processMessage = processMessage; _sbMessage = processMessage.Message; _message = serializer.Deserialize <T>(_sbMessage.Body.ToMemory()); }
private async Task MessageHandlerAsync(ProcessMessageEventArgs args) { var messageAsString = args.Message.Body.ToString(); await _messageHandler(messageAsString); await args.CompleteMessageAsync(args.Message); }
private async Task _processor_ProcessMessageAsync(ProcessMessageEventArgs arg) { EndedHow = Ended.Success; _wait.Set(); await Task.CompletedTask; }
// handle received messages async Task MessageHandler(ProcessMessageEventArgs args) { var body = args.Message.Body.ToString(); _cacheContainerService.RefreshCache(body); // complete the message. messages is deleted from the subscription. await args.CompleteMessageAsync(args.Message); }
private async Task MessageHandler(ProcessMessageEventArgs e) { string data = e.Message.Body.ToString(); mensajes.Add(data); //DEBEMOS IR ELIMINANDO LOS MENSAJES DE LA COLA COMO LEIDOS/PROCESADOS await e.CompleteMessageAsync(e.Message); }
private async Task ClientOnProcessMessageAsync(ProcessMessageEventArgs arg) { var stateHandler = new ServiceBusMessageStateHandler <TTopic>(arg, _serializer, _deadLetterLimit, _hostConfiguration.DependencyInjection); using (var cts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken, arg.CancellationToken)) { await _processor.ProcessAsync(stateHandler, cts.Token).ConfigureAwait(false); } }
static async Task MessageHandler(ProcessMessageEventArgs args) { var body = args.Message.Body.ToString(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Received: {body}"); await args.CompleteMessageAsync(args.Message); }
// handle received messages static async Task MessageHandler(ProcessMessageEventArgs args) { string body = args.Message.Body.ToString(); Console.WriteLine($"Received: {body}"); // complete the message. messages is deleted from the queue. await args.CompleteMessageAsync(args.Message); }
private async Task ProcessMessageAsync(ProcessMessageEventArgs args) { logger.LogDebug("Processing message received by Service Bus"); // Services with scoped lifetime cannot be injected directly into a HostedService using var scope = serviceScopeFactory.CreateScope(); var pushNotifyer = scope.ServiceProvider.GetRequiredService <IPushNotifyer>(); await pushNotifyer.SendAsync(args.Message.Body.ToString(), "ANY"); }
// handle received messages static async Task MessageHandler(ProcessMessageEventArgs args) { string body = args.Message.Body.ToString(); _nomes.Add(body); // complete the message. messages is deleted from the queue. await args.CompleteMessageAsync(args.Message); }
static async Task ProcessMessagesAsync(ProcessMessageEventArgs args) { // Process the message. Console.WriteLine($"Received message: SequenceNumber:{args.Message.SequenceNumber} Body:{Encoding.UTF8.GetString(args.Message.Body)}"); // Complete the message so that it is not received again. // This can be done only if the queue Client is created in ReceiveMode.PeekLock mode (which is the default). await args.CompleteMessageAsync(args.Message); }
static void server_ProcessMessage(object sender, ProcessMessageEventArgs<MyContext> eventArgs) { Message request = eventArgs.Context.Request; Console.WriteLine(); Console.WriteLine("=========="); Console.WriteLine(); Console.WriteLine("request:"); Console.WriteLine("Timestamp: " + eventArgs.Timestamp); Console.WriteLine("TransportTime: " + eventArgs.TransitTime); Console.WriteLine(request.ToString()); Message response = eventArgs.Context.Response; if (request.Values.ContainsKey("Action")) { switch (request.Values["Action"]) { case "Time?": response.Values.Add("Return", "My local time is " + DateTime.Now); break; case "Write": if (request.Values.ContainsKey("Text")) Console.WriteLine(request.Values["Text"]); else response.ErrorMessage = "Text not set!"; break; default: response.ErrorMessage = "Unknown action '" + request.Values["Action"]; break; } } else response.ErrorMessage = "I don't know what to do with this message!"; Console.WriteLine(); Console.WriteLine("Response:"); Console.WriteLine(response); }
private void server_ProcessMessage(object sender, ProcessMessageEventArgs<WebHookContext> eventArgs) { var context = eventArgs.Context; var request = context.Request; var response = context.Response; if (eventArgs.TransitTime == null) { throw new WebCommunicator.Exceptions.CommunicationException("Transit Time not set."); } if (eventArgs.TransitTime.Value.TotalMinutes > 5) { throw new WebCommunicator.Exceptions.CommunicationException("Transit Time too long. (max time is 5 minutes, transit time for this message was " + eventArgs.TransitTime + ")"); } if (!request.Values.ContainsKey("Action")) { throw new WebCommunicator.Exceptions.CommunicationException("Action not set."); } string action = request.Values["Action"]; if (!actionHandlers.ContainsKey(action)) { throw new WebCommunicator.Exceptions.CommunicationException("I don't know how to handle that action. (" + action + ")"); } if (context.Computer == null) { response.ErrorMessage = "computer is null. (14729)"; return; } if (context.User == null) { response.ErrorMessage = "user is null. (85621)"; return; } actionHandlers[action].ProcessMessage(context); context.Database.Dispose(); }