Пример #1
0
 public AzureCommandLogReader(CloudStorageAccount account, string tableName, ITextSerializer serializer) : 
     base(account, tableName, serializer)
 {
     this.tableName = tableName;
     this.serializer = serializer;
     this.tableClient = account.CreateCloudTableClient();
 }
Пример #2
0
 public CommandBus(Func<IBusContext> contextFactory, ITextSerializer serializer)
 {
     if (contextFactory == null) throw new ArgumentNullException(nameof(contextFactory));
     if (serializer == null) throw new ArgumentNullException(nameof(serializer));
     _contextFactory = contextFactory;
     _serializer = serializer;
 }
Пример #3
0
 public EventBus(IBusContext context, ITextSerializer serializer)
 {
     if (context == null) throw new ArgumentNullException(nameof(context));
     if (serializer == null) throw new ArgumentNullException(nameof(serializer));
     _context = context;
     _serializer = serializer;
 }
        // Can't really infer the topic from the subscription, since subscriptions of the same 
        // name can exist across different topics (i.e. "all" currently)
        public EventProcessor CreateEventProcessor(string subscription, IEventHandler handler, ITextSerializer serializer)
        {
            if (!this.initialized)
                throw new InvalidOperationException("Service bus configuration has not been initialized.");

            var topicSettings = this.settings.Topics.Find(x => x.IsEventBus);
            if (topicSettings == null)
                throw new ArgumentOutOfRangeException("No topic has been marked with the IsEventBus attribute. Cannot create event processor.");

            var subscriptionSettings = topicSettings.Subscriptions.Find(x => x.Name == subscription);
            if (subscriptionSettings == null)
                throw new ArgumentOutOfRangeException(string.Format(
                    CultureInfo.CurrentCulture,
                    "Subscription '{0}' for topic '{1}' has not been registered in the service bus configuration.",
                    subscription, topicSettings.Path));

            var receiver = subscriptionSettings.RequiresSession ?
                (IMessageReceiver)new SessionSubscriptionReceiver(this.settings, topicSettings.Path, subscription) :
                (IMessageReceiver)new SubscriptionReceiver(this.settings, topicSettings.Path, subscription);

            var processor = new EventProcessor(receiver, serializer);
            processor.Register(handler);

            return processor;
        }
Пример #5
0
        public static SerializedEvent ApplyConsumerFilter(SerializedEvent e, string consumer, ITextSerializer serializer, Func<string, ITextSerializer, string, bool> filter)
        {
            if (filter(consumer, serializer, e.Payload))
                return e;

            var originalEvent = serializer.Deserialize<IEvent>(e.Payload);
            var cloaked = new CloakedEvent(originalEvent.EventCollectionVersion, originalEvent.StreamType);
            return new SerializedEvent(e.EventCollectionVersion, serializer.Serialize(cloaked));
        }
Пример #6
0
 public CommandProcessor(
     IMessageReceiver messageReceiver,
     ICommandRouter commandRouter,
     ITextSerializer serializer)
 {
     _messageReceiver = messageReceiver;
     _commandRouter = commandRouter;
     _serializer = serializer;
 }
        public AzureEventLogReader(CloudStorageAccount account, string tableName, ITextSerializer serializer)
        {
            if (account == null) throw new ArgumentNullException("account");
            if (tableName == null) throw new ArgumentNullException("tableName");
            if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentException("tableName");
            if (serializer == null) throw new ArgumentNullException("serializer");

            this.account = account;
            this.tableName = tableName;
            this.tableClient = account.CreateCloudTableClient();
            this.serializer = serializer;
        }
