public async Task <IActionResult> AddCheck(string id) { var check = EventGenerator.CheckWritten(id); await _eventStoreRepository.AddEventAsync(id, check); return(RedirectToAction("Details", new { id = id })); }
public StreamSetupSteps(EventGenerator eventGenerator, StreamInfoContainer streamInfo, InMemoryStoreSessionContainer sessionContainer) { this.eventGenerator = eventGenerator; this.streamInfo = streamInfo; this.sessionContainer = sessionContainer; }
public void SetUp() { _activtyRepo = new Mock <IActivityRepository>(); _eventRepo = new Mock <IEventRepository>(); _sut = new EventGenerator(_eventRepo.Object, _activtyRepo.Object); }
public async Task <IActionResult> CreateAsync() { var openEvent = EventGenerator.BankAccountOpened(); await _eventStoreRepository.AddEventAsync(openEvent.AccountNumber, openEvent); return(RedirectToAction("Index")); }
/// <summary> /// CollectData turn on logging of data from 'eventSourceName' to the file 'dataFileName'. /// It will then call EventGenerator.CreateEvents and wait 12 seconds for it to generate some data. /// </summary> static void CollectData(string eventSourceName, string dataFileName) { // Today you have to be Admin to turn on ETW events (anyone can write ETW events). if (!(TraceEventSession.IsElevated() ?? false)) { Out.WriteLine("To turn on ETW events you need to be Administrator, please run from an Admin process."); Debugger.Break(); return; } // As mentioned below, sessions can outlive the process that created them. Thus you need a way of // naming the session so that you can 'reconnect' to it from another process. This is what the name // is for. It can be anything, but it should be descriptive and unique. If you expect multiple versions // of your program to run simultaneously, you need to generate unique names (e.g. add a process ID suffix) // however this is dangerous because you can leave data collection on if the program ends unexpectedly. // // In this case we tell the session to place the data in MonitorToFileData.etl. var sessionName = "SimpleMontitorSession"; Out.WriteLine("Creating a '{0}' session writing to {1}", sessionName, dataFileName); Out.WriteLine("Use 'logman query -ets' to see active sessions."); Out.WriteLine("Use 'logman stop {0} -ets' to manually stop orphans.", sessionName); using (var session = new TraceEventSession(sessionName, dataFileName)) // Since we give it a file name, the data goes there. { /* BY DEFAULT ETW SESSIONS SURVIVE THE DEATH OF THE PROESS THAT CREATES THEM! */ // Unlike most other resources on the system, ETW session live beyond the lifetime of the // process that created them. This is very useful in some scenarios, but also creates the // very real possibility of leaving 'orphan' sessions running. // // To help avoid this by default TraceEventSession sets 'StopOnDispose' so that it will stop // the ETW session if the TraceEventSession dies. Thus executions that 'clean up' the TraceEventSession // will clean up the ETW session. This covers many cases (including throwing exceptions) // // However if the process is killed manually (including control C) this cleanup will not happen. // Thus best practices include // // * Add a Control C handler that calls session.Dispose() so it gets cleaned up in this common case // * use the same session name run-to-run so you don't create many orphans. // // By default TraceEventSessions are in 'create' mode where it assumes you want to create a new session. // In this mode if a session already exists, it is stopped and the new one is created. // // Here we install the Control C handler. It is OK if Dispose is called more than once. Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { session.Dispose(); }; // Enable my provider, you can call many of these on the same session to get other events. var restarted = session.EnableProvider(MyEventSource.Log.Name); if (restarted) // Generally you don't bother with this warning, but for the demo we do. { Out.WriteLine("The session {0} was already active, it has been restarted.", sessionName); } // Start another thread that Causes MyEventSource to create some events // Normally this code as well as the EventSource itself would be in a different process. EventGenerator.CreateEvents(); Out.WriteLine("Waiting 12 seconds for events to come in."); Thread.Sleep(12000); } }
private void Download(object param) { var save = new SaveFileDialog { Filter = "zip|*.zip", Title = "Download Submission" }; save.ShowDialog(); if (save.FileName == "") { return; } using (var stream = (FileStream)save.OpenFile()) { using (var writer = new BinaryWriter(stream)) { writer.Write(Submission.SolutionData); } } //Notify that a submission has been downloaded var generator = EventGenerator.GetInstance(); generator.NotifySolutionDownloaded(Submission); }
public async Task ProducerUpdatesPropertiesAfterPublishingEvents() { await using (EventHubScope scope = await EventHubScope.CreateAsync(1)) { var connectionString = EventHubsTestEnvironment.Instance.BuildConnectionStringForEventHub(scope.EventHubName); var options = new EventHubProducerClientOptions { EnableIdempotentPartitions = true }; await using var producer = new EventHubProducerClient(connectionString, options); var cancellationSource = new CancellationTokenSource(); cancellationSource.CancelAfter(EventHubsTestEnvironment.Instance.TestExecutionTimeLimit); var partition = (await producer.GetPartitionIdsAsync(cancellationSource.Token)).First(); var initialPartitionProperties = await producer.GetPartitionPublishingPropertiesAsync(partition); var sendOptions = new SendEventOptions { PartitionId = partition }; var events = EventGenerator.CreateEvents(10).ToArray(); await producer.SendAsync(events, sendOptions, cancellationSource.Token); var updatedPartitionProperties = await producer.GetPartitionPublishingPropertiesAsync(partition); Assert.That(updatedPartitionProperties.IsIdempotentPublishingEnabled, Is.True, "Idempotent publishing should be enabled."); Assert.That(updatedPartitionProperties.ProducerGroupId, Is.EqualTo(initialPartitionProperties.ProducerGroupId), "The producer group identifier should not have changed."); Assert.That(updatedPartitionProperties.OwnerLevel, Is.EqualTo(initialPartitionProperties.OwnerLevel), "The owner level should not have changed."); Assert.That(updatedPartitionProperties.LastPublishedSequenceNumber, Is.GreaterThan(initialPartitionProperties.LastPublishedSequenceNumber), "The last published sequence number should have increased."); } }
public async Task ProducerAllowsPublishingConcurrentlyToDifferentPartitions() { await using (EventHubScope scope = await EventHubScope.CreateAsync(4)) { var connectionString = EventHubsTestEnvironment.Instance.BuildConnectionStringForEventHub(scope.EventHubName); var options = new EventHubProducerClientOptions { EnableIdempotentPartitions = true }; await using var producer = new EventHubProducerClient(connectionString, options); var cancellationSource = new CancellationTokenSource(); cancellationSource.CancelAfter(EventHubsTestEnvironment.Instance.TestExecutionTimeLimit); async Task sendEvents(string partition, int delayMilliseconds) { await Task.Delay(delayMilliseconds); await producer.SendAsync(EventGenerator.CreateEvents(5), new SendEventOptions { PartitionId = partition }, cancellationSource.Token); } var partitions = await producer.GetPartitionIdsAsync(cancellationSource.Token); var pendingSends = new List <Task>(); foreach (var partition in partitions) { pendingSends.Add(sendEvents(partition, 50)); pendingSends.Add(sendEvents(partition, 0)); } Assert.That(async() => await Task.WhenAll(pendingSends), Throws.Nothing); } }
public async Task ProducerManagesConcurrencyWhenPublishingEvents() { await using (EventHubScope scope = await EventHubScope.CreateAsync(1)) { var connectionString = EventHubsTestEnvironment.Instance.BuildConnectionStringForEventHub(scope.EventHubName); var options = new EventHubProducerClientOptions { EnableIdempotentPartitions = true }; await using var producer = new EventHubProducerClient(connectionString, options); var cancellationSource = new CancellationTokenSource(); cancellationSource.CancelAfter(EventHubsTestEnvironment.Instance.TestExecutionTimeLimit); var partition = (await producer.GetPartitionIdsAsync(cancellationSource.Token)).First(); var sendOptions = new SendEventOptions { PartitionId = partition }; async Task sendEvents(int delayMilliseconds) { await Task.Delay(delayMilliseconds); await producer.SendAsync(EventGenerator.CreateEvents(2), sendOptions, cancellationSource.Token); } var pendingSends = Task.WhenAll( sendEvents(100), sendEvents(50), sendEvents(0) ); Assert.That(async() => await pendingSends, Throws.Nothing); } }
public async Task <IActionResult> CloseAccount(string id) { var close = EventGenerator.BankAccountClosed(id); await _eventStoreRepository.AddEventAsync(id, close); return(RedirectToAction("Details", new { id = id })); }
public async Task <IActionResult> AddDeposit(string id) { var deposit = EventGenerator.DepositMoney(id); await _eventStoreRepository.AddEventAsync(id, deposit); return(RedirectToAction("Details", new { id = id })); }
private async Task PerformEnqueue(EventHubBufferedProducerClient producer, CancellationToken cancellationToken) { var events = EventGenerator.CreateEvents(_testConfiguration.MaximumEventListSize, _testConfiguration.EventEnqueueListSize, _testConfiguration.LargeMessageRandomFactorPercent, _testConfiguration.PublishingBodyMinBytes, _testConfiguration.PublishingBodyRegularMaxBytes); try { await producer.EnqueueEventsAsync(events, cancellationToken).ConfigureAwait(false); _metrics.Client.GetMetric(_metrics.EventsEnqueued).TrackValue(_testConfiguration.EventEnqueueListSize); } catch (TaskCanceledException) { // Run is completed. } catch (Exception ex) { var eventProperties = new Dictionary <String, String>(); // Track that the exception took place during the enqueuing of an event eventProperties.Add("Process", "Enqueue"); _metrics.Client.TrackException(ex, eventProperties); } }
public void TestGenerateDelegateEvents() { var gen = new CodeUnitGenerator("TestCodeGen"); var classGen = new ClassGenerator("TestClass"); var delegateGen = new DelegateGenerator("MyEventHandler") .AddParameter("TestClass", "myRef") .AddReturnType(typeof(bool)); var eventGen = new EventGenerator("OnSomeTrigger", delegateGen.delegateType); classGen.AddEvent(eventGen); var fireEventMethod = new MethodGenerator("FireEvent") .AddStatement(new StatementBuilder() //.AddSnippetExpression("Debug.Log();DoMoreStuff();")); .InvokeEvent(eventGen, new ParamBuilder() .AddPrimitiveExpression("new TestClass()"))); classGen.AddMethod(fireEventMethod); gen.AddType(delegateGen); gen.AddType(classGen); var classSubscriber = new ClassGenerator("MySubscribeClass"); var field = new FieldGenerator("TestClass", "eventSource"); classSubscriber.AddField(field); var constructor = new ConstructorGenerator(classSubscriber.classType); classSubscriber.AddMethod(constructor); var eventHandler = new MethodGenerator("OnSomeTrigger", delegateGen) .AddStatement(new StatementBuilder() .AddSnippet("Debug.Log(\"Expression1\");") .AddSnippet("Debug.Log(\"Expression2\");")); var subscribeMethod = new MethodGenerator("AddListener") .AddStatement(new StatementBuilder() .AttachEvent(eventHandler, new FieldTarget(field), eventGen)); classSubscriber.AddMethod( new MethodGenerator("Unsubscribe").AddStatement( new StatementBuilder() .DetachEvent(eventHandler, new FieldTarget(field), eventGen))); classSubscriber.AddMethod(eventHandler); classSubscriber.AddMethod(subscribeMethod); gen.AddType(classSubscriber); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); //Debug.Log(output); Assert.IsTrue(output.Contains("OnSomeTrigger")); Assert.IsTrue(output.Contains("FireEvent")); Assert.IsTrue(output.Contains("+=")); Assert.IsTrue(output.Contains("-=")); Assert.IsTrue(output.Contains("delegate")); Assert.IsTrue(output.Contains("event")); }
/// <summary> /// Seeds the Event Hub partition with enough events to satisfy the read operations the test scenario /// is expected to perform. /// </summary> /// /// <param name="producer">The producer to use for publishing events; ownership is assumed to be retained by the caller.</param> /// <param name="bodySizeBytes">The size, in bytes, that the body of events used to seed the Event Hub should be.</param> /// <param name="eventCount">The number of events that should be published, distributed among partitions.</param> /// private static async Task SeedEventsToBeReadAsync(EventHubProducerClient producer, int bodySizeBytes, int eventCount) { // Use the same event body for all events being published, to ensure consistency of the data being // read and processed for the test. var eventBody = EventGenerator.CreateRandomBody(bodySizeBytes); var remainingEvents = eventCount; while (remainingEvents > 0) { using var batch = await producer.CreateBatchAsync().ConfigureAwait(false); while ((batch.TryAdd(EventGenerator.CreateEventFromBody(eventBody))) && (remainingEvents > 0)) { --remainingEvents; } // If there were no events in the batch, then a single event was generated that is too large to // ever send. In this context, it will be detected on the first TryAdd call, since events are // sharing a common body. if (batch.Count == 0) { throw new InvalidOperationException("There was an event too large to fit into a batch."); } await producer.SendAsync(batch).ConfigureAwait(false); } }
/// <summary> /// Seeds the Event Hub partition with enough events to satisfy the read operations the test scenario /// is expected to perform. /// </summary> /// /// <param name="producer">The producer to use for publishing events; ownership is assumed to be retained by the caller.</param> /// /// <remarks> /// This method makes heavy use of class state, including the /// test environment and command line options. /// </remarks> /// private async Task SeedEventsToBeReadAsync(EventHubProducerClient producer) { // Calculate the number of events needed to satisfy the number of events per iteration // and then buffer it to allow for the warm-up. var eventCount = Options.BatchSize * Options.Iterations * 3; var eventBody = EventGenerator.CreateRandomBody(Options.BodySize); var batchOptions = new CreateBatchOptions { PartitionId = PartitionId }; foreach (var eventData in EventGenerator.CreateEventsFromBody(eventCount, eventBody)) { using var batch = await producer.CreateBatchAsync(batchOptions).ConfigureAwait(false); // Fill the batch with as many events that will fit. while (batch.TryAdd(EventGenerator.CreateEventFromBody(eventBody))) { } // If there were no events in the batch, then a single event was generated that is too large to // ever send. In this context, it will be detected on the first TryAdd call, since events are // sharing a common body. if (batch.Count == 0) { throw new InvalidOperationException("There was an event too large to fit into a batch."); } await producer.SendAsync(batch).ConfigureAwait(false); } }
/// <summary> /// Executes the performance test scenario asynchronously. /// </summary> /// /// <param name="cancellationToken">The token used to signal when cancellation is requested.</param> /// public async override Task <int> RunBatchAsync(CancellationToken cancellationToken) { using var batch = await s_producer.CreateBatchAsync(_batchOptions, cancellationToken).ConfigureAwait(false); // Fill the batch with events using the same body. This will result in a batch of events of equal size. // The events will only differ by the id property that is assigned to them. foreach (var eventData in EventGenerator.CreateEventsFromBody(Options.BatchSize, s_eventBody)) { if (!batch.TryAdd(eventData)) { throw new InvalidOperationException("It was not possible to fit the requested number of events in a single batch."); } } try { await s_producer.SendAsync(batch, cancellationToken).ConfigureAwait(false); return(Options.BatchSize); } catch (EventHubsException ex) when(cancellationToken.IsCancellationRequested && ex.IsTransient) { // If SendAsync() is canceled during a retry loop, the most recent exception is thrown. // If the exception is transient, it should be wrapped in an OperationCanceledException // which is ignored by the performance framework. throw new OperationCanceledException("EventHubsException thrown during cancellation", ex); } }
public async Task ProducerInitializesPropertiesWhenPublishing() { await using (EventHubScope scope = await EventHubScope.CreateAsync(1)) { var connectionString = EventHubsTestEnvironment.Instance.BuildConnectionStringForEventHub(scope.EventHubName); var options = new IdempotentProducerOptions { EnableIdempotentPartitions = true }; await using var producer = new IdempotentProducer(connectionString, options); var cancellationSource = new CancellationTokenSource(); cancellationSource.CancelAfter(EventHubsTestEnvironment.Instance.TestExecutionTimeLimit); var partition = (await producer.GetPartitionIdsAsync(cancellationSource.Token)).First(); var sendOptions = new SendEventOptions { PartitionId = partition }; var events = EventGenerator.CreateEvents(10).ToArray(); await producer.SendAsync(events, sendOptions, cancellationSource.Token); var partitionProperties = await producer.GetPartitionPublishingPropertiesAsync(partition); Assert.That(partitionProperties, Is.Not.Null, "The properties should have been created."); Assert.That(partitionProperties.IsIdempotentPublishingEnabled, Is.True, "Idempotent publishing should be enabled."); Assert.That(partitionProperties.ProducerGroupId.HasValue, Is.True, "The producer group identifier should have a value."); Assert.That(partitionProperties.OwnerLevel.HasValue, Is.True, "The owner level should have a value."); Assert.That(partitionProperties.LastPublishedSequenceNumber.HasValue, Is.True, "The last published sequence number should have a value."); } }
public async Task ProducerCanPublishBatches(EventHubsTransportType transportType) { await using (EventHubScope scope = await EventHubScope.CreateAsync(1)) { var connectionString = EventHubsTestEnvironment.Instance.BuildConnectionStringForEventHub(scope.EventHubName); var options = new IdempotentProducerOptions { EnableIdempotentPartitions = true, ConnectionOptions = new EventHubConnectionOptions { TransportType = transportType } }; await using var producer = new IdempotentProducer(connectionString, options); var cancellationSource = new CancellationTokenSource(); cancellationSource.CancelAfter(EventHubsTestEnvironment.Instance.TestExecutionTimeLimit); var partition = (await producer.GetPartitionIdsAsync()).First(); var batchOptions = new CreateBatchOptions { PartitionId = partition }; using var firstBatch = await producer.CreateBatchAsync(batchOptions, cancellationSource.Token); firstBatch.TryAdd(EventGenerator.CreateEvents(1).First()); using var secondBatch = await producer.CreateBatchAsync(batchOptions, cancellationSource.Token); secondBatch.TryAdd(EventGenerator.CreateEvents(1).First()); secondBatch.TryAdd(EventGenerator.CreateEvents(1).First()); Assert.That(async() => await producer.SendAsync(firstBatch, cancellationSource.Token), Throws.Nothing, "The first publishing operation was not successful."); Assert.That(async() => await producer.SendAsync(secondBatch, cancellationSource.Token), Throws.Nothing, "The second publishing operation was not successful."); } }
private static (ImmutableArray <Diagnostic> Diagnostics, string Output) GetGeneratedOutput(string source) { var syntaxTree = CSharpSyntaxTree.ParseText(source); var references = new List <MetadataReference>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (!assembly.IsDynamic) { references.Add(MetadataReference.CreateFromFile(assembly.Location)); } } var compilation = CSharpCompilation.Create("foo", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var diagnostics = compilation.GetDiagnostics(); if (diagnostics.Any()) { return(diagnostics, string.Empty); } var generator = new EventGenerator(); var driver = CSharpGeneratorDriver.Create(generator); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out diagnostics); return(diagnostics, outputCompilation.SyntaxTrees.Last().ToString()); }
private static void RunHandler( TimeSpan interval, TimeSpan timeout, TimeSpan period, TimeSpan frequency) { var receiver = new Receiver(); var generator = new EventGenerator <ReportEvent>( frequency, () => DataGenerator.GenetationReportEvent(timeout)); void receiveData(ReportEvent[] data) => receiver.Receive(data); var dictionary = new QueueByTime <ReportEvent>(timeout, interval); dictionary.PulledData += receiveData; void addData(ReportEvent data) => dictionary.Push(data.Time, data); generator.Generated += addData; generator.Start(); Task.Delay(period).Wait(); generator.Stop(); dictionary.PulledData -= receiveData; generator.Generated -= addData; }
private void Form1_Load(object sender, EventArgs e) { //Initializing Pictures and Buttons // // // // // // // Change the links of the images and the wav to run the program// // // // // // // pictureBox1.Image = Image.FromFile(@"H:\Visual Basic 2008 - PROJECTS C#\LiftSimulator-v.Timer-v.1\FormLiftSimulator\Images\blue.png"); button10.Image = Image.FromFile(@"H:\Visual Basic 2008 - PROJECTS C#\LiftSimulator-v.Timer-v.1\FormLiftSimulator\Images\downLightBlue.png"); button9.Image = Image.FromFile(@"H:\Visual Basic 2008 - PROJECTS C#\LiftSimulator-v.Timer-v.1\FormLiftSimulator\Images\downLightBlue.png"); button7.Image = Image.FromFile(@"H:\Visual Basic 2008 - PROJECTS C#\LiftSimulator-v.Timer-v.1\FormLiftSimulator\Images\downLightBlue.png"); button5.Image = Image.FromFile(@"H:\Visual Basic 2008 - PROJECTS C#\LiftSimulator-v.Timer-v.1\FormLiftSimulator\Images\upLightBlue.png"); button6.Image = Image.FromFile(@"H:\Visual Basic 2008 - PROJECTS C#\LiftSimulator-v.Timer-v.1\FormLiftSimulator\Images\upLightBlue.png"); button8.Image = Image.FromFile(@"H:\Visual Basic 2008 - PROJECTS C#\LiftSimulator-v.Timer-v.1\FormLiftSimulator\Images\upLightBlue.png"); //play welcome wav "welcome to the simulator" playWelcome(); //initializing the labels in the lift and on the floors label5.Text = "0"; label13.Text = "0"; label14.Text = "0"; label15.Text = "0"; label16.Text = "0"; //Initializing Generator's State generatorState = "PAUSE"; //The two other basic objects of the project(Controller and EventGenerator) myController = new Controller(); myEventGenerator = new EventGenerator(); //Setting up the timers myTimer1 = new System.Windows.Forms.Timer(); myTimer1.Interval = 25; //steady delay for timer 1 myTimer1.Tick += timer1_Tick; myTimer2 = new System.Windows.Forms.Timer(); myTimer2.Interval = 25; //steady delay for timer 2 myTimer2.Tick += timer2_Tick; myTimer3 = new System.Windows.Forms.Timer(); myTimer3.Interval = meantTime; //adjustable delay for timer 3 myTimer3.Tick += timer3_Tick; //Type First given speed value label7.Text = Convert.ToString(myController.speed); //Controller Thread is executing in parallel with the Form Code controllerThread = new Thread(new ThreadStart(myController.ControllerMethod)); controllerThread.Start(); //initialize the directionFlag myController.directionFlag = "STABLE"; }
public SaveEventsStreamSteps(InProcEventStoreIntegrationContext eventStoreContainer, EventGenerator eventGenerator, TestDataContext testDataContext) { this.eventStoreContainer = eventStoreContainer ?? throw new ArgumentNullException(nameof(eventStoreContainer)); this.eventGenerator = eventGenerator ?? throw new ArgumentNullException(nameof(eventGenerator)); this.testDataContext = testDataContext ?? throw new ArgumentNullException(nameof(testDataContext)); }
// The constructor is given the event generator class instance public TheClass(EventGenerator evGen) { // create a unique identifier for the class _identifier = Guid.NewGuid(); // subscribe to the event _eventGenerator = evGen; _eventGenerator.TheEvent += TheEvent; }
private void OnDestroy() { if (_instance == this) { _instance = null; } TurnController.TurnStartEvent -= GenerateEvents; }
// Use this for initialization void Start() { eg = GameObject.FindObjectOfType <EventGenerator>(); em = GetComponent <EventMove>(); player = GameObject.FindObjectOfType <PlayerCharacter>(); //PlayEvent(race, classes, player.money); }
/// <summary> /// Performs the tasks needed to initialize and set up the environment for the test scenario. /// This setup will take place once for each instance, running after the global setup has /// completed. /// </summary> /// public override async Task SetupAsync() { await base.SetupAsync(); Scope = await EventHubScope.CreateAsync(Options.PartitionCount).ConfigureAwait(false); var producerOptions = new EventHubBufferedProducerClientOptions { MaximumWaitTime = (Options.MaximumWaitTimeMilliseconds.HasValue) ? TimeSpan.FromMilliseconds(Options.MaximumWaitTimeMilliseconds.Value) : null, MaximumEventBufferLengthPerPartition = Options.MaximumBufferLength, MaximumConcurrentSendsPerPartition = Options.MaximumConcurrentSendsPerPartition }; if (Options.MaximumConcurrentSends.HasValue) { producerOptions.MaximumConcurrentSends = Options.MaximumConcurrentSends.Value; } _producer = new EventHubBufferedProducerClient(TestEnvironment.EventHubsConnectionString, Scope.EventHubName, producerOptions); // Create the handlers that call into the performance test infrastructure to // report when errors and events are observed. _producer.SendEventBatchFailedAsync += args => { // Do not flag cancellation as a failure; it is expected for in-flight batches when // the test run is cleaning up. if (!typeof(OperationCanceledException).IsAssignableFrom(args.Exception.GetType())) { ErrorRaised(args.Exception); } return(Task.CompletedTask); }; _producer.SendEventBatchSucceededAsync += args => { for (var index = 0; index < args.EventBatch.Count; ++index) { EventRaised(); } return(Task.CompletedTask); }; // Read the available partitions and buffer a single events to establish the // connection and link and start reading the buffers. Partitions = await _producer.GetPartitionIdsAsync().ConfigureAwait(false); await _producer.EnqueueEventsAsync(EventGenerator.CreateEvents(1)).ConfigureAwait(false); // Start the background publishing task. _backgroundCancellationSource = new CancellationTokenSource(); _backgroundBufferingTask = EnqueueEvents(_backgroundCancellationSource.Token); }
private void MoveCaret(Key key) { var evtArgs = EventGenerator.CreateKeyEventArgs(key); if (Common.Context.CaretMoveCommand.CanExecute(evtArgs)) { Common.Context.CaretMoveCommand.Execute(evtArgs); } }
private void SetupServiceClient() { _eventHandler = new VsEventHandler(this, EventGenerator.GetInstance()); //need the toolManager to open the intervention window _eventHandler.InterventionUpdate += InterventionReceivedUpdate; _client = ServiceClient.GetInstance(_eventHandler, _errorLogger); _client.PropertyChanged += ServiceClientPropertyChanged; _client.ReceivedNewSocialActivity += ServiceClientReceivedSocialUpdate; }
/// <summary> /// Performs the tasks needed to initialize and set up the environment for the test scenario. /// When multiple instances are run in parallel, the setup will take place once, prior to the /// execution of the first test instance. /// </summary> /// public async override Task GlobalSetupAsync() { await base.GlobalSetupAsync().ConfigureAwait(false); s_scope = await EventHubScope.CreateAsync(Options.PartitionCount).ConfigureAwait(false); s_producer = new EventHubProducerClient(TestEnvironment.EventHubsConnectionString, s_scope.EventHubName); s_eventBody = EventGenerator.CreateRandomBody(Options.BodySize); }
public SaveEventsStreamSteps( EventStoreIntegrationContext eventStoreContainer, EventGenerator eventGenerator, IList <TestDataContext> testDataContexts) { this.eventStoreContainer = eventStoreContainer ?? throw new ArgumentNullException(nameof(eventStoreContainer)); this.eventGenerator = eventGenerator ?? throw new ArgumentNullException(nameof(eventGenerator)); this.testDataContexts = testDataContexts ?? throw new ArgumentNullException(nameof(testDataContexts)); }
public void SetUp() { _activtyRepo = new Mock<IActivityRepository>(); _eventRepo = new Mock<IEventRepository>(); _sut = new EventGenerator(_eventRepo.Object, _activtyRepo.Object); }
/** * Start the controller. * * @throws InterruptedException */ public void run() { long start = wallTimer.ElapsedMilliseconds; long endTime = start + runTime; long now; double currentRate = 0.0; long averageSleep = (long) (Millis2Seconds / averageRate); totalEvents = 0; wallTimer.Start(); double burstRate = 0.0; int burstSize = 0; // ensure that first sample time is different from start time... int settleTime = 2 * Millis; appLog.info("Settling for {0}: ", settleTime); Thread.Sleep(settleTime); // just run some queries if (queryOnly) { appLog.info("Query-Only..."); long eventId = 1; while (wallTimer.ElapsedMilliseconds < endTime) { EventViewTask viewTask = new EventViewTask(this, eventId++); //queryExecutor.schedule(new EventViewTask(this, eventId++), 2, TimeUnit.MILLISECONDS); queryExecutor.schedule(viewTask, 2); totalEvents++; double wallTime = (1.0 * wallTimer.ElapsedTicks) / Stopwatch.Frequency; double queryTime = (1.0 * totalQueryTime) / Stopwatch.Frequency; appLog.info("Processed {0:N} events containing {1:N} records in {2:F2} secs" + "\n\tThroughput:\t{3:F2} events/sec at {4:F2} ips;" + "\n\tSpeed:\t\t{5:N} inserts in {6:F2} secs = {7:F2} ips" + "\n\tQueries:\t{8:N} queries got {9:N} records in {10:F2} secs at {11:F2} qps", totalEvents, totalInserts, wallTime, (totalEvents / wallTime), 0, totalInserts, 0, 0, totalQueries, totalQueryRecords, queryTime, (totalQueries / queryTime)); //if (((ThreadPoolExecutor) queryExecutor).getQueue().size() > 10) { if (totalEvents + 10 > totalQueries) { appLog.info("{0} queries waiting - sleeping", totalEvents - totalQueries); Thread.Sleep(200); } } return; } do { EventGenerator generator = new EventGenerator(this, unique++); //insertExecutor.execute(new EventGenerator(this, unique++)); insertExecutor.execute(generator); totalEvents++; //int queueSize = ((ThreadPoolExecutor) insertExecutor).getQueue().size()); //Int64 queueSize = totalScheduled - totalEvents; long queueSize = insertExecutor.QueueSize(); appLog.info("Event scheduled. Queue size={0}", queueSize); now = wallTimer.ElapsedMilliseconds; currentRate = (Millis2Seconds * totalEvents) / (now - start); appLog.info("now={0}; endTime={1}; elapsed={2}; time left={3}", now, endTime, now - start, endTime - now); // randomly create a burst if (burstSize == 0 && burstProbability > 0 && Percent * random.NextDouble() <= burstProbability) { burstSize = minBurst + random.Next(maxBurst - minBurst); appLog.info("Creating burst of {0}", burstSize); } if (burstSize > 0) { burstSize--; } else { if (averageRate > 0) { int sleepTime = (int) (averageSleep * (currentRate / averageRate)); if (now + sleepTime > endTime) sleepTime = 1 * Millis; appLog.info("Current Rate= {0:F2}; sleeping for {1:N} ms", currentRate, sleepTime); if (timingSpeedup > 1) { sleepTime = (int)(sleepTime / timingSpeedup); appLog.info("Warp-drive: speedup {0:F}; sleeping for {1} ms", timingSpeedup, sleepTime); } Thread.Sleep(sleepTime); } //queueSize = ((ThreadPoolExecutor) insertExecutor).getQueue().size(); //queueSize = totalScheduled = totalInserts; while (maxQueued >= 0 && insertExecutor.QueueSize() > maxQueued) { //queueSize = totalScheduled = totalInserts; queueSize = insertExecutor.QueueSize(); appLog.info("Queue size {0} is over limit {1} - sleeping", queueSize, maxQueued); Thread.Sleep(1 * Millis / (queueSize > 1 ? 2 : 20)); if (insertExecutor.QueueSize() > maxQueued) { appLog.info("Queue still has {0} items; there are {1} active SqlSessions", insertExecutor.QueueSize(), SqlSession.activeSessions()); } } // queueSize = ((ThreadPoolExecutor) insertExecutor).getQueue().size(); //queueSize = totalScheduled - totalInserts; queueSize = insertExecutor.QueueSize(); appLog.info("Sleeping done. Queue size={0}", queueSize); } //wallTime = Environment.TickCount - start; double wallTime = 1.0 * wallTimer.ElapsedTicks / Stopwatch.Frequency; double insertTime = (1.0 * totalInsertTime) / Stopwatch.Frequency; double queryTime = (1.0 * totalQueryTime) / Stopwatch.Frequency; appLog.info("Processed {0:N0} events containing {1:N0} records in {2:F2} secs" + "\n\tThroughput:\t{3:F2} events/sec at {4:F2} ips;" + "\n\tSpeed:\t\t{5:N0} inserts in {6:F2} secs = {7:F2} ips" + "\n\tQueries:\t{8:N0} queries got {9:N} records in {10:F2} secs at {11:F2} qps", totalEvents, totalInserts, wallTime, (totalEvents / wallTime), (totalInserts / wallTime), totalInserts, (insertTime), (totalInserts / insertTime), totalQueries, totalQueryRecords, totalQueryTime, (totalQueries / queryTime)); } while (wallTimer.ElapsedMilliseconds < endTime); }
public override void SetModel(GameObject ObjectModel) { base.SetModel (ObjectModel); CharacterMotor = Model.GetComponent<ModelMotor> (); if (CharacterMotor != null) { CharacterMotor.OnReachCheckPointEvent += OnReachCheckPoint; CharacterMotor.OnReachDestinationEvent += OnReachDestination; } CharacterEventGenerator = Model.GetComponent<EventGenerator> (); if(CharacterEventGenerator != null) { CharacterEventGenerator.OnClickAndTapOnCharacterEvent += OnCharacterPointerClick; } }
private void generateObjectMotionsToolStripMenuItem_Click(object sender, EventArgs e) { IOTGlobal global = (IOTGlobal)Global.getInstance(); MoveForm f = new MoveForm(); f.ShowDialog(); if (f.ok != true) return; //if (f.DialogResult != System.Windows.Forms.DialogResult.OK) // return; int nodeCount = (int)(global.objectNum * f.nodeRatio); double nodeSpeed = f.nodeSpeed; int eventCount = f.eventCount; bool clear = f.clear; EventGenerator generator = new EventGenerator(); if (clear) generator.ClearEvents("MOV"); generator.GenerateRandomObjectMotionEvents(true, false, nodeSpeed, eventCount, nodeCount, NodeType.OBJECT); MessageBox.Show("Done"); }
private void generateReaderMotionToolStripMenuItem_Click(object sender, EventArgs e) { IOTGlobal global = (IOTGlobal)Global.getInstance(); MoveForm f = new MoveForm(); DialogResult r = f.ShowDialog(); if (f.ok != true) return; int nodeCount = (int)(global.readerNum * f.nodeRatio); double nodeSpeed = f.nodeSpeed; int eventCount = f.eventCount; bool clear = f.clear; EventGenerator generator = new EventGenerator(); if (clear) generator.ClearEvents("MOV"); generator.GenerateRandomObjectMotionEvents(true, true, nodeSpeed, eventCount, nodeCount, NodeType.READER); MessageBox.Show("Done"); }
private void generateSendDataToolStripMenuItem_Click(object sender, EventArgs e) { IOTGlobal global = (IOTGlobal)Global.getInstance(); EventGenerator generator = new EventGenerator(); generator.ClearEvents("SND_DATA"); generator.GenerateSendEvents(true, false, global.objects, global.orgs, false, "SND_DATA"); MessageBox.Show("Done"); }