public DomainObjectStateRuntime(IDomainObject domainObject, EventsourceDIContext diContext, IStateEventMapping mapper, EventSourceConfiguration config) { this.domainObject = domainObject; this.diContext = diContext; stateToEventMapper = mapper; }
private void EnableAsNecessary(EventSource eventSource) { // Special case: enable TPL activity flow for better tracing of nested activities. if (eventSource.Guid == TplEventSourceGuid) { this.EnableEvents(eventSource, EventLevel.LogAlways, (EventKeywords)TaskFlowActivityIds); } else { EventSourceConfiguration provider = this.EventSources.FirstOrDefault(p => p.ProviderName == eventSource.Name); if (provider != null) { // LIMITATION: There is a known issue where if we listen to the FrameworkEventSource, the dataflow pipeline may hang when it // tries to process the Threadpool event. The reason is the dataflow pipeline itself is using Task library for scheduling async // tasks, which then itself also fires Threadpool events on FrameworkEventSource at unexpected locations, and trigger deadlocks. // Hence, we like special case this and mask out Threadpool events. EventKeywords keywords = provider.Keywords; if (provider.ProviderName == "System.Diagnostics.Eventing.FrameworkEventSource") { // Turn off the Threadpool | ThreadTransfer keyword. Definition is at http://referencesource.microsoft.com/#mscorlib/system/diagnostics/eventing/frameworkeventsource.cs // However, if keywords was to begin with, then we need to set it to All first, which is 0xFFFFF.... if (keywords == 0) { keywords = EventKeywords.All; } keywords &= (EventKeywords) ~0x12; } this.EnableEvents(eventSource, provider.Level, keywords); } } }
public void ApplyConfig(EventSourceConfiguration configuration, EventsourceDIContext diContext, IStateEventMapping eventMapping, IDomainObjectRepository repo) { stateRuntime = new DomainObjectStateRuntime(this, diContext, eventMapping, configuration); domainObjectRepository = repo; }
public static IServiceCollection AddCqrs(this IServiceCollection services, IConfiguration config, ILoggerFactory logger) { Console.WriteLine("Adding CQRS..."); string eventSecret = "0mDJVERJ34e4qLC6JYvT!$_d#+54d"; string url = config["events:host"]; string db = config["events:db"]; services.AddServiceProviderAcitvator(); Console.WriteLine($"ES DB: {url} - {db}"); IMongoDatabase mongodb = new MongoClient(url).GetDatabase(db); EventSourceConfiguration esconfig = new EventSourceConfiguration() .HashEvents(eventSecret) .SetDomainObjectAssemblies(typeof(SampleDomainObject).Assembly) .SetServiceProviderActivator() .SetMongoDomainObjectRepository(mongodb) .SetConventionBasedInMemoryCommandBus(); esconfig.StateActivator = new ServiceCollectionActivator(); esconfig.LoggerFactory = logger; serivces.AddEventSource(esconfig); serivces.AddSingleton(esconfig); Console.WriteLine("CQRS added"); return serivces; }
public static IDomainObjectRepository AddCqrs(IMongoDatabase db) { var configuration = new EventSourceConfiguration(); configuration.Activator = new ActivatorDomainObjectActivator(); configuration.StateActivator = new ActivatorDomainObjectActivator(); return(new MongoDomainObjectRepository(configuration, db)); }
public static EventSourceConfiguration SetServiceProviderActivator(this EventSourceConfiguration config) { var activator = new ServiceCollectionActivator(); config.Activator = activator; config.StateActivator = activator; return(config); }
protected DomainObjectRepositoryBase(EventSourceConfiguration configuration) { Precondition.For(configuration, nameof(configuration)) .NotNull("Configuration for domainobject repository must not be null!"); this.configuration = configuration; logger = configuration.LoggerFactory.CreateLogger(GetType()); }
public static EventSourceConfiguration SetEventstoreEventsource(this EventSourceConfiguration config, IEventStoreConnection connection) { EventStoreContext context = EventStoreContext.CreateDefault(config.Prefix, connection, config.Activator); var repo = new EventStoreRepository(context, config); config.DomainObjectRepository = repo; return(config); }
public static EventSourceConfiguration SetMongoDomainObjectRepository(this EventSourceConfiguration config, IMongoDatabase db) { Precondition.For(() => db).NotNull(); Precondition.For(() => config).NotNull(); Precondition.For(() => config.Activator).NotNull(); var repo = new MongoDomainObjectRepository(config, db); config.DomainObjectRepository = repo; return(config); }
private static void ConfigureEventSource(IServiceCollection services) { var cfg = new EventSourceConfiguration() .SetEventSecret("232") .SetDomainObjectAssemblies(typeof(SampleBo).Assembly); services .AddServiceProviderDomainObjectAcitvator() .AddMongoDomainObjectRepository(() => new MongoClient("mongodb://localhost:27017/?connectTimeoutMS=10000") .GetDatabase("eventTests2")) .AddConventionBasedInMemoryCommandBus(cfg) .AddEventSource(cfg); }
public static IServiceCollection AddEventSource(this IServiceCollection services) { var cfg = new EventSourceConfiguration() .SetEventSecret("232") //Your secret key which is used to sign the vents .SetDomainObjectAssemblies(typeof(Customer).Assembly); //Tell the place where your domainobjects are services .AddServiceProviderDomainObjectAcitvator() .AddMongoDomainObjectRepository(() => new MongoClient("mongodb://localhost:27017/?connectTimeoutMS=10000") .GetDatabase("eventTests2")) .AddConventionBasedInMemoryCommandBus(cfg) .AddEventSource(cfg); return(services); }
protected DomainObjectRepositoryBase(EventSourceConfiguration configuration, IImmediateConventionDenormalizerPipeline denormalizerPipeline, EventsourceDIContext diContext, IStateEventMapping eventMapping, ILoggerFactory loggerFactory) { Precondition.For(configuration, nameof(configuration)) .NotNull("Configuration for domainobject repository must not be null!"); this.denormalizerPipeline = denormalizerPipeline; this.configuration = configuration; this.eventMapping = eventMapping; this.diContext = diContext; if (loggerFactory != null) { logger = loggerFactory.CreateLogger(GetType()); } else { logger = new NoopLogger(); } }
public static InMemoryCommandBus CreateConventionCommandBus(IDomainObjectRepository repository, ILoggerFactory loggerFactory, EventSourceConfiguration configuration) { Precondition.For(repository, nameof(repository)).NotNull(); Precondition.For(loggerFactory, nameof(loggerFactory)).NotNull(); Precondition.For(configuration, nameof(configuration)).NotNull(); var logger = loggerFactory.CreateLogger <InMemoryCommandBus>(); logger.LogInformation("Building InMemory CommandBus with convention based pipeline"); var invoker = new ConventionCommandInvoker(repository, loggerFactory); var handler = new ConventionCommandPipeline(invoker, new DomainObjectLocator(), loggerFactory, configuration.DomainObjectAssemblies); var bus = new InMemoryCommandBus(handler, loggerFactory); return(bus); }
public static IServiceCollection AddCqrs(this IServiceCollection services, IConfiguration config) { string eventSecret = "0mDJVERJ34e4qLC6JYvT!$_d#+54d"; var esconfig = new EventSourceConfiguration() .SetEventSecret(eventSecret) .SetDomainObjectAssemblies(typeof(DomainObjectSample).Assembly); string url = config["events:host"]; string db = config["events:db"]; services .AddServiceProviderDomainObjectAcitvator() .AddMongoDomainObjectRepository(() => new MongoClient(url).GetDatabase(db), false, false) .AddConventionBasedInMemoryCommandBus(esconfig) .AddEventSource(esconfig); Console.WriteLine("CQRS added"); return(services); }
public void ShouldInstantiatePipelineFromValidConfiguration() { string pipelineConfiguration = @" { ""inputs"": [ { ""type"": ""EventSource"", ""sources"": [ { ""providerName"": ""Microsoft-ServiceFabric-Services"" }, { ""providerName"": ""MyCompany-AirTrafficControlApplication-Frontend"" } ] } ], ""filters"": [ { ""type"": ""metadata"", ""metadata"": ""importance"", ""include"": ""Level == Verbose"", ""importance"": ""can be discarded"" } ], ""outputs"": [ { ""type"": ""StdOutput"", ""filters"": [ { ""type"": ""metadata"", ""metadata"": ""metric"", ""include"": ""ProviderName == Microsoft-ServiceFabric-Services && EventName == StatefulRunAsyncFailure"", ""metricName"": ""StatefulRunAsyncFailure"", ""metricValue"": ""1.0"" } ] } ], ""schemaVersion"": ""2016-08-11"", ""settings"": { ""maxConcurrency"": ""2"", ""pipelineCompletionTimeoutMsec"": ""1000"" }, ""healthReporter"": { ""type"": ""CustomHealthReporter"", }, ""extensions"": [ { ""category"": ""healthReporter"", ""type"": ""CustomHealthReporter"", ""qualifiedTypeName"": ""Microsoft.Diagnostics.EventFlow.TestHelpers.CustomHealthReporter, Microsoft.Diagnostics.EventFlow.TestHelpers"" } ] }"; try { using (var configFile = new TemporaryFile()) { configFile.Write(pipelineConfiguration); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile(configFile.FilePath); var configuration = builder.Build(); using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(configuration)) { Assert.NotNull(pipeline); Assert.Single(pipeline.Inputs); var eventSourceInput = pipeline.Inputs.First() as EventSourceInput; Assert.NotNull(eventSourceInput); var expectedEventSources = new EventSourceConfiguration[3]; expectedEventSources[0] = new EventSourceConfiguration { ProviderName = "Microsoft-ServiceFabric-Services" }; expectedEventSources[1] = new EventSourceConfiguration { ProviderName = "MyCompany-AirTrafficControlApplication-Frontend" }; // Microsoft-ApplicationInsights-Data is disabled by default to work around https://github.com/dotnet/coreclr/issues/14434 expectedEventSources[2] = new EventSourceConfiguration { DisabledProviderNamePrefix = "Microsoft-ApplicationInsights-Data" }; Assert.True(eventSourceInput.EventSources.SequenceEqual(expectedEventSources)); var metadata = new EventMetadata("importance"); metadata.Properties.Add("importance", "can be discarded"); var metadataFilter = new EventMetadataFilter(metadata); metadataFilter.IncludeCondition = "Level == Verbose"; Assert.True(pipeline.GlobalFilters.Count == 1); Assert.True(pipeline.GlobalFilters.First().Equals(metadataFilter)); Assert.Single(pipeline.Sinks); EventSink sink = pipeline.Sinks.First(); var stdSender = sink.Output as StdOutput; Assert.NotNull(stdSender); metadata = new EventMetadata("metric"); metadata.Properties.Add("metricName", "StatefulRunAsyncFailure"); metadata.Properties.Add("metricValue", "1.0"); metadataFilter = new EventMetadataFilter(metadata); metadataFilter.IncludeCondition = "ProviderName == Microsoft-ServiceFabric-Services && EventName == StatefulRunAsyncFailure"; Assert.True(sink.Filters.Count == 1); Assert.True(sink.Filters.First().Equals(metadataFilter)); } } } finally { TryDeleteFile(CsvHealthReporter.DefaultLogFilePrefix); } }
protected DomainObjectRepositoryBase(EventSourceConfiguration configuration) { this.configuration = configuration; }
static void Main(string[] args) { var healthReporter = new BenchmarkHealthReporter(); var esConfiguration = new EventSourceConfiguration(); esConfiguration.ProviderName = "Microsoft-AzureTools-BenchmarkEventSource"; var eventSourceInput = new EventSourceInput(new EventSourceConfiguration[] { esConfiguration }, healthReporter); var metadata = new EventMetadata("importantEvent"); metadata.Properties.Add("Importance", "High"); EventMetadataFilter metadataFilter = new EventMetadataFilter(metadata); metadataFilter.IncludeCondition = "name==ImportantEvent"; var oddSequenceNumberFilter = new CallbackFilter((e) => HasLongPropertyWhere(e.Payload, "sequenceNumber", (n) => (n & 0x1) != 0)); var evenSequenceNumberFilter = new CallbackFilter((e) => HasLongPropertyWhere(e.Payload, "sequenceNumber", (n) => (n & 0x1) == 0)); var oddSequenceNumberOutput = new BenchmarkOutput("Odd sequence number output"); var evenSequenceNumberOutput = new BenchmarkOutput("Even sequence number output"); var sinks = new EventSink[] { new EventSink(oddSequenceNumberOutput, new IFilter[] { oddSequenceNumberFilter }), new EventSink(evenSequenceNumberOutput, new IFilter[] { evenSequenceNumberFilter }) }; var configuration = new DiagnosticPipelineConfiguration(); configuration.PipelineCompletionTimeoutMsec = Convert.ToInt32(CoolDownTime.TotalMilliseconds); var pipeline = new DiagnosticPipeline( healthReporter, new IObservable <EventData>[] { eventSourceInput }, new IFilter[] { metadataFilter }, sinks, configuration); Console.WriteLine(string.Format("Starting test... will take {0} seconds", (WarmUpTime + MeasurementTime).TotalSeconds)); Console.WriteLine("A dot represents 10 000 events submitted"); DateTimeOffset startTime = DateTimeOffset.Now; DateTimeOffset measurementStartTime = startTime + WarmUpTime; DateTimeOffset measurementStopTime = measurementStartTime + MeasurementTime; DateTimeOffset stopTime = measurementStopTime + CoolDownTime; bool debugMode = args.Length == 1 && string.Equals(args[0], "debug", StringComparison.OrdinalIgnoreCase); long eventSequenceNo = 1; bool measuring = debugMode; long measuredEventCount = 0; while (true) { // Every tenth event is important string name = "RegularEvent"; if (eventSequenceNo % 10 == 0) { name = "ImportantEvent"; } BenchmarkEventSource.Log.ComplexMessage( Guid.NewGuid(), Guid.NewGuid(), eventSequenceNo++, name, DateTime.Now, DateTime.UtcNow, "Complex event message. blah blah"); if (measuring) { measuredEventCount++; } if (debugMode) { if (measuredEventCount == 10) { break; } } else { if (eventSequenceNo % EventBatchSize == 0) { DateTimeOffset now = DateTimeOffset.Now; // In this benchmmark we do not really have a cooldown period, so we do not have to account for not-measuring period at the end. if (!measuring) { bool shouldBeMeasuring = (now >= measurementStartTime && now < measurementStopTime); if (shouldBeMeasuring) { oddSequenceNumberOutput.ResetCounter(); evenSequenceNumberOutput.ResetCounter(); healthReporter.ResetCounters(); measuring = true; } } if (eventSequenceNo % 10000 == 0) { Console.Write("."); } if (now >= stopTime) { break; } } } } Console.WriteLine(string.Empty); Console.WriteLine("Enterning cooldown period..."); Thread.Sleep(CoolDownTime); pipeline.Dispose(); Console.WriteLine(string.Empty); Console.WriteLine($"Total events raised during measurement period: {measuredEventCount}"); Console.WriteLine(oddSequenceNumberOutput.Summary); Console.WriteLine(evenSequenceNumberOutput.Summary); double processingRate = (oddSequenceNumberOutput.EventCount + evenSequenceNumberOutput.EventCount) / MeasurementTime.TotalSeconds; Console.WriteLine($"Processing rate (events/sec): {processingRate}"); Console.WriteLine(healthReporter.Summary); Console.WriteLine("Press any key to exit"); Console.ReadKey(intercept: true); }
public static EventSourceConfiguration SetServiceCollectionActivator(this EventSourceConfiguration config, IUnityContainer container) { config.Activator = new UnityDomainObjectActivator(container); return(config); }
public void ApplyConfig(EventSourceConfiguration configuration) { this.stateActivator = configuration.StateActivator; }
/// <summary> /// Initializes a new instance of the <see cref="AttributeIndex"/> class. /// </summary> /// <param name="parent">The parent.</param> public AttributeIndex(EventSourceConfiguration parent) { _parent = parent; }
static async Task Main(string[] args) { var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); var db = serviceProvider.GetRequiredService <IMongoDatabase>(); var cfg = new EventSourceConfiguration() { Activator = new ActivatorDomainObjectActivator(), LoggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(), StateActivator = new ActivatorDomainObjectActivator() }; var repo = new MongoDomainObjectRepository(cfg, db); var bo2 = await repo.Get <SampleBo>("53fda695-5186-4253-a495-8f989d03dbf3"); bo2.Next(); Console.WriteLine("next"); Console.ReadLine(); var bo = new SampleBo(Guid.NewGuid().ToString()); bo.ApplyConfig(cfg); bo.Execute(); bo.Next(); repo.SaveAsync(bo).Wait(); repo.SaveAsync(bo).Wait(); bo.Execute(); bo.Execute(); repo.SaveAsync(bo).Wait(); //bo = new SampleBo("1"); // bo.Execute(); // repo.SaveAsync(bo).Wait(); //bo = new SampleBo("2"); //bo.Execute(); //repo.SaveAsync(bo).Wait(); //bo = new SampleBo("3"); //bo.Execute(); //bo.Next(); //repo.SaveAsync(bo).Wait(); //bo.CommitChanges(); //bo.Next(); //repo.SaveAsync(bo).Wait(); //Console.WriteLine(repo.Exists<SampleBo>("1").Result.ToString(), " - ", // repo.GetVersion<SampleBo>("1").Result); //Console.WriteLine(repo.Exists<SampleBo>("2").Result.ToString(), " - ", // repo.GetVersion<SampleBo>("2").Result); //Console.WriteLine(repo.Exists<SampleBo>("3").Result.ToString(), " - ", // repo.GetVersion<SampleBo>("3").Result); //Console.WriteLine(repo.Exists<SampleBo>("4").Result.ToString()); //test(repo).Wait(); Console.ReadLine(); }
public void ApplyConfig(EventSourceConfiguration configuration) { stateRuntime = new DomainObjectStateRuntime(this, configuration); }
public static EventSourceConfiguration SetEventstoreDomainObjectRepository(this EventSourceConfiguration config, IEventStoreConnection db) { // TODO throw new NotImplementedException(); }
/// <summary> /// Loads from configuration. /// </summary> /// <param name="descriptor">The descriptor.</param> /// <param name="service">The service.</param> /// <param name="configuration">The configuration.</param> public static void LoadFromConfiguration(this EventSourceManager.ISetupDescriptor descriptor, Lazy <IEventSource> service, EventSourceConfiguration configuration) { if (service == null) { throw new ArgumentNullException("service"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } }
/// <summary> /// Loads from configuration. /// </summary> /// <param name="service">The service.</param> /// <param name="configuration">The configuration.</param> /// <returns></returns> public static Lazy <IEventSource> LoadFromConfiguration(this Lazy <IEventSource> service, EventSourceConfiguration configuration) { EventSourceManager.GetSetupDescriptor(service).LoadFromConfiguration(service, configuration); return(service); }
public DomainObjectStateRuntime(IDomainObject domainObject, EventSourceConfiguration config) { this.domainObject = domainObject; activator = config.StateActivator; stateToEventMapper = config.StateToEventMapper; }
public FakeRepository(EventSourceConfiguration configuration) : base(configuration) { }
public FakeRepository(EventSourceConfiguration configuration, EventsourceDIContext diContext) : base( configuration, null, diContext, new StateEventMapping(), null) { }
public MongoDomainObjectRepository(EventSourceConfiguration configuration, IMongoDatabase db) : base(configuration) { repository = new MongoCommitRepository(db); }
public EventStoreRepository(EventStoreContext context, EventSourceConfiguration configuration) : base(configuration) { this.context = context; }