protected override Task OnStart(IMessageSession session)
                {
                    context.SettingIsAvailable = settings != null;

                    context.IsDone = true;
                    return Task.FromResult(0);
                }
            protected override Task OnStart(IMessageSession session)
            {
                counter = PerformanceCounterHelper.InstantiatePerformanceCounter("SLA violation countdown", counterInstanceName);
                timer = new Timer(RemoveOldDataPoints, null, 0, 2000);

                return TaskEx.CompletedTask;
            }
            protected override Task OnStop(IMessageSession session)
            {
                timer.Dispose();
                counter.Dispose();

                return TaskEx.CompletedTask;
            }
 static Task SendHandlerMessage(IMessageSession endpointInstance)
 {
     Console.WriteLine();
     Console.WriteLine("HandlerMessage sent");
     var message = new HandlerMessage();
     return endpointInstance.SendLocal(message);
 }
 protected override async Task OnStart(IMessageSession session)
 {
     foreach (var eventType in messagesHandledByThisEndpoint)
     {
         await session.Subscribe(eventType).ConfigureAwait(false);
         Logger.DebugFormat("Auto subscribed to event {0}", eventType);
     }
 }
        public Task StopFeatures(IMessageSession session)
        {
            var featureStopTasks = features.Where(f => f.Feature.IsActive)
                .SelectMany(f => f.TaskControllers)
                .Select(task => task.Stop(session));

            return Task.WhenAll(featureStopTasks);
        }
