LCOV - code coverage report
Current view: top level - Cqrs/Bus - InProcessBus.cs Hit Total Coverage
Test: doc-coverage.info Lines: 8 18 44.4 %
Date: 2017-07-26

          Line data    Source code
       1             : #region Copyright
       2             : // // -----------------------------------------------------------------------
       3             : // // <copyright company="cdmdotnet Limited">
       4             : // //   Copyright cdmdotnet Limited. All rights reserved.
       5             : // // </copyright>
       6             : // // -----------------------------------------------------------------------
       7             : #endregion
       8             : 
       9             : using System;
      10             : using System.Collections.Concurrent;
      11             : using System.Collections.Generic;
      12             : using System.Diagnostics;
      13             : using System.Linq;
      14             : using cdmdotnet.Logging;
      15             : using Cqrs.Authentication;
      16             : using Cqrs.Commands;
      17             : using Cqrs.Configuration;
      18             : using Cqrs.Events;
      19             : using Cqrs.Messages;
      20             : using SpinWait = Cqrs.Infrastructure.SpinWait;
      21             : 
      22             : namespace Cqrs.Bus
      23             : {
      24             :         public class InProcessBus<TAuthenticationToken>
      25             :                 : ISendAndWaitCommandSender<TAuthenticationToken>
      26             :                 , IEventPublisher<TAuthenticationToken>
      27             :                 , IEventHandlerRegistrar
      28             :                 , ICommandHandlerRegistrar
      29             :                 , ICommandReceiver<TAuthenticationToken>
      30             :                 , IEventReceiver<TAuthenticationToken>
      31           0 :         {
      32             :                 private static RouteManager Routes { get; set; }
      33             : 
      34             :                 protected IAuthenticationTokenHelper<TAuthenticationToken> AuthenticationTokenHelper { get; private set; }
      35             : 
      36             :                 protected ICorrelationIdHelper CorrelationIdHelper { get; private set; }
      37             : 
      38             :                 protected IDependencyResolver DependencyResolver { get; private set; }
      39             : 
      40             :                 protected ILogger Logger { get; private set; }
      41             : 
      42             :                 protected IConfigurationManager ConfigurationManager { get; private set; }
      43             : 
      44             :                 protected IBusHelper BusHelper { get; private set; }
      45             : 
      46             :                 protected IDictionary<Guid, IList<IEvent<TAuthenticationToken>>> EventWaits { get; private set; }
      47             : 
      48             :                 protected ITelemetryHelper TelemetryHelper { get; set; }
      49             : 
      50             :                 static InProcessBus()
      51             :                 {
      52             :                         Routes = new RouteManager();
      53             :                 }
      54             : 
      55           0 :                 public InProcessBus(IAuthenticationTokenHelper<TAuthenticationToken> authenticationTokenHelper, ICorrelationIdHelper correlationIdHelper, IDependencyResolver dependencyResolver, ILogger logger, IConfigurationManager configurationManager, IBusHelper busHelper)
      56             :                 {
      57             :                         AuthenticationTokenHelper = authenticationTokenHelper;
      58             :                         CorrelationIdHelper = correlationIdHelper;
      59             :                         DependencyResolver = dependencyResolver;
      60             :                         Logger = logger;
      61             :                         ConfigurationManager = configurationManager;
      62             :                         BusHelper = busHelper;
      63             :                         EventWaits = new ConcurrentDictionary<Guid, IList<IEvent<TAuthenticationToken>>>();
      64             :                         TelemetryHelper = configurationManager.CreateTelemetryHelper("Cqrs.InProcessBus.UseApplicationInsightTelemetryHelper", correlationIdHelper);
      65             :                 }
      66             : 
      67           0 :                 protected virtual void PrepareCommand<TCommand>(TCommand command)
      68             :                         where TCommand : ICommand<TAuthenticationToken>
      69             :                 {
      70             :                         if (command.AuthenticationToken == null || command.AuthenticationToken.Equals(default(TAuthenticationToken)))
      71             :                                 command.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
      72             :                         command.CorrelationId = CorrelationIdHelper.GetCorrelationId();
      73             : 
      74             :                         if (string.IsNullOrWhiteSpace(command.OriginatingFramework))
      75             :                                 command.OriginatingFramework = "Built-In";
      76             : 
      77             :                         var frameworks = new List<string>();
      78             :                         if (command.Frameworks != null)
      79             :                                 frameworks.AddRange(command.Frameworks);
      80             :                         frameworks.Add("Built-In");
      81             :                         command.Frameworks = frameworks;
      82             :                 }
      83             : 
      84           0 :                 protected virtual bool PrepareAndValidateCommand<TCommand>(TCommand command, out RouteHandlerDelegate commandHandler)
      85             :                         where TCommand : ICommand<TAuthenticationToken>
      86             :                 {
      87             :                         Type commandType = command.GetType();
      88             : 
      89             :                         if (command.Frameworks != null && command.Frameworks.Contains("Built-In"))
      90             :                         {
      91             :                                 Logger.LogInfo("The provided command has already been processed by the Built-In bus.", string.Format("{0}\\PrepareAndValidateEvent({1})", GetType().FullName, commandType.FullName));
      92             :                                 commandHandler = null;
      93             :                                 return false;
      94             :                         }
      95             : 
      96             :                         ICommandValidator<TAuthenticationToken, TCommand> commandValidator = null;
      97             :                         try
      98             :                         {
      99             :                                 commandValidator = DependencyResolver.Resolve<ICommandValidator<TAuthenticationToken, TCommand>>();
     100             :                         }
     101             :                         catch (Exception exception)
     102             :                         {
     103             :                                 Logger.LogDebug("Locating an ICommandValidator failed.", string.Format("{0}\\Handle({1})", GetType().FullName, commandType.FullName), exception);
     104             :                         }
     105             : 
     106             :                         if (commandValidator != null && !commandValidator.IsCommandValid(command))
     107             :                         {
     108             :                                 Logger.LogInfo("The provided command is not valid.", string.Format("{0}\\Handle({1})", GetType().FullName, commandType.FullName));
     109             :                                 commandHandler = null;
     110             :                                 return false;
     111             :                         }
     112             : 
     113             :                         PrepareCommand(command);
     114             : 
     115             :                         bool isRequired = BusHelper.IsEventRequired(commandType);
     116             : 
     117             :                         commandHandler = Routes.GetSingleHandler(command, isRequired);
     118             :                         // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
     119             :                         if (commandHandler == null)
     120             :                         {
     121             :                                 Logger.LogDebug(string.Format("The command handler for '{0}' is not required.", commandType.FullName));
     122             :                                 return false;
     123             :                         }
     124             : 
     125             :                         return true;
     126             :                 }
     127             : 
     128             :                 #region Implementation of ICommandSender<TAuthenticationToken>
     129             : 
     130             :                 void ICommandPublisher<TAuthenticationToken>.Publish<TCommand>(TCommand command)
     131             :                 {
     132             :                         Send(command);
     133             :                 }
     134             : 
     135           0 :                 public virtual void Send<TCommand>(TCommand command)
     136             :                         where TCommand : ICommand<TAuthenticationToken>
     137             :                 {
     138             :                         DateTimeOffset startedAt = DateTimeOffset.UtcNow;
     139             :                         Stopwatch mainStopWatch = Stopwatch.StartNew();
     140             :                         string responseCode = "200";
     141             :                         bool wasSuccessfull = false;
     142             : 
     143             :                         IDictionary<string, string> telemetryProperties = new Dictionary<string, string> { { "Type", "InProcessBus" } };
     144             :                         string telemetryName = string.Format("{0}/{1}", command.GetType().FullName, command.Id);
     145             :                         var telemeteredCommand = command as ITelemeteredMessage;
     146             :                         if (telemeteredCommand != null)
     147             :                                 telemetryName = telemeteredCommand.TelemetryName;
     148             :                         telemetryName = string.Format("Command/{0}", telemetryName);
     149             : 
     150             :                         try
     151             :                         {
     152             :                                 RouteHandlerDelegate commandHandler;
     153             :                                 if (!PrepareAndValidateCommand(command, out commandHandler))
     154             :                                         return;
     155             : 
     156             :                                 try
     157             :                                 {
     158             :                                         Action<IMessage> handler = commandHandler.Delegate;
     159             :                                         handler(command);
     160             :                                 }
     161             :                                 catch (Exception exception)
     162             :                                 {
     163             :                                         responseCode = "500";
     164             :                                         Logger.LogError("An issue occurred while trying to publish a command.", exception: exception, metaData: new Dictionary<string, object> {{"Command", command}});
     165             :                                         throw;
     166             :                                 }
     167             : 
     168             :                                 Logger.LogInfo(string.Format("A command was sent of type {0}.", command.GetType().FullName));
     169             :                                 wasSuccessfull = true;
     170             :                         }
     171             :                         finally
     172             :                         {
     173             :                                 mainStopWatch.Stop();
     174             :                                 TelemetryHelper.TrackDependency("InProcessBus/CommandBus", "Command", telemetryName, null, startedAt, mainStopWatch.Elapsed, responseCode, wasSuccessfull, telemetryProperties);
     175             :                         }
     176             :                 }
     177             : 
     178             :                 void ICommandPublisher<TAuthenticationToken>.Publish<TCommand>(IEnumerable<TCommand> commands)
     179             :                 {
     180             :                         Send(commands);
     181             :                 }
     182             : 
     183           0 :                 public virtual void Send<TCommand>(IEnumerable<TCommand> commands)
     184             :                         where TCommand : ICommand<TAuthenticationToken>
     185             :                 {
     186             :                         IEnumerable<TCommand> sourceCommands = commands.ToList();
     187             : 
     188             :                         DateTimeOffset startedAt = DateTimeOffset.UtcNow;
     189             :                         Stopwatch mainStopWatch = Stopwatch.StartNew();
     190             :                         string responseCode = "500";
     191             :                         bool wasSuccessfull = false;
     192             : 
     193             :                         IDictionary<string, string> telemetryProperties = new Dictionary<string, string> { { "Type", "InProcessBus" } };
     194             :                         string telemetryName = "Commands";
     195             :                         string telemetryNames = string.Empty;
     196             :                         foreach (TCommand command in sourceCommands)
     197             :                         {
     198             :                                 string subTelemetryName = string.Format("{0}/{1}", command.GetType().FullName, command.Id);
     199             :                                 var telemeteredCommand = command as ITelemeteredMessage;
     200             :                                 if (telemeteredCommand != null)
     201             :                                         subTelemetryName = telemeteredCommand.TelemetryName;
     202             :                                 telemetryNames = string.Format("{0}{1},", telemetryNames, subTelemetryName);
     203             :                         }
     204             :                         if (telemetryNames.Length > 0)
     205             :                                 telemetryNames = telemetryNames.Substring(0, telemetryNames.Length - 1);
     206             :                         telemetryProperties.Add("Commands", telemetryNames);
     207             : 
     208             :                         try
     209             :                         {
     210             :                                 foreach (TCommand command in sourceCommands)
     211             :                                         Send(command);
     212             : 
     213             :                                 responseCode = "200";
     214             :                                 wasSuccessfull = true;
     215             :                         }
     216             :                         finally
     217             :                         {
     218             :                                 mainStopWatch.Stop();
     219             :                                 TelemetryHelper.TrackDependency("InProcessBus/CommandBus", "Command", telemetryName, null, startedAt, mainStopWatch.Elapsed, responseCode, wasSuccessfull, telemetryProperties);
     220             :                         }
     221             :                 }
     222             : 
     223             :                 /// <summary>
     224             :                 /// Sends the provided <paramref name="command"></paramref> and waits for an event of <typeparamref name="TEvent"/>
     225             :                 /// </summary>
     226             :                 /// <param name="command">The <typeparamref name="TCommand"/> to send.</param>
     227             :                 /// <param name="eventReceiver">If provided, is the <see cref="IEventReceiver{TAuthenticationToken}" /> that the event is expected to be returned on.</param>
     228           1 :                 public virtual TEvent SendAndWait<TCommand, TEvent>(TCommand command, IEventReceiver<TAuthenticationToken> eventReceiver = null)
     229             :                         where TCommand : ICommand<TAuthenticationToken>
     230             :                 {
     231             :                         return SendAndWait<TCommand, TEvent>(command, -1, eventReceiver);
     232             :                 }
     233             : 
     234             :                 /// <summary>
     235             :                 /// Sends the provided <paramref name="command"></paramref> and waits for an event of <typeparamref name="TEvent"/> or exits if the specified timeout is expired.
     236             :                 /// </summary>
     237             :                 /// <param name="command">The <typeparamref name="TCommand"/> to send.</param>
     238             :                 /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see cref="F:System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param>
     239             :                 /// <param name="eventReceiver">If provided, is the <see cref="IEventReceiver{TAuthenticationToken}" /> that the event is expected to be returned on.</param>
     240           1 :                 public virtual TEvent SendAndWait<TCommand, TEvent>(TCommand command, int millisecondsTimeout, IEventReceiver<TAuthenticationToken> eventReceiver = null)
     241             :                         where TCommand : ICommand<TAuthenticationToken>
     242             :                 {
     243             :                         return SendAndWait(command, events => (TEvent)events.SingleOrDefault(@event => @events is TEvent), millisecondsTimeout, eventReceiver);
     244             :                 }
     245             : 
     246             :                 /// <summary>
     247             :                 /// Sends the provided <paramref name="command"></paramref> and waits for an event of <typeparamref name="TEvent"/> or exits if the specified timeout is expired.
     248             :                 /// </summary>
     249             :                 /// <param name="command">The <typeparamref name="TCommand"/> to send.</param>
     250             :                 /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param>
     251             :                 /// <param name="eventReceiver">If provided, is the <see cref="IEventReceiver{TAuthenticationToken}" /> that the event is expected to be returned on.</param>
     252           1 :                 public virtual TEvent SendAndWait<TCommand, TEvent>(TCommand command, TimeSpan timeout, IEventReceiver<TAuthenticationToken> eventReceiver = null)
     253             :                         where TCommand : ICommand<TAuthenticationToken>
     254             :                 {
     255             :                         long num = (long)timeout.TotalMilliseconds;
     256             :                         if (num < -1L || num > int.MaxValue)
     257             :                                 throw new ArgumentOutOfRangeException("timeout", timeout, "SpinWait_SpinUntil_TimeoutWrong");
     258             :                         return SendAndWait<TCommand, TEvent>(command, (int)timeout.TotalMilliseconds, eventReceiver);
     259             :                 }
     260             : 
     261             :                 /// <summary>
     262             :                 /// Sends the provided <paramref name="command"></paramref> and waits until the specified condition is satisfied an event of <typeparamref name="TEvent"/>
     263             :                 /// </summary>
     264             :                 /// <param name="command">The <typeparamref name="TCommand"/> to send.</param>
     265             :                 /// <param name="condition">A delegate to be executed over and over until it returns the <typeparamref name="TEvent"/> that is desired, return null to keep trying.</param>
     266             :                 /// <param name="eventReceiver">If provided, is the <see cref="IEventReceiver{TAuthenticationToken}" /> that the event is expected to be returned on.</param>
     267           1 :                 public virtual TEvent SendAndWait<TCommand, TEvent>(TCommand command, Func<IEnumerable<IEvent<TAuthenticationToken>>, TEvent> condition, IEventReceiver<TAuthenticationToken> eventReceiver = null)
     268             :                         where TCommand : ICommand<TAuthenticationToken>
     269             :                 {
     270             :                         return SendAndWait(command, condition, -1, eventReceiver);
     271             :                 }
     272             : 
     273             :                 /// <summary>
     274             :                 /// Sends the provided <paramref name="command"></paramref> and waits for an event of <typeparamref name="TEvent"/> or exits if the specified timeout is expired.
     275             :                 /// </summary>
     276             :                 /// <param name="command">The <typeparamref name="TCommand"/> to send.</param>
     277             :                 /// <param name="condition">A delegate to be executed over and over until it returns the <typeparamref name="TEvent"/> that is desired, return null to keep trying.</param>
     278             :                 /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see cref="F:System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param>
     279             :                 /// <param name="eventReceiver">If provided, is the <see cref="IEventReceiver{TAuthenticationToken}" /> that the event is expected to be returned on.</param>
     280           1 :                 public virtual TEvent SendAndWait<TCommand, TEvent>(TCommand command, Func<IEnumerable<IEvent<TAuthenticationToken>>, TEvent> condition, int millisecondsTimeout, IEventReceiver<TAuthenticationToken> eventReceiver = null)
     281             :                         where TCommand : ICommand<TAuthenticationToken>
     282             :                 {
     283             :                         DateTimeOffset startedAt = DateTimeOffset.UtcNow;
     284             :                         Stopwatch mainStopWatch = Stopwatch.StartNew();
     285             :                         string responseCode = "200";
     286             :                         bool wasSuccessfull = false;
     287             : 
     288             :                         IDictionary<string, string> telemetryProperties = new Dictionary<string, string> { { "Type", "InProcessBus" } };
     289             :                         string telemetryName = string.Format("{0}/{1}", command.GetType().FullName, command.Id);
     290             :                         var telemeteredCommand = command as ITelemeteredMessage;
     291             :                         if (telemeteredCommand != null)
     292             :                                 telemetryName = telemeteredCommand.TelemetryName;
     293             :                         telemetryName = string.Format("Command/{0}", telemetryName);
     294             : 
     295             :                         TEvent result;
     296             : 
     297             :                         try
     298             :                         {
     299             :                                 if (eventReceiver != null)
     300             :                                         throw new NotSupportedException("Specifying a different event receiver is not yet supported.");
     301             :                                 RouteHandlerDelegate commandHandler;
     302             :                                 if (!PrepareAndValidateCommand(command, out commandHandler))
     303             :                                         return (TEvent)(object)null;
     304             : 
     305             :                                 result = (TEvent)(object)null;
     306             :                                 EventWaits.Add(command.CorrelationId, new List<IEvent<TAuthenticationToken>>());
     307             : 
     308             :                                 Action<IMessage> handler = commandHandler.Delegate;
     309             :                                 handler(command);
     310             :                                 Logger.LogInfo(string.Format("A command was sent of type {0}.", command.GetType().FullName));
     311             :                                 wasSuccessfull = true;
     312             :                         }
     313             :                         finally
     314             :                         {
     315             :                                 mainStopWatch.Stop();
     316             :                                 TelemetryHelper.TrackDependency("InProcessBus/CommandBus", "Command", telemetryName, null, startedAt, mainStopWatch.Elapsed, responseCode, wasSuccessfull, telemetryProperties);
     317             :                         }
     318             : 
     319             :                         SpinWait.SpinUntil(() =>
     320             :                         {
     321             :                                 IList<IEvent<TAuthenticationToken>> events = EventWaits[command.CorrelationId];
     322             : 
     323             :                                 result = condition(events);
     324             : 
     325             :                                 return result != null;
     326             :                         }, millisecondsTimeout, SpinWait.DefaultSleepInMilliseconds);
     327             : 
     328             :                         TelemetryHelper.TrackDependency("InProcessBus/CommandBus", "Command/AndWait", string.Format("Command/AndWait{0}", telemetryName.Substring(7)), null, startedAt, mainStopWatch.Elapsed, responseCode, wasSuccessfull, telemetryProperties);
     329             :                         return result;
     330             :                 }
     331             : 
     332             :                 /// <summary>
     333             :                 /// Sends the provided <paramref name="command"></paramref> and waits for an event of <typeparamref name="TEvent"/> or exits if the specified timeout is expired.
     334             :                 /// </summary>
     335             :                 /// <param name="command">The <typeparamref name="TCommand"/> to send.</param>
     336             :                 /// <param name="condition">A delegate to be executed over and over until it returns the <typeparamref name="TEvent"/> that is desired, return null to keep trying.</param>
     337             :                 /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param>
     338             :                 /// <param name="eventReceiver">If provided, is the <see cref="IEventReceiver{TAuthenticationToken}" /> that the event is expected to be returned on.</param>
     339           1 :                 public virtual TEvent SendAndWait<TCommand, TEvent>(TCommand command, Func<IEnumerable<IEvent<TAuthenticationToken>>, TEvent> condition, TimeSpan timeout, IEventReceiver<TAuthenticationToken> eventReceiver = null)
     340             :                         where TCommand : ICommand<TAuthenticationToken>
     341             :                 {
     342             :                         long num = (long)timeout.TotalMilliseconds;
     343             :                         if (num < -1L || num > int.MaxValue)
     344             :                                 throw new ArgumentOutOfRangeException("timeout", timeout, "SpinWait_SpinUntil_TimeoutWrong");
     345             :                         return SendAndWait(command, condition, (int)timeout.TotalMilliseconds, eventReceiver);
     346             :                 }
     347             : 
     348             :                 #endregion
     349             : 
     350             :                 #region Implementation of IEventPublisher<TAuthenticationToken>
     351             : 
     352           0 :                 public virtual void Publish<TEvent>(TEvent @event)
     353             :                         where TEvent : IEvent<TAuthenticationToken>
     354             :                 {
     355             :                         DateTimeOffset startedAt = DateTimeOffset.UtcNow;
     356             :                         Stopwatch mainStopWatch = Stopwatch.StartNew();
     357             :                         string responseCode = "200";
     358             :                         bool wasSuccessfull = false;
     359             : 
     360             :                         IDictionary<string, string> telemetryProperties = new Dictionary<string, string> { { "Type", "InProcessBus" } };
     361             :                         string telemetryName = string.Format("{0}/{1}", @event.GetType().FullName, @event.Id);
     362             :                         var telemeteredEvent = @event as ITelemeteredMessage;
     363             :                         if (telemeteredEvent != null)
     364             :                                 telemetryName = telemeteredEvent.TelemetryName;
     365             :                         telemetryName = string.Format("Event/{0}", telemetryName);
     366             : 
     367             :                         try
     368             :                         {
     369             :                                 Type eventType = @event.GetType();
     370             : 
     371             :                                 if (@event.Frameworks != null && @event.Frameworks.Contains("Built-In"))
     372             :                                 {
     373             :                                         Logger.LogInfo("The provided event has already been processed by the Built-In bus.", string.Format("{0}\\PrepareAndValidateEvent({1})", GetType().FullName, eventType.FullName));
     374             :                                         return;
     375             :                                 }
     376             : 
     377             :                                 if (@event.AuthenticationToken == null || @event.AuthenticationToken.Equals(default(TAuthenticationToken)))
     378             :                                         @event.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
     379             :                                 @event.CorrelationId = CorrelationIdHelper.GetCorrelationId();
     380             : 
     381             :                                 if (string.IsNullOrWhiteSpace(@event.OriginatingFramework))
     382             :                                 {
     383             :                                         @event.TimeStamp = DateTimeOffset.UtcNow;
     384             :                                         @event.OriginatingFramework = "Built-In";
     385             :                                 }
     386             : 
     387             :                                 var frameworks = new List<string>();
     388             :                                 if (@event.Frameworks != null)
     389             :                                         frameworks.AddRange(@event.Frameworks);
     390             :                                 frameworks.Add("Built-In");
     391             :                                 @event.Frameworks = frameworks;
     392             : 
     393             :                                 bool isRequired;
     394             :                                 if (!ConfigurationManager.TryGetSetting(string.Format("{0}.IsRequired", eventType.FullName), out isRequired))
     395             :                                         isRequired = true;
     396             : 
     397             :                                 IEnumerable<Action<IMessage>> handlers = Routes.GetHandlers(@event, isRequired).Select(x => x.Delegate).ToList();
     398             :                                 // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
     399             :                                 if (!handlers.Any())
     400             :                                         Logger.LogDebug(string.Format("An event handler for '{0}' is not required.", eventType.FullName));
     401             : 
     402             :                                 foreach (Action<IMessage> handler in handlers)
     403             :                                 {
     404             :                                         IList<IEvent<TAuthenticationToken>> events;
     405             :                                         if (EventWaits.TryGetValue(@event.CorrelationId, out events))
     406             :                                                 events.Add(@event);
     407             :                                         handler(@event);
     408             :                                 }
     409             : 
     410             :                                 Logger.LogInfo(string.Format("An event was sent of type {0}.", eventType.FullName));
     411             :                                 wasSuccessfull = true;
     412             :                         }
     413             :                         catch (Exception exception)
     414             :                         {
     415             :                                 responseCode = "500";
     416             :                                 Logger.LogError("An issue occurred while trying to publish an event.", exception: exception, metaData: new Dictionary<string, object> { { "Event", @event } });
     417             :                                 throw;
     418             :                         }
     419             :                         finally
     420             :                         {
     421             :                                 mainStopWatch.Stop();
     422             :                                 TelemetryHelper.TrackDependency("InProcessBus/EventBus", "Event", telemetryName, null, startedAt, mainStopWatch.Elapsed, responseCode, wasSuccessfull, telemetryProperties);
     423             :                         }
     424             :                 }
     425             : 
     426           0 :                 public virtual void Publish<TEvent>(IEnumerable<TEvent> events)
     427             :                         where TEvent : IEvent<TAuthenticationToken>
     428             :                 {
     429             :                         IEnumerable<TEvent> sourceEvents = events.ToList();
     430             : 
     431             :                         DateTimeOffset startedAt = DateTimeOffset.UtcNow;
     432             :                         Stopwatch mainStopWatch = Stopwatch.StartNew();
     433             :                         string responseCode = "500";
     434             :                         bool wasSuccessfull = false;
     435             : 
     436             :                         IDictionary<string, string> telemetryProperties = new Dictionary<string, string> { { "Type", "InProcessBus" } };
     437             :                         string telemetryName = "Events";
     438             :                         string telemetryNames = string.Empty;
     439             :                         foreach (TEvent @event in sourceEvents)
     440             :                         {
     441             :                                 string subTelemetryName = string.Format("{0}/{1}", @event.GetType().FullName, @event.Id);
     442             :                                 var telemeteredCommand = @event as ITelemeteredMessage;
     443             :                                 if (telemeteredCommand != null)
     444             :                                         subTelemetryName = telemeteredCommand.TelemetryName;
     445             :                                 telemetryNames = string.Format("{0}{1},", telemetryNames, subTelemetryName);
     446             :                         }
     447             :                         if (telemetryNames.Length > 0)
     448             :                                 telemetryNames = telemetryNames.Substring(0, telemetryNames.Length - 1);
     449             :                         telemetryProperties.Add("Events", telemetryNames);
     450             : 
     451             :                         try
     452             :                         {
     453             :                                 foreach (TEvent @event in events)
     454             :                                         Publish(@event);
     455             : 
     456             :                                 responseCode = "200";
     457             :                                 wasSuccessfull = true;
     458             :                         }
     459             :                         finally
     460             :                         {
     461             :                                 mainStopWatch.Stop();
     462             :                                 TelemetryHelper.TrackDependency("InProcessBus/EventBus", "Event", telemetryName, null, startedAt, mainStopWatch.Elapsed, responseCode, wasSuccessfull, telemetryProperties);
     463             :                         }
     464             :                 }
     465             : 
     466             :                 #endregion
     467             : 
     468             :                 #region Implementation of IHandlerRegistrar
     469             : 
     470             :                 /// <summary>
     471             :                 /// Register an event or command handler that will listen and respond to events or commands.
     472             :                 /// </summary>
     473           1 :                 public virtual void RegisterHandler<TMessage>(Action<TMessage> handler, Type targetedType, bool holdMessageLock = true)
     474             :                         where TMessage : IMessage
     475             :                 {
     476             :                         Action<TMessage> registerableHandler = BusHelper.BuildTelemeteredActionHandler<TMessage, TAuthenticationToken>(TelemetryHelper, handler, holdMessageLock, "In-Process/Bus");
     477             : 
     478             :                         Routes.RegisterHandler(registerableHandler, targetedType);
     479             : 
     480             :                         TelemetryHelper.TrackEvent(string.Format("Cqrs/RegisterHandler/{0}", typeof(TMessage).FullName), new Dictionary<string, string> { { "Type", "In-Process/Bus" } });
     481             :                         TelemetryHelper.Flush();
     482             :                 }
     483             : 
     484             :                 /// <summary>
     485             :                 /// Register an event or command handler that will listen and respond to events or commands.
     486             :                 /// </summary>
     487           1 :                 public virtual void RegisterHandler<TMessage>(Action<TMessage> handler, bool holdMessageLock = true)
     488             :                         where TMessage : IMessage
     489             :                 {
     490             :                         RegisterHandler(handler, null, holdMessageLock);
     491             :                 }
     492             : 
     493             :                 #endregion
     494             : 
     495             :                 #region Implementation of ICommandReceiver
     496             : 
     497           0 :                 public virtual bool? ReceiveCommand(ICommand<TAuthenticationToken> command)
     498             :                 {
     499             :                         Send(command);
     500             :                         return true;
     501             :                 }
     502             : 
     503           0 :                 public virtual bool? ReceiveEvent(IEvent<TAuthenticationToken> @event)
     504             :                 {
     505             :                         Publish(@event);
     506             :                         return true;
     507             :                 }
     508             : 
     509             :                 void ICommandReceiver.Start()
     510             :                 {
     511             :                         // This is in-process so doesn't need to do anything
     512             :                 }
     513             : 
     514             :                 #endregion
     515             : 
     516             :                 #region Implementation of IEventReceiver
     517             : 
     518             :                 void IEventReceiver.Start()
     519             :                 {
     520             :                         // This is in-process so doesn't need to do anything
     521             :                 }
     522             : 
     523             :                 #endregion
     524             :         }
     525             : }

Generated by: LCOV version 1.10