### C# NBomber Configuration and Reporting Setup Source: https://context7.com/pragmaticflow/nbomber/llms.txt Shows how to configure NBomber tests in C#, including setting test suite and report names, output folder, report formats (HTML, CSV, Markdown), reporting interval, and minimum log level. It also demonstrates loading external configuration files for test execution and infrastructure. ```csharp using NBomber.Contracts; using NBomber.CSharp; using Serilog.Events; var scenario = Scenario.Create("my_scenario", async context => { await Task.Delay(500); return Response.Ok(); }) .WithLoadSimulations( Simulation.KeepConstant(copies: 10, during: TimeSpan.FromSeconds(30)) ); var stats = NBomberRunner .RegisterScenarios(scenario) .WithTestSuite("performance_tests") .WithTestName("baseline_test") .WithReportFileName("my_test_report") .WithReportFolder("./test_results") .WithReportFormats(ReportFormat.Html, ReportFormat.Csv, ReportFormat.Md) .WithReportingInterval(TimeSpan.FromSeconds(10)) .WithMinimumLogLevel(LogEventLevel.Information) .LoadConfig("./config.json") // Load NBomber configuration .LoadInfraConfig("./infra-config.json") // Load infrastructure configuration .EnableHintsAnalyzer(true) // Enable performance hints analyzer .Run(); // Access test results var scenarioStats = stats.ScenarioStats[0]; var requestCount = scenarioStats.Ok.Request.Count; var errorRate = scenarioStats.Fail.Request.Percent; ``` -------------------------------- ### NBomber Load Simulation - Inject Rate (Open Systems) Source: https://context7.com/pragmaticflow/nbomber/llms.txt This C# example demonstrates simulating open systems with NBomber, where requests are injected at a constant rate regardless of response times. This is suitable for protocols like HTTP and REST services. It includes examples of ramping up, maintaining a constant rate, and injecting a random rate. ```csharp using NBomber.CSharp; // Open systems maintain arrival rate without waiting for responses // Suitable for stateless protocols like HTTP var scenario = Scenario.Create("hello_world_scenario", async context => { await Task.Delay(1_000); return Response.Ok(); }) .WithoutWarmUp() .WithLoadSimulations( // Ramp up from 0 to 50 requests/sec over 1 minute Simulation.RampingInject(rate: 50, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromMinutes(1)), // Maintain constant 50 requests/sec for 1 minute Simulation.Inject(rate: 50, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromMinutes(1)), // Random rate between 10-50 requests/sec for 30 seconds Simulation.InjectRandom(minRate: 10, maxRate: 50, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromSeconds(30)) ); NBomberRunner .RegisterScenarios(scenario) .Run(); ``` -------------------------------- ### Perform HTTP Load Testing with NBomber in C# Source: https://context7.com/pragmaticflow/nbomber/llms.txt Illustrates how to conduct HTTP load tests using NBomber in C#. This snippet shows configuring an HTTP client, defining a GET request with headers, and sending it. It includes setting up warm-up duration and multiple load simulation patterns (ramping and constant). It also demonstrates registering network and HTTP metrics plugins for monitoring. ```csharp using NBomber.CSharp; using NBomber.Http; using NBomber.Http.CSharp; using NBomber.Plugins.Network.Ping; var httpClient = Http.CreateDefaultClient(); var scenario = Scenario.Create("http_scenario", async context => { var request = Http.CreateRequest("GET", "https://nbomber.com") .WithHeader("Content-Type", "application/json"); // .WithBody(new StringContent("{ \"data\": \"value\" }", Encoding.UTF8, "application/json")); var response = await Http.Send(httpClient, request); return response; }) .WithWarmUpDuration(TimeSpan.FromSeconds(3)) .WithLoadSimulations( Simulation.RampingInject(rate: 50, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromMinutes(1)), Simulation.Inject(rate: 50, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromMinutes(1)), Simulation.RampingInject(rate: 0, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromMinutes(1)) ); NBomberRunner .RegisterScenarios(scenario) .WithWorkerPlugins( new PingPlugin(PingPluginConfig.CreateDefault("nbomber.com")), new HttpMetricsPlugin([HttpVersion.Version1]) ) .Run(); ``` -------------------------------- ### Create Step-Based Scenarios for Granular Measurement in C# Source: https://context7.com/pragmaticflow/nbomber/llms.txt Shows how to define load test scenarios composed of individual steps in C#. Each step's performance is measured independently, allowing for detailed analysis of different actions within a single scenario. This example defines two steps, checks their responses, and returns a success or failure status based on the outcome. It uses both ramping and constant load simulation patterns. ```csharp using NBomber.CSharp; var scenario = Scenario.Create("hello_world_scenario", async context => { var step1 = await Step.Run("step_1", context, async () => { await Task.Delay(1000); return Response.Ok(payload: "step_1 response", sizeBytes: 10); }); var step2 = await Step.Run("step_2", context, async () => { await Task.Delay(1000); return Response.Ok(payload: "step_2 response", sizeBytes: 10); }); return step1.Payload.Value == "step_1 response" && step2.Payload.Value == "step_2 response" ? Response.Ok(statusCode: "200") : Response.Fail(statusCode: "500"); }) .WithoutWarmUp() .WithLoadSimulations( Simulation.RampingConstant(copies: 50, during: TimeSpan.FromSeconds(30)), Simulation.KeepConstant(copies: 50, during: TimeSpan.FromSeconds(30)) ); NBomberRunner .RegisterScenarios(scenario) .Run(); ``` -------------------------------- ### Set Thresholds and Assertions in NBomber (C#) Source: https://context7.com/pragmaticflow/nbomber/llms.txt This example demonstrates how to define runtime thresholds and assertions in NBomber using C# to validate performance requirements. It covers scenario-level and step-level error rate checks, status code validation with abort conditions, and success rate verification. Thresholds can also be defined in a JSON configuration file. ```csharp using NBomber.Contracts; using NBomber.CSharp; using NBomber.Http.CSharp; using var httpClient = Http.CreateDefaultClient(); var scenario = Scenario.Create("http_scenario", async context => { var step1 = await Step.Run("step_1", context, async () => { var request = Http.CreateRequest("GET", "https://nbomber.com") .WithHeader("Content-Type", "application/json"); var response = await Http.Send(httpClient, request); return response; }); return Response.Ok(); }) .WithoutWarmUp() .WithLoadSimulations(Simulation.Inject(rate: 1, interval: TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30))) .WithThresholds( // Scenario threshold: error rate must be < 10% Threshold.Create(scenarioStats => scenarioStats.Fail.Request.Percent < 10), // Step threshold: error rate must be < 10% Threshold.Create("step_1", stepStats => stepStats.Fail.Request.Percent < 10), // Check for specific status codes with abort conditions Threshold.Create( scenarioStats => scenarioStats.Fail.StatusCodes.Exists("404"), abortWhenErrorCount: 5, // Abort test after 5 threshold violations startCheckAfter: TimeSpan.FromSeconds(10) // Delay threshold check by 10 seconds ), // Verify success rate: 200 status codes must be >= 80% Threshold.Create(scenarioStats => scenarioStats.Ok.StatusCodes.Exists("200") && scenarioStats.Ok.StatusCodes.Get("200").Percent >= 80) ); var result = NBomberRunner .RegisterScenarios(scenario) .LoadConfig("Features/Thresholds/nbomber-config.json") // Can also define thresholds in JSON .Run(); // Check for failed thresholds var failedThreshold = result.Thresholds.FirstOrDefault(x => x.IsFailed); ``` -------------------------------- ### C# NBomber Distributed Cluster Mode Setup Source: https://context7.com/pragmaticflow/nbomber/llms.txt Illustrates how to configure and run NBomber tests in a distributed cluster mode using C#. This enables generating higher load by distributing test execution across multiple machines. It includes setting up worker plugins, loading cluster configuration, and enabling local development cluster mode. ```csharp using NBomber.Contracts; using NBomber.CSharp; using NBomber.Http; using NBomber.Http.CSharp; using NBomber.Plugins.Network.Ping; var httpClient = new HttpClient(); var scenario = Scenario.Create("http_scenario", async context => { var request = Http.CreateRequest("GET", "https://nbomber.com") .WithHeader("Content-Type", "application/json"); var response = await Http.Send(httpClient, request); return response; }) .WithWarmUpDuration(TimeSpan.FromSeconds(3)) .WithLoadSimulations( Simulation.RampingInject(rate: 10, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromSeconds(10)), Simulation.Inject(rate: 10, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromSeconds(30)), Simulation.RampingInject(rate: 0, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromSeconds(30)) ); NBomberRunner .RegisterScenarios(scenario) .WithWorkerPlugins( new PingPlugin(PingPluginConfig.CreateDefault("nbomber.com")), new HttpMetricsPlugin([HttpVersion.Version1]) ) .LoadConfig("cluster-config.json") // Contains cluster configuration .EnableLocalDevCluster(true) // Enable local development cluster mode .Run(); // CLI arguments for distributed mode: // --config=cluster-config.json --cluster-local-dev=true ``` -------------------------------- ### NBomber Load Simulation - Keep Constant (Closed Systems) Source: https://context7.com/pragmaticflow/nbomber/llms.txt This C# example demonstrates simulating closed systems with NBomber, where a fixed number of concurrent clients make sequential requests. This is suitable for stateful protocols and persistent connections like databases or message brokers. It includes examples of ramping up concurrent copies and maintaining a constant number. ```csharp using NBomber.CSharp; // Closed systems maintain constant concurrent connections // Suitable for stateful protocols and persistent connections var scenario = Scenario.Create("hello_world_scenario", async context => { await Task.Delay(1_000); return Response.Ok(); }) .WithoutWarmUp() .WithLoadSimulations( // Ramp up from 0 to 50 concurrent copies over 30 seconds Simulation.RampingConstant(copies: 50, during: TimeSpan.FromSeconds(30)), // Maintain 50 concurrent copies for 30 seconds Simulation.KeepConstant(copies: 50, during: TimeSpan.FromSeconds(30)) ); NBomberRunner .RegisterScenarios(scenario) .Run(); ``` -------------------------------- ### NBomber Data Feeding from JSON Source: https://context7.com/pragmaticflow/nbomber/llms.txt This C# example shows how to feed test data from JSON files into NBomber scenarios for data-driven load testing. It defines a `JsonUser` class and uses `Data.LoadJson` to load data from a local file or a URL. The `DataFeed.Constant` method is used to create a data feed from the loaded data. ```csharp using NBomber.CSharp; using NBomber.Data; using NBomber.Data.CSharp; public class JsonUser { public int Id { get; set; } public string Name { get; set; } } private IDataFeed _usersFeed; var scenario = Scenario.Create("scenario", async ctx => { var user = _usersFeed.GetNextItem(ctx.ScenarioInfo); await Task.Delay(1_000); ctx.Logger.Information($"ScenarioCopyId: {ctx.ScenarioInfo.InstanceNumber}, UserId: {user.Id}"); return Response.Ok(); }) .WithInit(ctx => { // Load data from local file var users = Data.LoadJson("./Features/DataDemo/data.json"); // Or load from URL // var users = Data.LoadJson("https://example.com/users.json"); _usersFeed = DataFeed.Constant(users); return Task.CompletedTask; }) .WithoutWarmUp() .WithLoadSimulations(Simulation.KeepConstant(copies: 3, during: TimeSpan.FromSeconds(30))); NBomberRunner .RegisterScenarios(scenario) .Run(); ``` -------------------------------- ### Scenario Initialization and Cleanup in NBomber (C#) Source: https://context7.com/pragmaticflow/nbomber/llms.txt This C# code illustrates how to manage scenario initialization and cleanup phases in NBomber. The `WithInit` method is used to set up resources before test execution, and `WithClean` is used to release them afterward. This is crucial for managing dependencies like database connections or API clients. ```csharp using NBomber.CSharp; var scenario = Scenario.Create("http_scenario", async context => { // Scenario execution logic await Task.Delay(1_000); return Response.Ok(); }) .WithInit(ctx => { // Initialize resources: database connections, API clients, test data, etc. // Runs once before warm-up and bombing phases ctx.Logger.Information("Initializing scenario resources..."); return Task.CompletedTask; }) .WithClean(ctx => { // Clean up resources: close connections, delete test data, etc. // Runs once after warm-up and bombing phases ctx.Logger.Information("Cleaning up scenario resources..."); return Task.CompletedTask; }) .WithWarmUpDuration(TimeSpan.FromSeconds(30)) .WithLoadSimulations( Simulation.KeepConstant(copies: 50, during: TimeSpan.FromMinutes(5)) ); NBomberRunner .RegisterScenarios(scenario) .Run(); ``` -------------------------------- ### Display Hints Table Source: https://github.com/pragmaticflow/nbomber/blob/dev/src/NBomber/Resources/HtmlReport/index.html This code displays a table of hints, including their source type, name, and the hint message itself. It iterates over a `hints` array to populate the table rows. The table has a warning-themed header. ```html
hints
source name hint
{{hint.SourceType}} {{hint.SourceName}} {{hint.Hint}}
``` -------------------------------- ### Initialize NBomber Application Source: https://github.com/pragmaticflow/nbomber/blob/dev/src/NBomber/Resources/HtmlReport/index.html This is a JavaScript snippet that initializes the NBomber application. It takes an element ID and a viewModel object as arguments. This is likely the entry point for the frontend application. ```javascript initApp('#app', viewModel); ``` -------------------------------- ### NBomber Load Test Scenario and Execution in C# Source: https://github.com/pragmaticflow/nbomber/blob/dev/README.md This C# code defines a simple load test scenario named 'hello_world_scenario'. It simulates a task that takes 1 second to complete and injects load at a rate of 10 requests per second for 30 seconds. The NBomberRunner then registers and executes this scenario. This snippet requires the NBomber library. ```csharp var scenario = Scenario.Create("hello_world_scenario", async context => { // you can define and execute any logic here, // for example: send http request, SQL query etc // NBomber will measure how much time it takes to execute your logic await Task.Delay(1_000); return Response.Ok(); }) .WithLoadSimulations( Simulation.Inject(rate: 10, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromSeconds(30)) ); NBomberRunner .RegisterScenarios(scenario) .Run(); ``` -------------------------------- ### Create and Execute Basic Load Test Scenario in C# Source: https://context7.com/pragmaticflow/nbomber/llms.txt Demonstrates the creation of a simple load test scenario using NBomber's C# API. This scenario defines a basic asynchronous operation and measures its execution time. It allows for custom logic like HTTP requests or database operations. The scenario is configured with a specific injection rate and duration. ```csharp using NBomber.CSharp; var scenario = Scenario.Create("hello_world_scenario", async context => { // Define any logic: HTTP requests, database queries, message publishing, etc. // NBomber measures execution time automatically await Task.Delay(500); return Response.Ok(); }) .WithoutWarmUp() .WithLoadSimulations( Simulation.Inject(rate: 150, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromSeconds(30)) ); NBomberRunner .RegisterScenarios(scenario) .Run(); ``` -------------------------------- ### C# Client Pool for Reusing HTTP Connections Source: https://context7.com/pragmaticflow/nbomber/llms.txt Demonstrates how to use a `ClientPool` in C# with NBomber to share and reuse `HttpClient` connections across scenario instances. This pattern improves efficiency by reducing the overhead of creating new connections for each request. It includes initialization and cleanup of the client pool. ```csharp using NBomber; using NBomber.CSharp; var clientPool = new ClientPool(); var scenario = Scenario.Create("http_scenario", async context => { // Get client for this scenario instance var httpClient = clientPool.GetClient(context.ScenarioInfo); // Use the client var response = await httpClient.GetAsync("https://api.example.com/data"); return response.IsSuccessStatusCode ? Response.Ok(sizeBytes: (int)response.Content.Headers.ContentLength) : Response.Fail(); }) .WithInit(ctx => { // Initialize client pool with multiple connections for (int i = 0; i < 10; i++) { var client = new HttpClient(); clientPool.AddClient(client); } return Task.CompletedTask; }) .WithClean(ctx => { // Dispose all clients in pool clientPool.DisposeClients(); return Task.CompletedTask; }) .WithLoadSimulations( Simulation.KeepConstant(copies: 100, during: TimeSpan.FromMinutes(5)) ); NBomberRunner .RegisterScenarios(scenario) .Run(); ``` -------------------------------- ### Display NBomber Scenario and Environment Information (HTML/Vue.js) Source: https://github.com/pragmaticflow/nbomber/blob/dev/src/NBomber/Resources/HtmlReport/index.html This snippet displays detailed information about a specific NBomber scenario, including its name, the environment it's running in (machine name, OS, .NET runtime, processor, cores), and overall performance statistics such as iterations, success/failure counts, and data transfer size. It utilizes Vue.js directives for dynamic data binding and conditional rendering. ```html NBomber Scenario

No Data

scenario #{{scenarioIndex + 1}}: {{scenarioName}}
Environment
Machine Name OS .NET Runtime Processor Cores
{{nodeInfo.MachineName}} {{nodeInfo.OS.VersionString}} {{nodeInfo.DotNetVersion}} {{nodeInfo.Processor}} {{nodeInfo.CoresCount}}

iterations: {{getRequestCount(scenarioStats)}}, ok: {{scenarioStats.Ok.Request.Count}}, fail: {{scenarioStats.Fail.Request.Count}}, all data: {{toMb(getAllBytes(scenarioStats))}} MB

``` -------------------------------- ### Display Scenario Stats - Data Transfer Source: https://github.com/pragmaticflow/nbomber/blob/dev/src/NBomber/Resources/HtmlReport/index.html This snippet displays scenario statistics related to data transfer. It iterates through step statistics and presents data in KB and MB. It relies on a `scenarioStats` object with `StepStats` and a `toKb` and `toMb` helper functions. ```html

{{statsName.toLowerCase()}} stats

data transfer
step min, KB mean, KB max, KB all, MB
{{stepStats.StepName}} {{toKb(stepStats[statsName].DataTransfer.MinBytes)}} {{toKb(stepStats[statsName].DataTransfer.MeanBytes)}} {{toKb(stepStats[statsName].DataTransfer.MaxBytes)}} {{toMb(stepStats[statsName].DataTransfer.AllBytes)}}
``` -------------------------------- ### Display Plugin Statistics Table Source: https://github.com/pragmaticflow/nbomber/blob/dev/src/NBomber/Resources/HtmlReport/index.html This code snippet renders a table to display plugin statistics. It dynamically generates table headers and rows based on the `table.cols` and `table.rows` properties from the `tables` array. It is conditional on `pluginsStats` being true. ```html
plugin stats: {{table.name}}
{{col}}
{{value}}
``` -------------------------------- ### Define and Track Custom Metrics in NBomber (C#) Source: https://context7.com/pragmaticflow/nbomber/llms.txt This snippet shows how to define and track custom metrics like counters and gauges in NBomber using C#. It covers metric creation, incrementing/setting values, and registering them within a scenario's initialization phase. The final metric values can be retrieved after the test run. ```csharp using NBomber.Contracts; using NBomber.CSharp; // Define custom metrics var counter = Metric.CreateCounter("my-counter", unitOfMeasure: "MB"); var gauge = Metric.CreateGauge("my-gauge", unitOfMeasure: "KB"); var scenario = Scenario.Create("scenario", async context => { await Task.Delay(500); counter.Add(1); // Increment counter gauge.Set(6.5); // Set gauge value return Response.Ok(); }) .WithInit(ctx => { // Register custom metrics ctx.RegisterMetric(counter); ctx.RegisterMetric(gauge); return Task.CompletedTask; }) .WithoutWarmUp() .WithLoadSimulations( Simulation.Inject(rate: 150, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromSeconds(30)) ); var stats = NBomberRunner .RegisterScenarios(scenario) .Run(); // Retrieve final metric values var counterValue = stats.Metrics.Counters.Find("my-counter").Value; var gaugeValue = stats.Metrics.Gauges.Find("my-gauge").Value; ``` -------------------------------- ### Display NBomber Scenario Request Number and RPS Table (HTML/Vue.js) Source: https://github.com/pragmaticflow/nbomber/blob/dev/src/NBomber/Resources/HtmlReport/index.html This snippet displays a summary table of NBomber scenario statistics, focusing on request numbers and requests per second (RPS) for each step. It includes columns for the step name, total requests, 'ok' or 'failed' request counts (conditionally displayed), and RPS. This table provides a quick overview of the load generated and handled by each step. ```html

{{statsName.toLowerCase()}} stats

request number
step all ok failed RPS
{{stepStats.StepName}} {{getRequestCount(stepStats)}} {{stepStats.Ok.Request.Count}} {{stepStats.Fail.Request.Count}} {{stepStats[statsName].Request.RPS}}
``` -------------------------------- ### Display NBomber Scenario Latency Percentile Table (HTML/Vue.js) Source: https://github.com/pragmaticflow/nbomber/blob/dev/src/NBomber/Resources/HtmlReport/index.html This snippet presents a table summarizing latency statistics for each step within an NBomber scenario. It focuses on minimum, mean, maximum, standard deviation, and percentile values (p50, p75, p95, p99) of latency in milliseconds. This table is useful for understanding the response time distribution and identifying potential performance bottlenecks. ```html

{{statsName.toLowerCase()}} stats

latency, ms latency percentile, ms
step min mean max StdDev p50 p75 p95 p99
{{stepStats.StepName}} {{stepStats[statsName].Latency.MinMs}} {{stepStats[statsName].Latency.MeanMs}} {{stepStats[statsName].Latency.MaxMs}} {{stepStats[statsName].Latency.StdDev}} {{stepStats[statsName].Latency.Percent50}} {{stepStats[statsName].Latency.Percent75}} {{stepStats[statsName].Latency.Percent95}} {{stepStats[statsName].Latency.Percent99}}
``` -------------------------------- ### Display NBomber Scenario Statistics Table (HTML/Vue.js) Source: https://github.com/pragmaticflow/nbomber/blob/dev/src/NBomber/Resources/HtmlReport/index.html This snippet presents a detailed performance statistics table for an NBomber scenario, broken down by step. It includes metrics such as request counts (all, ok, failed), requests per second (RPS), latency (min, mean, max, StdDev, percentiles), and data transfer (min, mean, max, all). The table dynamically adjusts columns based on whether failed statistics are present. ```html

{{statsName.toLowerCase()}} stats

request number latency, ms latency percentile, ms data transfer
step all    ok    failed RPS min mean max StdDev p50 p75 p95 p99 min, KB mean, KB max, KB all, MB
{{stepStats.StepName}} {{stepStats.Ok.Request.Count + stepStats.Fail.Request.Count}} {{stepStats.Ok.Request.Count}} {{stepStats.Fail.Request.Count}} {{stepStats[statsName].Request.RPS}} {{stepStats[statsName].Latency.MinMs}} {{stepStats[statsName].Latency.MeanMs}} {{stepStats[statsName].Latency.MaxMs}} {{stepStats[statsName].Latency.StdDev}} {{stepStats[statsName].Latency.Percent50}} {{stepStats[statsName].Latency.Percent75}} {{stepStats[statsName].Latency.Percent95}} {{stepStats[statsName].Latency.Percent99}} {{toKb(stepStats[statsName].DataTransfer.MinBytes)}} {{toKb(stepStats[statsName].DataTransfer.MeanBytes)}} {{toKb(stepStats[statsName].DataTransfer.MaxBytes)}} {{toMb(stepStats[statsName].DataTransfer.AllBytes)}}
``` -------------------------------- ### C# NBomber: Simulate API Responses with Status Codes and Payloads Source: https://context7.com/pragmaticflow/nbomber/llms.txt This C# code snippet uses NBomber to simulate API calls and generate different types of responses. It demonstrates how to return success responses with payloads and metrics (Response.Ok) and failure responses with specific status codes and messages (Response.Fail) for scenarios like resource not found, timeouts, and general errors. It requires the NBomber.CSharp package. ```csharp using NBomber.CSharp; var scenario = Scenario.Create("response_example", async context => { try { // Simulate API call var data = await FetchDataAsync(); if (data != null) { // Success response with payload and metrics return Response.Ok( payload: data, statusCode: "200", sizeBytes: 1024, message: "Request successful" ); } else { // Failed response with status code and message return Response.Fail( statusCode: "404", message: "Resource not found", sizeBytes: 0 ); } } catch (TimeoutException) { // Timeout failure return Response.Fail( statusCode: "timeout", message: "Request timed out after 30 seconds" ); } catch (Exception ex) { // Generic error return Response.Fail( statusCode: "500", message: ex.Message ); } }) .WithLoadSimulations( Simulation.Inject(rate: 50, interval: TimeSpan.FromSeconds(1), during: TimeSpan.FromMinutes(1)) ); NBomberRunner.RegisterScenarios(scenario).Run(); // Dummy function to simulate data fetching async Task FetchDataAsync() { await Task.Delay(100); // Simulate network latency return "Sample Data"; } ``` -------------------------------- ### Test WebSocket Connections with NBomber Source: https://context7.com/pragmaticflow/nbomber/llms.txt This C# code snippet demonstrates how to test WebSocket connections using NBomber. It measures connect, send, receive, and disconnect operations step-by-step. Ensure the WebSocket server is running at 'ws://localhost:60528/ws'. ```csharp using NBomber.CSharp; using NBomber.Data; using NBomber.WebSockets; var payload = Data.GenerateRandomBytes(sizeInBytes: 500); var scenario = Scenario.Create("ping_pong_websockets", async ctx => { using var websocket = new WebSocket(new WebSocketConfig()); var connect = await Step.Run("connect", ctx, async () => { await websocket.Connect("ws://localhost:60528/ws"); return Response.Ok(); }); var ping = await Step.Run("ping", ctx, async () => { await websocket.Send(payload); return Response.Ok(sizeBytes: payload.Length); }); var pong = await Step.Run("pong", ctx, async () => { using var response = await websocket.Receive(ctx.ScenarioCancellationToken); // var str = Encoding.UTF8.GetString(response.Data.Span); // var user = JsonSerializer.Deserialize(response.Data.Span); return Response.Ok(sizeBytes: response.Data.Length); }); var disconnect = await Step.Run("disconnect", ctx, async () => { await websocket.Close(); return Response.Ok(); }); return Response.Ok(); }) .WithWarmUpDuration(TimeSpan.FromSeconds(3)) .WithLoadSimulations( Simulation.KeepConstant(1, TimeSpan.FromSeconds(30)) ); NBomberRunner .RegisterScenarios(scenario) .Run(); ``` -------------------------------- ### Display Status Codes Table and Chart Source: https://github.com/pragmaticflow/nbomber/blob/dev/src/NBomber/Resources/HtmlReport/index.html This snippet displays HTTP status codes, their counts, and messages in a table. It also includes a `chart-status-codes` component which is conditionally shown based on `showCharts`. Error codes are highlighted in red. ```html

status codes

status code count message
{{statusCode.StatusCode}} {{statusCode.Count}} {{statusCode.Message}}
``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.