Пример #8
0
        public static void File(string input, string output = null, ITextSerializer serializer = null)
        {
            ConfigurationDictionary data;
            TextReader fin;

            fin = (input != "-") ? new StreamReader(input) : Console.In;

            if (serializer == null)
            {
                if (input == "-" || !TryParseTextSerializer(Path.GetExtension(input).Substring(1), out serializer))
                {
                    Console.Error.WriteLine("Serializer cannot be inferred");
                    return;
                }
            }

            using (fin)
                data = serializer.Deserialize(fin);

            string generatorName;
            IGenerator generator;
            if (data.TryGetValueAs("Generator", out generatorName))
            {
                if (!TryParseGenerator(generatorName, out generator))
                {
                    Console.Error.WriteLine($"Unknown generator \"{generatorName}\"");
                    return;
                }
            }
            else
            {
                Console.Error.WriteLine("No generator specified");
                return;
            }

            TextWriter fout;

            if (output == null)
                output = (input == "-") ? "-" : Path.ChangeExtension(input, generator.DefaultExtension(data));

            fout = (output != "-") ? new StreamWriter(output) : Console.Out;

            using (fout)
            {
                bool pd = input.IndexOfAny(new char[] { '/', '\\' }) != -1;
                if (pd)
                    PushDirectory(Path.GetDirectoryName(input));
                generator.Generate(data, fout);
                if (pd)
                    PopDirectory();
            }
        }
        public given_an_empty_event_log()
        {
            this.tableName = "AzureEventLogFixture" + new Random((int)DateTime.Now.Ticks).Next();
            var settings = InfrastructureSettings.Read("Settings.xml").EventSourcing;
            this.account = CloudStorageAccount.Parse(settings.ConnectionString);

            this.eventA = new EventA();
            this.eventB = new EventB();
            this.eventC = new EventC();

            this.metadata = Mock.Of<IMetadataProvider>(x =>
                x.GetMetadata(eventA) == new Dictionary<string, string>
                {
                    { StandardMetadata.SourceId, eventA.SourceId.ToString() },
                    { StandardMetadata.SourceType, "SourceA" }, 
                    { StandardMetadata.Kind, StandardMetadata.EventKind },
                    { StandardMetadata.AssemblyName, "A" }, 
                    { StandardMetadata.Namespace, "Namespace" }, 
                    { StandardMetadata.FullName, "Namespace.EventA" }, 
                    { StandardMetadata.TypeName, "EventA" }, 
                } &&
                x.GetMetadata(eventB) == new Dictionary<string, string>
                {
                    { StandardMetadata.SourceId, eventB.SourceId.ToString() },
                    { StandardMetadata.SourceType, "SourceB" }, 
                    { StandardMetadata.Kind, StandardMetadata.EventKind },
                    { StandardMetadata.AssemblyName, "B" }, 
                    { StandardMetadata.Namespace, "Namespace" }, 
                    { StandardMetadata.FullName, "Namespace.EventB" }, 
                    { StandardMetadata.TypeName, "EventB" }, 
                } &&
                x.GetMetadata(eventC) == new Dictionary<string, string>
                {
                    { StandardMetadata.SourceId, eventC.SourceId.ToString() },
                    { StandardMetadata.SourceType, "SourceC" }, 
                    { StandardMetadata.Kind, StandardMetadata.EventKind },
                    { StandardMetadata.AssemblyName, "B" }, 
                    { StandardMetadata.Namespace, "AnotherNamespace" }, 
                    { StandardMetadata.FullName, "AnotherNamespace.EventC" }, 
                    { StandardMetadata.TypeName, "EventC" }, 
                });

            this.serializer = new JsonTextSerializer();
            this.writer = new AzureMessageLogWriter(this.account, this.tableName);
            this.sut = new AzureEventLogReader(this.account, this.tableName, new JsonTextSerializer());

            this.startEnqueueTime = new DateTime(2012, 06, 30, 23, 59, 0, DateTimeKind.Utc);
            Save(eventA, startEnqueueTime);
            Save(eventB, startEnqueueTime.AddMinutes(5));
            Save(eventC, startEnqueueTime.AddMinutes(6));
        }
Пример #10
0
        /// <summary>
        /// Default Constructor.
        /// </summary>
        public DefaultTextSerializer()
        {
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath;
            string binPath = string.IsNullOrEmpty(relativeSearchPath) ? baseDir : Path.Combine(baseDir, relativeSearchPath);
            string jsonDllPath = string.IsNullOrEmpty(binPath) ? "Newtonsoft.Json.dll" : Path.Combine(binPath, "Newtonsoft.Json.dll");

            if (File.Exists(jsonDllPath) || AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetName().Name == "Newtonsoft.Json")) {
                this.serializer = new JsonSerializer();
            }
            else {
                this.serializer = new OwnSerializer();
            }
        }
Пример #11
0
 /// <summary>
 /// Parameterized constructor.
 /// </summary>
 public EventSourcedRepository(IEventStore eventStore,
     ISnapshotStore snapshotStore,
     ISnapshotPolicy snapshotPolicy,
     IMemoryCache cache,
     IEventBus eventBus,
     IAggregateRootFactory aggregateFactory,
     IBinarySerializer binarySerializer,
     ITextSerializer textSerializer)
 {
     this._eventStore = eventStore;
     this._snapshotStore = snapshotStore;
     this._snapshotPolicy = snapshotPolicy;
     this._cache = cache;
     this._eventBus = eventBus;
     this._aggregateFactory = aggregateFactory;
     this._binarySerializer = binarySerializer;
     this._textSerializer = textSerializer;
     this._logger = LogManager.GetLogger("ThinkNet");
 }
        public void GeneratePastEventLogMessagesForConferenceManagement(
            CloudTableClient messageLogClient, string messageLogName,
            string conferenceManagementConnectionString,
            IMetadataProvider metadataProvider, ITextSerializer serializer)
        {
            retryPolicy.ExecuteAction(() => messageLogClient.CreateTableIfNotExist(messageLogName));

            // set the creation date to just before releasing V1 (previous month).
            var eventCreationDate = new DateTime(2012, 04, 01, 0, 0, 0, DateTimeKind.Utc);

            var generatedEvents = this.GenerateMissedConferenceManagementIntegrationEvents(conferenceManagementConnectionString);
            foreach (var evt in generatedEvents)
            {
                // generate events in ascending order. If there is a conflict when saving (currently silently swallowed by AzureEventLogWriter), 
                // then the migration process is being run for the second time, which is wrong.
                // TODO: what happens if the process crashes middleway.
                eventCreationDate = eventCreationDate.AddSeconds(1);
                var metadata = metadataProvider.GetMetadata(evt);
                var entry = new MessageLogEntity
                {
                    PartitionKey = eventCreationDate.ToString("yyyMM"),
                    // could have a prefix instead of suffix to be able to search
                    RowKey = eventCreationDate.Ticks.ToString("D20") + "_Generated",
                    CreationDate = eventCreationDate.ToString("o"),
                    MessageId = null,
                    CorrelationId = null,
                    SourceType = null,
                    SourceId = evt.SourceId.ToString(),
                    AssemblyName = metadata[StandardMetadata.AssemblyName],
                    FullName = metadata[StandardMetadata.FullName],
                    Namespace = metadata[StandardMetadata.Namespace],
                    TypeName = metadata[StandardMetadata.TypeName],
                    Kind = StandardMetadata.EventKind,
                    Payload = serializer.Serialize(evt),
                };

                var context = messageLogClient.GetDataServiceContext();
                context.AddObject(messageLogName, entry);
                retryPolicy.ExecuteAction(() => context.SaveChanges());
            }
        }
