Skip to content

Commit 905deb5

Browse files
committed
Ex10 code and exercise instructions review
1 parent 9f7963b commit 905deb5

File tree

16 files changed

+140
-129
lines changed

16 files changed

+140
-129
lines changed

DownloadableCodeProjects/standalone-lab-projects/implement-performance-profiling/ContosoOnlineStore/Benchmarks/OrderProcessingBenchmarks.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,27 +23,27 @@ public class OrderProcessingBenchmarks
2323
public void Setup()
2424
{
2525
var services = new ServiceCollection();
26-
26+
2727
// Configure logging
2828
services.AddLogging(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Warning));
29-
29+
3030
// Configure settings
3131
var appSettings = new AppSettings();
3232
services.AddSingleton(Options.Create(appSettings));
33-
33+
3434
// Register services
3535
services.AddSingleton<ISecurityValidationService, SecurityValidationService>();
3636
services.AddSingleton<IProductCatalog, ProductCatalog>();
3737
services.AddSingleton<IInventoryManager, InventoryManager>();
3838
services.AddSingleton<IEmailService, EmailService>();
3939
services.AddSingleton<IOrderProcessor, OrderProcessor>();
40-
40+
4141
_serviceProvider = services.BuildServiceProvider();
42-
42+
4343
_catalog = _serviceProvider.GetRequiredService<IProductCatalog>();
4444
_inventory = _serviceProvider.GetRequiredService<IInventoryManager>();
4545
_orderProcessor = _serviceProvider.GetRequiredService<IOrderProcessor>();
46-
46+
4747
// Create test order
4848
_testOrder = new Order("[email protected]", "123 Test Street, Test City, WA 98101");
4949
_testOrder.AddItem(new OrderItem(1, 2));

DownloadableCodeProjects/standalone-lab-projects/implement-performance-profiling/ContosoOnlineStore/Configuration/AppSettings.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,36 +6,36 @@ public class AppSettings
66
{
77
[Range(1, 1000)]
88
public int MaxOrderItems { get; set; } = 50;
9-
9+
1010
[Range(100, 30000)]
1111
public int EmailTimeoutMs { get; set; } = 2000;
12-
12+
1313
public bool EnableDetailedLogging { get; set; } = true;
14-
14+
1515
public SecuritySettings SecuritySettings { get; set; } = new();
16-
16+
1717
public PerformanceSettings PerformanceSettings { get; set; } = new();
1818
}
1919

2020
public class SecuritySettings
2121
{
2222
[Range(0.01, 100000.00)]
2323
public decimal MaxProductPrice { get; set; } = 10000.00m;
24-
24+
2525
[Range(0.01, 1000.00)]
2626
public decimal MinProductPrice { get; set; } = 0.01m;
27-
27+
2828
public bool AllowNegativeInventory { get; set; } = false;
2929
}
3030

3131
public class PerformanceSettings
3232
{
3333
[Range(1, 1440)]
3434
public int CacheExpirationMinutes { get; set; } = 30;
35-
35+
3636
[Range(1000, 60000)]
3737
public int DatabaseTimeoutMs { get; set; } = 5000;
38-
38+
3939
[Range(1, 1000)]
4040
public int MaxConcurrentOrders { get; set; } = 100;
4141
}

