Wa0000.
Wa0000.
Assignment-4
Q.1 we are part of a team developing a high-performance web application. The application
needs to frequently access various types of data from different sources (e.g., database
queries, API responses, configuration settings). To improve performance, you need to
implement a generic caching system that can store and retrieve data of any type, and
manage cache expiration policies.
• Requirements:
• Generic Cache Class:
– Create a generic class Cache<T> that can store data of any type T.
– Provide methods to add data to the cache, retrieve data from the cache, and remove data
from the cache.
– Implement cache expiration, where each cached item has a time-to-live (TTL) value.
• Cache Expiration:
– Implement a mechanism to automatically remove expired items from the cache.
– Provide methods to refresh the TTL of cached items.
• Thread Safety:
– Ensure that the cache is thread-safe, as the web application may have multiple concurrent
requests.
• Performance:
– Optimize the cache for high performance, considering both memory usage and access speed.
Code:-
using System;
using System.Collections.Concurrent;
using System.Threading;
public class CacheItem<T>
{
public T Value { get; }
public DateTime ExpiryTime { get; private set; }
public CacheItem(T value, TimeSpan ttl)
{
Value = value;
ExpiryTime = DateTime.Now.Add(ttl);
}
public void RefreshTTL(TimeSpan ttl)
{
ExpiryTime = DateTime.Now.Add(ttl);
}
public bool IsExpired => DateTime.Now > ExpiryTime;
}
public class Cache<T>
{
private readonly ConcurrentDictionary<string, CacheItem<T>> _cache = new();
private readonly Timer _cleanupTimer;
private readonly TimeSpan _cleanupInterval = TimeSpan.FromSeconds(5);
public Cache()
{
_cleanupTimer = new Timer(CleanupExpiredItems, null, _cleanupInterval, _cleanupInterval);
}
public void Add(string key, T value, TimeSpan ttl)
{
var item = new CacheItem<T>(value, ttl);
_cache[key] = item;
Console.WriteLine($"[Added] Key: {key}, Value: {value}, TTL: {ttl.TotalSeconds} seconds");
}
public T Get(string key)
{
if (_cache.TryGetValue(key, out var item))
{
if (!item.IsExpired)
{
Console.WriteLine($"[Hit] Key: {key}, Value: {item.Value}");
return item.Value;
}
_cache.TryRemove(key, out _);
Console.WriteLine($"[Expired] Key: {key} removed");
}
else
{
Console.WriteLine($"[Miss] Key: {key} not found");
}
return default;
}
public bool Remove(string key)
{
bool removed = _cache.TryRemove(key, out _);
Console.WriteLine(removed ? $"[Removed] Key: {key}" : $"[Remove Failed] Key: {key} not
found");
return removed;
}
public bool RefreshTTL(string key, TimeSpan newTTL)
{
if (_cache.TryGetValue(key, out var item))
{
item.RefreshTTL(newTTL);
Console.WriteLine($"[Refreshed] Key: {key}, New TTL: {newTTL.TotalSeconds} seconds");
return true;
}
Console.WriteLine($"[Refresh Failed] Key: {key} not found");
return false;
}
private void CleanupExpiredItems(object state)
{
foreach (var pair in _cache)
{
if (pair.Value.IsExpired)
{
_cache.TryRemove(pair.Key, out _);
Console.WriteLine($"[Auto Cleanup] Key: {pair.Key} expired and removed");
}
}
}
public void PrintAll()
{
Console.WriteLine("\n[Cache Contents]");
foreach (var pair in _cache)
{
string status = pair.Value.IsExpired ? "Expired" : "Valid";
Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value.Value}, Expires At:
{pair.Value.ExpiryTime} ({status})");
}
Console.WriteLine();
}
}
class Program
{
static void Main()
{
var cache = new Cache<string>();
while (true)
{
Console.WriteLine("\nChoose an option:");
Console.WriteLine("1. Add item");
Console.WriteLine("2. Get item");
Console.WriteLine("3. Remove item");
Console.WriteLine("4. Refresh TTL");
Console.WriteLine("5. Print all items");
Console.WriteLine("6. Exit");
Console.Write("Enter choice: ");
string choice = Console.ReadLine();
switch (choice)
{
case "1":
Console.Write("Enter key: ");
string key = Console.ReadLine();
Console.Write("Enter value: ");
string value = Console.ReadLine();
Console.Write("Enter TTL in seconds: ");
if (int.TryParse(Console.ReadLine(), out int ttlSec))
cache.Add(key, value, TimeSpan.FromSeconds(ttlSec));
else
Console.WriteLine("Invalid TTL!");
break;
case "2":
Console.Write("Enter key to get: ");
cache.Get(Console.ReadLine());
break;
case "3":
Console.Write("Enter key to remove: ");
cache.Remove(Console.ReadLine());
break;
case "4":
Console.Write("Enter key to refresh TTL: ");
string refreshKey = Console.ReadLine();
Console.Write("Enter new TTL in seconds: ");
if (int.TryParse(Console.ReadLine(), out int newTTL))
cache.RefreshTTL(refreshKey, TimeSpan.FromSeconds(newTTL));
else
Console.WriteLine("Invalid TTL!");
break;
case "5":
cache.PrintAll();
break;
case "6":
Console.WriteLine("Exiting...");
return;
default:
Console.WriteLine("Invalid choice!");
break;
}
}
}
}
Output:-
Q.2 .you are tasked with designing an optimized data storage and retrieval system for a
large-scale application. The system needs to support the following operations efficiently:
• Add User: Add a user with a unique ID and associated data.
• Delete User: Delete a user by ID.
• Find User: Find a user by ID and retrieve their data.
• Find Users by Attribute: Find all users that match a given attribute.
using System;
using System.Collections.Generic;
using System.Linq;
usersById[user.Id] = user;
Console.WriteLine($"User added: {user}");
}
public void DeleteUser(int id)
{
if (usersById.Remove(id))
Console.WriteLine($"User with ID {id} deleted.");
else
Console.WriteLine($"User with ID {id} not found.");
}
if (sorted == null)
{
Console.WriteLine("Invalid sort attribute.");
return;
}
while (true)
{
Console.WriteLine("\nSelect an operation:");
Console.WriteLine("1. Add User");
Console.WriteLine("2. Delete User");
Console.WriteLine("3. Find User by ID");
Console.WriteLine("4. Find Users by Attribute");
Console.WriteLine("5. Sort Users");
Console.WriteLine("6. Print All Users");
Console.WriteLine("7. Exit");
Console.Write("Enter choice: ");
case "7":
Console.WriteLine("Exiting...");
return;
default:
Console.WriteLine("Invalid choice.");
break;
}
}
}
}
Output: -
Q.3. You are given a list of orders from an e-commerce platform. Each order contains an
order ID, a customer name, a list of items purchased, and the date of the order. Your task is
to:
• Calculate the total number of items purchased by each customer.
• Identify the top 3 customers who purchased the most items.
• Determine the most popular item (the item purchased the most number of times).
• List all orders sorted by date.
Explanation
• Order Class:
• Defines the structure of an order with OrderID, CustomerName, Items, and OrderDate.
• Main Method: • Creates a sample list of orders.
• Uses a dictionary to track the total number of items purchased by each customer.
• Identifies the top 3 customers who purchased the most items.
• Uses another dictionary to count the occurrences of each item and determines the most
popular item.
• Sorts the orders by date and prints them.
Code:-
using System;
using System.Collections.Generic;
using System.Linq;
public class Order
{
public int OrderID { get; set; }
public string CustomerName { get; set; }
public List<string> Items { get; set; }
public DateTime OrderDate { get; set; }
public Order(int orderId, string customerName, List<string> items, DateTime orderDate)
{
OrderID = orderId;
CustomerName = customerName;
Items = items;
OrderDate = orderDate;
}
public override string ToString()
{
return $"OrderID: {OrderID}, Customer: {CustomerName}, Items: [{string.Join(", ", Items)}], Date:
{OrderDate.ToShortDateString()}";
}
}
class Program
{
static void Main()
{
List<Order> orders = new List<Order>
{
new Order(101, "Alice", new List<string> { "Laptop", "Mouse" }, new DateTime(2023, 5, 20)),
new Order(102, "Bob", new List<string> { "Keyboard", "Mouse", "Monitor" }, new
DateTime(2023, 5, 22)),
new Order(103, "Alice", new List<string> { "Laptop Bag" }, new DateTime(2023, 5, 23)),
new Order(104, "Charlie", new List<string> { "Monitor", "Mouse", "Monitor" }, new
DateTime(2023, 5, 21)),
new Order(105, "David", new List<string> { "Mouse", "Mouse", "Mouse" }, new
DateTime(2023, 5, 24))
};
Dictionary<string, int> customerItemCounts = new Dictionary<string, int>();
customerItemCounts[order.CustomerName] += order.Items.Count;
}
Console.WriteLine("Total Items Purchased by Each Customer:");
foreach (var kvp in customerItemCounts)
Console.WriteLine($"{kvp.Key}: {kvp.Value} items");
Console.WriteLine("\nTop 3 Customers by Items Purchased:");
var top3 = customerItemCounts.OrderByDescending(kvp => kvp.Value).Take(3);
foreach (var kvp in top3)
Console.WriteLine($"{kvp.Key}: {kvp.Value} items");
Dictionary<string, int> itemCounts = new Dictionary<string, int>();
foreach (var order in orders)
{
foreach (var item in order.Items)
{
if (!itemCounts.ContainsKey(item))
itemCounts[item] = 0;
itemCounts[item]++;
}
}
var mostPopularItem = itemCounts.OrderByDescending(kvp => kvp.Value).First();
Console.WriteLine($"\nMost Popular Item: {mostPopularItem.Key} (Purchased
{mostPopularItem.Value} times)");
Console.WriteLine("\nAll Orders Sorted by Date:");
var sortedOrders = orders.OrderBy(o => o.OrderDate);
foreach (var order in sortedOrders)
Console.WriteLine(order);
}
}
Output:-
Q.4.You are tasked with developing a robust logging and retry mechanism for a system that
performs various operations, including database access, file I/O, and network
communication. The system should handle exceptions gracefully, log detailed information
about the exceptions, and retry the operations a configurable number of times before giving
up.
Requirements:
• Exception Handling:
– Catch and handle specific exceptions (SqlException, IOException, HttpRequestException)
differently.
– For other exceptions, log them and rethrow to higher-level handlers.
• Logging:
– Log the exception details, including the stack trace and the operation that caused the
exception.
– Use a logging framework such as NLog or log4net.
• Retry Mechanism:
– Retry the failed operation a configurable number of times with an exponential backoff
strategy.
– Log each retry attempt with its attempt number and the delay before the next retry.
• Configuration:
– The maximum number of retry attempts and the base delay for the exponential backoff
should be configurable through app settings.
Code:-
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
namespace RetryMechanismBasic
{
class Program
{
static int MaxRetries = 3;
static int BaseDelayMs = 1000;
static string LogFile = "log.txt";
OUTPUT:-