Пример #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EventBus"/> class.
 /// </summary>
 /// <param name="serializer">The serializer to use for the message body.</param>
 public EventBus(IMessageSender sender, IMetadataProvider metadataProvider, ITextSerializer serializer)
 {
     this.sender           = sender;
     this.metadataProvider = metadataProvider;
     this.serializer       = serializer;
 }
Пример #14
0
        public void MigrateEventSourcedAndGeneratePastEventLogs(
            CloudTableClient messageLogClient, string messageLogName,
            CloudTableClient originalEventStoreClient, string originalEventStoreName,
            CloudTableClient newEventStoreClient, string newEventStoreName,
            IMetadataProvider metadataProvider, ITextSerializer serializer)
        {
            retryPolicy.ExecuteAction(() => newEventStoreClient.CreateTableIfNotExist(newEventStoreName));

            var    currentEventStoreContext      = newEventStoreClient.GetDataServiceContext();
            string currentEventStorePartitionKey = null;
            int    currentEventStoreCount        = 0;

            var    currentMessageLogContext      = messageLogClient.GetDataServiceContext();
            string currentMessageLogPartitionKey = null;
            int    currentMessageLogCount        = 0;

            foreach (var esEntry in this.GetAllEventSourcingEntries(originalEventStoreClient, originalEventStoreName))
            {
                // Copies the original values from the stored entry
                var migratedEntry = Mapper.Map <EventTableServiceEntity>(esEntry);

                // get the metadata, as it was not stored in the event store
                var metadata = metadataProvider.GetMetadata(serializer.Deserialize <IVersionedEvent>(esEntry.Payload));
                migratedEntry.AssemblyName = metadata[StandardMetadata.AssemblyName];
                migratedEntry.FullName     = metadata[StandardMetadata.FullName];
                migratedEntry.Namespace    = metadata[StandardMetadata.Namespace];
                migratedEntry.TypeName     = metadata[StandardMetadata.TypeName];
                migratedEntry.CreationDate = esEntry.Timestamp.ToString("o");

                if (currentEventStorePartitionKey == null)
                {
                    currentEventStorePartitionKey = migratedEntry.PartitionKey;
                    ++currentEventStoreCount;
                }
                else if (currentEventStorePartitionKey != migratedEntry.PartitionKey || ++currentEventStoreCount == 100)
                {
                    retryPolicy.ExecuteAction(() => currentEventStoreContext.SaveChanges(SaveChangesOptions.Batch));
                    currentEventStoreContext      = newEventStoreClient.GetDataServiceContext();
                    currentEventStorePartitionKey = migratedEntry.PartitionKey;
                    currentEventStoreCount        = 0;
                }

                currentEventStoreContext.AddObject(newEventStoreName, migratedEntry);

                const string RowKeyVersionLowerLimit = "0000000000";
                const string RowKeyVersionUpperLimit = "9999999999";

                if (migratedEntry.RowKey.CompareTo(RowKeyVersionLowerLimit) >= 0 &&
                    migratedEntry.RowKey.CompareTo(RowKeyVersionUpperLimit) <= 0)
                {
                    var messageId = migratedEntry.PartitionKey + "_" + migratedEntry.RowKey; //This is the message ID used in the past (deterministic).
                    var logEntry  = Mapper.Map <MessageLogEntity>(migratedEntry);
                    logEntry.PartitionKey  = esEntry.Timestamp.ToString("yyyMM");
                    logEntry.RowKey        = esEntry.Timestamp.Ticks.ToString("D20") + "_" + messageId;
                    logEntry.MessageId     = messageId;
                    logEntry.CorrelationId = null;
                    logEntry.Kind          = StandardMetadata.EventKind;

                    if (currentMessageLogPartitionKey == null)
                    {
                        currentMessageLogPartitionKey = logEntry.PartitionKey;
                        ++currentMessageLogCount;
                    }
                    else if (currentMessageLogPartitionKey != logEntry.PartitionKey || ++currentMessageLogCount == 100)
                    {
                        retryPolicy.ExecuteAction(() => currentMessageLogContext.SaveChanges(SaveChangesOptions.Batch));
                        currentMessageLogContext      = messageLogClient.GetDataServiceContext();
                        currentMessageLogPartitionKey = logEntry.PartitionKey;
                        currentMessageLogCount        = 0;
                    }

                    currentMessageLogContext.AddObject(messageLogName, logEntry);
                }
            }

            // save any remaining entries
            retryPolicy.ExecuteAction(() => currentEventStoreContext.SaveChanges(SaveChangesOptions.Batch));
            retryPolicy.ExecuteAction(() => currentMessageLogContext.SaveChanges(SaveChangesOptions.Batch));
        }
