Skip to content

Instantly share code, notes, and snippets.

View ramonsmits's full-sized avatar

Ramon Smits ramonsmits

View GitHub Profile
@ramonsmits
ramonsmits / Program.cs
Created May 5, 2017 13:40
Global mutex preventing multiple instances
class Program
{
static Mutex SingleInstanceMutex = AcquireGlobalMutex("Receiver");
static Mutex AcquireGlobalMutex(string id, int durationInSeconds = 1)
{
var m = new Mutex(true, @"Global\" + id);
var maxWaitDuration = TimeSpan.FromSeconds(durationInSeconds);
if (!m.WaitOne(maxWaitDuration)) throw new InvalidOperationException("Failed to acquire mutex.");
return m;
@ramonsmits
ramonsmits / SendDoSomethingTask.cs
Last active July 5, 2017 12:55
NServiceBus scheduler alternative - NServiceBus V6 & NServiceBus.Host V7
public class SendDoSomethingTask : IWantToRunWhenEndpointStartsAndStops
{
ILog log = LogManager.GetLogger<SendDoSomethingTask>();
Task loop;
CancellationTokenSource cancellationTokenSource;
public Task Start(IMessageSession session)
{
cancellationTokenSource = new CancellationTokenSource();
loop = Task.Run(async () =>
@ramonsmits
ramonsmits / LogDispatchedMessageIdBehavior.cs
Created July 11, 2017 13:17
Log the message ID's from the messages that have been dispatched to the transport
using System;
using System.Threading.Tasks;
using NServiceBus.Logging;
using NServiceBus.Pipeline;
/// <code>
/// endpointConfiguration.Pipeline.Register(behavior: new LogDispatchedMessageIdBehavior(), description: LogDispatchedMessageIdBehavior.Description);
/// </code>
class LogDispatchedMessageIdBehavior : Behavior<IBatchDispatchContext>
{
@ramonsmits
ramonsmits / MetricsViaPerformanceCounters.cs
Created August 1, 2017 11:33
Metrics published via performance counter. Shows a simple way to create and/or update counters
using System;
using System.Diagnostics;
using System.Linq;
interface IMetrics
{
void UpdateDuration(Stopwatch value);
}
class MetricsViaPerformanceCounters : IDisposable, IMetrics
@ramonsmits
ramonsmits / ExponentialBackoffPolicy.cs
Last active October 10, 2017 20:54
NServiceBus custom recoverability policy - Exponential backoff with jitter
using System;
using NServiceBus;
using NServiceBus.Transport;
class ExponentialBackoffPolicy
{
static Random random = new Random();
public static RecoverabilityAction Process(RecoverabilityConfig config, ErrorContext context)
{
@ramonsmits
ramonsmits / StartableEndpointExtensions.cs
Created February 13, 2018 18:43
NServiceBus StartWithRetry extension method to retry the start for a number of times
static class StartableEndpointExtensions
{
public static async Task<IEndpointInstance> StartWithRetry(
this IStartableEndpoint startableEndpoint,
int maxAttempts = 10
)
{
var attempts = 0;
while (true)
{
@ramonsmits
ramonsmits / ShippingSpeedMetricCollector.cs
Last active March 14, 2018 12:39
Business metric collector and calculation sample using NServiceBus events and sagas
using System;
using System.Threading.Tasks;
using NServiceBus;
class ShippingSpeedMetricCollector
: Saga<ShippingSpeedData>
, IAmStartedByMessages<OrderCreated>
, IHandleMessages<OrderCancelled>
, IHandleMessages<OrderShipped>
{
@ramonsmits
ramonsmits / RavenBatchOptimizer.cs
Created March 16, 2018 12:15
Code sample provided by RavenHQ for batching up writes
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Raven.Client;
/// <summary>
/// This class allows performing high throughput document store operations, using a batching mechanism
/// That mechanism collects up to 128 documents into a single batch and stores them in a single operation, reducing
@ramonsmits
ramonsmits / .cs
Created March 20, 2018 14:35
NServiceBus: Run the installers by invoking `endpointConfiguration.EnableInstallers()` and then `Endpoint.Create(..)` to run installers but not start the endpoint instance
if (args.Length == 1 && args[0] == "install")
{
await Console.Out.WriteLineAsync("Running installers...").ConfigureAwait(false);
var endpointConfiguration = CreateConfiguration();
endpointConfiguration.EnableInstallers();
await Endpoint.Create(endpointConfiguration).ConfigureAwait(false);
return; // Exit application, we are not going to start the endpoint and process messages
}
@ramonsmits
ramonsmits / .cs
Created March 22, 2018 13:51
NServiceBus add StackTrace information to outgoing message
// Via send options.
var sendOptions = new SendOptions();
sendOptions.SetHeader("StackTrace", System.Environment.StackTrace);
await context.Send(myMessage, sendOptions).ConfigureAwait(false);
// Via outgoing message mutator, requires registering the mutator via the endpoint configuration.
class AddStackTraceMutator : IMutateOutgoingTransportMessages
{
public Task MutateOutgoing(MutateOutgoingTransportMessageContext context)