diff --git a/week-1/day-2/exercise-1/Circle/Circle.cs b/week-1/day-2/exercise-1/Circle/Circle.cs index 065ffa5d..22083426 100644 --- a/week-1/day-2/exercise-1/Circle/Circle.cs +++ b/week-1/day-2/exercise-1/Circle/Circle.cs @@ -6,8 +6,26 @@ namespace Circle { - internal class Circle + public class Circle { - // Implement the Circle class here + private double Radius; + // Constructor for the Circle class, initializes the radius + public Circle(double radius) + { + Radius = radius; + } + + // Method to calculate and return the area of the circle + public double GetArea() + { + return Math.Round(Math.PI * Radius * Radius); // Calculate and round the area + // Alternative: return Math.PI * Math.Pow(Radius, 2); + } + + // Method to calculate and return the circumference of the circle + public double GetCircumference() + { + return Math.Round(2 * Math.PI * Radius); // Calculate and round the circumference + } } } diff --git a/week-1/day-2/exercise-1/Circle/Program.cs b/week-1/day-2/exercise-1/Circle/Program.cs index 0df91b0d..980c4a80 100644 --- a/week-1/day-2/exercise-1/Circle/Program.cs +++ b/week-1/day-2/exercise-1/Circle/Program.cs @@ -1,10 +1,17 @@ namespace Circle { - internal class Program + public class Program { + // Entry point of the program static void Main(string[] args) { - // Create a Circle object and display its area and circumference + double radius = 5.5; // Define the radius of the circle + + Circle areaObj = new Circle(radius); // Create a Circle object with the given radius + + // Print the calculated area and circumference of the circle + Console.WriteLine("The Area of Circle is " + areaObj.GetArea()); + Console.WriteLine("The Circumference of Circle is " + areaObj.GetCircumference()); } } } \ No newline at end of file diff --git a/week-1/day-2/exercise-2/BankAccount/BankAccount.cs b/week-1/day-2/exercise-2/BankAccount/BankAccount.cs new file mode 100644 index 00000000..4d969f2f --- /dev/null +++ b/week-1/day-2/exercise-2/BankAccount/BankAccount.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BankAccount +{ + // Abstract class + public abstract class BankAccount + { + // Properties + public long AccountNumber; // The account number associated with the bank account. + public double Balance; // The current balance in the bank account. + + // Methods + public abstract void Deposit(double amount); // Abstract method to deposit money into the account. + public abstract void Withdraw(double amount); // Abstract method to withdraw money from the account. + } + + // First Derived class + class SavingsAccount : BankAccount + { + private double InterestRate; // The interest rate for the savings account. + + // Constructor to initialize the savings account. + public SavingsAccount(long accountNumber, double balance, double interestRate) + { + AccountNumber = accountNumber; + Balance = balance; + InterestRate = interestRate; + } + + // Deposit method for savings account. + public override void Deposit(double amount) + { + Balance += amount; + } + + // Withdraw method for savings account. + public override void Withdraw(double amount) + { + if (amount <= Balance) + { + Balance -= amount; + } + else + { + Console.WriteLine($"Insufficient Balance. Your Main Balance is {Balance}"); + } + } + } + + // Second Derived class + class CheckingAccount : BankAccount + { + private double OverdraftLimit; // The overdraft limit for the checking account. + + // Constructor to initialize the checking account. + public CheckingAccount(long accountNumber, double balance, double overdraftLimit) + { + AccountNumber = accountNumber; + Balance = balance; + OverdraftLimit = overdraftLimit; + } + + // Deposit method for checking account. + public override void Deposit(double amount) + { + Balance += amount; + } + + // Withdraw method for checking account. + public override void Withdraw(double amount) + { + if (amount <= OverdraftLimit + Balance) + { + Balance -= amount; + } + else + { + Console.WriteLine("Exceed the limit of withdrawn for existing balance and overdraft limit."); + } + } + } +} diff --git a/week-1/day-2/exercise-2/BankAccount/Program.cs b/week-1/day-2/exercise-2/BankAccount/Program.cs index c58c30e2..a7ba13a0 100644 --- a/week-1/day-2/exercise-2/BankAccount/Program.cs +++ b/week-1/day-2/exercise-2/BankAccount/Program.cs @@ -1,10 +1,22 @@ namespace BankAccount { - internal class Program + public class Program { static void Main(string[] args) { - // Create SavingsAccount and CheckingAccount objects and perform operations + // Creating instances of SavingsAccount and CheckingAccount + SavingsAccount savingsAccount = new SavingsAccount(34572637483, 1000.50, 0.4); + CheckingAccount checkingAccount = new CheckingAccount(34572637483, 200, 400); + + // Performing operations on the savings account + savingsAccount.Deposit(1000); + savingsAccount.Withdraw(750); + Console.WriteLine($"SavingsAccount Balance is: {savingsAccount.Balance}"); + + // Performing operations on the checking account + checkingAccount.Deposit(1000); + checkingAccount.Withdraw(3000); + Console.WriteLine($"CheckingAccount Balance is: {checkingAccount.Balance}"); } } } \ No newline at end of file diff --git a/week-1/day-2/exercise-3/AnimalExercise/Animal.cs b/week-1/day-2/exercise-3/AnimalExercise/Animal.cs new file mode 100644 index 00000000..fb2ff9ba --- /dev/null +++ b/week-1/day-2/exercise-3/AnimalExercise/Animal.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AnimalExercise +{ + // Abstract class for animals + public abstract class Animal + { + // Properties of an animal + public string? Name; // Name of the animal (can be null) + public int Age; // Age of the animal + + // Abstract method for making a sound + // The body of this method must be provided by derived classes + public abstract void MakeSound(); + } + + // Interface for movable objects + interface IMovable + { + void Move(); // Method to define movement behavior + } + + // First derived class: Dog + class Dog : Animal, IMovable + { + public override void MakeSound() + { + // Implementation of the MakeSound method for a dog + Console.WriteLine("Dog Sounds - Woof Woof..."); + } + + public void Move() + { + // Implementation of the Move method for a dog + Console.WriteLine("This is the Move() method."); + } + } + + // Second derived class: Cat + class Cat : Animal, IMovable + { + public override void MakeSound() + { + // Implementation of the MakeSound method for a cat + Console.WriteLine("Cat Sounds - Meow Meow...\n"); + } + + public void Move() + { + // Implementation of the Move method for a cat + Console.WriteLine("This is the Move() method."); + } + } +} diff --git a/week-1/day-2/exercise-3/AnimalExercise/Program.cs b/week-1/day-2/exercise-3/AnimalExercise/Program.cs index 5928b7cb..5ddb7434 100644 --- a/week-1/day-2/exercise-3/AnimalExercise/Program.cs +++ b/week-1/day-2/exercise-3/AnimalExercise/Program.cs @@ -1,10 +1,20 @@ namespace AnimalExercise { - internal class Program + public class Program { static void Main(string[] args) { - // Create a list of Animal objects, add Dog and Cat instances, and call their methods + // Create instances of Dog and Cat + Dog dogSound = new Dog(); + Cat catSound = new Cat(); + + // Call the MakeSound method for both objects + dogSound.MakeSound(); + catSound.MakeSound(); + + // Call the Move method for both objects + dogSound.Move(); + catSound.Move(); } } } \ No newline at end of file diff --git a/week-1/day-2/exercise-4/VehicleManagementSystem/IRepository.cs b/week-1/day-2/exercise-4/VehicleManagementSystem/IRepository.cs new file mode 100644 index 00000000..d227067d --- /dev/null +++ b/week-1/day-2/exercise-4/VehicleManagementSystem/IRepository.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VehicleManagementSystem +{ + public interface IRepository + { + T GetById(int id); + + IEnumerable GetAll(); + + void Add(T entity); + + void Update(T entity); + + void Delete(T entity); + } +} diff --git a/week-1/day-2/exercise-4/VehicleManagementSystem/IVehicle.cs b/week-1/day-2/exercise-4/VehicleManagementSystem/IVehicle.cs new file mode 100644 index 00000000..bc32cdb7 --- /dev/null +++ b/week-1/day-2/exercise-4/VehicleManagementSystem/IVehicle.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VehicleManagementSystem +{ + // Define an interface for vehicles. + public interface IVehicle + { + void Drive(); + } + + // Define a class representing a Car, which implements the IVehicle interface. + public class Car : IVehicle + { + // Implement the Drive method for the Car class. + public void Drive() + { + Console.WriteLine("Driving Car."); + } + } + + // Define a class representing a Truck, which implements the IVehicle interface. + public class Truck : IVehicle + { + // Implement the Drive method for the Truck class. + public void Drive() + { + Console.WriteLine("Driving Truck."); + } + } +} diff --git a/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs b/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs index 77395b3a..1ffd9b80 100644 --- a/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs +++ b/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs @@ -1,10 +1,68 @@ namespace VehicleManagementSystem { - internal class Program + public class Program { static void Main(string[] args) { - Console.WriteLine("Hello, World!"); + // Prompt the user to input a vehicle type + Console.WriteLine("1. Factory Design Method."); + Console.Write("Enter a vehicle type car or truck: "); + string? vehicleType = Console.ReadLine(); + // Retrieve the appropriate vehicle factory based on user input + VehicleFactory vehicleFactory = GetVehicleFactory(vehicleType); + + if (vehicleFactory != null) + { + // Use the factory to create a vehicle and perform a drive action + IVehicle vehicle = vehicleFactory.CreateVehicle(); + Console.WriteLine("\nVehicle created:"); + vehicle.Drive(); + } + else + { + Console.WriteLine("Invalid vehicle type."); + } + + Console.WriteLine("\n2.Repository CRUD operation.\n"); + + // Create instances of VehicleRepository and VehicleLogger + VehicleRepository vehicleRepository = new VehicleRepository(); + VehicleLogger vehicleLogger = VehicleLogger.Instance; + + // Create a VehicleService and associate it with the repository and logger + VehicleService vehicleService = new VehicleService(vehicleRepository, vehicleLogger); + + // Create instances of CarFactory and TruckFactory + CarFactory carFactory = new CarFactory(); + TruckFactory truckFactory = new TruckFactory(); + + // List vehicles and demonstrate adding/removing vehicles + vehicleService.AddVehicle(carFactory); + vehicleService.AddVehicle(carFactory); + vehicleService.AddVehicle(truckFactory); + + vehicleService.ListVehicles(); + vehicleService.RemoveVehicle(1); + vehicleService.AddVehicle(truckFactory); + vehicleService.ListVehicles(); + + // Demonstrate performing actions on vehicles + vehicleService.DoSomethingWithVehicle(1); + vehicleService.DoSomethingWithVehicle(2); + } + + // Helper function to get the appropriate vehicle factory based on input + static VehicleFactory GetVehicleFactory(string vehicleType) + { + switch (vehicleType.ToLower()) + { + case "car": + return new CarFactory(); + case "truck": + return new TruckFactory(); + default: + return null; + } } } } \ No newline at end of file diff --git a/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleFactory.cs b/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleFactory.cs new file mode 100644 index 00000000..2da1b359 --- /dev/null +++ b/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleFactory.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VehicleManagementSystem +{ + // Abstract factory class that defines a method for creating vehicles + public abstract class VehicleFactory + { + // Abstract method for creating a vehicle + public abstract IVehicle CreateVehicle(); + + // Method that demonstrates using the created vehicle + public void DoSomethingWithVehicle() + { + // Create a vehicle using the factory method + IVehicle vehicle = CreateVehicle(); + + // Drive the created vehicle + vehicle.Drive(); + } + } + + // Concrete factory class that creates cars + public class CarFactory : VehicleFactory + { + // Override the CreateVehicle method to create a car + public override IVehicle CreateVehicle() + { + return new Car(); + } + } + + // Concrete factory class that creates trucks + public class TruckFactory : VehicleFactory + { + // Override the CreateVehicle method to create a truck + public override IVehicle CreateVehicle() + { + return new Truck(); + } + } +} diff --git a/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleLogger.cs b/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleLogger.cs new file mode 100644 index 00000000..42b13400 --- /dev/null +++ b/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleLogger.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VehicleManagementSystem +{ + // Define a class for logging vehicle-related messages + public class VehicleLogger + { + // Private constructor to prevent external instantiation + private VehicleLogger() { } + + // Create an object for Thread Safety to use double check locking + private static readonly object locker = new object(); + + // Create a private instance variable for the singleton pattern + private static VehicleLogger? instance; + + // Define a public property to access the singleton instance + public static VehicleLogger Instance + { + get + { + // Thread Safety Singleton using Double-Check Locking + if (instance == null) + { + lock (locker) + { + // If instance is still null, create a new instance + if (instance == null) + { + instance = new VehicleLogger(); + } + } + } + // Return the singleton instance + return instance; + } + } + + // Method for logging vehicle-related messages + public void Log(string message) + { + Console.WriteLine($"Vehicle Logging: {message}"); + } + } +} diff --git a/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleRepository.cs b/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleRepository.cs new file mode 100644 index 00000000..b3cc1c99 --- /dev/null +++ b/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleRepository.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VehicleManagementSystem +{ + // This class implements the IRepository interface for IVehicle objects. + public class VehicleRepository : IRepository + { + // Private dictionary to store vehicles with their unique IDs. + private Dictionary vehicles = new Dictionary(); + + // Used to generate the next available ID for new vehicles. + private int nextId = 1; + + // Adds a new vehicle to the repository. + public void Add(IVehicle entity) + { + int id = nextId++; + vehicles[id] = entity; + } + + // Deletes a vehicle from the repository. + public void Delete(IVehicle entity) + { + // Find the key-value pair associated with the specified entity. + var item = vehicles.FirstOrDefault(v => v.Value == entity); + + // If the entity is found, remove it from the dictionary. + if (item.Value != null) + { + vehicles.Remove(item.Key); + } + } + + // Retrieves all vehicles from the repository. + public IEnumerable GetAll() + { + return vehicles.Values; + } + + // Retrieves a vehicle by its ID from the repository. + public IVehicle GetById(int id) + { + // Try to get the vehicle associated with the given ID. + vehicles.TryGetValue(id, out IVehicle vehicle); + return vehicle; + } + + // Updates a vehicle in the repository (not implemented in this version). + public void Update(IVehicle entity) + { + throw new NotImplementedException(); + } + } +} diff --git a/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleService.cs b/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleService.cs new file mode 100644 index 00000000..f78b59d1 --- /dev/null +++ b/week-1/day-2/exercise-4/VehicleManagementSystem/VehicleService.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VehicleManagementSystem +{ + // The VehicleService class handles operations related to vehicles using a repository and logger. + public class VehicleService + { + private readonly IRepository _vehicleRepository; // Repository to store vehicles. + private VehicleLogger _vehicleLogger; // Logger to record vehicle-related actions. + + // Constructor for VehicleService. + public VehicleService(IRepository vehicleRepository, VehicleLogger vehicleLogger) + { + _vehicleRepository = vehicleRepository; + _vehicleLogger = vehicleLogger; + } + + // Adds a vehicle to the repository using a factory and logs the action. + public void AddVehicle(VehicleFactory factory) + { + IVehicle vehicle = factory.CreateVehicle(); + _vehicleRepository.Add(vehicle); + _vehicleLogger.Log("Vehicle added successfully"); + } + + // Removes a vehicle from the repository by ID and logs the action. + public void RemoveVehicle(int id) + { + IVehicle vehicle = _vehicleRepository.GetById(id); + if (vehicle != null) + { + _vehicleRepository.Delete(vehicle); + _vehicleLogger.Log("Vehicle Removed Successfully."); + } + else + { + _vehicleLogger.Log("Vehicle Not Found."); + } + } + + // Lists all vehicles in the repository and invokes the Drive method for each vehicle. + public void ListVehicles() + { + foreach (IVehicle vehicle in _vehicleRepository.GetAll()) + { + vehicle.Drive(); + } + } + + // Performs an action on a vehicle by ID, logs the action, and invokes the Drive method. + public void DoSomethingWithVehicle(int id) + { + IVehicle vehicle = _vehicleRepository.GetById(id); + if (vehicle != null) + { + vehicle.Drive(); + _vehicleLogger.Log("Something happened with the vehicle. Drive Slowly"); + } + } + } +} diff --git a/week-1/day-3/exercise-1/FactorialApp/Program.cs b/week-1/day-3/exercise-1/FactorialApp/Program.cs index f116eeca..13c178ee 100644 --- a/week-1/day-3/exercise-1/FactorialApp/Program.cs +++ b/week-1/day-3/exercise-1/FactorialApp/Program.cs @@ -2,19 +2,53 @@ { public class Program { - public static void Main() + static void Main(string[] args) { - Console.Write("Enter a number: "); - int number = int.Parse(Console.ReadLine()); + int value; - long factorial = CalculateFactorial(number); + // User input + Console.Write("Enter the number to find factorial: "); + string? input = Console.ReadLine(); // Read user input as a string. Because ReadLine function always return string. - Console.WriteLine($"The factorial of {number} is: {factorial}"); + try + { + // Parse the input string as an integer. + value = int.Parse(input); + + if (value < 0) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("Factorial of negative numbers can't be found."); + } + else + { + // Here the Recursive Factorial method is being called and then display the factorial. + long fact = Fact(value); + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"Factorial of given number {input} is: " + fact); + } + + } + catch (FormatException) + { + // Handle the user input if the user entered wrong input. + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"The given input '{input}' is not an integer. Input should be an integer only."); + } + Console.ResetColor(); } - public static long CalculateFactorial(int number) + // Recursive method to calculate the factorial of a given value. + static long Fact(int value) { - throw new NotImplementedException(); + if (value == 0 || value == 1) + { + return 1; + } + else + { + return (value * Fact(value - 1)); + } } } } \ No newline at end of file diff --git a/week-1/day-3/exercise-1/FactorialApp/Properties/launchSettings.json b/week-1/day-3/exercise-1/FactorialApp/Properties/launchSettings.json new file mode 100644 index 00000000..33504c94 --- /dev/null +++ b/week-1/day-3/exercise-1/FactorialApp/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "WSL": { + "commandName": "WSL2", + "distributionName": "" + } + } +} \ No newline at end of file diff --git a/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs b/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs index a4ec62d9..6962016e 100644 --- a/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs +++ b/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs @@ -223,7 +223,20 @@ public int[] DijkstraShortestPath(int source) visited[i] = false; } - distances[source] = int.MinValue; + /* Here the int.MinValue is taking the minimum value which repersent the minimum + * value of int data type and it indicate that the distance from the source vertex + * to itself is negative infinity. + * + * But in Dijkstra algorithm distances[source] always indicate the distance from + * the source vertex to itself and it must be set 0. + * + * The use of very negative values can lead to integer overflow issues when performing + * arithmetic operations. Dijkstra's algorithm is designed to work with distances that + * are real and non-negative values. + */ + // distances[source] = int.MinValue; + + distances[source] = 0; for (int count = 0; count < vertices - 1; count++) { diff --git a/week-1/day-4/exercise-1/StackApp/ICustomStack.cs b/week-1/day-4/exercise-1/StackApp/ICustomStack.cs index 55f3936d..55e06784 100644 --- a/week-1/day-4/exercise-1/StackApp/ICustomStack.cs +++ b/week-1/day-4/exercise-1/StackApp/ICustomStack.cs @@ -1,4 +1,7 @@ -namespace StackApp +using static System.Formats.Asn1.AsnWriter; +using System.Collections.Generic; + +namespace StackApp { internal interface ICustomStack { @@ -6,4 +9,32 @@ internal interface ICustomStack T Pop(); bool IsEmpty(); } + + // Define a custom stack class that implements the interface ICustomStack + internal class CustomStack : ICustomStack + { + // List to store stack items + private readonly List items = new List(); + public void Push(T item) + { + items.Add(item); + } + + public T Pop() + { + if (IsEmpty()) + { + throw new InvalidOperationException("Stack is Empty."); + } + int lastIndex = items.Count - 1; + T item = items[lastIndex]; + items.RemoveAt(lastIndex); + return item; + } + + public bool IsEmpty() + { + return items.Count() == 0; + } + } } diff --git a/week-1/day-4/exercise-1/StackApp/Program.cs b/week-1/day-4/exercise-1/StackApp/Program.cs index e089f665..e9ed15f2 100644 --- a/week-1/day-4/exercise-1/StackApp/Program.cs +++ b/week-1/day-4/exercise-1/StackApp/Program.cs @@ -4,13 +4,50 @@ internal class Program { static void Main(string[] args) { - //ICustomStack intStack = new CustomStack(); - //intStack.Push(1); - //intStack.Push(2); - //intStack.Push(3); - //Console.WriteLine(intStack.Pop()); // Output: 3 - //Console.WriteLine(intStack.Pop()); // Output: 2 - //Console.WriteLine(intStack.IsEmpty()); // Output: False + ICustomStack intStack = new CustomStack(); + + intStack.Push(1); + intStack.Push(2); + intStack.Push(3); + + Console.WriteLine(intStack.Pop()); // Output: 3 + Console.WriteLine(intStack.Pop()); // Output: 2 + Console.WriteLine(intStack.IsEmpty() + "\n"); // Output: False + + ICustomStack stringStack = new CustomStack(); + + stringStack.Push("Ashish"); + stringStack.Push("Vipul"); + + Console.WriteLine(stringStack.Pop()); // Output: Vipul + Console.WriteLine(stringStack.Pop()); // Output: Ashish + Console.WriteLine(stringStack.IsEmpty() + "\n"); // Output: True + + //Custom Object. + ICustomStack personStack = new CustomStack(); + + personStack.Push(new Person("Krishna", 20)); + personStack.Push(new Person("Ashish", 22)); + + Console.WriteLine(personStack.Pop()); // Output: {Name = Ashish, Age = 22} + Console.WriteLine(personStack.IsEmpty()); // Output: False + + } + } + + public class Person + { + public string Name { get; set; } + public int Age { get; set; } + + public Person(string name, int age) + { + Name = name; + Age = age; + } + public override string ToString() + { + return $"Person{{Name = {Name}, Age = {Age}}}"; } } } \ No newline at end of file diff --git a/week-1/day-4/exercise-2/IteratorsApp/Program.cs b/week-1/day-4/exercise-2/IteratorsApp/Program.cs index f3cb1ae8..da47c5d5 100644 --- a/week-1/day-4/exercise-2/IteratorsApp/Program.cs +++ b/week-1/day-4/exercise-2/IteratorsApp/Program.cs @@ -4,17 +4,26 @@ internal class Program { static void Main(string[] args) { - var fibonacci = FibonacciSequence().Take(10); - foreach (int number in fibonacci) + // Display the Fibonacci sequence up to the ten number. + Console.WriteLine("Fibonacci Sequence is: "); + foreach (var i in FibonacciSequence(10)) { - Console.WriteLine(number); + Console.Write(i + " "); } } // https://www.c-sharpcorner.com/UploadFile/5ef30d/understanding-yield-return-in-C-Sharp/ // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/yield - public static IEnumerable FibonacciSequence() + public static IEnumerable FibonacciSequence(int length) { - throw new NotImplementedException(); + int a = 0, b = 1; + + for (int i = 0; i < length; i++) + { + yield return a; + int c = a + b; + a = b; + b = c; + } } } } \ No newline at end of file diff --git a/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs b/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs index 95e8ac84..6bbae354 100644 --- a/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs +++ b/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs @@ -4,20 +4,42 @@ internal class Program { static void Main(string[] args) { - List people = new List + List peopleList = new List { new Person { Name = "John", Age = 25, Country = "USA" }, - new Person { Name = "Jane", Age = 30, Country = "Canada" }, + new Person { Name = "Jane", Age = 31, Country = "Canada" }, new Person { Name = "Mark", Age = 28, Country = "USA" }, new Person { Name = "Emily", Age = 22, Country = "Australia" } }; //Write queries using LINQ for following operations - //1. Get all people from USA - //2. Get all people above 30 - //3. Sort people by name - //4. Project/Select only Name and Country of all people + //1. Get all people above 30 + var aboveCertainAge = peopleList.Where(people => people.Age > 30); + + //2. Sort people by name + var sortByName = peopleList.OrderBy(people => people.Name).ToList(); + + //3. Project/Select only Name and Country of all people + var byNameAndCountry = peopleList.Select(people => new { people.Name, people.Country }).ToList(); + + Console.WriteLine("Peoples above 30 are:"); + foreach (var people in aboveCertainAge) + { + Console.WriteLine(people.Name + " " + people.Age); + } + + Console.WriteLine("\nSorted by Name: "); + foreach (var people in sortByName) + { + Console.WriteLine(people.Name); + } + Console.WriteLine("\nPeople's Name and Country details: "); + foreach (var people in byNameAndCountry) + { + Console.WriteLine(people.Name + " " + people.Country); + + } } } diff --git a/week-1/day-4/exercise-4/LinqToXmlApp/Modified_Books.xml b/week-1/day-4/exercise-4/LinqToXmlApp/Modified_Books.xml new file mode 100644 index 00000000..a1329074 --- /dev/null +++ b/week-1/day-4/exercise-4/LinqToXmlApp/Modified_Books.xml @@ -0,0 +1,23 @@ + + + + A Suitable Boy + Updated Author + Novel + + + The Alchemist + Paulo Coelho + Fiction + + + Turbulence + Samit Basu + Science Fiction + + + New Book + New Author + Fantasy + + \ No newline at end of file diff --git a/week-1/day-4/exercise-4/LinqToXmlApp/Program.cs b/week-1/day-4/exercise-4/LinqToXmlApp/Program.cs index 315df143..624fdd2a 100644 --- a/week-1/day-4/exercise-4/LinqToXmlApp/Program.cs +++ b/week-1/day-4/exercise-4/LinqToXmlApp/Program.cs @@ -1,4 +1,6 @@ -namespace LinqToXmlApp +using System.Xml.Linq; + +namespace LinqToXmlApp { internal class Program { @@ -16,27 +18,57 @@ static void Main(string[] args) // Write above book structure as a c# string string xmlString = @" - Book Title 1 - Author 1 - Genre 1 + A Suitable Boy + Vikram Seth + Novel - Book Title 2 - Author 2 - Genre 2 + The Alchemist + Paulo Coelho + Fiction - Book Title 3 - Author 3 - Genre 3 + Turbulence + Samit Basu + Science Fiction "; // Create an XDocument object from the XML string + XDocument doc = XDocument.Parse(xmlString); + + // Query for books in a specific genre. + string genre = "Novel"; + var bookGener = doc.Root.Elements("Book").Where(book => book.Element("Genre").Value == genre); + + // Modify the XML document by adding a new book or updating existing book information. + XElement newBook = new XElement("Book", + new XElement("Title", "New Book"), + new XElement("Author", "New Author"), + new XElement("Genre", "Fantasy")); + + doc.Root.Add(newBook); + + // Updating existing book information. + var updateBook = doc.Root.Elements("Book").FirstOrDefault(book => book.Element("Title").Value == "A Suitable Boy"); + + if (updateBook != null) + { + updateBook.Element("Author").Value = "Updated Author"; + } - // Write the title of all books to the console + // The Modified file savaed to this Location. + doc.Save("C:\\Users\\admin\\source\\repos\\Day-2\\four-weeks-training\\week-1\\day-4\\exercise-4\\LinqToXmlApp\\Modified_Books.xml"); - // Write the title of all books with genre "Genre 1" to the console + Console.WriteLine($"Books in specific {genre} genre: "); + foreach (var book in bookGener) + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"Title: {book.Element("Title").Value}"); + Console.WriteLine($"Author: {book.Element("Author").Value}"); + Console.WriteLine($"Genre: {book.Element("Genre").Value}"); + Console.ResetColor(); + } } } diff --git a/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs b/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs index b18cea78..c7023013 100644 --- a/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs +++ b/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs @@ -15,7 +15,7 @@ static void Main(string[] args) // Optimized implementation sw.Restart(); - + IEnumerable optimizedQuery = data.AsParallel().Where(x => x > 100).OrderByDescending(x => x).Take(10); sw.Stop(); Console.WriteLine("Optimized Query: {0} ms", sw.ElapsedMilliseconds); } diff --git a/week-1/day-4/exercise-6/LinqFilterAndSort/Program.cs b/week-1/day-4/exercise-6/LinqFilterAndSort/Program.cs index 5c6d6240..e4549c43 100644 --- a/week-1/day-4/exercise-6/LinqFilterAndSort/Program.cs +++ b/week-1/day-4/exercise-6/LinqFilterAndSort/Program.cs @@ -1,12 +1,45 @@ -namespace LinqFilterAndSort +using System; + +namespace LinqFilterAndSort { internal class Program { static void Main(string[] args) { // Create a list of Person objects - // Use LINQ to filter and sort the list - // Print the filtered and sorted list of people to the console + List peopleList = new List() + { + new Person { FirstName = "Prince", LastName = "Kumar", Age = 16, }, + new Person { FirstName = "Sumant", LastName = "Kumar", Age = 18, }, + new Person { FirstName = "Alok", LastName = "Anand", Age = 25, }, + new Person { FirstName = "ShashiKant", LastName = "Singh", Age = 57, } + }; + + //1. filter the list to only include people who are 18 years old or older. + var aboveCertainAge = peopleList.Where(people => people.Age >= 18); + + //2. Sort people by name + var sortedPeople = peopleList.OrderBy(people => people.LastName).ThenBy(people => people.FirstName).ToList(); + + Console.WriteLine("People who are 18 years old or older:"); + foreach (var people in aboveCertainAge) + { + Console.WriteLine($"{people.FirstName} {people.LastName}, Age {people.Age}"); + } + + Console.WriteLine("\nSorted by Name: "); + Console.WriteLine($"LastName\t FirstName"); + foreach (var people in sortedPeople) + { + Console.WriteLine($"{people.LastName}\t\t {people.FirstName}"); + } } } + public class Person + { + public string? FirstName { get; set; } + public string? LastName { get; set; } + public int Age { get; set; } + + } } \ No newline at end of file diff --git a/week-1/day-4/exercise-7/LinqListNumbers/Program.cs b/week-1/day-4/exercise-7/LinqListNumbers/Program.cs index 6caadd07..4d80b47e 100644 --- a/week-1/day-4/exercise-7/LinqListNumbers/Program.cs +++ b/week-1/day-4/exercise-7/LinqListNumbers/Program.cs @@ -9,10 +9,39 @@ static void Main(string[] args) // Use LINQ to perform the following operations: // 1. Find all even numbers + Console.WriteLine("All even numbers are."); + var evenNumbers = numbers.Where(num => num % 2 == 0).ToList(); + foreach (int number in evenNumbers) + { + Console.ForegroundColor = ConsoleColor.Green; + Console.Write(number + " "); + Console.ResetColor(); + } + // 2. Find all numbers greater than a specific value (e.g., 20) + Console.WriteLine("\n\nAll numbers greater then 20 are."); + var greaterThenSpecific = numbers.Where(num => num > 20).ToList(); + foreach (int number in greaterThenSpecific) + { + Console.ForegroundColor = ConsoleColor.Green; + Console.Write(number + " "); + Console.ResetColor(); + } + // 3. Calculate the sum of all numbers + int sum = numbers.Sum(); + Console.WriteLine("\n\nSum of all numbers: " + sum); + // 4. Calculate the average of all numbers + double average = numbers.Average(); + Console.WriteLine("\nAverage of all numbers: " + average); + // 5. Find the minimum and maximum values in the list + int min = numbers.Min(); + Console.WriteLine("\nMinimum of all numbers: " + min); + + int max = numbers.Max(); + Console.WriteLine("\nMaximum of all numbers: " + max); } } } \ No newline at end of file diff --git a/week-1/day-4/exercise-8/LinqGroupAggregate/Program.cs b/week-1/day-4/exercise-8/LinqGroupAggregate/Program.cs index 04dbd615..2e94061f 100644 --- a/week-1/day-4/exercise-8/LinqGroupAggregate/Program.cs +++ b/week-1/day-4/exercise-8/LinqGroupAggregate/Program.cs @@ -15,11 +15,32 @@ static void Main(string[] args) new Product { Name = "Sneakers", Category = "Footwear", Price = 100.00M } }; - // Use LINQ to perform the following operations: + /// Use LINQ to perform the following operations: // 1. Group products by category + var groupByCategory = products.GroupBy(product => product.Category); + // 2. Count the number of products in each category + var countProductByCategory = groupByCategory.ToDictionary( + group => group.Key, + group => group.Count()); + + // 3. Calculate the total price of products in each category + var totalPriceByCategory = groupByCategory.ToDictionary( + group => group.Key, + group => group.Sum(product => product.Price)); + // 4. Find the most expensive product in each category + var expensiveProductByCategory = groupByCategory.Select( + group => group.OrderBy(product => product.Price).Last()); + + foreach (var item in groupByCategory) + { + Console.WriteLine($"Category: {item.Key}"); + Console.WriteLine($"Product Count: {countProductByCategory[item.Key]}"); + Console.WriteLine($"Total Price: {totalPriceByCategory[item.Key]}"); + Console.WriteLine($"Expensive Product: {expensiveProductByCategory.Single(p => p.Category == item.Key).Name}\n"); + } } } } \ No newline at end of file diff --git a/week-1/day-5/exercise-1/FileLoggerDisposableApp/FileLogg.txt b/week-1/day-5/exercise-1/FileLoggerDisposableApp/FileLogg.txt new file mode 100644 index 00000000..26513dc2 --- /dev/null +++ b/week-1/day-5/exercise-1/FileLoggerDisposableApp/FileLogg.txt @@ -0,0 +1 @@ +Log message at: 8/11/2023 3:56:59 PM diff --git a/week-1/day-5/exercise-1/FileLoggerDisposableApp/Program.cs b/week-1/day-5/exercise-1/FileLoggerDisposableApp/Program.cs index 30a23ac7..d6958d6c 100644 --- a/week-1/day-5/exercise-1/FileLoggerDisposableApp/Program.cs +++ b/week-1/day-5/exercise-1/FileLoggerDisposableApp/Program.cs @@ -5,6 +5,12 @@ internal class Program static void Main(string[] args) { // Use FileLogger and dispose of it properly + string path = "C:\\Users\\admin\\source\\repos\\Day-2\\four-weeks-training\\week-1\\day-5" + + "\\exercise-1\\FileLoggerDisposableApp\\FileLogg.txt"; + using (FileLogger logger = new FileLogger(path)) + { + logger.Log("Log message at:"); + } } } @@ -15,16 +21,42 @@ class FileLogger : IDisposable public FileLogger(string filePath) { // Initialize StreamWriter instance + _writer = new StreamWriter(filePath, true); } public void Dispose() { // Implement IDisposable pattern + // Dispose of unmanaged resources. + Dispose(true); + // Suppress finalization. + GC.SuppressFinalize(this); + } + + private bool _disposedValue; + private void Dispose(bool isDisposing) + { + if (!_disposedValue) + { + if (isDisposing) + { + _writer.Dispose(); + _writer = null; + } + _disposedValue = true; + } } public void Log(string message) { // Write message to the file + _writer.WriteLine(message + " " + DateTime.Now.ToString()); + Console.WriteLine("Log message saved to logg file."); + } + + ~FileLogger() + { + Dispose(false); } } } \ No newline at end of file diff --git a/week-1/day-5/exercise-2/CovariantAndContravariantGenerics/Program.cs b/week-1/day-5/exercise-2/CovariantAndContravariantGenerics/Program.cs index eb4e0605..3e4196e1 100644 --- a/week-1/day-5/exercise-2/CovariantAndContravariantGenerics/Program.cs +++ b/week-1/day-5/exercise-2/CovariantAndContravariantGenerics/Program.cs @@ -10,7 +10,15 @@ class StringToIntProcessor : IProcessor // Implement Process method public int Process(string input) { - throw new NotImplementedException(); + bool output = int.TryParse(input, out int result); + if (output) + { + return result; + } + else + { + throw new ArgumentException("Not a valid input integer."); + } } } @@ -19,7 +27,7 @@ class DoubleToStringProcessor : IProcessor // Implement Process method public string Process(double input) { - throw new NotImplementedException(); + return input.ToString(); } } internal class Program @@ -27,6 +35,17 @@ internal class Program static void Main(string[] args) { // Demonstrate covariance and contravariance with IProcessor interface + IProcessor stringToInt = new StringToIntProcessor(); + + IProcessor doubleToStrng = new DoubleToStringProcessor(); + + //Process String to Integer + int intResult1 = stringToInt.Process("42"); + Console.WriteLine($"Result for String to Int process: {intResult1} and (Type: {intResult1.GetType()})"); + + //Process Double to String + string stringResult1 = doubleToStrng.Process(34.22); + Console.WriteLine($"Result for String to Int process: {stringResult1} and (Type: {stringResult1.GetType()})"); } } } \ No newline at end of file diff --git a/week-1/day-5/exercise-3/AsyncAwaitBasics/Program.cs b/week-1/day-5/exercise-3/AsyncAwaitBasics/Program.cs index 5d7df133..8d66b85b 100644 --- a/week-1/day-5/exercise-3/AsyncAwaitBasics/Program.cs +++ b/week-1/day-5/exercise-3/AsyncAwaitBasics/Program.cs @@ -1,20 +1,38 @@ -namespace AsyncAwaitBasics +using System.Diagnostics; + +namespace AsyncAwaitBasics { internal class Program { static async Task Main(string[] args) { // Call PerformCalculations and measure time taken using Stopwatch + Stopwatch sw = Stopwatch.StartNew(); + + await PerformCalculations(3); + + sw.Stop(); + Console.WriteLine("Total Time taken: {0} ms", sw.ElapsedMilliseconds); } static async Task SimulateLongRunningTask(int delayInSeconds) { // Implement long-running task simulation + await Task.Delay(TimeSpan.FromSeconds(delayInSeconds)); } static async Task PerformCalculations(int numberOfTasks) { // Start long-running tasks concurrently and wait for them to complete + Task[] task = new Task[numberOfTasks]; + + for (int i = 0; i < numberOfTasks; i++) + { + task[i] = SimulateLongRunningTask(i + 1); + } + await Task.WhenAll(task); + + Console.WriteLine("Task Completed."); } } } \ No newline at end of file diff --git a/week-1/day-5/exercise-4/AsynAwaitWeatherForcasting/AsynAwaitWeatherForcasting.csproj b/week-1/day-5/exercise-4/AsynAwaitWeatherForcasting/AsynAwaitWeatherForcasting.csproj index f02677bf..9cf5c969 100644 --- a/week-1/day-5/exercise-4/AsynAwaitWeatherForcasting/AsynAwaitWeatherForcasting.csproj +++ b/week-1/day-5/exercise-4/AsynAwaitWeatherForcasting/AsynAwaitWeatherForcasting.csproj @@ -7,4 +7,8 @@ enable + + + + diff --git a/week-1/day-5/exercise-4/AsynAwaitWeatherForcasting/Program.cs b/week-1/day-5/exercise-4/AsynAwaitWeatherForcasting/Program.cs index a64153a4..95a3e22d 100644 --- a/week-1/day-5/exercise-4/AsynAwaitWeatherForcasting/Program.cs +++ b/week-1/day-5/exercise-4/AsynAwaitWeatherForcasting/Program.cs @@ -1,21 +1,68 @@ -namespace AsynAwaitWeatherForcasting +using Newtonsoft.Json; + +namespace AsynAwaitWeatherForcasting { internal class Program { - static void Main(string[] args) + static async Task Main(string[] args) { string city = "Vadodara, India"; + string key = "929b546db3a40dc10e07b8c87cf143c2"; + string url = $"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={key}"; // Call the method to fetch weather data + WeatherData weatherData = await FetchWeatherDataAsync(url); // Display the weather data with city name + if (weatherData != null) + { + Console.WriteLine($"Temperature: {Math.Round(weatherData.Main.Temp - 273.15f)}°C"); + Console.WriteLine($"Description: {weatherData.Weather[0].Description}"); + } + else + { + Console.WriteLine("Something went wrong, Api fetching failed."); + } + } // Call OpenWeatherMap API to fetch weather data https://openweathermap.org/api // Create a C# object from the JSON response // Replace Task with the C# object Task - static async Task FetchWeatherDataAsync(string url) + static async Task FetchWeatherDataAsync(string url) { // Fetch web page content asynchronously using HttpClient - throw new NotImplementedException(); + using (HttpClient httpClient = new HttpClient()) + { + HttpResponseMessage response = await httpClient.GetAsync(url); + + if (response.IsSuccessStatusCode) + { + string content = await response.Content.ReadAsStringAsync(); + WeatherData weatherData = JsonConvert.DeserializeObject(content); + return weatherData; + } + else + { + Console.WriteLine($"API call failed with status code: {response.StatusCode}"); + return null; + } + } + } } + + public class WeatherData + { + public WeatherMain Main { get; set; } + public WeatherDescription[] Weather { get; set; } + } + + public class WeatherMain + { + public float Temp { get; set; } + } + + public class WeatherDescription + { + public string Description { get; set; } + } } \ No newline at end of file