Пример #15
0
 protected abstract Envelope <TMessage> Convert(TDescriptor descriptor, ITextSerializer serializer);
Пример #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandBus"/> class.
 /// </summary>
 /// <param name="serializer">The serializer to use for the message body.</param>
 public CommandBus(IMessageSender sender, ITextSerializer serializer)
 {
     this.sender = sender;
     this.serializer = serializer;
 }
Пример #17
0
        public EventProcessor CreateEventProcessor(string topic, string subscription, SubscriptionSettings subscriptionSettings, IEventHandler handler, ITextSerializer serializer, bool instrumentationEnabled = false)
        {
            var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            var retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            var namespaceManager = settings.GetNamespaceManager();
            var topicSettings = new TopicSettings
            {
                IsEventBus = true,
                DuplicateDetectionHistoryTimeWindow = new TimeSpan(0, 30, 0),
                Path = topic
            };
            retryPolicy.ExecuteAction(() => CreateSubscriptionIfNotExists(namespaceManager, topicSettings, subscriptionSettings));
            retryPolicy.ExecuteAction(() => UpdateRules(namespaceManager, topicSettings, subscriptionSettings, settings.GetMessagingFactory()));

            IMessageReceiver receiver;

            if (subscriptionSettings.RequiresSession)
            {
                var instrumentation = new SessionSubscriptionReceiverInstrumentation(subscription, instrumentationEnabled);
                try
                {
                    receiver = (IMessageReceiver)new SessionSubscriptionReceiver(this.settings, topic, subscription, true, instrumentation);
                }
                catch
                {
                    instrumentation.Dispose();
                    throw;
                }
            }
            else
            {
                var instrumentation = new SubscriptionReceiverInstrumentation(subscription, instrumentationEnabled);
                try
                {
                    receiver = (IMessageReceiver)new SubscriptionReceiver(this.settings, topic, subscription, true, instrumentation);
                }
                catch
                {
                    instrumentation.Dispose();
                    throw;
                }
            }

            EventProcessor processor;
            try
            {
                processor = new EventProcessor(receiver, serializer);
            }
            catch
            {
                using (receiver as IDisposable) { }
                throw;
            }

            try
            {
                processor.Register(handler);

                return processor;
            }
            catch
            {
                processor.Dispose();
                throw;
            }
        }
Пример #18
0
 string ITextConverter.WriteObject(ITextSerializer serializer, object obj)
 {
     return(WriteJson((JsonSerializer)serializer, obj));
 }
Пример #19
0
 object ITextConverter.ReadObject(ITextSerializer serializer, Type dataType, string text)
 {
     return(ReadJson((JsonSerializer)serializer, dataType, text));
 }
Пример #20
0
 public EventProcessor(IMessageReceiver receiver, ITextSerializer serializer)
     : base(receiver, serializer)
 {
     messageDispatcher = new EventDispatcher();
 }
Пример #21
0
 public OrderDao(Func <ConferenceRegistrationDbContext> contextFactory, IBlobStorage blobStorage, ITextSerializer serializer)
 {
     this.contextFactory = contextFactory;
     this.blobStorage    = blobStorage;
     this.serializer     = serializer;
 }
Пример #22
0
 public HomeworkClient(Configuration configuration, ITextSerializer serializer)
 {
     this.configuration = configuration;
     this.serializer    = serializer;
 }
Пример #23
0
        public ProcessManagerRepository([Import] DbContext context, [Import] IBus <CommandDispatcher, ICommandHandler> commandBus, [Import] ITextSerializer serializer)
        {
            this.commandBus = commandBus;
            this.serializer = serializer;
            this.context    = context;

            messagingRandomRetry = new MessagingRandomRetry();
            sqlIncrementalRetry  = new SqlIncrementalRetry();
        }
Пример #24
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="MessageProcessor" /> class.
 /// </summary>
 protected MessageProcessor(IMessageReceiver receiver, ITextSerializer serializer)
 {
     this.receiver = receiver;
     Serializer    = serializer;
 }