Exemple #7
0
 protected override async Task OnStart(IMessageSession session)
 {
     var result = await lazy.Value.PreStartupCheck().ConfigureAwait(false);
     if (!result.Succeeded)
     {
         throw new Exception("Pre start-up check failed: " + result.ErrorMessage);
     }
 }
 public Task Start(IMessageSession session)
 {
     ErrorsNotifications errors = busNotifications.Errors;
     errors.MessageHasBeenSentToSecondLevelRetries += (sender, retry) => LogToConsole(retry);
     errors.MessageHasFailedAFirstLevelRetryAttempt += (sender, retry) => LogToConsole(retry);
     errors.MessageSentToErrorQueue += (sender, retry) => LogToConsole(retry);
     return Task.FromResult(0);
 }
            protected override Task OnStart(IMessageSession session)
            {
                cancellationTokenSource = new CancellationTokenSource();

                NotifyEndpointStartup(DateTime.UtcNow);
                StartHeartbeats();

                return Task.FromResult(0);
            }
 public async Task StartFeatures(IBuilder builder, IMessageSession session)
 {
     foreach (var feature in features.Where(f => f.Feature.IsActive))
     {
         foreach (var taskController in feature.TaskControllers)
         {
             await taskController.Start(builder, session).ConfigureAwait(false);
         }
     }
 }
            protected override Task OnStart(IMessageSession session)
            {
                context.RequestedAt = DateTime.UtcNow;

                return session.ScheduleEvery(TimeSpan.FromMilliseconds(5), "MyTask", c =>
                {
                    context.InvokedAt = DateTime.UtcNow;
                    return Task.FromResult(0);
                });
            }
 static Task SendSagaMessage(IMessageSession endpointInstance)
 {
     Console.WriteLine();
     Console.WriteLine("StartSagaMessage sent");
     var message = new StartSagaMessage
     {
         SentTime = DateTimeOffset.UtcNow,
         TheId = Guid.NewGuid()
     };
     return endpointInstance.SendLocal(message);
 }
            protected override Task OnStop(IMessageSession session)
            {
                using (var waitHandle = new ManualResetEvent(false))
                {
                    cleanupTimer.Dispose(waitHandle);

                    // TODO: Use async synchronization primitive
                    waitHandle.WaitOne();
                }
                return TaskEx.CompletedTask;
            }
            protected override Task OnStart(IMessageSession session)
            {
                timeToKeepDeduplicationData = settings.GetOrDefault<TimeSpan?>("Outbox.TimeToKeepDeduplicationData") ?? TimeSpan.FromDays(7);

                frequencyToRunDeduplicationDataCleanup = settings.GetOrDefault<TimeSpan?>("Outbox.FrequencyToRunDeduplicationDataCleanup") ?? TimeSpan.FromMinutes(1);

                cancellationTokenSource = new CancellationTokenSource();
                cancellationToken = cancellationTokenSource.Token;

                cleanupTask = Task.Run(() => PerformCleanup(), CancellationToken.None);

                return TaskEx.CompletedTask;
            }
            protected override async Task OnStop(IMessageSession session)
            {
                cancellationTokenSource.Cancel();

                // ReSharper disable once MethodSupportsCancellation
                var timeoutTask = Task.Delay(TimeSpan.FromSeconds(30));
                var finishedTask = await Task.WhenAny(cleanupTask, timeoutTask).ConfigureAwait(false);

                if (finishedTask == timeoutTask)
                {
                    logger.Error("RavenOutboxCleaner failed to stop within the time allowed (30s).");
                }
            }
 protected override async Task OnStart(IMessageSession busSession)
 {
     await Task.Delay(TimeSpan.FromMinutes(1));
     while (true)
     {
         await Task.Delay(frequencyToRunCleanup, cancellationTokenSource.Token);
         if (cancellationTokenSource.IsCancellationRequested)
         {
             break;
         }
         var dateTime = DateTime.UtcNow - timeToKeepDeduplicationData;
         await outboxPersister.RemoveEntriesOlderThan(dateTime, cancellationTokenSource.Token);
     }
 }
        public async Task Stop(IMessageSession messageSession)
        {
            try
            {
                await instance.PerformStop(messageSession).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Log.Warn($"Exception occurred during stopping of feature startup task '{Name}'.", exception);
            }
            finally
            {
                DisposeIfNecessary(instance);
            }

        }
    static async Task SendMessageLargePayload(IMessageSession messageSession)
    {
        Console.WriteLine("Sending message...");

        #region SendMessageLargePayload

        MessageWithLargePayload message = new MessageWithLargePayload
        {
            Description = "This message contains a large payload that will be sent on the Azure data bus",
            LargePayload = new DataBusProperty<byte[]>(new byte[1024*1024*5]) // 5MB
        };
        await messageSession.Send("Samples.AzureBlobStorageDataBus.Receiver", message);

        #endregion

        Console.WriteLine("Message sent.");
    }
        static Task Schedule(IMessageSession session, TaskDefinition taskDefinition)
        {
            logger.DebugFormat("Task '{0}' (with id {1}) scheduled with timeSpan {2}", taskDefinition.Name, taskDefinition.Id, taskDefinition.Every);

            var options = new SendOptions();
            options.DelayDeliveryWith(taskDefinition.Every);
            options.RouteToThisEndpoint();
            options.Context.GetOrCreate<ScheduleBehavior.State>().TaskDefinition = taskDefinition;

            var scheduledTask = new ScheduledTask
            {
                TaskId = taskDefinition.Id,
                Name = taskDefinition.Name,
                Every = taskDefinition.Every
            };
            return session.Send(scheduledTask, options);
        }
    static async Task Run(IMessageSession messageSession)
    {
        Console.WriteLine("Press 'Enter' to send a large message (>4MB)");
        Console.WriteLine("Press any other key to exit");

        while (true)
        {
            ConsoleKeyInfo key = Console.ReadKey();

            if (key.Key == ConsoleKey.Enter)
            {
                await SendMessageLargePayload(messageSession);
            }
            else
            {
                return;
            }
        }
    }
            protected override async Task OnStart(IMessageSession session)
            {
                if (!customChecks.Any())
                {
                    return;
                }

                timerPeriodicChecks = new List<TimerBasedPeriodicCheck>(customChecks.Count);
                serviceControlBackend = new ServiceControlBackend(dispatchMessages, settings, criticalError);
                await serviceControlBackend.VerifyIfServiceControlQueueExists().ConfigureAwait(false);

                foreach (var check in customChecks)
                {
                    var timerBasedPeriodicCheck = new TimerBasedPeriodicCheck(check, serviceControlBackend);
                    timerBasedPeriodicCheck.Start();

                    timerPeriodicChecks.Add(timerBasedPeriodicCheck);
                }
            }
