0% found this document useful (0 votes)
28 views

c#.net

Uploaded by

mprachi853
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

c#.net

Uploaded by

mprachi853
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIVERSITY INSTITUTE OF ENGINEERING

Department of Computer Science & Engineering


(BE-CSE/IT-5th Sem)

Subject Name: C#.net


(In house Summer Training)

Assignment No- 4

Submitted to: Submitted by:

Faculty name: Er. ROOP SHARMA Name: Prachi Mishra

UID: 22BCS17061

SECTION: IOT 630

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;

public class Cache<T>


{
private readonly ConcurrentDictionary<string, CacheItem<T>> cache = new ConcurrentDictionary<string,
CacheItem<T>>();

public void Add(string key, T item, TimeSpan ttl)


{
var expirationTime = DateTime.UtcNow.Add(ttl);
var cacheItem = new CacheItem<T>(item, expirationTime);
cache[key] = cacheItem;
}

public bool TryGetValue(string key, out T item)


{
if (cache.TryGetValue(key, out CacheItem<T> cacheItem))
{
if (cacheItem.IsExpired)
{
cache.TryRemove(key, out
_);item = default(T);
return false;
}
else
{item = cacheItem.Value;
return true;
}
}
else
{
item =
default(T);return
false;
}
}

public void Remove(string key)


{
cache.TryRemove(key, out _);
}

public void RefreshTTL(string key, TimeSpan newTTL)


{
if (cache.TryGetValue(key, out CacheItem<T> cacheItem))
{
cacheItem.ExpirationTime = DateTime.UtcNow.Add(newTTL);
}
}

private class CacheItem<TValue>


{
public TValue Value { get; }
public DateTime ExpirationTime { get; set; }

public CacheItem(TValue value, DateTime expirationTime)


{
Value = value;
ExpirationTime = expirationTime;
}

public bool IsExpired => DateTime.UtcNow >= ExpirationTime;


}
}

class Program
{
static void Main()
{
var cache = new Cache<string>();

// Add an item with a TTL of 1 minute


cache.Add("key1", "value1", TimeSpan.FromMinutes(1));

if (cache.TryGetValue("key1", out string cachedValue))


{
Console.WriteLine("Cached Value: " + cachedValue);
}
else
{
Console.WriteLine("Item not found or expired.");
}
Thread.Sleep(TimeSpan.FromSeconds(70));
if (cache.TryGetValue("key1", out string expiredValue))
{
Console.WriteLine("Cached Value (expired): " + expiredValue);
}
else
{
Console.WriteLine("Item not found or expired.");
}
}
}

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

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

RemoveFromAttribute("Location", user.Location.GetHashCode(), user);

private void IndexAttribute(string attributeName, int attributeValue, User user)