Пример #25
0
 public EventProcessor(IMessageReceiver receiver, ITextSerializer serializer)
     : base(receiver, serializer)
 {
 }
        public AzureEventSourcedRepository(IEventStore eventStore, IEventStoreBusPublisher publisher, ITextSerializer serializer, IMetadataProvider metadataProvider, ObjectCache cache)
        {
            this.eventStore       = eventStore;
            this.publisher        = publisher;
            this.serializer       = serializer;
            this.metadataProvider = metadataProvider;
            this.cache            = cache;

            // TODO: could be replaced with a compiled lambda to make it more performant
            var constructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(IEnumerable <IVersionedEvent>) });

            if (constructor == null)
            {
                throw new InvalidCastException(
                          "Type T must have a constructor with the following signature: .ctor(Guid, IEnumerable<IVersionedEvent>)");
            }
            this.entityFactory = (id, events) => (T)constructor.Invoke(new object[] { id, events });

            if (typeof(IMementoOriginator).IsAssignableFrom(typeof(T)) && this.cache != null)
            {
                // TODO: could be replaced with a compiled lambda to make it more performant
                var mementoConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(IMemento), typeof(IEnumerable <IVersionedEvent>) });
                if (mementoConstructor == null)
                {
                    throw new InvalidCastException(
                              "Type T must have a constructor with the following signature: .ctor(Guid, IMemento, IEnumerable<IVersionedEvent>)");
                }
                this.originatorEntityFactory  = (id, memento, events) => (T)mementoConstructor.Invoke(new object[] { id, memento, events });
                this.cacheMementoIfApplicable = (T originator) =>
                {
                    string key     = GetPartitionKey(originator.Id);
                    var    memento = ((IMementoOriginator)originator).SaveToMemento();
                    this.cache.Set(
                        key,
                        new Tuple <IMemento, DateTime?>(memento, DateTime.UtcNow),
                        new CacheItemPolicy {
                        AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(30)
                    });
                };
                this.getMementoFromCache = id => (Tuple <IMemento, DateTime?>) this.cache.Get(GetPartitionKey(id));
                this.markCacheAsStale    = id =>
                {
                    var key  = GetPartitionKey(id);
                    var item = (Tuple <IMemento, DateTime?>) this.cache.Get(key);
                    if (item != null && item.Item2.HasValue)
                    {
                        item = new Tuple <IMemento, DateTime?>(item.Item1, null);
                        this.cache.Set(
                            key,
                            item,
                            new CacheItemPolicy {
                            AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(30)
                        });
                    }
                };
            }
            else
            {
                // if no cache object or is not a cache originator, then no-op
                this.cacheMementoIfApplicable = o => { };
                this.getMementoFromCache      = id => { return(null); };
                this.markCacheAsStale         = id => { };
            }
        }
Пример #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MessageProcessor"/> class.
 /// </summary>
 protected MessageProcessor(IMessageReceiver receiver, ITextSerializer serializer)
 {
     this.receiver = receiver;
     this.serializer = serializer;
 }
Пример #28
0
        private static async Task <ServiceResponse <T> > GetResponse <T>(HttpResponseMessage response, ITextSerializer serializer)
        {
            var returnResponse = new ServiceResponse <T>(response.StatusCode);

            if (!response.IsSuccessStatusCode)
            {
                return(returnResponse);
            }

            try
            {
                //// get response string
                returnResponse.Content = await response.Content.ReadAsStringAsync();

                //// serialize the response to object
                returnResponse.Value = serializer.Deserialize <T>(returnResponse.Content);
            }
            catch (Exception ex)
            {
                returnResponse.Error = ex;
            }

            return(returnResponse);
        }
Пример #29
0
 string ITextConverter.WriteObject(ITextSerializer serializer, object obj)
 {
     return(WriteXml((XmlSerializer)serializer, obj));
 }
Пример #30
0
 public VcdbChangeRequestCommentsBusinessService(IVcdbUnitOfWork vcdbUnitOfWork, ITextSerializer serializer)
     : base(vcdbUnitOfWork, serializer)
 {
     _vcdbUnitOfWork = vcdbUnitOfWork;
     _commentsStagingRepositoryService = vcdbUnitOfWork.GetRepositoryService <CommentsStaging>()
                                         as ISqlServerEfRepositoryService <CommentsStaging>;
 }
Пример #31
0
 protected KafkaReceiver(ITextSerializer serializer, ITopicProvider topicProvider)
 {
     _serializer = serializer;
     _decoder    = new DefaultDecoder();
     _topic      = topicProvider.GetTopic(typeof(TDescriptor));
 }
