diff --git a/examples/BulkLocationImporter.cs b/examples/BulkLocationImporter.cs index 3b5e03f..5761f05 100644 --- a/examples/BulkLocationImporter.cs +++ b/examples/BulkLocationImporter.cs @@ -50,7 +50,7 @@ public async Task ImportFromCsv(string csvFilePath) var locations = LoadLocationsFromCsv(csvFilePath); Console.WriteLine($"Loaded {locations.Count} locations"); - await ImportLocationsInBatches(locations); + await ImportLocationsInBatches(locations).ConfigureAwait(false); Console.WriteLine("\n✓ Import completed successfully!"); } @@ -173,7 +173,7 @@ private async Task ImportLocationsInBatches(List locations) foreach (var location in batch) { - var success = await SendLocation(location); + var success = await SendLocation(location).ConfigureAwait(false); if (success) { successCount++; @@ -186,7 +186,7 @@ private async Task ImportLocationsInBatches(List locations) if (i < batches.Count - 1) { - await Task.Delay(500); // Rate limiting between batches + await Task.Delay(500).ConfigureAwait(false); // Rate limiting between batches } } @@ -206,7 +206,7 @@ private async Task SendLocation(object location) var content = new StringContent(json, Encoding.UTF8, "application/json"); content.Headers.Add("X-API-Key", _apiKey); - var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/locations", content); + var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/locations", content).ConfigureAwait(false); return response.IsSuccessStatusCode; } catch @@ -274,6 +274,6 @@ public static async Task Main(string[] args) var csvFile = args[2]; var importer = new BulkLocationImporter(baseUrl, apiKey); - await importer.ImportFromCsv(csvFile); + await importer.ImportFromCsv(csvFile).ConfigureAwait(false); } } diff --git a/examples/GeofenceAlertsClient.cs b/examples/GeofenceAlertsClient.cs index 18eb8fe..0344d44 100644 --- a/examples/GeofenceAlertsClient.cs +++ b/examples/GeofenceAlertsClient.cs @@ -204,10 +204,10 @@ public async Task Connect() { try { - await _connection.StartAsync(); + await _connection.StartAsync().ConfigureAwait(false); Console.WriteLine("✓ Connected to SignalR hub"); - await _connection.InvokeAsync("SubscribeToVehicle", _vehicleId); + await _connection.InvokeAsync("SubscribeToVehicle", _vehicleId).ConfigureAwait(false); Console.WriteLine($"✓ Subscribed to vehicle: {_vehicleId}"); } catch (Exception ex) @@ -223,8 +223,8 @@ public async Task Disconnect() { try { - await _connection.InvokeAsync("UnsubscribeFromVehicle", _vehicleId); - await _connection.StopAsync(); + await _connection.InvokeAsync("UnsubscribeFromVehicle", _vehicleId).ConfigureAwait(false); + await _connection.StopAsync().ConfigureAwait(false); Console.WriteLine("✓ Disconnected from hub"); } catch (Exception ex) @@ -240,7 +240,7 @@ public async Task RunExample() { Console.WriteLine("=== Geofence Alerts Client ===\n"); - await Connect(); + await Connect().ConfigureAwait(false); AddGeofence("Warehouse", 40.7128, -74.0060, 1.0); AddGeofence("Office", 40.7489, -73.9680, 0.5); @@ -249,7 +249,7 @@ public async Task RunExample() Console.WriteLine("\n✓ Listening for geofence alerts (press Enter to exit)...\n"); Console.ReadLine(); - await Disconnect(); + await Disconnect().ConfigureAwait(false); } private class Alert @@ -275,6 +275,6 @@ public static async Task Main(string[] args) var vehicleId = args.Length > 1 ? args[1] : Guid.NewGuid().ToString(); var client = new GeofenceAlertsClient(hubUrl, vehicleId); - await client.RunExample(); + await client.RunExample().ConfigureAwait(false); } } diff --git a/examples/LocationUpdateSimulator.cs b/examples/LocationUpdateSimulator.cs index d520fd8..dd55743 100644 --- a/examples/LocationUpdateSimulator.cs +++ b/examples/LocationUpdateSimulator.cs @@ -51,8 +51,8 @@ public async Task RunSimulation(int vehicleCount = 5, int durationSeconds = 60) try { - vehicleIds = await CreateVehicles(vehicleCount); - await SimulateMovement(vehicleIds, durationSeconds); + vehicleIds = await CreateVehicles(vehicleCount).ConfigureAwait(false); + await SimulateMovement(vehicleIds, durationSeconds).ConfigureAwait(false); } catch (Exception ex) { @@ -86,11 +86,11 @@ private async Task> CreateVehicles(int count) var content = new StringContent(json, Encoding.UTF8, "application/json"); content.Headers.Add("X-API-Key", _apiKey); - var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/vehicles", content); + var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/vehicles", content).ConfigureAwait(false); if (response.IsSuccessStatusCode) { - var result = await response.Content.ReadAsStringAsync(); + var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var doc = JsonDocument.Parse(result); var vehicleId = doc.RootElement.GetProperty("id").GetString(); @@ -120,7 +120,7 @@ private async Task SimulateMovement(List vehicleIds, int durationSeconds foreach (var vehicleId in vehicleIds) { var location = GenerateLocation(vehicleId); - var success = await SendLocation(location); + var success = await SendLocation(location).ConfigureAwait(false); if (success) { @@ -132,7 +132,7 @@ private async Task SimulateMovement(List vehicleIds, int durationSeconds var remaining = Math.Max(0, durationSeconds - elapsed); Console.WriteLine($"[{elapsed:F0}s] Sent {locationCount} updates (remaining: {remaining:F0}s)"); - await Task.Delay(2000); // Update every 2 seconds + await Task.Delay(2000).ConfigureAwait(false); // Update every 2 seconds } Console.WriteLine($"\n✓ Simulation completed: {locationCount} total location updates sent"); @@ -175,7 +175,7 @@ private async Task SendLocation(object location) var content = new StringContent(json, Encoding.UTF8, "application/json"); content.Headers.Add("X-API-Key", _apiKey); - var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/locations", content); + var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/locations", content).ConfigureAwait(false); return response.IsSuccessStatusCode; } catch @@ -196,6 +196,6 @@ public static async Task Main(string[] args) var durationSeconds = args.Length > 3 ? int.Parse(args[3]) : 60; var simulator = new LocationUpdateSimulator(baseUrl, apiKey); - await simulator.RunSimulation(vehicleCount, durationSeconds); + await simulator.RunSimulation(vehicleCount, durationSeconds).ConfigureAwait(false); } } diff --git a/examples/RouteOptimizationClient.cs b/examples/RouteOptimizationClient.cs index edbf7cd..b137e41 100644 --- a/examples/RouteOptimizationClient.cs +++ b/examples/RouteOptimizationClient.cs @@ -77,11 +77,11 @@ public async Task CreateDeliveryRoute(string vehicleId) var content = new StringContent(json, Encoding.UTF8, "application/json"); content.Headers.Add("X-API-Key", _apiKey); - var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/routes", content); + var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/routes", content).ConfigureAwait(false); if (response.IsSuccessStatusCode) { - var result = await response.Content.ReadAsStringAsync(); + var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var doc = JsonDocument.Parse(result); var routeId = doc.RootElement.GetProperty("id").GetString(); @@ -89,7 +89,7 @@ public async Task CreateDeliveryRoute(string vehicleId) Console.WriteLine($" Total Distance: {totalDistance:F2} km"); Console.WriteLine($" Estimated Duration: {route.estimatedDuration} minutes"); - await GetRouteDetails(routeId ?? ""); + await GetRouteDetails(routeId ?? "").ConfigureAwait(false); } else { @@ -108,12 +108,12 @@ private async Task GetRouteDetails(string routeId) var request = new HttpRequestMessage(HttpMethod.Get, $"{_baseUrl}/api/v1/routes/{routeId}"); request.Headers.Add("X-API-Key", _apiKey); - var response = await _httpClient.SendAsync(request); + var response = await _httpClient.SendAsync(request).ConfigureAwait(false); if (!response.IsSuccessStatusCode) return; - var result = await response.Content.ReadAsStringAsync(); + var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var doc = JsonDocument.Parse(result); var route = doc.RootElement; @@ -202,7 +202,7 @@ public async Task SimulateRouteExecution(string routeId) for (int i = 0; i < steps.Length; i++) { Console.WriteLine($" [{steps[i]}%] {statuses[i]}"); - await Task.Delay(1000); + await Task.Delay(1000).ConfigureAwait(false); } Console.WriteLine("\n✓ Route execution simulation completed"); @@ -215,7 +215,7 @@ public async Task RunExample(string vehicleId) { try { - await CreateDeliveryRoute(vehicleId); + await CreateDeliveryRoute(vehicleId).ConfigureAwait(false); } catch (Exception ex) { @@ -233,6 +233,6 @@ public static async Task Main(string[] args) var vehicleId = args.Length > 2 ? args[2] : Guid.NewGuid().ToString(); var client = new RouteOptimizationClient(baseUrl, apiKey); - await client.RunExample(vehicleId); + await client.RunExample(vehicleId).ConfigureAwait(false); } } diff --git a/examples/SessionAnalyticsReporter.cs b/examples/SessionAnalyticsReporter.cs index baf1fe1..697f10b 100644 --- a/examples/SessionAnalyticsReporter.cs +++ b/examples/SessionAnalyticsReporter.cs @@ -40,7 +40,7 @@ public async Task GenerateVehicleAnalyticsReport(string vehicleId) try { - var sessions = await GetVehicleSessions(vehicleId); + var sessions = await GetVehicleSessions(vehicleId).ConfigureAwait(false); if (sessions.Count == 0) { Console.WriteLine("No tracking sessions found for this vehicle."); @@ -214,7 +214,7 @@ public async Task ExportAnalyticsToCsv(string vehicleId, string outputPath) { Console.WriteLine($"Exporting analytics to: {outputPath}"); - var sessions = await GetVehicleSessions(vehicleId); + var sessions = await GetVehicleSessions(vehicleId).ConfigureAwait(false); using (var writer = new StreamWriter(outputPath)) { @@ -239,7 +239,7 @@ public async Task ExportAnalyticsToCsv(string vehicleId, string outputPath) /// public async Task RunExample(string vehicleId) { - await GenerateVehicleAnalyticsReport(vehicleId); + await GenerateVehicleAnalyticsReport(vehicleId).ConfigureAwait(false); } private class SessionData @@ -277,6 +277,6 @@ public static async Task Main(string[] args) var vehicleId = args.Length > 2 ? args[2] : Guid.NewGuid().ToString(); var reporter = new SessionAnalyticsReporter(baseUrl, apiKey); - await reporter.RunExample(vehicleId); + await reporter.RunExample(vehicleId).ConfigureAwait(false); } } diff --git a/examples/VehicleTrackerClient.cs b/examples/VehicleTrackerClient.cs index 40f8a88..3eec104 100644 --- a/examples/VehicleTrackerClient.cs +++ b/examples/VehicleTrackerClient.cs @@ -35,10 +35,10 @@ public async Task RunExample() try { - var vehicleId = await CreateVehicle(); - await RecordLocations(vehicleId); - await RetrieveLocationHistory(vehicleId); - await GetVehicleDetails(vehicleId); + var vehicleId = await CreateVehicle().ConfigureAwait(false); + await RecordLocations(vehicleId).ConfigureAwait(false); + await RetrieveLocationHistory(vehicleId).ConfigureAwait(false); + await GetVehicleDetails(vehicleId).ConfigureAwait(false); } catch (Exception ex) { @@ -66,15 +66,15 @@ private async Task CreateVehicle() var content = new StringContent(json, Encoding.UTF8, "application/json"); content.Headers.Add("X-API-Key", _apiKey); - var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/vehicles", content); + var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/vehicles", content).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { - var error = await response.Content.ReadAsStringAsync(); + var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Exception($"Failed to create vehicle: {error}"); } - var result = await response.Content.ReadAsStringAsync(); + var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var doc = JsonDocument.Parse(result); var vehicleId = doc.RootElement.GetProperty("id").GetString(); @@ -115,14 +115,14 @@ private async Task RecordLocations(string vehicleId) var content = new StringContent(json, Encoding.UTF8, "application/json"); content.Headers.Add("X-API-Key", _apiKey); - var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/locations", content); + var response = await _httpClient.PostAsync($"{_baseUrl}/api/v1/locations", content).ConfigureAwait(false); if (response.IsSuccessStatusCode) { Console.WriteLine($" ✓ Location recorded: ({lat}, {lon})"); } - await Task.Delay(500); // Small delay between updates + await Task.Delay(500).ConfigureAwait(false); // Small delay between updates } Console.WriteLine(); @@ -141,7 +141,7 @@ private async Task RetrieveLocationHistory(string vehicleId) ); request.Headers.Add("X-API-Key", _apiKey); - var response = await _httpClient.SendAsync(request); + var response = await _httpClient.SendAsync(request).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { @@ -149,7 +149,7 @@ private async Task RetrieveLocationHistory(string vehicleId) return; } - var result = await response.Content.ReadAsStringAsync(); + var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var doc = JsonDocument.Parse(result); var data = doc.RootElement.GetProperty("data"); @@ -175,7 +175,7 @@ private async Task GetVehicleDetails(string vehicleId) var request = new HttpRequestMessage(HttpMethod.Get, $"{_baseUrl}/api/v1/vehicles/{vehicleId}"); request.Headers.Add("X-API-Key", _apiKey); - var response = await _httpClient.SendAsync(request); + var response = await _httpClient.SendAsync(request).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { @@ -183,7 +183,7 @@ private async Task GetVehicleDetails(string vehicleId) return; } - var result = await response.Content.ReadAsStringAsync(); + var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var doc = JsonDocument.Parse(result); var vehicle = doc.RootElement; @@ -204,6 +204,6 @@ public static async Task Main(string[] args) var apiKey = args.Length > 1 ? args[1] : "default-api-key"; var client = new VehicleTrackerClient(baseUrl, apiKey); - await client.RunExample(); + await client.RunExample().ConfigureAwait(false); } } diff --git a/examples/docker-deployment/DockerDeploymentExample.cs b/examples/docker-deployment/DockerDeploymentExample.cs index 798b2ac..9844813 100644 --- a/examples/docker-deployment/DockerDeploymentExample.cs +++ b/examples/docker-deployment/DockerDeploymentExample.cs @@ -33,25 +33,25 @@ public async Task RunDockerExampleAsync() { // 1. Check API health Console.WriteLine("\n1. Checking API health..."); - var healthResponse = await _httpClient.GetAsync($"{_baseUrl}/health"); + var healthResponse = await _httpClient.GetAsync($"{_baseUrl}/health").ConfigureAwait(false); healthResponse.EnsureSuccessStatusCode(); - var health = await healthResponse.Content.ReadAsStringAsync(); + var health = await healthResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Console.WriteLine($"Health check: {health}"); // 2. Check API info Console.WriteLine("\n2. Checking API information..."); - var infoResponse = await _httpClient.GetAsync($"{_baseUrl}/api/info"); + var infoResponse = await _httpClient.GetAsync($"{_baseUrl}/api/info").ConfigureAwait(false); infoResponse.EnsureSuccessStatusCode(); - var info = await infoResponse.Content.ReadFromJsonAsync(); + var info = await infoResponse.Content.ReadFromJsonAsync().ConfigureAwait(false); Console.WriteLine($"API Version: {info?.Version}"); Console.WriteLine($"Environment: {info?.Environment}"); // 3. List existing vehicles (if any) Console.WriteLine("\n3. Listing existing vehicles..."); - var vehiclesResponse = await _httpClient.GetAsync($"{_baseUrl}/api/v1/vehicles?take=10"); + var vehiclesResponse = await _httpClient.GetAsync($"{_baseUrl}/api/v1/vehicles?take=10").ConfigureAwait(false); if (vehiclesResponse.IsSuccessStatusCode) { - var vehicles = await vehiclesResponse.Content.ReadFromJsonAsync>(); + var vehicles = await vehiclesResponse.Content.ReadFromJsonAsync>().ConfigureAwait(false); Console.WriteLine($"Found {vehicles?.Data.Count ?? 0} vehicles in the system"); } else @@ -70,9 +70,9 @@ public async Task RunDockerExampleAsync() Status = "Available" }; - var createResponse = await _httpClient.PostAsJsonAsync($"{_baseUrl}/api/v1/vehicles", testVehicle); + var createResponse = await _httpClient.PostAsJsonAsync($"{_baseUrl}/api/v1/vehicles", testVehicle).ConfigureAwait(false); createResponse.EnsureSuccessStatusCode(); - var vehicleId = await createResponse.Content.ReadFromJsonAsync(); + var vehicleId = await createResponse.Content.ReadFromJsonAsync().ConfigureAwait(false); Console.WriteLine($"Created vehicle: {vehicleId}"); // 5. Record a location update @@ -88,24 +88,24 @@ public async Task RunDockerExampleAsync() Timestamp = DateTime.UtcNow }; - var locationResponse = await _httpClient.PostAsJsonAsync($"{_baseUrl}/api/v1/locations", location); + var locationResponse = await _httpClient.PostAsJsonAsync($"{_baseUrl}/api/v1/locations", location).ConfigureAwait(false); locationResponse.EnsureSuccessStatusCode(); - var locationId = await locationResponse.Content.ReadFromJsonAsync(); + var locationId = await locationResponse.Content.ReadFromJsonAsync().ConfigureAwait(false); Console.WriteLine($"Recorded location: {locationId}"); // 6. Retrieve the location Console.WriteLine("\n6. Retrieving location..."); - var getLocationResponse = await _httpClient.GetAsync($"{_baseUrl}/api/v1/locations/{locationId}"); + var getLocationResponse = await _httpClient.GetAsync($"{_baseUrl}/api/v1/locations/{locationId}").ConfigureAwait(false); getLocationResponse.EnsureSuccessStatusCode(); - var retrievedLocation = await getLocationResponse.Content.ReadFromJsonAsync(); + var retrievedLocation = await getLocationResponse.Content.ReadFromJsonAsync().ConfigureAwait(false); Console.WriteLine($"Retrieved location: Vehicle {retrievedLocation?.VehicleId} at ({retrievedLocation?.Latitude}, {retrievedLocation?.Longitude})"); // 7. List vehicles again to see our new vehicle Console.WriteLine("\n7. Listing vehicles after creation..."); - var updatedVehiclesResponse = await _httpClient.GetAsync($"{_baseUrl}/api/v1/vehicles?take=10"); + var updatedVehiclesResponse = await _httpClient.GetAsync($"{_baseUrl}/api/v1/vehicles?take=10").ConfigureAwait(false); if (updatedVehiclesResponse.IsSuccessStatusCode) { - var updatedVehicles = await updatedVehiclesResponse.Content.ReadFromJsonAsync>(); + var updatedVehicles = await updatedVehiclesResponse.Content.ReadFromJsonAsync>().ConfigureAwait(false); var newVehicle = updatedVehicles?.Data.Find(v => v.Id == vehicleId); Console.WriteLine($"Vehicle found: {newVehicle?.LicensePlate} - Status: {newVehicle?.Status}"); } diff --git a/examples/v2-basic-usage/V2BasicUsageClient.cs b/examples/v2-basic-usage/V2BasicUsageClient.cs index 1be746c..777fa0f 100644 --- a/examples/v2-basic-usage/V2BasicUsageClient.cs +++ b/examples/v2-basic-usage/V2BasicUsageClient.cs @@ -44,7 +44,7 @@ public async Task RunBasicWorkflowAsync() ); vehicleResponse.EnsureSuccessStatusCode(); - var vehicleId = await vehicleResponse.Content.ReadFromJsonAsync(); + var vehicleId = await vehicleResponse.Content.ReadFromJsonAsync().ConfigureAwait(false); Console.WriteLine($"Created vehicle with ID: {vehicleId}"); // 2. Start a tracking session @@ -62,7 +62,7 @@ public async Task RunBasicWorkflowAsync() ); sessionResponse.EnsureSuccessStatusCode(); - var sessionId = await sessionResponse.Content.ReadFromJsonAsync(); + var sessionId = await sessionResponse.Content.ReadFromJsonAsync().ConfigureAwait(false); Console.WriteLine($"Started tracking session: {sessionId}"); // 3. Simulate sending location updates (in a real app, this would come from GPS) @@ -86,7 +86,7 @@ public async Task RunBasicWorkflowAsync() Console.WriteLine($"Sent location update: ({location.Latitude}, {location.Longitude})"); // Simulate time between updates - await Task.Delay(1000); + await Task.Delay(1000).ConfigureAwait(false); } // 4. Complete the tracking session diff --git a/src/SignalRMapRealtime/BackgroundJobs/SessionCleanupWorker.cs b/src/SignalRMapRealtime/BackgroundJobs/SessionCleanupWorker.cs index a89beff..5d53804 100644 --- a/src/SignalRMapRealtime/BackgroundJobs/SessionCleanupWorker.cs +++ b/src/SignalRMapRealtime/BackgroundJobs/SessionCleanupWorker.cs @@ -39,10 +39,10 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { - await CleanupInactiveSessions(stoppingToken); - await ArchiveOldLocations(stoppingToken); + await CleanupInactiveSessions(stoppingToken).ConfigureAwait(false); + await ArchiveOldLocations(stoppingToken).ConfigureAwait(false); - await Task.Delay(_executionInterval, stoppingToken); + await Task.Delay(_executionInterval, stoppingToken).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -53,7 +53,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogError(ex, "Error in session cleanup worker"); // Continue on error to prevent worker from stopping - await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); + await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken).ConfigureAwait(false); } } @@ -89,7 +89,7 @@ private async Task CleanupInactiveSessions(CancellationToken cancellationToken) session.UpdatedAt = DateTime.UtcNow; } - await dbContext.SaveChangesAsync(cancellationToken); + await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); _logger.LogInformation("Cleaned up {Count} inactive sessions", inactiveSessions.Count); } @@ -118,7 +118,7 @@ private async Task ArchiveOldLocations(CancellationToken cancellationToken) // In production, export to archive storage (e.g., Azure Blob, S3) before deleting dbContext.Locations.RemoveRange(oldLocations); - await dbContext.SaveChangesAsync(cancellationToken); + await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); _logger.LogInformation("Archived {Count} old locations", oldLocations.Count); } diff --git a/src/SignalRMapRealtime/Data/Repositories/AssetRepository.cs b/src/SignalRMapRealtime/Data/Repositories/AssetRepository.cs index 6f87955..ae8305b 100644 --- a/src/SignalRMapRealtime/Data/Repositories/AssetRepository.cs +++ b/src/SignalRMapRealtime/Data/Repositories/AssetRepository.cs @@ -139,6 +139,6 @@ public async Task> GetNotRecentlyTrackedAsync(int hoursNoTrac public async Task CountByConditionAsync(string condition) { ArgumentException.ThrowIfNullOrWhiteSpace(condition); - return await _context.Assets.CountAsync(a => a.Condition == condition); + return await _context.Assets.CountAsync(a => a.Condition == condition).ConfigureAwait(false); } } diff --git a/src/SignalRMapRealtime/Data/Repositories/BaseRepository.cs b/src/SignalRMapRealtime/Data/Repositories/BaseRepository.cs index 65ba0c3..f7a314b 100644 --- a/src/SignalRMapRealtime/Data/Repositories/BaseRepository.cs +++ b/src/SignalRMapRealtime/Data/Repositories/BaseRepository.cs @@ -34,7 +34,7 @@ public BaseRepository(ApplicationDbContext context) /// public async Task GetByIdAsync(Guid id, CancellationToken cancellationToken = default) { - return await _dbSet.FindAsync(new object[] { id }, cancellationToken: cancellationToken); + return await _dbSet.FindAsync(new object[] { id }, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -42,7 +42,7 @@ public BaseRepository(ApplicationDbContext context) /// public async Task> GetAllAsync(CancellationToken cancellationToken = default) { - return await _dbSet.ToListAsync(cancellationToken); + return await _dbSet.ToListAsync(cancellationToken).ConfigureAwait(false); } /// @@ -51,7 +51,7 @@ public async Task> GetAllAsync(CancellationToken cancellationToke public async Task> FindAsync(Func predicate, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(predicate); - return await Task.FromResult(_dbSet.Where(predicate).ToList()); + return await Task.FromResult(_dbSet.Where(predicate).ToList()).ConfigureAwait(false); } /// @@ -60,7 +60,7 @@ public async Task> FindAsync(Func predicate, Cancellatio public async Task FindSingleAsync(Func predicate, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(predicate); - return await Task.FromResult(_dbSet.FirstOrDefault(predicate)); + return await Task.FromResult(_dbSet.FirstOrDefault(predicate)).ConfigureAwait(false); } /// @@ -69,7 +69,7 @@ public async Task> FindAsync(Func predicate, Cancellatio public async Task AddAsync(T entity, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(entity); - await _dbSet.AddAsync(entity, cancellationToken); + await _dbSet.AddAsync(entity, cancellationToken).ConfigureAwait(false); } /// @@ -78,7 +78,7 @@ public async Task AddAsync(T entity, CancellationToken cancellationToken = defau public async Task AddRangeAsync(IEnumerable entities, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(entities); - await _dbSet.AddRangeAsync(entities, cancellationToken); + await _dbSet.AddRangeAsync(entities, cancellationToken).ConfigureAwait(false); } /// @@ -116,7 +116,7 @@ public async Task RemoveRangeAsync(IEnumerable entities, CancellationToken ca /// public async Task RemoveByIdAsync(Guid id, CancellationToken cancellationToken = default) { - var entity = await GetByIdAsync(id, cancellationToken); + var entity = await GetByIdAsync(id, cancellationToken).ConfigureAwait(false); if (entity is not null) { _dbSet.Remove(entity); @@ -128,7 +128,7 @@ public async Task RemoveByIdAsync(Guid id, CancellationToken cancellationToken = /// public async Task SaveChangesAsync(CancellationToken cancellationToken = default) { - return await _context.SaveChangesAsync(cancellationToken); + return await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } /// @@ -144,6 +144,6 @@ public async Task ExistsAsync(Guid id, CancellationToken cancellationToken /// public async Task CountAsync(CancellationToken cancellationToken = default) { - return await _dbSet.CountAsync(cancellationToken); + return await _dbSet.CountAsync(cancellationToken).ConfigureAwait(false); } } diff --git a/src/SignalRMapRealtime/Data/Repositories/LocationRepository.cs b/src/SignalRMapRealtime/Data/Repositories/LocationRepository.cs index f1ab18d..93f8af4 100644 --- a/src/SignalRMapRealtime/Data/Repositories/LocationRepository.cs +++ b/src/SignalRMapRealtime/Data/Repositories/LocationRepository.cs @@ -124,7 +124,7 @@ public async Task DeleteOldLocationsAsync(int daysOld = 90) .ToListAsync(); _context.Locations.RemoveRange(locationsToDelete); - return await _context.SaveChangesAsync(); + return await _context.SaveChangesAsync().ConfigureAwait(false); } /// diff --git a/src/SignalRMapRealtime/Data/Repositories/UserRepository.cs b/src/SignalRMapRealtime/Data/Repositories/UserRepository.cs index 140bc27..fa9279c 100644 --- a/src/SignalRMapRealtime/Data/Repositories/UserRepository.cs +++ b/src/SignalRMapRealtime/Data/Repositories/UserRepository.cs @@ -109,11 +109,11 @@ public async Task> GetRecentlyLoggedInUsersAsync(int days = 7) /// public async Task DeactivateUserAsync(int userId) { - var user = await _context.Users.FindAsync(userId); + var user = await _context.Users.FindAsync(userId).ConfigureAwait(false); if (user is null) return false; user.Deactivate(); - await SaveChangesAsync(); + await SaveChangesAsync().ConfigureAwait(false); return true; } @@ -133,6 +133,6 @@ public async Task> GetUsersByJobTitleAsync(string jobTitle) /// public async Task GetOnlineUserCountAsync() { - return await _context.Users.CountAsync(u => u.IsOnline && u.IsActive); + return await _context.Users.CountAsync(u => u.IsOnline && u.IsActive).ConfigureAwait(false); } } diff --git a/src/SignalRMapRealtime/Data/Repositories/VehicleRepository.cs b/src/SignalRMapRealtime/Data/Repositories/VehicleRepository.cs index 800ebda..e68deb3 100644 --- a/src/SignalRMapRealtime/Data/Repositories/VehicleRepository.cs +++ b/src/SignalRMapRealtime/Data/Repositories/VehicleRepository.cs @@ -114,7 +114,7 @@ public async Task> GetSpeedingVehiclesAsync() /// public async Task GetOnlineVehicleCountAsync() { - return await _context.Vehicles.CountAsync(v => v.IsOnline); + return await _context.Vehicles.CountAsync(v => v.IsOnline).ConfigureAwait(false); } /// diff --git a/src/SignalRMapRealtime/Events/EventBus.cs b/src/SignalRMapRealtime/Events/EventBus.cs index cc7d524..7df6045 100644 --- a/src/SignalRMapRealtime/Events/EventBus.cs +++ b/src/SignalRMapRealtime/Events/EventBus.cs @@ -93,7 +93,7 @@ public async Task PublishAsync(T @event) where T : DomainEvent } }); - await Task.WhenAll(tasks); + await Task.WhenAll(tasks).ConfigureAwait(false); _logger.LogInformation( "Event {EventName} (ID: {EventId}) published successfully", diff --git a/src/SignalRMapRealtime/Hubs/LocationHub.cs b/src/SignalRMapRealtime/Hubs/LocationHub.cs index e1f2854..b7a06b7 100644 --- a/src/SignalRMapRealtime/Hubs/LocationHub.cs +++ b/src/SignalRMapRealtime/Hubs/LocationHub.cs @@ -45,8 +45,8 @@ public LocationHub(ILocationService locationService, IVehicleService vehicleServ /// public override async Task OnConnectedAsync() { - _logger.LogInformation($"Client {Context.ConnectionId} connected"); - await base.OnConnectedAsync(); + _logger.LogInformation("Client {ConnectionId} connected", Context.ConnectionId); + await base.OnConnectedAsync().ConfigureAwait(false); } /// @@ -55,7 +55,7 @@ public override async Task OnConnectedAsync() public override async Task OnDisconnectedAsync(Exception? exception) { _logger.LogInformation($"Client {Context.ConnectionId} disconnected. Exception: {exception?.Message}"); - await base.OnDisconnectedAsync(exception); + await base.OnDisconnectedAsync(exception).ConfigureAwait(false); } /// @@ -65,20 +65,20 @@ public async Task SendLocationUpdate(CreateLocationDto locationDto) { try { - var location = await _locationService.RecordLocationAsync(locationDto); + var location = await _locationService.RecordLocationAsync(locationDto).ConfigureAwait(false); // Broadcast to all connected clients - await Clients.All.SendAsync("LocationUpdated", location); + await Clients.All.SendAsync("LocationUpdated", location).ConfigureAwait(false); // Notify vehicle-specific listeners - await Clients.Group($"vehicle-{locationDto.VehicleId}").SendAsync("VehicleLocationUpdated", location); + await Clients.Group($"vehicle-{locationDto.VehicleId}").SendAsync("VehicleLocationUpdated", location).ConfigureAwait(false); - _logger.LogInformation($"Location updated for vehicle {locationDto.VehicleId}"); + _logger.LogInformation("Location updated for vehicle {VehicleId}", locationDto.VehicleId); } catch (Exception ex) { - _logger.LogError($"Error sending location update: {ex.Message}"); - await Clients.Caller.SendAsync("Error", "Failed to update location"); + _logger.LogError("Error sending location update: {Message}", ex.Message); + await Clients.Caller.SendAsync("Error", "Failed to update location").ConfigureAwait(false); } } @@ -89,12 +89,12 @@ public async Task BroadcastVehicleStatusChange(int vehicleId, string newStatus) { try { - await Clients.All.SendAsync("VehicleStatusChanged", new { vehicleId, newStatus, timestamp = DateTime.UtcNow }); - _logger.LogInformation($"Vehicle {vehicleId} status changed to {newStatus}"); + await Clients.All.SendAsync("VehicleStatusChanged", new { vehicleId, newStatus, timestamp = DateTime.UtcNow }).ConfigureAwait(false); + _logger.LogInformation("Vehicle {VehicleId} status changed to {NewStatus}", vehicleId, newStatus); } catch (Exception ex) { - _logger.LogError($"Error broadcasting vehicle status: {ex.Message}"); + _logger.LogError("Error broadcasting vehicle status: {Message}", ex.Message); } } @@ -105,14 +105,14 @@ public async Task SubscribeToVehicle(int vehicleId) { try { - await Groups.AddToGroupAsync(Context.ConnectionId, $"vehicle-{vehicleId}"); - await Clients.Caller.SendAsync("SubscribedToVehicle", vehicleId); - _logger.LogInformation($"Client {Context.ConnectionId} subscribed to vehicle {vehicleId}"); + await Groups.AddToGroupAsync(Context.ConnectionId, $"vehicle-{vehicleId}").ConfigureAwait(false); + await Clients.Caller.SendAsync("SubscribedToVehicle", vehicleId).ConfigureAwait(false); + _logger.LogInformation("Client {ConnectionId} subscribed to vehicle {VehicleId}", Context.ConnectionId, vehicleId); } catch (Exception ex) { - _logger.LogError($"Error subscribing to vehicle: {ex.Message}"); - await Clients.Caller.SendAsync("Error", "Failed to subscribe to vehicle"); + _logger.LogError("Error subscribing to vehicle: {Message}", ex.Message); + await Clients.Caller.SendAsync("Error", "Failed to subscribe to vehicle").ConfigureAwait(false); } } @@ -123,14 +123,14 @@ public async Task UnsubscribeFromVehicle(int vehicleId) { try { - await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"vehicle-{vehicleId}"); - await Clients.Caller.SendAsync("UnsubscribedFromVehicle", vehicleId); - _logger.LogInformation($"Client {Context.ConnectionId} unsubscribed from vehicle {vehicleId}"); + await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"vehicle-{vehicleId}").ConfigureAwait(false); + await Clients.Caller.SendAsync("UnsubscribedFromVehicle", vehicleId).ConfigureAwait(false); + _logger.LogInformation("Client {ConnectionId} unsubscribed from vehicle {VehicleId}", Context.ConnectionId, vehicleId); } catch (Exception ex) { - _logger.LogError($"Error unsubscribing from vehicle: {ex.Message}"); - await Clients.Caller.SendAsync("Error", "Failed to unsubscribe from vehicle"); + _logger.LogError("Error unsubscribing from vehicle: {Message}", ex.Message); + await Clients.Caller.SendAsync("Error", "Failed to unsubscribe from vehicle").ConfigureAwait(false); } } @@ -141,13 +141,13 @@ public async Task RequestVehicleLocation(int vehicleId) { try { - var location = await _locationService.GetLatestLocationAsync(vehicleId); - await Clients.Caller.SendAsync("VehicleLocation", location); + var location = await _locationService.GetLatestLocationAsync(vehicleId).ConfigureAwait(false); + await Clients.Caller.SendAsync("VehicleLocation", location).ConfigureAwait(false); } catch (Exception ex) { - _logger.LogError($"Error requesting vehicle location: {ex.Message}"); - await Clients.Caller.SendAsync("Error", "Failed to retrieve vehicle location"); + _logger.LogError("Error requesting vehicle location: {Message}", ex.Message); + await Clients.Caller.SendAsync("Error", "Failed to retrieve vehicle location").ConfigureAwait(false); } } @@ -158,12 +158,12 @@ public async Task BroadcastRouteProgress(int routeId, int completionPercentage, { try { - await Clients.All.SendAsync("RouteProgressUpdated", new { routeId, completionPercentage, status, timestamp = DateTime.UtcNow }); - _logger.LogInformation($"Route {routeId} progress: {completionPercentage}%"); + await Clients.All.SendAsync("RouteProgressUpdated", new { routeId, completionPercentage, status, timestamp = DateTime.UtcNow }).ConfigureAwait(false); + _logger.LogInformation("Route {RouteId} progress: {CompletionPercentage}%", routeId, completionPercentage); } catch (Exception ex) { - _logger.LogError($"Error broadcasting route progress: {ex.Message}"); + _logger.LogError("Error broadcasting route progress: {Message}", ex.Message); } } @@ -175,12 +175,12 @@ public async Task SendAlert(int vehicleId, string alertType, string message) try { var alert = new { vehicleId, alertType, message, timestamp = DateTime.UtcNow }; - await Clients.All.SendAsync("Alert", alert); - _logger.LogWarning($"Alert for vehicle {vehicleId}: {alertType} - {message}"); + await Clients.All.SendAsync("Alert", alert).ConfigureAwait(false); + _logger.LogWarning("Alert for vehicle {VehicleId}: {AlertType} - {Message}", vehicleId, alertType, message); } catch (Exception ex) { - _logger.LogError($"Error sending alert: {ex.Message}"); + _logger.LogError("Error sending alert: {Message}", ex.Message); } } @@ -191,13 +191,13 @@ public async Task RequestOnlineVehicleCount() { try { - var count = await _vehicleService.GetOnlineVehicleCountAsync(); - await Clients.Caller.SendAsync("OnlineVehicleCount", count); + var count = await _vehicleService.GetOnlineVehicleCountAsync().ConfigureAwait(false); + await Clients.Caller.SendAsync("OnlineVehicleCount", count).ConfigureAwait(false); } catch (Exception ex) { - _logger.LogError($"Error requesting online vehicle count: {ex.Message}"); - await Clients.Caller.SendAsync("Error", "Failed to retrieve vehicle count"); + _logger.LogError("Error requesting online vehicle count: {Message}", ex.Message); + await Clients.Caller.SendAsync("Error", "Failed to retrieve vehicle count").ConfigureAwait(false); } } @@ -209,12 +209,12 @@ public async Task BroadcastFleetStatus(string fleetName, int onlineCount, int to try { var status = new { fleetName, onlineCount, totalCount, percentage = (onlineCount * 100) / totalCount, timestamp = DateTime.UtcNow }; - await Clients.All.SendAsync("FleetStatusUpdated", status); - _logger.LogInformation($"Fleet {fleetName} status: {onlineCount}/{totalCount} online"); + await Clients.All.SendAsync("FleetStatusUpdated", status).ConfigureAwait(false); + _logger.LogInformation("Fleet {FleetName} status: {OnlineCount}/{TotalCount} online", fleetName, onlineCount, totalCount); } catch (Exception ex) { - _logger.LogError($"Error broadcasting fleet status: {ex.Message}"); + _logger.LogError("Error broadcasting fleet status: {Message}", ex.Message); } } @@ -225,11 +225,11 @@ public async Task Ping() { try { - await Clients.Caller.SendAsync("Pong"); + await Clients.Caller.SendAsync("Pong").ConfigureAwait(false); } catch (Exception ex) { - _logger.LogError($"Error handling ping: {ex.Message}"); + _logger.LogError("Error handling ping: {Message}", ex.Message); } } } diff --git a/src/SignalRMapRealtime/Hubs/RoutePlaybackHub.cs b/src/SignalRMapRealtime/Hubs/RoutePlaybackHub.cs index 2547dbe..11dd9b9 100644 --- a/src/SignalRMapRealtime/Hubs/RoutePlaybackHub.cs +++ b/src/SignalRMapRealtime/Hubs/RoutePlaybackHub.cs @@ -76,7 +76,7 @@ public RoutePlaybackHub(IRoutePlaybackService playbackService, ILogger @@ -84,7 +84,7 @@ public override async Task OnDisconnectedAsync(Exception? exception) { _logger.LogInformation("Playback client {ConnectionId} disconnected. Reason: {Reason}", Context.ConnectionId, exception?.Message ?? "clean disconnect"); - await base.OnDisconnectedAsync(exception); + await base.OnDisconnectedAsync(exception).ConfigureAwait(false); } /// @@ -97,8 +97,8 @@ public async Task StartPlayback(StartPlaybackRequest request) { try { - var playbackId = await _playbackService.StartPlaybackAsync(request); - await Groups.AddToGroupAsync(Context.ConnectionId, PlaybackGroup(playbackId)); + var playbackId = await _playbackService.StartPlaybackAsync(request).ConfigureAwait(false); + await Groups.AddToGroupAsync(Context.ConnectionId, PlaybackGroup(playbackId)).ConfigureAwait(false); await Clients.Caller.SendAsync("PlaybackStarted", new { @@ -117,7 +117,7 @@ public async Task StartPlayback(StartPlaybackRequest request) { _logger.LogError(ex, "Client {ConnectionId} failed to start playback for session {SessionId}", Context.ConnectionId, request.SessionId); - await Clients.Caller.SendAsync("PlaybackError", new { Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { Error = ex.Message }).ConfigureAwait(false); } } @@ -130,14 +130,14 @@ public async Task PausePlayback(Guid playbackId) { try { - await _playbackService.PausePlaybackAsync(playbackId); - var state = await _playbackService.GetPlaybackStateAsync(playbackId); - await Clients.Group(PlaybackGroup(playbackId)).SendAsync("PlaybackPaused", state); + await _playbackService.PausePlaybackAsync(playbackId).ConfigureAwait(false); + var state = await _playbackService.GetPlaybackStateAsync(playbackId).ConfigureAwait(false); + await Clients.Group(PlaybackGroup(playbackId)).SendAsync("PlaybackPaused", state).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Error pausing playback {PlaybackId}", playbackId); - await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }).ConfigureAwait(false); } } @@ -150,14 +150,14 @@ public async Task ResumePlayback(Guid playbackId) { try { - await _playbackService.ResumePlaybackAsync(playbackId); - var state = await _playbackService.GetPlaybackStateAsync(playbackId); - await Clients.Group(PlaybackGroup(playbackId)).SendAsync("PlaybackResumed", state); + await _playbackService.ResumePlaybackAsync(playbackId).ConfigureAwait(false); + var state = await _playbackService.GetPlaybackStateAsync(playbackId).ConfigureAwait(false); + await Clients.Group(PlaybackGroup(playbackId)).SendAsync("PlaybackResumed", state).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Error resuming playback {PlaybackId}", playbackId); - await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }).ConfigureAwait(false); } } @@ -176,8 +176,8 @@ public async Task StopPlayback(Guid playbackId) StoppedAt = DateTime.UtcNow }); - await _playbackService.StopPlaybackAsync(playbackId); - await Groups.RemoveFromGroupAsync(Context.ConnectionId, PlaybackGroup(playbackId)); + await _playbackService.StopPlaybackAsync(playbackId).ConfigureAwait(false); + await Groups.RemoveFromGroupAsync(Context.ConnectionId, PlaybackGroup(playbackId)).ConfigureAwait(false); _logger.LogInformation("Client {ConnectionId} stopped playback {PlaybackId}", Context.ConnectionId, playbackId); @@ -185,7 +185,7 @@ public async Task StopPlayback(Guid playbackId) catch (Exception ex) { _logger.LogError(ex, "Error stopping playback {PlaybackId}", playbackId); - await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }).ConfigureAwait(false); } } @@ -199,8 +199,8 @@ public async Task SeekTo(Guid playbackId, DateTime timestamp) { try { - await _playbackService.SeekToTimestampAsync(playbackId, timestamp); - var state = await _playbackService.GetPlaybackStateAsync(playbackId); + await _playbackService.SeekToTimestampAsync(playbackId, timestamp).ConfigureAwait(false); + var state = await _playbackService.GetPlaybackStateAsync(playbackId).ConfigureAwait(false); await Clients.Group(PlaybackGroup(playbackId)).SendAsync("PlaybackSeeked", new { @@ -212,7 +212,7 @@ public async Task SeekTo(Guid playbackId, DateTime timestamp) catch (Exception ex) { _logger.LogError(ex, "Error seeking playback {PlaybackId} to {Timestamp}", playbackId, timestamp); - await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }).ConfigureAwait(false); } } @@ -227,8 +227,8 @@ public async Task SetSpeed(Guid playbackId, double speedMultiplier) { try { - await _playbackService.SetPlaybackSpeedAsync(playbackId, speedMultiplier); - var state = await _playbackService.GetPlaybackStateAsync(playbackId); + await _playbackService.SetPlaybackSpeedAsync(playbackId, speedMultiplier).ConfigureAwait(false); + var state = await _playbackService.GetPlaybackStateAsync(playbackId).ConfigureAwait(false); await Clients.Group(PlaybackGroup(playbackId)).SendAsync("PlaybackSpeedChanged", new { @@ -239,7 +239,7 @@ public async Task SetSpeed(Guid playbackId, double speedMultiplier) catch (Exception ex) { _logger.LogError(ex, "Error setting speed for playback {PlaybackId}", playbackId); - await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }).ConfigureAwait(false); } } @@ -252,7 +252,7 @@ public async Task SubscribeToPlayback(Guid playbackId) { try { - var state = await _playbackService.GetPlaybackStateAsync(playbackId); + var state = await _playbackService.GetPlaybackStateAsync(playbackId).ConfigureAwait(false); if (state is null) { @@ -264,8 +264,8 @@ public async Task SubscribeToPlayback(Guid playbackId) return; } - await Groups.AddToGroupAsync(Context.ConnectionId, PlaybackGroup(playbackId)); - await Clients.Caller.SendAsync("SubscribedToPlayback", state); + await Groups.AddToGroupAsync(Context.ConnectionId, PlaybackGroup(playbackId)).ConfigureAwait(false); + await Clients.Caller.SendAsync("SubscribedToPlayback", state).ConfigureAwait(false); _logger.LogInformation("Client {ConnectionId} subscribed to playback {PlaybackId}", Context.ConnectionId, playbackId); @@ -274,7 +274,7 @@ public async Task SubscribeToPlayback(Guid playbackId) { _logger.LogError(ex, "Error subscribing client {ConnectionId} to playback {PlaybackId}", Context.ConnectionId, playbackId); - await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }).ConfigureAwait(false); } } @@ -288,8 +288,8 @@ public async Task UnsubscribeFromPlayback(Guid playbackId) { try { - await Groups.RemoveFromGroupAsync(Context.ConnectionId, PlaybackGroup(playbackId)); - await Clients.Caller.SendAsync("UnsubscribedFromPlayback", playbackId); + await Groups.RemoveFromGroupAsync(Context.ConnectionId, PlaybackGroup(playbackId)).ConfigureAwait(false); + await Clients.Caller.SendAsync("UnsubscribedFromPlayback", playbackId).ConfigureAwait(false); _logger.LogInformation("Client {ConnectionId} unsubscribed from playback {PlaybackId}", Context.ConnectionId, playbackId); @@ -309,13 +309,13 @@ public async Task GetPlaybackState(Guid playbackId) { try { - var state = await _playbackService.GetPlaybackStateAsync(playbackId); - await Clients.Caller.SendAsync("PlaybackState", state); + var state = await _playbackService.GetPlaybackStateAsync(playbackId).ConfigureAwait(false); + await Clients.Caller.SendAsync("PlaybackState", state).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Error fetching state for playback {PlaybackId}", playbackId); - await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { PlaybackId = playbackId, Error = ex.Message }).ConfigureAwait(false); } } @@ -328,8 +328,8 @@ public async Task RequestTimeline(int sessionId) { try { - var timeline = await _playbackService.BuildTimelineAsync(sessionId); - await Clients.Caller.SendAsync("TimelineReady", timeline); + var timeline = await _playbackService.BuildTimelineAsync(sessionId).ConfigureAwait(false); + await Clients.Caller.SendAsync("TimelineReady", timeline).ConfigureAwait(false); _logger.LogInformation("Timeline for session {SessionId} delivered to client {ConnectionId}", sessionId, Context.ConnectionId); @@ -337,7 +337,7 @@ public async Task RequestTimeline(int sessionId) catch (Exception ex) { _logger.LogError(ex, "Error building timeline for session {SessionId}", sessionId); - await Clients.Caller.SendAsync("PlaybackError", new { Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { Error = ex.Message }).ConfigureAwait(false); } } @@ -352,14 +352,14 @@ public async Task RequestSnapshot(int sessionId, DateTime timestamp) { try { - var snapshot = await _playbackService.GetSnapshotAtTimestampAsync(sessionId, timestamp); - await Clients.Caller.SendAsync("SnapshotReady", snapshot); + var snapshot = await _playbackService.GetSnapshotAtTimestampAsync(sessionId, timestamp).ConfigureAwait(false); + await Clients.Caller.SendAsync("SnapshotReady", snapshot).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Error fetching snapshot for session {SessionId} at {Timestamp}", sessionId, timestamp); - await Clients.Caller.SendAsync("PlaybackError", new { Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { Error = ex.Message }).ConfigureAwait(false); } } @@ -372,13 +372,13 @@ public async Task RequestStatistics(int sessionId) { try { - var statistics = await _playbackService.GetPlaybackStatisticsAsync(sessionId); - await Clients.Caller.SendAsync("StatisticsReady", statistics); + var statistics = await _playbackService.GetPlaybackStatisticsAsync(sessionId).ConfigureAwait(false); + await Clients.Caller.SendAsync("StatisticsReady", statistics).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Error computing statistics for session {SessionId}", sessionId); - await Clients.Caller.SendAsync("PlaybackError", new { Error = ex.Message }); + await Clients.Caller.SendAsync("PlaybackError", new { Error = ex.Message }).ConfigureAwait(false); } } diff --git a/src/SignalRMapRealtime/Integration/WebhookHandler.cs b/src/SignalRMapRealtime/Integration/WebhookHandler.cs index e7f56df..c0fd5c2 100644 --- a/src/SignalRMapRealtime/Integration/WebhookHandler.cs +++ b/src/SignalRMapRealtime/Integration/WebhookHandler.cs @@ -136,7 +136,7 @@ private async Task HandleTrackingServiceWebhook(string TriggeredBy = "WebhookService" }; - await _eventBus.PublishAsync(locationEvent); + await _eventBus.PublishAsync(locationEvent).ConfigureAwait(false); return new WebhookProcessingResult { Success = true, ProcessedAt = DateTime.UtcNow }; } diff --git a/src/SignalRMapRealtime/Services/CacheService.cs b/src/SignalRMapRealtime/Services/CacheService.cs index 974c811..d207c11 100644 --- a/src/SignalRMapRealtime/Services/CacheService.cs +++ b/src/SignalRMapRealtime/Services/CacheService.cs @@ -79,7 +79,7 @@ public MemoryCacheService( public async Task GetOrCreateAsync(string key, Func> factory, TimeSpan? expiration = null) { if (!_options.Enabled) - return await factory(); + return await factory().ConfigureAwait(false); if (_memoryCache.TryGetValue(key, out T? cachedValue)) { @@ -89,7 +89,7 @@ public async Task GetOrCreateAsync(string key, Func> factory, Time _logger.LogDebug("Cache miss for key: {Key}. Creating value...", key); - var value = await factory(); + var value = await factory().ConfigureAwait(false); var cacheOptions = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = expiration ?? TimeSpan.FromSeconds(_options.DefaultDurationSeconds), diff --git a/src/SignalRMapRealtime/Services/GeofenceService.cs b/src/SignalRMapRealtime/Services/GeofenceService.cs index 2e35e73..d78ec93 100644 --- a/src/SignalRMapRealtime/Services/GeofenceService.cs +++ b/src/SignalRMapRealtime/Services/GeofenceService.cs @@ -126,10 +126,10 @@ public async Task> CheckLocationAsync( var alerts = new List(); foreach (var id in currentIds.Except(previousIds).ToList()) - await EmitAlertAsync(alerts, id, vehicleId, latitude, longitude, "Entered"); + await EmitAlertAsync(alerts, id, vehicleId, latitude, longitude, "Entered").ConfigureAwait(false); foreach (var id in previousIds.Except(currentIds).ToList()) - await EmitAlertAsync(alerts, id, vehicleId, latitude, longitude, "Exited"); + await EmitAlertAsync(alerts, id, vehicleId, latitude, longitude, "Exited").ConfigureAwait(false); _presence[vehicleId] = currentIds; diff --git a/src/SignalRMapRealtime/Services/LocationService.cs b/src/SignalRMapRealtime/Services/LocationService.cs index 1a81ed3..2ce7f88 100644 --- a/src/SignalRMapRealtime/Services/LocationService.cs +++ b/src/SignalRMapRealtime/Services/LocationService.cs @@ -46,7 +46,7 @@ public async Task RecordLocationAsync(CreateLocationDto locationDto if (!ValidateCoordinates(locationDto.Latitude, locationDto.Longitude)) throw new InvalidLocationException(locationDto.Latitude, locationDto.Longitude); - var vehicle = await _vehicleRepository.GetByIdAsync(locationDto.VehicleId, cancellationToken); + var vehicle = await _vehicleRepository.GetByIdAsync(locationDto.VehicleId, cancellationToken).ConfigureAwait(false); if (vehicle is null) throw new VehicleNotFoundException(locationDto.VehicleId); @@ -66,12 +66,12 @@ public async Task RecordLocationAsync(CreateLocationDto locationDto CreatedAt = DateTime.UtcNow }; - await _locationRepository.AddAsync(location, cancellationToken); - await _locationRepository.SaveChangesAsync(cancellationToken); + await _locationRepository.AddAsync(location, cancellationToken).ConfigureAwait(false); + await _locationRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); vehicle.RecordLocation(location); - await _vehicleRepository.UpdateAsync(vehicle, cancellationToken); - await _vehicleRepository.SaveChangesAsync(cancellationToken); + await _vehicleRepository.UpdateAsync(vehicle, cancellationToken).ConfigureAwait(false); + await _vehicleRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return _mapper.Map(location); } @@ -81,7 +81,7 @@ public async Task RecordLocationAsync(CreateLocationDto locationDto /// public async Task GetLatestLocationAsync(Guid vehicleId, CancellationToken cancellationToken = default) { - var location = await _locationRepository.GetLatestLocationByVehicleAsync(vehicleId); + var location = await _locationRepository.GetLatestLocationByVehicleAsync(vehicleId).ConfigureAwait(false); return location is null ? null : _mapper.Map(location); } @@ -90,7 +90,7 @@ public async Task RecordLocationAsync(CreateLocationDto locationDto /// public async Task> GetLocationHistoryAsync(Guid vehicleId, DateTime startTime, DateTime endTime, CancellationToken cancellationToken = default) { - var locations = await _locationRepository.GetLocationsByTimeRangeAsync(vehicleId, startTime, endTime); + var locations = await _locationRepository.GetLocationsByTimeRangeAsync(vehicleId, startTime, endTime).ConfigureAwait(false); return _mapper.Map>(locations); } @@ -99,7 +99,7 @@ public async Task> GetLocationHistoryAsync(Guid vehicle /// public async Task> GetRecentLocationsAsync(Guid vehicleId, int hoursBack = 24, CancellationToken cancellationToken = default) { - var locations = await _locationRepository.GetRecentLocationsAsync(vehicleId, hoursBack); + var locations = await _locationRepository.GetRecentLocationsAsync(vehicleId, hoursBack).ConfigureAwait(false); return _mapper.Map>(locations); } @@ -108,7 +108,7 @@ public async Task> GetRecentLocationsAsync(Guid vehicle /// public async Task> GetLocationsNearbyAsync(double centerLat, double centerLng, double radiusKm = 1.0, CancellationToken cancellationToken = default) { - var locations = await _locationRepository.GetLocationsNearbyAsync(centerLat, centerLng, radiusKm); + var locations = await _locationRepository.GetLocationsNearbyAsync(centerLat, centerLng, radiusKm).ConfigureAwait(false); return _mapper.Map>(locations); } @@ -117,9 +117,9 @@ public async Task> GetLocationsNearbyAsync(double cente /// public async Task GetLocationStatsAsync(Guid vehicleId, DateTime startTime, DateTime endTime, CancellationToken cancellationToken = default) { - var (count, minSpeed, maxSpeed, avgSpeed) = await _locationRepository.GetLocationStatsAsync(vehicleId, startTime, endTime); + var (count, minSpeed, maxSpeed, avgSpeed) = await _locationRepository.GetLocationStatsAsync(vehicleId, startTime, endTime).ConfigureAwait(false); - var locations = await _locationRepository.GetLocationsByTimeRangeAsync(vehicleId, startTime, endTime); + var locations = await _locationRepository.GetLocationsByTimeRangeAsync(vehicleId, startTime, endTime).ConfigureAwait(false); double totalDistance = 0; var sortedLocations = locations.OrderBy(l => l.RecordedAt).ToList(); @@ -143,7 +143,7 @@ public async Task GetLocationStatsAsync(Guid vehicleId, DateTi /// public async Task> GetLocationsByTypeAsync(LocationType locationType, CancellationToken cancellationToken = default) { - var locations = await _locationRepository.GetLocationsByTypeAsync(locationType); + var locations = await _locationRepository.GetLocationsByTypeAsync(locationType).ConfigureAwait(false); return _mapper.Map>(locations); } @@ -152,7 +152,7 @@ public async Task> GetLocationsByTypeAsync(LocationType /// public async Task UpdateLocationAsync(Guid locationId, UpdateLocationDto locationDto, CancellationToken cancellationToken = default) { - var location = await _locationRepository.GetByIdAsync(locationId, cancellationToken); + var location = await _locationRepository.GetByIdAsync(locationId, cancellationToken).ConfigureAwait(false); if (location is null) throw new InvalidLocationException("Location not found."); @@ -167,8 +167,8 @@ public async Task UpdateLocationAsync(Guid locationId, UpdateLocati if (locationDto.LocationType.HasValue) location.LocationType = locationDto.LocationType.Value; - await _locationRepository.UpdateAsync(location, cancellationToken); - await _locationRepository.SaveChangesAsync(cancellationToken); + await _locationRepository.UpdateAsync(location, cancellationToken).ConfigureAwait(false); + await _locationRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return _mapper.Map(location); } @@ -178,7 +178,7 @@ public async Task UpdateLocationAsync(Guid locationId, UpdateLocati /// public async Task> GetLocationsAsync(int pageNumber, int pageSize, CancellationToken cancellationToken = default) { - var locations = await _locationRepository.GetAllAsync(cancellationToken); + var locations = await _locationRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); var locationDtos = _mapper.Map>(locations); return PaginatedResponse.FromList(locationDtos, pageNumber, pageSize); } @@ -188,7 +188,7 @@ public async Task> GetLocationsAsync(int pageNumb /// public async Task GetLocationByIdAsync(Guid id, CancellationToken cancellationToken = default) { - var location = await _locationRepository.GetByIdAsync(id, cancellationToken); + var location = await _locationRepository.GetByIdAsync(id, cancellationToken).ConfigureAwait(false); return location is null ? null : _mapper.Map(location); } @@ -197,8 +197,8 @@ public async Task> GetLocationsAsync(int pageNumb /// public async Task DeleteLocationAsync(Guid id, CancellationToken cancellationToken = default) { - await _locationRepository.RemoveByIdAsync(id, cancellationToken); - await _locationRepository.SaveChangesAsync(cancellationToken); + await _locationRepository.RemoveByIdAsync(id, cancellationToken).ConfigureAwait(false); + await _locationRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } /// @@ -232,6 +232,6 @@ public double CalculateDistance(double lat1, double lon1, double lat2, double lo /// public async Task CleanupOldLocationsAsync(int daysOld = 90, CancellationToken cancellationToken = default) { - return await _locationRepository.DeleteOldLocationsAsync(daysOld); + return await _locationRepository.DeleteOldLocationsAsync(daysOld).ConfigureAwait(false); } } diff --git a/src/SignalRMapRealtime/Services/NotificationService.cs b/src/SignalRMapRealtime/Services/NotificationService.cs index 8232ba4..19c9021 100644 --- a/src/SignalRMapRealtime/Services/NotificationService.cs +++ b/src/SignalRMapRealtime/Services/NotificationService.cs @@ -155,7 +155,7 @@ public async Task SendMultiChannelAsync(string recipient, string subject, string if (includePush) tasks.Add(SendPushAsync(recipient, subject, body)); - await Task.WhenAll(tasks); + await Task.WhenAll(tasks).ConfigureAwait(false); } /// diff --git a/src/SignalRMapRealtime/Services/RoutePlaybackService.cs b/src/SignalRMapRealtime/Services/RoutePlaybackService.cs index e9c3833..8fa8a17 100644 --- a/src/SignalRMapRealtime/Services/RoutePlaybackService.cs +++ b/src/SignalRMapRealtime/Services/RoutePlaybackService.cs @@ -69,7 +69,7 @@ public async Task StartPlaybackAsync(StartPlaybackRequest request, Cancell throw new InvalidOperationException( $"The engine has reached its maximum of {_options.MaxConcurrentPlaybacks} concurrent playback sessions."); - var locations = await LoadLocationsAsync(request.SessionId, cancellationToken); + var locations = await LoadLocationsAsync(request.SessionId, cancellationToken).ConfigureAwait(false); if (locations.Count == 0) throw new ArgumentException( @@ -129,7 +129,7 @@ public async Task StopPlaybackAsync(Guid playbackId, CancellationToken cancellat state.Status = PlaybackStatus.Idle; state.PauseGate.Set(); - await state.Cts.CancelAsync(); + await state.Cts.CancelAsync().ConfigureAwait(false); if (state.PlaybackTask is not null) await state.PlaybackTask.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing); @@ -177,7 +177,7 @@ public Task> GetActivePlaybacksAsync() /// public async Task BuildTimelineAsync(int sessionId, CancellationToken cancellationToken = default) { - var locations = await LoadLocationsAsync(sessionId, cancellationToken); + var locations = await LoadLocationsAsync(sessionId, cancellationToken).ConfigureAwait(false); if (locations.Count == 0) return null; var entries = BuildTimelineEntries(locations); @@ -201,7 +201,7 @@ public Task> GetActivePlaybacksAsync() /// public async Task GetSnapshotAtTimestampAsync(int sessionId, DateTime timestamp, CancellationToken cancellationToken = default) { - var locations = await LoadLocationsAsync(sessionId, cancellationToken); + var locations = await LoadLocationsAsync(sessionId, cancellationToken).ConfigureAwait(false); if (locations.Count == 0) return null; var clamped = timestamp < locations[0].RecordedAt ? locations[0].RecordedAt @@ -216,7 +216,7 @@ public Task> GetActivePlaybacksAsync() /// public async Task GetPlaybackStatisticsAsync(int sessionId, CancellationToken cancellationToken = default) { - var locations = await LoadLocationsAsync(sessionId, cancellationToken); + var locations = await LoadLocationsAsync(sessionId, cancellationToken).ConfigureAwait(false); if (locations.Count == 0) return null; var speedSamples = locations.Where(l => l.Speed.HasValue).Select(l => l.Speed!.Value).ToList(); @@ -256,7 +256,7 @@ private async Task> LoadLocationsAsync(int sessionId, Ca { using var scope = _scopeFactory.CreateScope(); var repo = scope.ServiceProvider.GetRequiredService(); - var raw = await repo.GetLocationsBySessionAsync(sessionId); + var raw = await repo.GetLocationsBySessionAsync(sessionId).ConfigureAwait(false); var ordered = raw.OrderBy(l => l.RecordedAt).ToList(); return ordered.Count > _options.MaxLocationsPerPlayback @@ -306,7 +306,7 @@ await _hubContext.Clients _options.MinFrameIntervalMs, _options.MaxFrameIntervalMs); - await Task.Delay(delayMs, state.Cts.Token); + await Task.Delay(delayMs, state.Cts.Token).ConfigureAwait(false); } } @@ -541,7 +541,7 @@ private static PlaybackSessionDto MapToDto(PlaybackState state) public async ValueTask DisposeAsync() { foreach (var id in _sessions.Keys.ToArray()) - await StopPlaybackAsync(id); + await StopPlaybackAsync(id).ConfigureAwait(false); } // ------------------------------------------------------------------------- diff --git a/src/SignalRMapRealtime/Services/TrackingService.cs b/src/SignalRMapRealtime/Services/TrackingService.cs index beb66a5..8776e96 100644 --- a/src/SignalRMapRealtime/Services/TrackingService.cs +++ b/src/SignalRMapRealtime/Services/TrackingService.cs @@ -38,7 +38,7 @@ public TrackingService(TrackingSessionRepository sessionRepository, VehicleRepos /// public async Task StartTrackingSessionAsync(int vehicleId, string sessionName = "", int? routeId = null, CancellationToken cancellationToken = default) { - var vehicle = await _vehicleRepository.GetByIdAsync(vehicleId, cancellationToken); + var vehicle = await _vehicleRepository.GetByIdAsync(vehicleId, cancellationToken).ConfigureAwait(false); if (vehicle is null) throw new VehicleNotFoundException(vehicleId); @@ -60,10 +60,10 @@ public async Task StartTrackingSessionAsync(int vehicleId, string sessionNa session.StartSession(); vehicle.UpdateStatus(VehicleStatus.InTransit); - await _sessionRepository.AddAsync(session, cancellationToken); - await _sessionRepository.SaveChangesAsync(cancellationToken); - await _vehicleRepository.UpdateAsync(vehicle, cancellationToken); - await _vehicleRepository.SaveChangesAsync(cancellationToken); + await _sessionRepository.AddAsync(session, cancellationToken).ConfigureAwait(false); + await _sessionRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await _vehicleRepository.UpdateAsync(vehicle, cancellationToken).ConfigureAwait(false); + await _vehicleRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return session.Id; } @@ -73,13 +73,13 @@ public async Task StartTrackingSessionAsync(int vehicleId, string sessionNa /// public async Task PauseSessionAsync(int sessionId, CancellationToken cancellationToken = default) { - var session = await _sessionRepository.GetByIdAsync(sessionId, cancellationToken); + var session = await _sessionRepository.GetByIdAsync(sessionId, cancellationToken).ConfigureAwait(false); if (session is null || session.Status != SessionStatus.Active) return false; session.PauseSession(); - await _sessionRepository.UpdateAsync(session, cancellationToken); - await _sessionRepository.SaveChangesAsync(cancellationToken); + await _sessionRepository.UpdateAsync(session, cancellationToken).ConfigureAwait(false); + await _sessionRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return true; } @@ -88,13 +88,13 @@ public async Task PauseSessionAsync(int sessionId, CancellationToken cance /// public async Task ResumeSessionAsync(int sessionId, CancellationToken cancellationToken = default) { - var session = await _sessionRepository.GetByIdAsync(sessionId, cancellationToken); + var session = await _sessionRepository.GetByIdAsync(sessionId, cancellationToken).ConfigureAwait(false); if (session is null || session.Status != SessionStatus.Paused) return false; session.ResumeSession(); - await _sessionRepository.UpdateAsync(session, cancellationToken); - await _sessionRepository.SaveChangesAsync(cancellationToken); + await _sessionRepository.UpdateAsync(session, cancellationToken).ConfigureAwait(false); + await _sessionRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return true; } @@ -103,21 +103,21 @@ public async Task ResumeSessionAsync(int sessionId, CancellationToken canc /// public async Task CompleteSessionAsync(int sessionId, CancellationToken cancellationToken = default) { - var session = await _sessionRepository.GetSessionWithDetailsAsync(sessionId); + var session = await _sessionRepository.GetSessionWithDetailsAsync(sessionId).ConfigureAwait(false); if (session is null || session.Status == SessionStatus.Completed) return false; session.CompleteSession(); - var vehicle = await _vehicleRepository.GetByIdAsync(session.VehicleId, cancellationToken); + var vehicle = await _vehicleRepository.GetByIdAsync(session.VehicleId, cancellationToken).ConfigureAwait(false); if (vehicle is not null) { vehicle.UpdateStatus(VehicleStatus.AtDepot); - await _vehicleRepository.UpdateAsync(vehicle, cancellationToken); - await _vehicleRepository.SaveChangesAsync(cancellationToken); + await _vehicleRepository.UpdateAsync(vehicle, cancellationToken).ConfigureAwait(false); + await _vehicleRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } - await _sessionRepository.UpdateAsync(session, cancellationToken); - await _sessionRepository.SaveChangesAsync(cancellationToken); + await _sessionRepository.UpdateAsync(session, cancellationToken).ConfigureAwait(false); + await _sessionRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return true; } @@ -126,21 +126,21 @@ public async Task CompleteSessionAsync(int sessionId, CancellationToken ca /// public async Task CancelSessionAsync(int sessionId, string reason = "", CancellationToken cancellationToken = default) { - var session = await _sessionRepository.GetByIdAsync(sessionId, cancellationToken); + var session = await _sessionRepository.GetByIdAsync(sessionId, cancellationToken).ConfigureAwait(false); if (session is null) return false; session.CancelSession(reason); - var vehicle = await _vehicleRepository.GetByIdAsync(session.VehicleId, cancellationToken); + var vehicle = await _vehicleRepository.GetByIdAsync(session.VehicleId, cancellationToken).ConfigureAwait(false); if (vehicle is not null) { vehicle.UpdateStatus(VehicleStatus.Idle); - await _vehicleRepository.UpdateAsync(vehicle, cancellationToken); - await _vehicleRepository.SaveChangesAsync(cancellationToken); + await _vehicleRepository.UpdateAsync(vehicle, cancellationToken).ConfigureAwait(false); + await _vehicleRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } - await _sessionRepository.UpdateAsync(session, cancellationToken); - await _sessionRepository.SaveChangesAsync(cancellationToken); + await _sessionRepository.UpdateAsync(session, cancellationToken).ConfigureAwait(false); + await _sessionRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return true; } @@ -149,7 +149,7 @@ public async Task CancelSessionAsync(int sessionId, string reason = "", Ca /// public async Task GetActiveSessionAsync(int vehicleId, CancellationToken cancellationToken = default) { - var session = await _sessionRepository.GetActiveSessionByVehicleAsync(vehicleId); + var session = await _sessionRepository.GetActiveSessionByVehicleAsync(vehicleId).ConfigureAwait(false); return session; } @@ -158,7 +158,7 @@ public async Task CancelSessionAsync(int sessionId, string reason = "", Ca /// public async Task> GetSessionHistoryAsync(int vehicleId, CancellationToken cancellationToken = default) { - var sessions = await _sessionRepository.GetSessionsByVehicleAsync(vehicleId); + var sessions = await _sessionRepository.GetSessionsByVehicleAsync(vehicleId).ConfigureAwait(false); return sessions.Cast(); } @@ -167,7 +167,7 @@ public async Task> GetSessionHistoryAsync(int vehicleId, Can /// public async Task> GetSessionsByStatusAsync(SessionStatus status, CancellationToken cancellationToken = default) { - var sessions = await _sessionRepository.GetSessionsByStatusAsync(status); + var sessions = await _sessionRepository.GetSessionsByStatusAsync(status).ConfigureAwait(false); return sessions.Cast(); } @@ -176,7 +176,7 @@ public async Task> GetSessionsByStatusAsync(SessionStatus st /// public async Task> GetExpiredSessionsAsync(CancellationToken cancellationToken = default) { - var sessions = await _sessionRepository.GetExpiredSessionsAsync(); + var sessions = await _sessionRepository.GetExpiredSessionsAsync().ConfigureAwait(false); return sessions.Cast(); } @@ -185,7 +185,7 @@ public async Task> GetExpiredSessionsAsync(CancellationToken /// public async Task IsSessionActiveAsync(int sessionId, CancellationToken cancellationToken = default) { - var session = await _sessionRepository.GetByIdAsync(sessionId, cancellationToken); + var session = await _sessionRepository.GetByIdAsync(sessionId, cancellationToken).ConfigureAwait(false); return session?.Status == SessionStatus.Active; } @@ -194,7 +194,7 @@ public async Task IsSessionActiveAsync(int sessionId, CancellationToken ca /// public async Task GetSessionDetailsAsync(int sessionId, CancellationToken cancellationToken = default) { - return await _sessionRepository.GetSessionWithDetailsAsync(sessionId); + return await _sessionRepository.GetSessionWithDetailsAsync(sessionId).ConfigureAwait(false); } /// @@ -202,7 +202,7 @@ public async Task IsSessionActiveAsync(int sessionId, CancellationToken ca /// public async Task GetSessionDistanceAsync(int sessionId, CancellationToken cancellationToken = default) { - var session = await _sessionRepository.GetSessionWithDetailsAsync(sessionId); + var session = await _sessionRepository.GetSessionWithDetailsAsync(sessionId).ConfigureAwait(false); return session?.TotalDistance ?? 0; } @@ -211,7 +211,7 @@ public async Task GetSessionDistanceAsync(int sessionId, CancellationTok /// public async Task GetSessionAverageSpeedAsync(int sessionId, CancellationToken cancellationToken = default) { - var session = await _sessionRepository.GetSessionWithDetailsAsync(sessionId); + var session = await _sessionRepository.GetSessionWithDetailsAsync(sessionId).ConfigureAwait(false); return session?.AverageSpeed ?? 0; } } diff --git a/src/SignalRMapRealtime/Services/VehicleService.cs b/src/SignalRMapRealtime/Services/VehicleService.cs index fb065c7..9328450 100644 --- a/src/SignalRMapRealtime/Services/VehicleService.cs +++ b/src/SignalRMapRealtime/Services/VehicleService.cs @@ -48,7 +48,7 @@ public async Task CreateVehicleAsync(CreateVehicleDto vehicleDto, Ca if (vehicleDto.DriverId.HasValue) { - var driver = await _userRepository.GetByIdAsync(vehicleDto.DriverId.Value, cancellationToken); + var driver = await _userRepository.GetByIdAsync(vehicleDto.DriverId.Value, cancellationToken).ConfigureAwait(false); if (driver is null) throw new InvalidOperationException($"Driver with ID {vehicleDto.DriverId} not found."); } @@ -69,8 +69,8 @@ public async Task CreateVehicleAsync(CreateVehicleDto vehicleDto, Ca UpdatedAt = DateTime.UtcNow }; - await _vehicleRepository.AddAsync(vehicle, cancellationToken); - await _vehicleRepository.SaveChangesAsync(cancellationToken); + await _vehicleRepository.AddAsync(vehicle, cancellationToken).ConfigureAwait(false); + await _vehicleRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return _mapper.Map(vehicle); } @@ -80,7 +80,7 @@ public async Task CreateVehicleAsync(CreateVehicleDto vehicleDto, Ca /// public async Task GetVehicleAsync(int vehicleId, CancellationToken cancellationToken = default) { - var vehicle = await _vehicleRepository.GetVehicleWithTrackingDataAsync(vehicleId); + var vehicle = await _vehicleRepository.GetVehicleWithTrackingDataAsync(vehicleId).ConfigureAwait(false); return vehicle is null ? null : _mapper.Map(vehicle); } @@ -89,7 +89,7 @@ public async Task CreateVehicleAsync(CreateVehicleDto vehicleDto, Ca /// public async Task> GetAllVehiclesAsync(CancellationToken cancellationToken = default) { - var vehicles = await _vehicleRepository.GetAllAsync(cancellationToken); + var vehicles = await _vehicleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); return _mapper.Map>(vehicles); } @@ -98,7 +98,7 @@ public async Task> GetAllVehiclesAsync(CancellationToken /// public async Task> GetVehiclesByStatusAsync(VehicleStatus status, CancellationToken cancellationToken = default) { - var vehicles = await _vehicleRepository.GetVehiclesByStatusAsync(status); + var vehicles = await _vehicleRepository.GetVehiclesByStatusAsync(status).ConfigureAwait(false); return _mapper.Map>(vehicles); } @@ -107,7 +107,7 @@ public async Task> GetVehiclesByStatusAsync(VehicleStatu /// public async Task> GetOnlineVehiclesAsync(CancellationToken cancellationToken = default) { - var vehicles = await _vehicleRepository.GetOnlineVehiclesAsync(); + var vehicles = await _vehicleRepository.GetOnlineVehiclesAsync().ConfigureAwait(false); return _mapper.Map>(vehicles); } @@ -116,7 +116,7 @@ public async Task> GetOnlineVehiclesAsync(CancellationTo /// public async Task> GetVehiclesByDriverAsync(int driverId, CancellationToken cancellationToken = default) { - var vehicles = await _vehicleRepository.GetVehiclesByDriverAsync(driverId); + var vehicles = await _vehicleRepository.GetVehiclesByDriverAsync(driverId).ConfigureAwait(false); return _mapper.Map>(vehicles); } @@ -125,7 +125,7 @@ public async Task> GetVehiclesByDriverAsync(int driverId /// public async Task UpdateVehicleAsync(int vehicleId, UpdateVehicleDto vehicleDto, CancellationToken cancellationToken = default) { - var vehicle = await _vehicleRepository.GetByIdAsync(vehicleId, cancellationToken); + var vehicle = await _vehicleRepository.GetByIdAsync(vehicleId, cancellationToken).ConfigureAwait(false); if (vehicle is null) throw new VehicleNotFoundException(vehicleId); @@ -141,8 +141,8 @@ public async Task UpdateVehicleAsync(int vehicleId, UpdateVehicleDto vehicle.MaxSpeed = vehicleDto.MaxSpeed; vehicle.UpdatedAt = DateTime.UtcNow; - await _vehicleRepository.UpdateAsync(vehicle, cancellationToken); - await _vehicleRepository.SaveChangesAsync(cancellationToken); + await _vehicleRepository.UpdateAsync(vehicle, cancellationToken).ConfigureAwait(false); + await _vehicleRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return _mapper.Map(vehicle); } @@ -152,13 +152,13 @@ public async Task UpdateVehicleAsync(int vehicleId, UpdateVehicleDto /// public async Task SetVehicleOnlineStatusAsync(int vehicleId, bool isOnline, CancellationToken cancellationToken = default) { - var vehicle = await _vehicleRepository.GetByIdAsync(vehicleId, cancellationToken); + var vehicle = await _vehicleRepository.GetByIdAsync(vehicleId, cancellationToken).ConfigureAwait(false); if (vehicle is null) return false; vehicle.SetOnlineStatus(isOnline); - await _vehicleRepository.UpdateAsync(vehicle, cancellationToken); - await _vehicleRepository.SaveChangesAsync(cancellationToken); + await _vehicleRepository.UpdateAsync(vehicle, cancellationToken).ConfigureAwait(false); + await _vehicleRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return true; } @@ -167,13 +167,13 @@ public async Task SetVehicleOnlineStatusAsync(int vehicleId, bool isOnline /// public async Task UpdateVehicleStatusAsync(int vehicleId, VehicleStatus newStatus, CancellationToken cancellationToken = default) { - var vehicle = await _vehicleRepository.GetByIdAsync(vehicleId, cancellationToken); + var vehicle = await _vehicleRepository.GetByIdAsync(vehicleId, cancellationToken).ConfigureAwait(false); if (vehicle is null) return false; vehicle.UpdateStatus(newStatus); - await _vehicleRepository.UpdateAsync(vehicle, cancellationToken); - await _vehicleRepository.SaveChangesAsync(cancellationToken); + await _vehicleRepository.UpdateAsync(vehicle, cancellationToken).ConfigureAwait(false); + await _vehicleRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return true; } @@ -182,7 +182,7 @@ public async Task UpdateVehicleStatusAsync(int vehicleId, VehicleStatus ne /// public async Task> GetLowFuelVehiclesAsync(double fuelThreshold = 20.0, CancellationToken cancellationToken = default) { - var vehicles = await _vehicleRepository.GetLowFuelVehiclesAsync(fuelThreshold); + var vehicles = await _vehicleRepository.GetLowFuelVehiclesAsync(fuelThreshold).ConfigureAwait(false); return _mapper.Map>(vehicles); } @@ -191,7 +191,7 @@ public async Task> GetLowFuelVehiclesAsync(double fuelTh /// public async Task> GetSpeedingVehiclesAsync(CancellationToken cancellationToken = default) { - var vehicles = await _vehicleRepository.GetSpeedingVehiclesAsync(); + var vehicles = await _vehicleRepository.GetSpeedingVehiclesAsync().ConfigureAwait(false); return _mapper.Map>(vehicles); } @@ -200,7 +200,7 @@ public async Task> GetSpeedingVehiclesAsync(Cancellation /// public async Task GetOnlineVehicleCountAsync(CancellationToken cancellationToken = default) { - return await _vehicleRepository.GetOnlineVehicleCountAsync(); + return await _vehicleRepository.GetOnlineVehicleCountAsync().ConfigureAwait(false); } /// @@ -208,7 +208,7 @@ public async Task GetOnlineVehicleCountAsync(CancellationToken cancellation /// public async Task VehicleExistsAsync(int vehicleId, CancellationToken cancellationToken = default) { - return await _vehicleRepository.ExistsAsync(vehicleId, cancellationToken); + return await _vehicleRepository.ExistsAsync(vehicleId, cancellationToken).ConfigureAwait(false); } /// @@ -216,12 +216,12 @@ public async Task VehicleExistsAsync(int vehicleId, CancellationToken canc /// public async Task DeleteVehicleAsync(int vehicleId, CancellationToken cancellationToken = default) { - var vehicle = await _vehicleRepository.GetByIdAsync(vehicleId, cancellationToken); + var vehicle = await _vehicleRepository.GetByIdAsync(vehicleId, cancellationToken).ConfigureAwait(false); if (vehicle is null) return false; - await _vehicleRepository.RemoveAsync(vehicle, cancellationToken); - await _vehicleRepository.SaveChangesAsync(cancellationToken); + await _vehicleRepository.RemoveAsync(vehicle, cancellationToken).ConfigureAwait(false); + await _vehicleRepository.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return true; } @@ -230,7 +230,7 @@ public async Task DeleteVehicleAsync(int vehicleId, CancellationToken canc /// public async Task> GetVehiclesByAssetTypeAsync(AssetType assetType, CancellationToken cancellationToken = default) { - var vehicles = await _vehicleRepository.GetVehiclesByAssetTypeAsync(assetType); + var vehicles = await _vehicleRepository.GetVehiclesByAssetTypeAsync(assetType).ConfigureAwait(false); return _mapper.Map>(vehicles); } } diff --git a/src/SignalRMapRealtime/Utilities/CollectionExtensions.cs b/src/SignalRMapRealtime/Utilities/CollectionExtensions.cs index f5b16af..f9206f5 100644 --- a/src/SignalRMapRealtime/Utilities/CollectionExtensions.cs +++ b/src/SignalRMapRealtime/Utilities/CollectionExtensions.cs @@ -159,7 +159,7 @@ public static async Task ForEachAsync(this IEnumerable source, Func