Exemple #22
0
        protected override Task OnStart(IMessageSession session)
        {
            try
            {
                var sc = new ServiceController
                {
                    ServiceName = "MSDTC",
                    MachineName = "."
                };

                if (sc.Status == ServiceControllerStatus.Running)
                {
                    log.Warn(@"The MSDTC service is running on this machine.
Because Outbox is enabled disabling MSDTC is recommended. This ensures that the Outbox behavior is working as expected and no other resources are enlisting in distributed transactions.");
                }
            }
                // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {
                // Ignore if we can't check it.
            }

            return TaskEx.CompletedTask;
        }
        internal static IReadOnlyDictionary <string, object> CreateBindingData(Message value, MessageReceiver receiver, IMessageSession messageSession, IReadOnlyDictionary <string, object> bindingDataFromValueType)
        {
            var bindingData = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            SafeAddValue(() => bindingData.Add(nameof(value.SystemProperties.DeliveryCount), value.SystemProperties.DeliveryCount));
            SafeAddValue(() => bindingData.Add(nameof(value.SystemProperties.DeadLetterSource), value.SystemProperties.DeadLetterSource));
            SafeAddValue(() => bindingData.Add(nameof(value.SystemProperties.LockToken), value.SystemProperties.IsLockTokenSet ? value.SystemProperties.LockToken : string.Empty));
            SafeAddValue(() => bindingData.Add(nameof(value.ExpiresAtUtc), value.ExpiresAtUtc));
            SafeAddValue(() => bindingData.Add(nameof(value.SystemProperties.EnqueuedTimeUtc), value.SystemProperties.EnqueuedTimeUtc));
            SafeAddValue(() => bindingData.Add(nameof(value.MessageId), value.MessageId));
            SafeAddValue(() => bindingData.Add(nameof(value.ContentType), value.ContentType));
            SafeAddValue(() => bindingData.Add(nameof(value.ReplyTo), value.ReplyTo));
            SafeAddValue(() => bindingData.Add(nameof(value.SystemProperties.SequenceNumber), value.SystemProperties.SequenceNumber));
            SafeAddValue(() => bindingData.Add(nameof(value.To), value.To));
            SafeAddValue(() => bindingData.Add(nameof(value.Label), value.Label));
            SafeAddValue(() => bindingData.Add(nameof(value.CorrelationId), value.CorrelationId));
            SafeAddValue(() => bindingData.Add(nameof(value.UserProperties), value.UserProperties));
            SafeAddValue(() => bindingData.Add("MessageReceiver", receiver));
            SafeAddValue(() => bindingData.Add("MessageSession", messageSession));

            if (bindingDataFromValueType != null)
            {
                foreach (KeyValuePair <string, object> item in bindingDataFromValueType)
                {
                    // In case of conflict, binding data from the value type overrides the built-in binding data above.
                    bindingData[item.Key] = item.Value;
                }
            }

            return(bindingData);
        }
Exemple #24
0
 protected override Task OnStop(IMessageSession session, CancellationToken cancellationToken)
 {
     return(Task.FromResult(0));
 }
 public SessionMessageLockContext(IMessageSession session, Message message)
 {
     _session = session;
     _message = message;
 }
 protected override Task OnStop(IMessageSession session)
 {
     return(Task.CompletedTask);
 }
 protected override Task OnStop(IMessageSession session, CancellationToken cancellationToken)
 {
     return(Task.CompletedTask);
 }
Exemple #28
0
 protected override Task OnStart(IMessageSession session)
 {
     behavior.Warmup();
     return(TaskEx.CompletedTask);
 }
Exemple #29
0
 protected override Task OnStop(IMessageSession session)
 {
     return(Task.FromResult(true));
 }
Exemple #30
0
 protected override Task OnStop(IMessageSession session) => Task.CompletedTask;
Exemple #31
0
 protected override Task OnStop(IMessageSession session) => timer.Stop();
Exemple #32
0
 internal Task Start(IMessageSession session)
 {
     return(OnStart(session));
 }