Пример #32
0
        public EventProcessor CreateEventProcessor(string subscription, IEventHandler handler, ITextSerializer serializer, bool instrumentationEnabled = false)
        {
            if (!this.initialized)
                throw new InvalidOperationException("Service bus configuration has not been initialized.");

            TopicSettings topicSettings = null;
            SubscriptionSettings subscriptionSettings = null;

            foreach (var settings in this.settings.Topics.Where(t => t.IsEventBus))
            {
                subscriptionSettings = settings.Subscriptions.Find(s => s.Name == subscription);
                if (subscriptionSettings != null)
                {
                    topicSettings = settings;
                    break;
                }
            }

            if (subscriptionSettings == null)
            {
                throw new ArgumentOutOfRangeException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        "Subscription '{0}' has not been registered for an event bus topic in the service bus configuration.",
                        subscription));
            }

            IMessageReceiver receiver;

            if (subscriptionSettings.RequiresSession)
            {
                var instrumentation = new SessionSubscriptionReceiverInstrumentation(subscription, instrumentationEnabled);
                try
                {
                    receiver = (IMessageReceiver)new SessionSubscriptionReceiver(this.settings, topicSettings.Path, subscription, true, instrumentation);
                }
                catch
                {
                    instrumentation.Dispose();
                    throw;
                }
            }
            else
            {
                var instrumentation = new SubscriptionReceiverInstrumentation(subscription, instrumentationEnabled);
                try
                {
                    receiver = (IMessageReceiver)new SubscriptionReceiver(this.settings, topicSettings.Path, subscription, true, instrumentation);
                }
                catch
                {
                    instrumentation.Dispose();
                    throw;
                }
            }

            EventProcessor processor;
            try
            {
                processor = new EventProcessor(receiver, serializer);
            }
            catch
            {
                using (receiver as IDisposable) { }
                throw;
            }

            try
            {
                processor.Register(handler);

                return processor;
            }
            catch
            {
                processor.Dispose();
                throw;
            }
        }
        public SqlProcessManagerDataContext(Func <DbContext> contextFactory, ICommandBus commandBus, ITextSerializer serializer)
        {
            this.commandBus = commandBus;
            this.context    = contextFactory.Invoke();
            this.serializer = serializer;

            this.retryPolicy = new RetryPolicy <SqlDatabaseTransientErrorDetectionStrategy>(new Incremental(3, TimeSpan.Zero, TimeSpan.FromSeconds(1))
            {
                FastFirstRetry = true
            });
            this.retryPolicy.Retrying += (s, e) =>
                                         Trace.TraceWarning("An error occurred in attempt number {1} to save the process manager state: {0}", e.LastException.Message, e.CurrentRetryCount);
        }
Пример #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EventBus"/> class.
 /// </summary>
 /// <param name="serializer">The serializer to use for the message body.</param>
 public EventBus(IMessageSender sender, ITextSerializer serializer)
 {
     this.sender = sender;
     this.serializer = serializer;
 }
Пример #35
0
 public static void Populate(this ITextSerializer serializer, string data, IValueContainer target)
 {
     using (var reader = new StringReader(data))
         serializer.Populate(reader, target);
 }
Пример #36
0
        public EventProcessor CreateEventProcessor(string subscription, IEventHandler handler, ITextSerializer serializer, bool instrumentationEnabled = false)
        {
            if (!this.initialized)
            {
                throw new InvalidOperationException("Service bus configuration has not been initialized.");
            }

            TopicSettings        topicSettings        = null;
            SubscriptionSettings subscriptionSettings = null;

            foreach (var settings in this.settings.Topics.Where(t => t.IsEventBus))
            {
                subscriptionSettings = settings.Subscriptions.Find(s => s.Name == subscription);
                if (subscriptionSettings != null)
                {
                    topicSettings = settings;
                    break;
                }
            }

            if (subscriptionSettings == null)
            {
                throw new ArgumentOutOfRangeException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              "Subscription '{0}' has not been registered for an event bus topic in the service bus configuration.",
                              subscription));
            }

            IMessageReceiver receiver;

            if (subscriptionSettings.RequiresSession)
            {
                var instrumentation = new SessionSubscriptionReceiverInstrumentation(subscription, instrumentationEnabled);
                try
                {
                    receiver = (IMessageReceiver) new SessionSubscriptionReceiver(this.settings, topicSettings.Path, subscription, true, instrumentation);
                }
                catch
                {
                    instrumentation.Dispose();
                    throw;
                }
            }
            else
            {
                var instrumentation = new SubscriptionReceiverInstrumentation(subscription, instrumentationEnabled);
                try
                {
                    receiver = (IMessageReceiver) new SubscriptionReceiver(this.settings, topicSettings.Path, subscription, true, instrumentation);
                }
                catch
                {
                    instrumentation.Dispose();
                    throw;
                }
            }

            EventProcessor processor;

            try
            {
                processor = new EventProcessor(receiver, serializer);
            }
            catch
            {
                using (receiver as IDisposable) { }
                throw;
            }

            try
            {
                processor.Register(handler);

                return(processor);
            }
            catch
            {
                processor.Dispose();
                throw;
            }
        }
 public SeatAssignmentsDao(IBlobStorage storage, ITextSerializer serializer)
 {
     this.storage = storage;
     this.serializer = serializer;
 }
Пример #38
0
 public RedisCacheProvider( IDatabase database, ITextSerializer serializer )
 {
   _database = database;
   _serializer = serializer;
 }