{
if (!usersByAttribute.ContainsKey(attributeName))

usersByAttribute[attributeName] = new SortedDictionary<int, List<User>>();

if (!usersByAttribute[attributeName].ContainsKey(attributeValue))

usersByAttribute[attributeName][attributeValue] = new List<User>();

usersByAttribute[attributeName][attributeValue].Add(user);

private void RemoveFromAttribute(string attributeName, int attributeValue, User user)

if (usersByAttribute.TryGetValue(attributeName, out SortedDictionary<int, List<User>>

attributeDict))

if (attributeDict.TryGetValue(attributeValue, out List<User> users))

users.Remove(user);

if (users.Count == 0)

attributeDict.Remove(attributeValue);

class Program

{
static void Main(string[] args)

UserStorage userStorage = new UserStorage();

userStorage.AddUser(new User { ID = 1, Name = "Prachi", Age = 18, Location = "UP" });

userStorage.AddUser(new User { ID = 2, Name = "Priya", Age = 17, Location = "LUP" });

userStorage.AddUser(new User { ID = 3, Name = "Priyam", Age = 16, Location = "UP" });

User user = userStorage.FindUser(1);

Console.WriteLine($"Found User: {user?.Name}, {user?.Age}, {user?.Location}");

List<User> usersByAge = userStorage.FindUsersByAttribute("Age", 30);

Console.WriteLine("Users with Age 18:");

foreach (User u in usersByAge)

Console.WriteLine($"{u.Name}, {u.Age}, {u.Location}");

List<User> sortedUsers = userStorage.SortUsersByAttribute("Age");

Console.WriteLine("Users sorted by Age:");

foreach (User u in sortedUsers)

Console.WriteLine($"{u.Name}, {u.Age}, {u.Location}");

userStorage.DeleteUser(2);

user = userStorage.FindUser(2);

Console.WriteLine($"Found User after Deletion: {user?.Name}");

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

var topCustomers = customerItemCount.OrderByDescending(c => c.Value).Take(3);


Console.WriteLine("Top 3 customers who purchased the most items:");
foreach (var customer in topCustomers)
{
Console.WriteLine($"{customer.Key}: {customer.Value} items");
}
var itemCount = new Dictionary<string, int>();
foreach (var order in orders)
{
foreach (var item in order.Items)
{
if (!itemCount.ContainsKey(item))
{
itemCount[item] = 0;
}
itemCount[item] += 1;
}
}
var mostPopularItem = itemCount.OrderByDescending(i => i.Value).First();
Console.WriteLine($"\nMost popular item: {mostPopularItem.Key}, purchased
{mostPopularItem.Value} times");
var sortedOrders = orders.OrderBy(o => o.OrderDate);
Console.WriteLine("\nOrders sorted by date:");
foreach (var order in sortedOrders)
{
Console.WriteLine($"OrderID: {order.OrderID}, CustomerName: {order.CustomerName},
OrderDate: {order.OrderDate.ToShortDateString()}, Items: {string.Join(", ", order.Items)}");
}
}
}

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

RemoveFromAttribute("Location", user.Location.GetHashCode(), user);


}
private void IndexAttribute(string attributeName, int attributeValue, User user)
{
if (!usersByAttribute.ContainsKey(attributeName))
{
usersByAttribute[attributeName] = new SortedDictionary<int, List<User>>();
}
if (!usersByAttribute[attributeName].ContainsKey(attributeValue))
{
usersByAttribute[attributeName][attributeValue] = new List<User>();
}
usersByAttribute[attributeName][attributeValue].Add(user);
}
private void RemoveFromAttribute(string attributeName, int attributeValue, User user)
{
if (usersByAttribute.TryGetValue(attributeName, out SortedDictionary<int, List<User>>
attributeDict))
{
if (attributeDict.TryGetValue(attributeValue, out List<User> users))
{
users.Remove(user);
if (users.Count == 0)
{
attributeDict.Remove(attributeValue);
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
UserStorage userStorage = new UserStorage();
userStorage.AddUser(new User { ID = 1, Name = "Riya", Age = 18, Location = "NY" });
userStorage.AddUser(new User { ID = 2, Name = "Sheena", Age = 20, Location = "LA" });
userStorage.AddUser(new User { ID = 3, Name = "Meera", Age = 22, Location = "NY" });
User user = userStorage.FindUser(1);
Console.WriteLine($"Found User: {user?.Name}, {user?.Age}, {user?.Location}");
List<User> usersByAge = userStorage.FindUsersByAttribute("Age", 30);
Console.WriteLine("Users with Age 18:");
foreach (User u in usersByAge)
{
Console.WriteLine($"{u.Name}, {u.Age}, {u.Location}");
}A

List<User> sortedUsers = userStorage.SortUsersByAttribute("Age");


Console.WriteLine("Users sorted by Age:");
foreach (User u in sortedUsers)
{
Console.WriteLine($"{u.Name}, {u.Age}, {u.Location}");
}
userStorage.DeleteUser(2);
user = userStorage.FindUser(2);
Console.WriteLine($"Found User after Deletion: {user?.Name}");
}
}

Output:

You might also like