Exemple #33
0
                    protected override async Task OnStart(IMessageSession session)
                    {
                        await BreakConnectionBySendingInvalidMessage();

                        await session.SendLocal(new MyRequest { MessageId = context.MessageId });
                    }
 public Task Start(IMessageSession session)
 {
     Logger.WriteLine("Inside IWantToRunWhenBusStartsAndStops.Start");
     return(Task.FromResult(0));
 }
Exemple #35
0
 public LineupState(IFixtureClient fixtureClient, IGetMatchDetails scraperApi, IGlobalSettingsClient globalSettingsClient, IMessageSession session, ILogger <LineupState> logger)
 {
     _fixtureClient        = fixtureClient;
     _scraperApi           = scraperApi;
     _globalSettingsClient = globalSettingsClient;
     _session         = session;
     _logger          = logger;
     _matchDetails    = new Dictionary <int, MatchDetails>();
     _currentFixtures = new List <Fixture>();
 }
Exemple #36
0
 public ScoringContoller(IScoringService scoringService, IMessageSession messageSession, IClock clock)
 {
     _scoringService = scoringService;
     _messageSession = messageSession;
     _clock          = clock;
 }
 public HomeController(IMessageSession messageSession,
                       StorageRepository storageRepository)
 {
     _messageSession    = messageSession;
     _storageRepository = storageRepository;
 }
 public Task Stop(IMessageSession session)
 {
     // perform shutdown logic
     return(Task.FromResult(0));
 }
Exemple #39
0
 public ValuesController(IMessageSession session)
 {
     this.session = session;
 }
 protected override Task OnStart(IMessageSession session)
 {
     cleanupTimer = new Timer(PerformCleanup, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
     return TaskEx.CompletedTask;
 }
 public SampleController(IMessageSession messageSession)
 {
     _messageSession = messageSession;
 }
 public Task Start(IMessageSession session)
 {
     // perform startup logic
     return Task.FromResult(0);
 }
Exemple #43
0
 protected override Task OnStart(IMessageSession session)
 {
     messageSession = session;
     return(Task.FromResult(true));
 }
Exemple #44
0
 public SenderWorker(IMessageSession messageSession, ILogger <SenderWorker> logger)
 {
     this.messageSession = messageSession;
     this.logger         = logger;
 }
 protected override Task OnStart(IMessageSession session)
 {
     subscriptionStorage?.Init();
     return(Task.CompletedTask);
 }
Exemple #46
0
 public HandlerWithIMessageSessionCtorDep(IMessageSession messageSession)
 {
     MessageSession = messageSession;
 }
Exemple #47
0
        async Task MessagePumpTaskAsync(IMessageSession session)
        {
            if (session == null)
            {
                return;
            }

            var renewLockCancellationTokenSource = new CancellationTokenSource();

            if (this.ShouldRenewSessionLock())
            {
                TaskExtensionHelper.Schedule(() => this.RenewSessionLockTaskAsync(session, renewLockCancellationTokenSource.Token));
            }

            var autoRenewLockCancellationTimer = new Timer(
                CancelAutoRenewLock,
                renewLockCancellationTokenSource,
                Timeout.Infinite,
                Timeout.Infinite);

            try
            {
                while (!this.pumpCancellationToken.IsCancellationRequested && !session.IsClosedOrClosing)
                {
                    Message message;
                    try
                    {
                        message = await session.ReceiveAsync(this.sessionHandlerOptions.MessageWaitTimeout).ConfigureAwait(false);
                    }
                    catch (Exception exception)
                    {
                        MessagingEventSource.Log.MessageReceivePumpTaskException(this.clientId, session.SessionId, exception);
                        if (exception is ServiceBusTimeoutException)
                        {
                            // Timeout Exceptions are pretty common. Not alerting the User on this.
                            continue;
                        }

                        if (!(exception is ObjectDisposedException && this.pumpCancellationToken.IsCancellationRequested))
                        {
                            await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Receive).ConfigureAwait(false);
                        }
                        break;
                    }

                    if (message == null)
                    {
                        MessagingEventSource.Log.SessionReceivePumpSessionEmpty(this.clientId, session.SessionId);
                        break;
                    }

                    bool     isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled();
                    Activity activity    = isDiagnosticSourceEnabled ? this.diagnosticSource.ProcessSessionStart(session, message) : null;
                    Task     processTask = null;

                    try
                    {
                        // Set the timer
                        autoRenewLockCancellationTimer.Change(this.sessionHandlerOptions.MaxAutoRenewDuration,
                                                              TimeSpan.FromMilliseconds(-1));
                        var callbackExceptionOccurred = false;
                        try
                        {
                            processTask = this.userOnSessionCallback(session, message, this.pumpCancellationToken);
                            await processTask.ConfigureAwait(false);
                        }
                        catch (Exception exception)
                        {
                            if (isDiagnosticSourceEnabled)
                            {
                                this.diagnosticSource.ReportException(exception);
                            }

                            MessagingEventSource.Log.MessageReceivePumpTaskException(this.clientId, session.SessionId, exception);
                            await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.UserCallback).ConfigureAwait(false);

                            callbackExceptionOccurred = true;
                            if (!(exception is MessageLockLostException || exception is SessionLockLostException))
                            {
                                await this.AbandonMessageIfNeededAsync(session, message).ConfigureAwait(false);
                            }
                        }
                        finally
                        {
                            autoRenewLockCancellationTimer.Change(Timeout.Infinite, Timeout.Infinite);
                        }

                        if (!callbackExceptionOccurred)
                        {
                            await this.CompleteMessageIfNeededAsync(session, message).ConfigureAwait(false);
                        }
                        else if (session.IsClosedOrClosing)
                        {
                            // If User closed the session as part of the callback, break out of the loop
                            break;
                        }
                    }
                    finally
                    {
                        this.diagnosticSource.ProcessSessionStop(activity, session, message, processTask?.Status);
                    }
                }
            }
            finally
            {
                renewLockCancellationTokenSource.Cancel();
                renewLockCancellationTokenSource.Dispose();
                autoRenewLockCancellationTimer.Dispose();

                await this.CloseSessionIfNeededAsync(session).ConfigureAwait(false);

                this.maxConcurrentSessionsSemaphoreSlim.Release();
            }
        }
