Exemplo n.º 1
0
        protected ResponsePacket InvokeHandler(Session session, Dictionary <string, object> parms)
        {
            ResponsePacket ret = null;

            handler.IfNotNull((h) => ret = h(session, parms));

            return(ret);
        }
Exemplo n.º 2
0
        public static long Write(
            int howMany,
            Func <int, IEvent> createEvent = null,
            Func <EventStoreDbContext> createEventStore = null,
            bool randomEventTypes   = false,
            bool saveAfterEachEvent = false)
        {
            if (createEvent == null)
            {
                if (randomEventTypes)
                {
                    createEvent = CreateRandomEvent;
                }
                else
                {
                    createEvent = CreateOrderItemAddedEvent;
                }
            }

            using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
                using (var eventStore = createEventStore.IfNotNull()
                                        .Then(c => c())
                                        .Else(() => EventStoreDbContext()))
                {
                    Enumerable.Range(1, howMany).ForEach(i =>
                    {
                        var e = createEvent(i);

                        e.IfTypeIs <Event>()
                        .ThenDo(ev =>
                        {
                            if (ev.AggregateId == Guid.Empty)
                            {
                                ev.AggregateId = Guid.NewGuid();
                            }

                            if (ev.SequenceNumber == 0)
                            {
                                ev.SequenceNumber = i;
                            }

                            if (saveAfterEachEvent)
                            {
                                eventStore.SaveChanges();
                            }
                        });

                        var storableEvent = e.ToStorableEvent();

                        eventStore.Events.Add(storableEvent);
                    });

                    eventStore.SaveChanges();

                    return(eventStore.HighestEventId());
                }
        }
Exemplo n.º 3
0
        public static long Write(int howMany,
                                 Func <int, IEvent> createEvent = null,
                                 Func <EventStoreDbContext> createEventStore = null)
        {
            createEvent = createEvent ?? (i => new Order.ItemAdded
            {
                SequenceNumber = i,
                AggregateId = Recipes.Any.Guid(),
                Price = 1.99m,
                ProductName = Recipes.Any.Paragraph(3),
                Quantity = 1
            });

            Console.WriteLine("writing {0} events", howMany);

            long lastEventId = 0;

            using (new TransactionScope(TransactionScopeOption.Suppress))
                using (var eventStore = createEventStore.IfNotNull()
                                        .Then(c => c())
                                        .Else(() => new EventStoreDbContext()))
                {
                    Enumerable.Range(1, howMany).ForEach(i =>
                    {
                        var e = createEvent(i);

                        e.IfTypeIs <Event>()
                        .ThenDo(ev =>
                        {
                            if (ev.AggregateId == Guid.Empty)
                            {
                                ev.AggregateId = Guid.NewGuid();
                            }

                            if (ev.SequenceNumber == 0)
                            {
                                ev.SequenceNumber = i;
                            }
                        });

                        var storableEvent = e.ToStorableEvent();

                        eventStore.Events.Add(storableEvent);
                        eventStore.SaveChanges();

                        lastEventId = storableEvent.Id;
                        Console.WriteLine("wrote event " + lastEventId);
                    });
                }

            return(lastEventId);
        }