DownloadableCodeProjects/standalone-lab-projects/implement-performance-profiling/ContosoOnlineStore/Exceptions/CustomExceptions.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@ namespace ContosoOnlineStore.Exceptions
55
public class ProductNotFoundException : Exception
66
{
77
public int ProductId { get; }
8-
9-
public ProductNotFoundException(int productId)
8+
9+
public ProductNotFoundException(int productId)
1010
: base($"Product with ID {productId} was not found.")
1111
{
1212
ProductId = productId;
1313
}
14-
15-
public ProductNotFoundException(int productId, Exception innerException)
14+
15+
public ProductNotFoundException(int productId, Exception innerException)
1616
: base($"Product with ID {productId} was not found.", innerException)
1717
{
1818
ProductId = productId;
@@ -24,8 +24,8 @@ public class InsufficientInventoryException : Exception
2424
public int ProductId { get; }
2525
public int RequestedQuantity { get; }
2626
public int AvailableQuantity { get; }
27-
28-
public InsufficientInventoryException(int productId, int requestedQuantity, int availableQuantity)
27+
28+
public InsufficientInventoryException(int productId, int requestedQuantity, int availableQuantity)
2929
: base($"Insufficient inventory for product ID {productId}. Requested: {requestedQuantity}, Available: {availableQuantity}")
3030
{
3131
ProductId = productId;
@@ -37,14 +37,14 @@ public InsufficientInventoryException(int productId, int requestedQuantity, int
3737
public class InvalidOrderException : Exception
3838
{
3939
public InvalidOrderException(string message) : base(message) { }
40-
40+
4141
public InvalidOrderException(string message, Exception innerException) : base(message, innerException) { }
4242
}
4343

4444
public class SecurityValidationException : Exception
4545
{
4646
public SecurityValidationException(string message) : base(message) { }
47-
47+
4848
public SecurityValidationException(string message, Exception innerException) : base(message, innerException) { }
4949
}
5050
}

DownloadableCodeProjects/standalone-lab-projects/implement-performance-profiling/ContosoOnlineStore/InventoryManager.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public InventoryManager(IProductCatalog catalog, ILogger<InventoryManager> logge
3535
_stockByProductId = new ConcurrentDictionary<int, int>();
3636
_reservedStock = new ConcurrentDictionary<int, int>();
3737
_lastStockUpdate = new Dictionary<int, DateTime>();
38-
38+
3939
InitializeInventory();
4040
}
4141

@@ -49,7 +49,7 @@ private void InitializeInventory()
4949
_lastStockUpdate[product.Id] = DateTime.UtcNow;
5050
_logger.LogDebug("Initialized stock for product {ProductId}: {Stock} units", product.Id, product.InitialStock);
5151
}
52-
52+
5353
_logger.LogInformation("Initialized inventory for {ProductCount} products", products.Count);
5454
}
5555

@@ -72,7 +72,7 @@ public int GetStockLevel(int productId)
7272
var reserved = _reservedStock.GetValueOrDefault(productId, 0);
7373
var availableStock = stock - reserved;
7474

75-
_logger.LogDebug("Stock level for product {ProductId}: {Stock} total, {Reserved} reserved, {Available} available",
75+
_logger.LogDebug("Stock level for product {ProductId}: {Stock} total, {Reserved} reserved, {Available} available",
7676
productId, stock, reserved, availableStock);
7777

7878
return Math.Max(0, availableStock);
@@ -112,7 +112,7 @@ public void UpdateStockLevels(Order order)
112112
_lastStockUpdate[item.ProductId] = DateTime.UtcNow;
113113
stockChanges[item.ProductId] = newStock;
114114

115-
_logger.LogInformation("Updated stock for product {ProductId}: {OldStock} -> {NewStock} (Change: -{Quantity})",
115+
_logger.LogInformation("Updated stock for product {ProductId}: {OldStock} -> {NewStock} (Change: -{Quantity})",
116116
item.ProductId, currentStock, newStock, item.Quantity);
117117
}
118118

@@ -142,7 +142,7 @@ public void ReserveStock(Order order)
142142
foreach (OrderItem item in order.Items)
143143
{
144144
_reservedStock.AddOrUpdate(item.ProductId, item.Quantity, (key, existing) => existing + item.Quantity);
145-
_logger.LogDebug("Reserved {Quantity} units of product {ProductId} for order {OrderId}",
145+
_logger.LogDebug("Reserved {Quantity} units of product {ProductId} for order {OrderId}",
146146
item.Quantity, item.ProductId, order.OrderId);
147147
}
148148
}
@@ -158,7 +158,7 @@ public void ReleaseReservedStock(Order order)
158158
foreach (OrderItem item in order.Items)
159159
{
160160
_reservedStock.AddOrUpdate(item.ProductId, 0, (key, existing) => Math.Max(0, existing - item.Quantity));
161-
_logger.LogDebug("Released {Quantity} reserved units of product {ProductId} for order {OrderId}",
161+
_logger.LogDebug("Released {Quantity} reserved units of product {ProductId} for order {OrderId}",
162162
item.Quantity, item.ProductId, order.OrderId);
163163
}
164164
}
@@ -179,7 +179,7 @@ public Dictionary<int, int> GetLowStockProducts(int threshold = 10)
179179
}
180180
}
181181