Exemple #48
0
            protected override async Task OnStart(IMessageSession session, CancellationToken cancellationToken)
            {
                await session.SendLocal(new MyMessage(), cancellationToken : cancellationToken);

                await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
            }
Exemple #49
0
 public AddToCartPostHandler(IMessageSession messageSession)
 {
     this.messageSession = messageSession;
 }
Exemple #50
0
 public DocumentController(IMessageSession messageSession, IDocumentService svc)
 {
     this.messageSession = messageSession;
     this.svc            = svc;
 }
 public Task Stop(IMessageSession session)
 {
     // perform shutdown logic
     return Task.FromResult(0);
 }
Exemple #52
0
 public PublishEmployerAccountsEvents(IMessageSession messageSession)
 {
     _messageSession = messageSession;
 }
Exemple #53
0
 public Task Start(IServiceProvider builder, IMessageSession messageSession, CancellationToken cancellationToken)
 {
     return(featureActivator.StartFeatures(builder, messageSession, cancellationToken));
 }
Exemple #54
0
 public Service(IMessageSession bus)
 {
     _bus = bus;
 }
 public async Task Start(IMessageSession session)
 {
    await session.SendLocal(new MyMessage());
 }
 public Task Start(IMessageSession session)
 {
     // perform startup logic
     return(Task.FromResult(0));
 }
 public  Task Stop(IMessageSession session)
 {
     return Task.FromResult(0);
 }
 protected override Task OnStart(IMessageSession session)
 {
     return TaskEx.CompletedTask;
 }
 protected override Task OnStop(IMessageSession session)
 {
     queryTimeouts.Shutdown();
     return TaskEx.CompletedTask;
 }
 protected override Task OnStart(IMessageSession session)
 {
     timer.Start(() =>
     {
         ReloadData();
         return TaskEx.CompletedTask;
     }, checkInterval, ex => log.Error("Unable to update instance mapping information because the instance mapping file couldn't be read.", ex));
     return TaskEx.CompletedTask;
 }