Пример #39
0
 public PadbSqlServerEfRepositoryService(DbContext context, ITextSerializer serializer) : base(context, serializer)
 {
 }
Пример #40
0
 public SlackService(IQueue <WebHookNotification> webHookNotificationQueue, FormattingPluginManager pluginManager, ITextSerializer serializer, ILoggerFactory loggerFactory = null)
 {
     _webHookNotificationQueue = webHookNotificationQueue;
     _pluginManager            = pluginManager;
     _serializer = serializer;
     _logger     = loggerFactory.CreateLogger <SlackService>();
 }
Пример #41
0
 public EncodingBinaryFrame(Type textSerializer, string containerFieldName=null)
 {
     innerSerializer = textSerializer.GetConstructor(new Type[0]).Invoke(new object[0]) as ITextSerializer;
 }
Пример #42
0
 public SqlMessageLog(string nameOrConnectionString, ITextSerializer serializer, IMetadataProvider metadataProvider)
 {
     this.nameOrConnectionString = nameOrConnectionString;
     this.serializer             = serializer;
     this.metadataProvider       = metadataProvider;
 }
Пример #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandProcessor"/> class.
 /// </summary>
 /// <param name="receiver">The receiver to use. If the receiver is <see cref="IDisposable"/>, it will be disposed when the processor is 
 /// disposed.</param>
 /// <param name="serializer">The serializer to use for the message body.</param>
 public CommandProcessor(IMessageReceiver receiver, ITextSerializer serializer)
     : base(receiver, serializer)
 {
     this.commandDispatcher = new CommandDispatcher();
 }
Пример #44
0
 public SqlQuery(string nameOrConnectionString, ITextSerializer serializer, QueryCriteria criteria)
 {
     this.nameOrConnectionString = nameOrConnectionString;
     this.serializer             = serializer;
     this.criteria = criteria;
 }
 public FakeProcessor(ManualResetEventSlim waiter, IMessageReceiver receiver, ITextSerializer serializer)
     : base(receiver, serializer)
 {
     this.waiter = waiter;
 }
Пример #46
0
 public RedisCacheProvider(IDatabase database, ITextSerializer serializer)
 {
     _database   = database;
     _serializer = serializer;
 }
Пример #47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EventBus"/> class.
 /// </summary>
 /// <param name="serializer">The serializer to use for the message body.</param>
 public EventBus(IMessageSender sender, IMetadataProvider metadata, ITextSerializer serializer)
 {
     this.sender = sender;
     this.metadata = metadata;
     this.serializer = serializer;
 }
 public MfrBodyCodeChangeRequestReviewEventHandler(IVcdbUnitOfWork vcdbUnitOfWork,
                                                   ITextSerializer serializer,
                                                   IMfrBodyCodeDataIndexer documentIndexer = null)
     : base(vcdbUnitOfWork, serializer, documentIndexer)
 {
 }