Exemplo n.º 4
0
        public static long Write(int howMany, 
            Func<int, IEvent> createEvent = null, 
            Func<EventStoreDbContext> createEventStore = null)
        {
            createEvent = createEvent ?? (i => new Order.ItemAdded
            {
                SequenceNumber = i,
                AggregateId = Recipes.Any.Guid(),
                Price = 1.99m,
                ProductName = Recipes.Any.Paragraph(3),
                Quantity = 1
            });

            Console.WriteLine("writing {0} events", howMany);

            long lastEventId = 0;

            using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
            using (var eventStore = createEventStore.IfNotNull()
                                                    .Then(c => c())
                                                    .Else(() => new EventStoreDbContext()))
            {
                Enumerable.Range(1, howMany).ForEach(i =>
                {
                    var e = createEvent(i);

                    e.IfTypeIs<Event>()
                     .ThenDo(ev =>
                     {
                         if (ev.AggregateId == Guid.Empty)
                         {
                             ev.AggregateId = Guid.NewGuid();
                         }

                         if (ev.SequenceNumber == 0)
                         {
                             ev.SequenceNumber = i;
                         }
                     });

                    var storableEvent = e.ToStorableEvent();

                    eventStore.Events.Add(storableEvent);
                    eventStore.SaveChanges();

                    lastEventId = storableEvent.Id;
                    Console.WriteLine("wrote event " + lastEventId);
                });
            }

            return lastEventId;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Create a <see cref="Stream"/> to an entry in the claim store that piggies back a kernel transaction if one can
        /// be factored.
        /// </summary>
        /// <param name="url">
        /// The claim store entry.
        /// </param>
        /// <param name="trackingModes">
        /// </param>
        /// <param name="transactionFactory">
        /// The <see cref="IKernelTransaction"/> factory.
        /// </param>
        /// <returns>
        /// The <see cref="Stream"/> to the claim store entry.
        /// </returns>
        private Stream CreateCapturingStream(string url, ActivityTrackingModes trackingModes, Func <IKernelTransaction> transactionFactory)
        {
            // RequiresCheckInAndOut entails payloads are first saved locally and moved by ClaimStore.Agent into claim
            // store where there will be a subfolder for each date that some payload has been saved/tracked to disk. To
            // ease the job of the ClaimStore.Agent the subfolder is not created locally (but the current date is however
            // kept in the name). When not RequiresCheckInAndOut, the payloads are tracked/saved to disk at the exact same
            // place that it will be redeemed from afterwards, that is in a subfolder corresponding to the current date (of
            // course, one needs to ensure the folders get created).

            string filePath;

            if (RequiresCheckInAndOut)
            {
                // .trk extension is used to denote simple message body's payload tracking scenarios, i.e. where the
                // message's payload is large enough that it would not fit in the BAM tracking database. Message body's
                // payload are therefore tracked to the local disk are then brought asynchronously to the central claim
                // store by the ClaimStore.Agent.

                // .chk extension is used to denote full-fledged claim check scenarios, i.e. where the actual message's
                // payload is claimed to disk (as with regular tracking) but also replaced by a token that needs to be
                // checked in and out. Message body's payload are claimed to the local disk and then brought asynchronously
                // to the central claim store by the ClaimStore.Agent. Because claims are brought asynchronously to the
                // central claim store, one has therefore to ensure a claim is available in the central claim store before
                // it could be redeemed.

                // The .chk and .trk extensions are there to allow the ClaimStore.Agent to distinguish these scenarios so
                // that it can, (1) bring claimed or tracked payloads to the central claim store and (2) make claims
                // available for redeem as soon as they have been brought to the central store.

                var extension = trackingModes.RequiresBodyClaimChecking() ? ".chk" : ".trk";
                filePath = Path.Combine(CheckInDirectory, url.Replace("\\", "") + extension);
            }
            else
            {
                filePath = Path.Combine(CheckInDirectory, url);
                // ReSharper disable once AssignNullToNotNullAttribute
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }
            return(FileTransacted.Create(filePath, 8192, transactionFactory.IfNotNull(ktf => ktf())));
        }
Exemplo n.º 6
0
 public TResult Execute(TKey key)
 {
     return(_strategies.ContainsKey(key) ? _strategies[key].Invoke() : _defaultStrategy.IfNotNull(fn => _defaultStrategy.Invoke()));
 }
 public TOut Execute(TKey key, TIn param)
 {
     return(_strategies.ContainsKey(key) ? _strategies[key].Invoke(param) : _defaultStrategy.IfNotNull(fn => _defaultStrategy(param)));
 }
        public static IEnumerable<EventHandlerProgress> Calculate(
            Func<DbContext> createDbContext,
            Func<EventStoreDbContext> createEventStoreDbContext = null)
        {
            if (createDbContext == null)
            {
                throw new ArgumentNullException("createDbContext");
            }

            int count;

            using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
            using (var db = createEventStoreDbContext.IfNotNull()
                                                     .Then(create => create())
                                                     .Else(() => new EventStoreDbContext()))
            {
                count = db.Events.Count();
            }

            if (count == 0)
            {
                return Enumerable.Empty<EventHandlerProgress>();
            }

            var now = Clock.Now();
            var progress = new List<EventHandlerProgress>();

            using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
            using (var db = createDbContext())
            {
                var readModelInfos = db.Set<ReadModelInfo>().ToArray();
                
                readModelInfos
                    .ForEach(i =>
                    {
                        var eventsProcessed = i.InitialCatchupEndTime.HasValue
                            ? i.BatchTotalEvents - i.BatchRemainingEvents
                            : i.InitialCatchupEvents - i.BatchRemainingEvents;

                        long? timeTakenForProcessedEvents = null;
                        if (i.BatchStartTime.HasValue && i.InitialCatchupStartTime.HasValue)
                        {
                            timeTakenForProcessedEvents = i.InitialCatchupEndTime.HasValue
                                ? (now - i.BatchStartTime).Value.Ticks
                                : (now - i.InitialCatchupStartTime).Value.Ticks;
                        }

                        if (eventsProcessed == 0)
                        {
                            return;
                        }

                        var eventHandlerProgress = new EventHandlerProgress
                        {
                            Name = i.Name,
                            InitialCatchupEvents = i.InitialCatchupEvents,
                            TimeTakenForInitialCatchup = i.InitialCatchupStartTime.HasValue
                                ? (i.InitialCatchupEndTime.HasValue ? i.InitialCatchupEndTime : now) - i.InitialCatchupStartTime
                                : null,
                            TimeRemainingForCatchup = eventsProcessed != 0 && timeTakenForProcessedEvents.HasValue
                                ? (TimeSpan?) TimeSpan.FromTicks((long) (timeTakenForProcessedEvents*(i.BatchRemainingEvents/(decimal) eventsProcessed)))
                                : null,
                            EventsRemaining = i.BatchRemainingEvents,
                            PercentageCompleted = (1 - ((decimal) i.BatchRemainingEvents/count))*100,
                            LatencyInMilliseconds = i.LatencyInMilliseconds,
                            LastUpdated = i.LastUpdated,
                            CurrentAsOfEventId = i.CurrentAsOfEventId,
                            FailedOnEventId = i.FailedOnEventId,
                            Error = i.Error
                        };

                        progress.Add(eventHandlerProgress);
                    });
            }

            return progress;
        }
Exemplo n.º 9
0
        public static IEnumerable <EventHandlerProgress> Calculate(
            Func <DbContext> createDbContext,
            Func <EventStoreDbContext> createEventStoreDbContext = null)
        {
            if (createDbContext == null)
            {
                throw new ArgumentNullException(nameof(createDbContext));
            }

            int count;

            using (var db = createEventStoreDbContext.IfNotNull()
                            .Then(create => create())
                            .Else(() => new EventStoreDbContext()))
            {
                count = db.Events.Count();
            }

            if (count == 0)
            {
                return(Enumerable.Empty <EventHandlerProgress>());
            }

            var now      = Clock.Now();
            var progress = new List <EventHandlerProgress>();

            ReadModelInfo[] readModelInfos;

            using (var db = createDbContext())
            {
                readModelInfos = db.Set <ReadModelInfo>().ToArray();
            }
            readModelInfos
            .ForEach(i =>
            {
                var eventsProcessed = i.InitialCatchupEndTime.HasValue
                            ? i.BatchTotalEvents - i.BatchRemainingEvents
                            : i.InitialCatchupEvents - i.BatchRemainingEvents;

                long?timeTakenForProcessedEvents = null;
                if (i.BatchStartTime.HasValue && i.InitialCatchupStartTime.HasValue)
                {
                    timeTakenForProcessedEvents = i.InitialCatchupEndTime.HasValue
                                ? (now - i.BatchStartTime).Value.Ticks
                                : (now - i.InitialCatchupStartTime).Value.Ticks;
                }

                if (eventsProcessed == 0)
                {
                    return;
                }

                var eventHandlerProgress = new EventHandlerProgress
                {
                    Name = i.Name,
                    InitialCatchupEvents       = i.InitialCatchupEvents,
                    TimeTakenForInitialCatchup = i.InitialCatchupStartTime.HasValue
                                ? (i.InitialCatchupEndTime.HasValue ? i.InitialCatchupEndTime : now) - i.InitialCatchupStartTime
                                : null,
                    TimeRemainingForCatchup = eventsProcessed != 0 && timeTakenForProcessedEvents.HasValue
                                ? (TimeSpan?)TimeSpan.FromTicks((long)(timeTakenForProcessedEvents * (i.BatchRemainingEvents / (decimal)eventsProcessed)))
                                : null,
                    EventsRemaining       = i.BatchRemainingEvents,
                    PercentageCompleted   = (1 - ((decimal)i.BatchRemainingEvents / count)) * 100,
                    LatencyInMilliseconds = i.LatencyInMilliseconds,
                    LastUpdated           = i.LastUpdated,
                    CurrentAsOfEventId    = i.CurrentAsOfEventId,
                    FailedOnEventId       = i.FailedOnEventId,
                    Error = i.Error
                };

                progress.Add(eventHandlerProgress);
            });
            return(progress);
        }
Exemplo n.º 10
0
 public static T Call <T>(this Func <T> action)
 {
     return(action.IfNotNull(x => x()));
 }