182-
_logger.LogInformation("Found {LowStockCount} products with stock below {Threshold}",
182+
_logger.LogInformation("Found {LowStockCount} products with stock below {Threshold}",
183183
lowStockProducts.Count, threshold);
184184

185185
return lowStockProducts;
@@ -189,7 +189,7 @@ public async Task<bool> RestockProductAsync(int productId, int quantity)
189189
{
190190
if (productId <= 0)
191191
throw new ArgumentException("Product ID must be positive", nameof(productId));
192-
192+
193193
if (quantity <= 0)
194194
throw new ArgumentException("Restock quantity must be positive", nameof(quantity));
195195

@@ -202,7 +202,7 @@ public async Task<bool> RestockProductAsync(int productId, int quantity)
202202
_stockByProductId[productId] = currentStock + quantity;
203203
_lastStockUpdate[productId] = DateTime.UtcNow;
204204

205-
_logger.LogInformation("Restocked product {ProductId}: {OldStock} -> {NewStock} (+{Quantity})",
205+
_logger.LogInformation("Restocked product {ProductId}: {OldStock} -> {NewStock} (+{Quantity})",
206206
productId, currentStock, currentStock + quantity, quantity);
207207
}
208208

DownloadableCodeProjects/standalone-lab-projects/implement-performance-profiling/ContosoOnlineStore/Order.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,21 @@ public class Order
66
{
77
[Range(1, int.MaxValue)]
88
public int OrderId { get; }
9-
9+
1010
[Required]
1111
[StringLength(100, MinimumLength = 1)]
1212
public string CustomerEmail { get; set; } = string.Empty;
13-
13+
1414
[Required]
1515
[StringLength(200, MinimumLength = 1)]
1616
public string ShippingAddress { get; set; } = string.Empty;
17-
17+
1818
public List<OrderItem> Items { get; }
19-
19+
2020
public DateTime OrderDate { get; }
21-
21+
2222
public OrderStatus Status { get; set; }
23-
23+
2424
public decimal TotalAmount { get; set; }
2525

2626
private static int _nextOrderId = 1;
@@ -47,7 +47,7 @@ public void AddItem(OrderItem item)
4747
{
4848
if (item == null)
4949
throw new ArgumentNullException(nameof(item));
50-
50+
5151
if (Items.Count >= 50)
5252
throw new InvalidOperationException("Cannot add more than 50 items to an order");
5353

DownloadableCodeProjects/standalone-lab-projects/implement-performance-profiling/ContosoOnlineStore/OrderItem.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,25 @@ public class OrderItem
66
{
77
[Range(1, int.MaxValue, ErrorMessage = "Product ID must be positive")]
88
public int ProductId { get; set; }
9-
9+
1010
[Range(1, 1000, ErrorMessage = "Quantity must be between 1 and 1000")]
1111
public int Quantity { get; set; }
12-
12+
1313
public decimal UnitPrice { get; set; }
14-
14+
1515
public decimal TotalPrice => UnitPrice * Quantity;
1616

1717
public OrderItem(int productId, int quantity, decimal unitPrice = 0)
1818
{
1919
if (productId <= 0)
2020
throw new ArgumentException("Product ID must be positive", nameof(productId));
21-
21+
2222
if (quantity <= 0)
2323
throw new ArgumentException("Quantity must be positive", nameof(quantity));
24-
24+
2525
if (quantity > 1000)
2626
throw new ArgumentException("Quantity cannot exceed 1000", nameof(quantity));
27-
27+
2828
if (unitPrice < 0)
2929
throw new ArgumentException("Unit price cannot be negative", nameof(unitPrice));
3030

DownloadableCodeProjects/standalone-lab-projects/implement-performance-profiling/ContosoOnlineStore/OrderProcessor.cs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@ public class OrderProcessor : IOrderProcessor
4040
private static int _orderCounter = 0;
4141

4242
public OrderProcessor(
43-
IProductCatalog catalog,
44-
IInventoryManager inventory,
43+
IProductCatalog catalog,
44+
IInventoryManager inventory,
4545
IEmailService emailService,
4646
ISecurityValidationService securityValidation,
4747
ILogger<OrderProcessor> logger,
@@ -78,14 +78,14 @@ public decimal CalculateOrderTotal(Order order)
7878
{
7979
// Security validation for each item
8080
_securityValidation.ValidateOrderItem(item, product);
81-
81+
8282
var itemTotal = product.Price * item.Quantity;
8383
subtotal += itemTotal;
84-
84+
8585
// Update order item with unit price for receipt
8686
item.UnitPrice = product.Price;
87-
88-
_logger.LogDebug("Calculated item total for product {ProductId}: {ItemTotal:C}",
87+
88+
_logger.LogDebug("Calculated item total for product {ProductId}: {ItemTotal:C}",
8989
product.Id, itemTotal);
9090
}
9191
else
@@ -100,7 +100,7 @@ public decimal CalculateOrderTotal(Order order)
100100
var shipping = CalculateShipping(order);
101101
var total = subtotal + tax + shipping;
102102

103-
_logger.LogInformation("Order total calculated: Subtotal={Subtotal:C}, Tax={Tax:C}, Shipping={Shipping:C}, Total={Total:C}",
103+
_logger.LogInformation("Order total calculated: Subtotal={Subtotal:C}, Tax={Tax:C}, Shipping={Shipping:C}, Total={Total:C}",
104104
subtotal, tax, shipping, total);
105105

106106
return total;
@@ -116,7 +116,7 @@ public async Task<decimal> FinalizeOrderAsync(Order order)
116116

117117
try
118118
{
119-
_logger.LogInformation("Finalizing order {OrderId} (Processing #{ProcessingNumber})",
119+
_logger.LogInformation("Finalizing order {OrderId} (Processing #{ProcessingNumber})",
120120
order.OrderId, _orderCounter);
121121

122122
// Validate order first
@@ -149,15 +149,15 @@ public async Task<decimal> FinalizeOrderAsync(Order order)
149149
order.Status = OrderStatus.Shipped; // Simulate immediate shipping for demo
150150

151151
var processingTime = DateTime.UtcNow - startTime;
152-
_logger.LogInformation("Order {OrderId} finalized successfully in {ProcessingTime}ms. Total: {Total:C}",
152+
_logger.LogInformation("Order {OrderId} finalized successfully in {ProcessingTime}ms. Total: {Total:C}",
153153
order.OrderId, processingTime.TotalMilliseconds, total);
154154

155155
return total;
156156
}
157157
catch (Exception ex)
158158
{
159159
_logger.LogError(ex, "Failed to finalize order {OrderId}", order.OrderId);
160-
160+
161161
// Release reserved stock on failure
162162
try
163163
{
@@ -188,11 +188,11 @@ public async Task<bool> ValidateOrderAsync(Order order)
188188
{
189189
// Performance bottleneck: Individual inventory checks
190190
await Task.Delay(10); // Simulate database query
191-
191+
192192
if (!_inventory.IsInStock(item.ProductId, item.Quantity))
193193
{
194194
var availableStock = _inventory.GetStockLevel(item.ProductId);
195-
_logger.LogWarning("Insufficient inventory for product {ProductId}. Requested: {Requested}, Available: {Available}",
195+
_logger.LogWarning("Insufficient inventory for product {ProductId}. Requested: {Requested}, Available: {Available}",
196196
item.ProductId, item.Quantity, availableStock);
197197
return false;
198198
}
@@ -272,7 +272,7 @@ public async Task<string> GenerateOrderReceiptAsync(Order order)
272272

273273
var receipt = receiptBuilder.ToString();
274274
_logger.LogDebug("Generated receipt for order {OrderId}", order.OrderId);
275-
275+
276276
return receipt;
277277
}
278278

@@ -348,9 +348,9 @@ public decimal CalculateShipping(Order order)
348348
var itemCount = order.GetTotalItemCount();
349349
var baseShipping = 5.99m;
350350
var perItemFee = 0.99m;
351-
351+
352352
var shippingCost = baseShipping + (perItemFee * Math.Max(0, itemCount - 1));
353-
353+
354354
// Free shipping for orders over $100
355355
if (order.TotalAmount > 100)
356356
{

DownloadableCodeProjects/standalone-lab-projects/implement-performance-profiling/ContosoOnlineStore/PERFORMANCE_GUIDE.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ The application includes performance counters that display:
142142

143143
Use BenchmarkDotNet for detailed analysis:
144144
```bash
145-
dotnet run benchmark
145+
dotnet run -- benchmark
146146
```
147147

148148
This provides:

0 commit comments

Comments
 (0)