Пример #49
0
 public OrderDao(Func<ConferenceRegistrationDbContext> contextFactory, IBlobStorage blobStorage, ITextSerializer serializer)
 {
     this.contextFactory = contextFactory;
     this.blobStorage = blobStorage;
     this.serializer = serializer;
 }
 public CommandProcessor(IMessageReceiver receiver, ITextSerializer serializer)
     : base(receiver, serializer)
 {
 }
        public void MigrateEventSourcedAndGeneratePastEventLogs(
            CloudTableClient messageLogClient, string messageLogName,
            CloudTableClient originalEventStoreClient, string originalEventStoreName,
            CloudTableClient newEventStoreClient, string newEventStoreName,
            IMetadataProvider metadataProvider, ITextSerializer serializer)
        {
            retryPolicy.ExecuteAction(() => newEventStoreClient.CreateTableIfNotExist(newEventStoreName));

            var currentEventStoreContext = newEventStoreClient.GetDataServiceContext();
            string currentEventStorePartitionKey = null;
            int currentEventStoreCount = 0;

            var currentMessageLogContext = messageLogClient.GetDataServiceContext();
            string currentMessageLogPartitionKey = null;
            int currentMessageLogCount = 0;

            foreach (var esEntry in this.GetAllEventSourcingEntries(originalEventStoreClient, originalEventStoreName))
            {
                // Copies the original values from the stored entry
                var migratedEntry = Mapper.Map<EventTableServiceEntity>(esEntry);

                // get the metadata, as it was not stored in the event store
                var metadata = metadataProvider.GetMetadata(serializer.Deserialize<IVersionedEvent>(esEntry.Payload));
                migratedEntry.AssemblyName = metadata[StandardMetadata.AssemblyName];
                migratedEntry.FullName = metadata[StandardMetadata.FullName];
                migratedEntry.Namespace = metadata[StandardMetadata.Namespace];
                migratedEntry.TypeName = metadata[StandardMetadata.TypeName];
                migratedEntry.CreationDate = esEntry.Timestamp.ToString("o");

                if (currentEventStorePartitionKey == null)
                {
                    currentEventStorePartitionKey = migratedEntry.PartitionKey;
                    ++currentEventStoreCount;
                }
                else if (currentEventStorePartitionKey != migratedEntry.PartitionKey || ++currentEventStoreCount == 100)
                {
                    retryPolicy.ExecuteAction(() => currentEventStoreContext.SaveChanges(SaveChangesOptions.Batch));
                    currentEventStoreContext = newEventStoreClient.GetDataServiceContext();
                    currentEventStorePartitionKey = migratedEntry.PartitionKey;
                    currentEventStoreCount = 0;
                }

                currentEventStoreContext.AddObject(newEventStoreName, migratedEntry);

                const string RowKeyVersionLowerLimit = "0000000000";
                const string RowKeyVersionUpperLimit = "9999999999";

                if (migratedEntry.RowKey.CompareTo(RowKeyVersionLowerLimit) >= 0 &&
                    migratedEntry.RowKey.CompareTo(RowKeyVersionUpperLimit) <= 0)
                {
                    var messageId = migratedEntry.PartitionKey + "_" + migratedEntry.RowKey; //This is the message ID used in the past (deterministic).
                    var logEntry = Mapper.Map<MessageLogEntity>(migratedEntry);
                    logEntry.PartitionKey = esEntry.Timestamp.ToString("yyyMM");
                    logEntry.RowKey = esEntry.Timestamp.Ticks.ToString("D20") + "_" + messageId;
                    logEntry.MessageId = messageId;
                    logEntry.CorrelationId = null;
                    logEntry.Kind = StandardMetadata.EventKind;

                    if (currentMessageLogPartitionKey == null)
                    {
                        currentMessageLogPartitionKey = logEntry.PartitionKey;
                        ++currentMessageLogCount;
                    }
                    else if (currentMessageLogPartitionKey != logEntry.PartitionKey || ++currentMessageLogCount == 100)
                    {
                        retryPolicy.ExecuteAction(() => currentMessageLogContext.SaveChanges(SaveChangesOptions.Batch));
                        currentMessageLogContext = messageLogClient.GetDataServiceContext();
                        currentMessageLogPartitionKey = logEntry.PartitionKey;
                        currentMessageLogCount = 0;
                    }

                    currentMessageLogContext.AddObject(messageLogName, logEntry);
                }
            }

            // save any remaining entries
            retryPolicy.ExecuteAction(() => currentEventStoreContext.SaveChanges(SaveChangesOptions.Batch));
            retryPolicy.ExecuteAction(() => currentMessageLogContext.SaveChanges(SaveChangesOptions.Batch));
        }
Пример #52
0
 public PublishableExceptionReceiver(ITextSerializer serializer, ITopicProvider topicProvider)
     : base(serializer, topicProvider)
 {
     constructorMap = new Dictionary <Type, ConstructorInfo>();
 }
Пример #53
0
 public EventProcessor(IMessageReceiver receiver, ITextSerializer serializer)
     : base(receiver, serializer)
 {
     this.messageDispatcher = new EventDispatcher();
 }
 public FakeProcessor(ManualResetEventSlim waiter, IMessageReceiver receiver, ITextSerializer serializer)
     : base(receiver, serializer)
 {
     this.waiter = waiter;
 }
Пример #55
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandBus"/> class.
 /// </summary>
 public CommandBus(IMessageSender sender, IMetadataProvider metadataProvider, ITextSerializer serializer)
 {
     this.sender = sender;
     this.metadataProvider = metadataProvider;
     this.serializer = serializer;
 }
Пример #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandBus"/> class.
 /// </summary>
 /// <param name="serializer">The serializer to use for the message body.</param>
 public CommandBus(IMessageSender sender, ITextSerializer serializer)
 {
     this.sender     = sender;
     this.serializer = serializer;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandProcessor"/> class.
 /// </summary>
 /// <param name="receiver">The receiver to use. If the receiver is <see cref="IDisposable"/>, it will be disposed when the processor is 
 /// disposed.</param>
 /// <param name="serializer">The serializer to use for the message body.</param>
 public CommandProcessor(IMessageReceiver receiver, ITextSerializer serializer)
     : base(receiver, serializer)
 {
 }
Пример #58
0
 protected ChangeRequestBusinessService(IUnitOfWork repositories, IMapper autoMapper, ITextSerializer serializer,
                                        IChangeRequestItemBusinessService <TItem> changeRequestItemBusinessService,
                                        IChangeRequestCommentsBusinessService <TComment> changeRequestCommentsBusinessService,
                                        IChangeRequestIndexingService changeRequestIndexingService) : base(repositories, serializer)
 {
     AutoMapper = autoMapper;
     _changeRequestItemBusinessService = changeRequestItemBusinessService;
     _changeRequestRepositoryService   = repositories.GetRepositoryService <T>();
 }
Пример #59
0
 public static bool DefaultFilter(string consumer, ITextSerializer serializer, string payload) => true;
Пример #60
0
 public CastingTextSerializer(ITextSerializer untypedSerializer, Type serializedType)
 {
     UntypedSerializer = untypedSerializer;
     SerializedType    = serializedType;
 }