0% found this document useful (0 votes)
4 views18 pages

Wa0000.

The document contains assignments for a C#.Net course focusing on developing a generic caching system and a user storage system, along with an e-commerce order processing task. It includes detailed requirements, code implementations, and expected outputs for each assignment. The assignments emphasize performance, thread safety, and efficient data management in software development.

Uploaded by

k4058335
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views18 pages

Wa0000.

The document contains assignments for a C#.Net course focusing on developing a generic caching system and a user storage system, along with an e-commerce order processing task. It includes detailed requirements, code implementations, and expected outputs for each assignment. The assignments emphasize performance, thread safety, and efficient data management in software development.

Uploaded by

k4058335
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIVERSITY INSTITUTE OF ENGINEERING

Department of Computer Science & Engineering (BE-CSE/IT-5th Sem)

Subject Name:- C#.Net (Inhouse Summer training)


Assignment 4

Submitted to: Submitted by: Anurit Bagga


UID:23BCS10242
Faculty Name: Er. Roop Sharma
Semester:5
Class/Section:607
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Assignment-4

Student Name: Anurit Bagga UID: 23BCS10242


Branch: CSE Date of Performance: 17-06-25
Subject Name: C # .NET Full Stack Mastery

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.

Sort Users: Sort users by a specific attribute.


Requirements:
• Add User
– This operation should be efficient even for a large number of users.
• Delete User
– This operation should remove the user and all associated data.
• Find User
– Finding a user by their unique ID should be very fast.
• Find Users by Attribute
– Finding users by a specific attribute (like age or location) should be efficient.
• Sort Users
Sorting users by a given attribute should be efficient and should not affect the original data order.
Code:-

using System;
using System.Collections.Generic;
using System.Linq;

public class User


{
public int Id { get; }
public string Name { get; }
public int Age { get; }
public string Location { get; }

public User(int id, string name, int age, string location)


{
Id = id;
Name = name;
Age = age;
Location = location;
}

public override string ToString()


{
return $"ID: {Id}, Name: {Name}, Age: {Age}, Location: {Location}";
}
}

public class UserStorageSystem


{
private readonly Dictionary<int, User> usersById = new();

public void AddUser(User user)


{
if (usersById.ContainsKey(user.Id))
{
Console.WriteLine($"User with ID {user.Id} already exists.");
return;
}

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.");
}

public void FindUser(int id)


{
if (usersById.TryGetValue(id, out var user))
Console.WriteLine($"User found: {user}");
else
Console.WriteLine($"User with ID {id} not found.");
}

public void FindUsersByAttribute(string attribute, string value)


{
var result = attribute.ToLower() switch
{
"age" => usersById.Values.Where(u => u.Age.ToString() == value),
"location" => usersById.Values.Where(u => u.Location.Equals(value,
StringComparison.OrdinalIgnoreCase)),
"name" => usersById.Values.Where(u => u.Name.Equals(value,
StringComparison.OrdinalIgnoreCase)),
_ => Enumerable.Empty<User>()
};

Console.WriteLine($"Users with {attribute} = {value}:");


foreach (var user in result)
Console.WriteLine(user);
}

public void SortUsers(string attribute)


{
IEnumerable<User> sorted = attribute.ToLower() switch
{
"id" => usersById.Values.OrderBy(u => u.Id),
"name" => usersById.Values.OrderBy(u => u.Name),
"age" => usersById.Values.OrderBy(u => u.Age),
"location" => usersById.Values.OrderBy(u => u.Location),
_ => null
};

if (sorted == null)
{
Console.WriteLine("Invalid sort attribute.");
return;
}

Console.WriteLine($"Users sorted by {attribute}:");


foreach (var user in sorted)
Console.WriteLine(user);
}

public void PrintAllUsers()


{
if (usersById.Count == 0)
{
Console.WriteLine("No users available.");
return;
}
Console.WriteLine("All users:");
foreach (var user in usersById.Values)
Console.WriteLine(user);
}
}
class Program
{
static void Main()
{
var system = new UserStorageSystem();

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: ");

string choice = Console.ReadLine();


switch (choice)
{
case "1":
Console.Write("Enter ID: ");
int id = int.Parse(Console.ReadLine());
Console.Write("Enter Name: ");
string name = Console.ReadLine();
Console.Write("Enter Age: ");
int age = int.Parse(Console.ReadLine());
Console.Write("Enter Location: ");
string location = Console.ReadLine();
system.AddUser(new User(id, name, age, location));
break;
case "2":
Console.Write("Enter ID to delete: ");
system.DeleteUser(int.Parse(Console.ReadLine()));
break;
case "3":
Console.Write("Enter ID to find: ");
system.FindUser(int.Parse(Console.ReadLine()));
break;
case "4":
Console.Write("Enter attribute (age, location, name): ");
string attr = Console.ReadLine();
Console.Write("Enter value to match: ");
string val = Console.ReadLine();
system.FindUsersByAttribute(attr, val);
break;
case "5":
Console.Write("Enter attribute to sort by (id, name, age, location): ");
system.SortUsers(Console.ReadLine());
break;
case "6":
system.PrintAllUsers();
break;

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>();

foreach (var order in orders)


{
if (!customerItemCounts.ContainsKey(order.CustomerName))
customerItemCounts[order.CustomerName] = 0;

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";

static void Main(string[] args)


{
Log("=== Starting Retry Test ===");

ExecuteWithRetry("File Operation", SimulateFileOperation);


ExecuteWithRetry("Network Operation", SimulateNetworkOperation);

Console.WriteLine("Retry mechanism completed. Check log.txt for details.");


}
static void ExecuteWithRetry(string operationName, Action operation)
{
for (int attempt = 1; attempt <= MaxRetries; attempt++)
{
try
{
Log($"Attempt {attempt} for {operationName}");
operation();
Log($"{operationName} succeeded.");
return;
}
catch (IOException ex)
{
Log($"[IOException] {operationName} failed: {ex.Message}");
}
catch (HttpRequestException ex)
{
Log($"[HttpRequestException] {operationName} failed: {ex.Message}");
}
catch (Exception ex)
{
Log($"[General Exception] {operationName} failed: {ex.Message}");
throw;
}
if (attempt < MaxRetries)
{
int delay = BaseDelayMs * (int)Math.Pow(2, attempt - 1);
Log($"Retrying in {delay}ms...");
Thread.Sleep(delay);
}
else
{
Log($"FAILED: {operationName} failed after {MaxRetries} attempts.");
}
}
}
static void SimulateFileOperation()
{
throw new IOException("File not found or inaccessible.");
}
static void SimulateNetworkOperation()
{
throw new HttpRequestException("Server not responding.");
}
static void Log(string message)
{
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} | {message}";
Console.WriteLine(logEntry);
File.AppendAllText(LogFile, logEntry + Environment.NewLine);
}
}
}

OUTPUT:-

You might also like