c#.net
c#.net
Assignment No- 4
UID: 22BCS17061
GROUP: A
1. we are part of a team developing a high-performance web application. The application
needs tofrequently 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
fromthe
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.
Solution:
using System;
using
System.Collections.Concurrent;using
System.Threading;
class Program
{
static void Main()
{
var cache = new Cache<string>();
Output:
2. you are tasked with designing an optimized data storage and retrieval system for a
large-scaleapplication. 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.
Solution:
using System.Collections.Generic;
using System.Linq;
class User
class UserStorage
public UserStorage()
if (!usersById.ContainsKey(user.ID))
usersById[user.ID] = user;
IndexUser(user);
else
if (usersById.ContainsKey(userId))
usersById.Remove(userId);
RemoveUserFromIndex(user);
else
return user;
else
return null;
attributeDict))
return users;
switch (attributeName.ToLower())
{
case "age":
return u1.Age.CompareTo(u2.Age);
case "location":
case "name":
default:
});
return sortedUsers;
{
if (!usersByAttribute.ContainsKey(attributeName))
if (!usersByAttribute[attributeName].ContainsKey(attributeValue))
usersByAttribute[attributeName][attributeValue].Add(user);
attributeDict))
users.Remove(user);
if (users.Count == 0)
attributeDict.Remove(attributeValue);
class Program
{
static void Main(string[] args)
userStorage.DeleteUser(2);
user = userStorage.FindUser(2);
}
Output:
}
3. You are given a list of orders from an e-commerce platform. Each order contains an
order ID, acustomer 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
popularitem.
• Sorts the orders by date and prints them.
Solution:
using System.Collections.Generic;
using System.Linq;
class Order
{
public int OrderID { get; set; }
public string CustomerName { get; set; }
public List<string> Items { get; set; }
public DateTime OrderDate { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Order> orders = new List<Order> {
new Order { OrderID = 1, CustomerName = "Prachi", Items = new List<string> { "chips", "biscuit"
}, OrderDate = new DateTime(2024, 6, 10) },
new Order { OrderID = 2, CustomerName = "Priya", Items = new List<string> { "biscuit",
"cookie" }, OrderDate = new DateTime(2024, 6, 12) },
new Order { OrderID = 3, CustomerName = "Priyam", Items = new List<string> { "chips",
"cookie" }, OrderDate = new DateTime(2024, 6, 11) },
new Order { OrderID = 4, CustomerName = "Sakshi", Items = new List<string> { "chips" },
OrderDate = new DateTime(2024, 6, 9) },
new Order { OrderID = 5, CustomerName = "Vaishnavi", Items = new List<string> { "biscuit",
"biscuit", "cookie" }, OrderDate = new DateTime(2024, 6, 14) }
};
var customerItemCount = new Dictionary<string, int>();
foreach (var order in orders)
{
if (!customerItemCount.ContainsKey(order.CustomerName))
{
customerItemCount[order.CustomerName] = 0;
}
customerItemCount[order.CustomerName] += order.Items.Count;
}
Output:
4. You are tasked with developing a robust logging and retry mechanism for a system that
performsvarious 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
shouldbe configurable through app settings.
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
class User
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Location { get; set; }
}
class UserStorage
{
private Dictionary<int, User> usersById;
private Dictionary<string, SortedDictionary<int, List<User>>> usersByAttribute;
public UserStorage()
{
usersById = new Dictionary<int, User>();
usersByAttribute = new Dictionary<string, SortedDictionary<int, List<User>>>();
}
public void AddUser(User user)
{
if (!usersById.ContainsKey(user.ID))
{
usersById[user.ID] = user;
IndexUser(user);
}
else
{
Console.WriteLine("User with this ID already exists.");
}
}
public void DeleteUser(int userId)
{
if (usersById.ContainsKey(userId))
{
User user = usersById[userId];
usersById.Remove(userId);
RemoveUserFromIndex(user);
}
else
{
Console.WriteLine("User with this ID does not exist.");
}
}
public User FindUser(int userId)
{
if (usersById.TryGetValue(userId, out User user))
{
return user;
}
else
{
Console.WriteLine("User not found.");
return null;
}
}
public List<User> FindUsersByAttribute(string attributeName, int attributeValue)
{
if (usersByAttribute.TryGetValue(attributeName, out SortedDictionary<int, List<User>>
attributeDict))
{
if (attributeDict.TryGetValue(attributeValue, out List<User> users))
{
return users;
}
}
return new List<User>();
}
public List<User> SortUsersByAttribute(string attributeName)
{
List<User> sortedUsers = usersById.Values.ToList();
sortedUsers.Sort((u1, u2) => {
switch (attributeName.ToLower())
{
case "age":
return u1.Age.CompareTo(u2.Age);
case "location":
return string.Compare(u1.Location, u2.Location, StringComparison.Ordinal);
case "name":
return string.Compare(u1.Name, u2.Name, StringComparison.Ordinal);
default:
throw new ArgumentException("Invalid attribute name.");
}
});
return sortedUsers;
}
private void IndexUser(User user)
{
IndexAttribute("Age", user.Age, user);
IndexAttribute("Location", user.Location.GetHashCode(), user);
}
private void RemoveUserFromIndex(User user)
{
RemoveFromAttribute("Age", user.Age, user);
Output: