From 58267cb5546c03be17dc4edb71c426ab02871fa6 Mon Sep 17 00:00:00 2001 From: pawankhandwe Date: Wed, 9 Aug 2023 12:05:09 +0530 Subject: [PATCH 1/9] Day-2 --- .gitmodules | 3 + week-1/day-2/exercise-1/Circle/Circle.cs | 15 + week-1/day-2/exercise-1/Circle/Program.cs | 3 + .../day-2/exercise-2/BankAccount/Program.cs | 164 ++++++++++- .../exercise-3/AnimalExercise/Program.cs | 61 ++++- .../VehicleManagementSystem/Program.cs | 256 +++++++++++++++++- 6 files changed, 497 insertions(+), 5 deletions(-) create mode 100644 .gitmodules diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..99f04275 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "week1"] + path = week1 + url = https://github.com/pawankhandwe/four-weeks-training.git diff --git a/week-1/day-2/exercise-1/Circle/Circle.cs b/week-1/day-2/exercise-1/Circle/Circle.cs index 065ffa5d..9016ec3f 100644 --- a/week-1/day-2/exercise-1/Circle/Circle.cs +++ b/week-1/day-2/exercise-1/Circle/Circle.cs @@ -9,5 +9,20 @@ namespace Circle internal class Circle { // Implement the Circle class here + + int radius; + public Circle(int Radius) + { + radius = Radius; + } + public double getArea() + { + + return Math.PI * Math.Pow(radius, 2); + } + public double GetCircumference() + { + return 2 * Math.PI * radius; + } } } diff --git a/week-1/day-2/exercise-1/Circle/Program.cs b/week-1/day-2/exercise-1/Circle/Program.cs index 0df91b0d..5ed733a9 100644 --- a/week-1/day-2/exercise-1/Circle/Program.cs +++ b/week-1/day-2/exercise-1/Circle/Program.cs @@ -5,6 +5,9 @@ internal class Program static void Main(string[] args) { // Create a Circle object and display its area and circumference + Circle c = new Circle(3); + Console.WriteLine("area of circle is " + c.getArea()); + Console.WriteLine("Circumference of circle is " + c.GetCircumference()); } } } \ No newline at end of file diff --git a/week-1/day-2/exercise-2/BankAccount/Program.cs b/week-1/day-2/exercise-2/BankAccount/Program.cs index c58c30e2..868e5d95 100644 --- a/week-1/day-2/exercise-2/BankAccount/Program.cs +++ b/week-1/day-2/exercise-2/BankAccount/Program.cs @@ -1,10 +1,168 @@ namespace BankAccount +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + { - internal class Program + public abstract class BankAccount { + protected Int64 AccountNumber = 326002120001175; + public Int32 Balance = 30000; + + protected abstract void Deposit(); + protected abstract void Withdraw(); static void Main(string[] args) { - // Create SavingsAccount and CheckingAccount objects and perform operations + Console.WriteLine("bank account"); + + CheckingAccount account = new CheckingAccount(); + + account.Withdraw(); + account.Deposit(); + + SavingsAccount savingsAccount = new SavingsAccount(); + savingsAccount.Withdraw(); + savingsAccount.Deposit(); } } -} \ No newline at end of file + + public class CheckingAccount : BankAccount + { + private int OverdraftLimit = 10000; + public Int32 Checkbalance; + public CheckingAccount() + { + Checkbalance = Balance; + Console.WriteLine("Account Balance is" + Checkbalance); + + } + protected override void Deposit() + { + + Console.WriteLine("how much you want to Deposit In current account"); + Int32 Money = Convert.ToInt32(Console.ReadLine()); + Boolean flg = false; + if (OverdraftLimit >= Money) + { + Checkbalance = Checkbalance + Money; + flg = true; + } + else + { + flg = false; + } + if (flg) + { + + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Your Deposit sucessful!! "); + Console.ResetColor(); + Console.WriteLine("Your current account balance is " + Checkbalance); + } + else + { + + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("Your Deposit failed!! "); + Console.ResetColor(); + } + } + protected override void Withdraw() + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine("how much you want to withdraw from current account"); + Console.ResetColor(); + Int32 Money = Convert.ToInt32(Console.ReadLine()); + Boolean flag = false; + if (OverdraftLimit >= Money) + { + flag = true; + Checkbalance = Checkbalance - Money; + } + else + { + flag = false; + } + if (flag) + { + + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("WITHDRAW SUCESSFUL !! "); + Console.ResetColor(); + Console.WriteLine("Your current account balance is " + Checkbalance); + } + else + { + + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("WITHDRAW failed !! "); Console.ResetColor(); + } + } + } + class SavingsAccount : BankAccount + { + private int InterestRate; + private int OverdraftLimits = 10000; + public Int32 Checkbal; + public SavingsAccount() + { + Checkbal = Balance; + } + protected override void Deposit() + { + Console.WriteLine("how much you want to Deposit In saving account"); + int Money = Convert.ToInt32(Console.ReadLine()); + Boolean flg = false; + if (OverdraftLimits >= Money) + { + flg = true; + Checkbal = Checkbal + Money; + } + else + { + flg = false; + } + if (flg) + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Your Deposit sucessful!! "); Console.ResetColor(); + Console.WriteLine("Your current account balance is " + Checkbal); + } + else + { + + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("Your Deposit failed !!"); Console.ResetColor(); + } + } + protected override void Withdraw() + { + Console.WriteLine("how much you want to withdraw In saving account"); + int Money = Convert.ToInt32(Console.ReadLine()); + bool flg = false; + if (OverdraftLimits >= Money) + { + flg = true; + Checkbal = Checkbal - Money; + } + else + { + flg = false; + } + if (flg) + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("withdraw sucessful!!"); Console.ResetColor(); + Console.WriteLine("Your current account balance is " + Checkbal); + } + else + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("WITHDRAW failed !! "); Console.ResetColor(); + } + } + } + +} diff --git a/week-1/day-2/exercise-3/AnimalExercise/Program.cs b/week-1/day-2/exercise-3/AnimalExercise/Program.cs index 5928b7cb..1f6528be 100644 --- a/week-1/day-2/exercise-3/AnimalExercise/Program.cs +++ b/week-1/day-2/exercise-3/AnimalExercise/Program.cs @@ -5,6 +5,65 @@ internal class Program static void Main(string[] args) { // Create a list of Animal objects, add Dog and Cat instances, and call their methods + String Name; + int Age; + protected abstract void MakeSound(); + + static void Main(string[] args) + { + Console.WriteLine("animals"); + List animals = new List(); + + Dog dog = new Dog { Name = "lebradog", Age = 3 }; + Dog dog2 = new Dog { Name = "bulldog", Age = 7 }; + Cat cat = new Cat { Name = "whisky", Age = 2 }; + Cat cat2 = new Cat { Name = "billi", Age = 2 }; + + animals.Add(dog); + animals.Add(dog2); + animals.Add(cat); + animals.Add(cat2); + + foreach (var animal in animals) + { + Console.WriteLine("Name:" + animal.Name + " , Age: " + animal.Age); + + animal.MakeSound(); + + if (animal is IMovable movable) + { + movable.move(); + } + + } + } + } + + + class Dog : Animal, IMovable + { + protected override void MakeSound() + { + Console.WriteLine("Woof"); + } + public void move() + { + Console.WriteLine("dog is moving ."); } } -} \ No newline at end of file + class Cat : Animal, IMovable + { + protected override void MakeSound() + { + Console.WriteLine("Meow"); + } + public void move() + { + Console.WriteLine("cat is moving ."); + } + } + interface IMovable + { + public void move(); + } +} diff --git a/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs b/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs index 77395b3a..f48a0ffc 100644 --- a/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs +++ b/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs @@ -4,7 +4,261 @@ internal class Program { static void Main(string[] args) { - Console.WriteLine("Hello, World!"); + Console.WriteLine("Welcome to VehicleManagementSystem"); + + IRepository vehicleRepository = new VehicleRepository(); + VehicleService vehicleService = new VehicleService(vehicleRepository); + + while (true) + + { + Console.ForegroundColor = ConsoleColor.Cyan; + Console.WriteLine("Choose an option:"); + Console.WriteLine("1. Add Vehicle"); + Console.WriteLine("2. Remove Vehicle"); + Console.WriteLine("3. Show Vehicles"); + Console.WriteLine("4. Exit"); + Console.ResetColor(); + int choice; + if (int.TryParse(Console.ReadLine(), out choice)) + { + switch (choice) + { + case 1: + Console.ForegroundColor = ConsoleColor.Blue; + + Console.WriteLine("Choose a vehicle type: Car or Truck"); + String vehicleTypeChoice = Console.ReadLine(); + Console.ResetColor(); + if (vehicleTypeChoice == "Car" || vehicleTypeChoice == "car") + { + vehicleService.AddVehicle(new CarFactory()); + } + else if (vehicleTypeChoice == "Truck" || vehicleTypeChoice == "truck") + { + vehicleService.AddVehicle(new TruckFactory()); + } + + break; + + case 2: + Console.WriteLine("Enter the ID of the vehicle to remove:"); + Int16 idToRemove = Convert.ToInt16(Console.ReadLine()); + vehicleService.RemoveVehicle(idToRemove); + break; + + case 3: + + vehicleService.ListVehicles(); + break; + + case 4: + return; + + default: + Console.WriteLine("invalid choice !"); + break; + } + } + else + { + Console.WriteLine("Invalid input. Please enter a valid option."); + } + + + VehicleLogger logger = VehicleLogger.Instance; + logger.Log("Vehicle operation completed"); + + + } + } + + public interface IVehicle + { + int Id { get; set; } + void Drive(); + } + + public class Car : IVehicle + { + public int Id { get; set; } + public void Drive() + { + ; + Console.WriteLine("driving a car with speed 120km/hour"); + + } + } + + + public class Truck : IVehicle + { + public int Id { get; set; } + public void Drive() + { + Console.WriteLine("driving a truck with speed 20km/hour"); + + } + } + public sealed class VehicleLogger + { + private static VehicleLogger instance; + private VehicleLogger() { } + + public static VehicleLogger Instance + { + get + { + if (instance == null) + { + instance = new VehicleLogger(); + } + return instance; + } + } + + public void Log(string message) + { + Console.WriteLine("Logging:" + message); + } + } + public abstract class VehicleFactory + { + public abstract IVehicle CreateVehicle(); + + public void DoSomethingWithVehicle() + { + IVehicle vehicle = CreateVehicle(); + Console.WriteLine("vehicle created !"); + vehicle.Drive(); + } + } + public class CarFactory : VehicleFactory + { + public override IVehicle CreateVehicle() + { + return new Car(); + } + } + + public class TruckFactory : VehicleFactory + { + public override IVehicle CreateVehicle() + { + return new Truck(); + } + } + + public interface IRepository + { + T GetById(int id); + IEnumerable GetAll(); + void Add(T entity); + void Update(T entity); + void Delete(T entity); + } + public class VehicleRepository : IRepository + { + private List vehicles = new List(); + public void Add(IVehicle entity) + { + entity.Id = GenerateNextId(); + vehicles.Add(entity); + } + public IVehicle GetById(int id) + { + return vehicles.FirstOrDefault(vehicle => vehicle.Id == id); + } + + public IEnumerable GetAll() + { + return vehicles; + } + + + + + public void Update(IVehicle entity) + { + IVehicle existingVehicle = vehicles.FirstOrDefault(vehicle => vehicle.Id == entity.Id); + if (existingVehicle != null) + { + // Update logic here + } + } + private int GenerateNextId() + { + if (vehicles.Count == 0) + { + return 1; + } + return vehicles.Max(vehicle => vehicle.Id) + 1; + } + public void Delete(IVehicle entity) + { + vehicles.Remove(entity); + } + } + public class VehicleService + { + private readonly IRepository vehicleRepository; + + public VehicleService(IRepository repository) + { + vehicleRepository = repository; + } + + public void AddVehicle(VehicleFactory factory) + { + IVehicle vehicle = factory.CreateVehicle(); + vehicleRepository.Add(vehicle); + } + + public void RemoveVehicle(int id) + { + IVehicle vehicle = vehicleRepository.GetById(id); + if (vehicle != null) + { + vehicleRepository.Delete(vehicle); + } + } + + public void ListVehicles() + { + IEnumerable vehicles = vehicleRepository.GetAll(); + + foreach (var vehicle in vehicles) + { + if (vehicle is Car) + { + + Console.ForegroundColor = ConsoleColor.DarkYellow; + Console.WriteLine("Vehicle ID :" + vehicle.Id + " , Vehicle Name : Car "); + Console.ResetColor(); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Vehicle ID :" + vehicle.Id + " , Vehicle Name : Truck "); + Console.ResetColor(); + } + + } + } + + public void DoSomethingWithVehicle(int id) + { + IVehicle vehicle = vehicleRepository.GetById(id); + if (vehicle != null) + { + // Perform some action with the vehicle + + Console.WriteLine("do nothing with vehicle !"); + + } + } + } + } } \ No newline at end of file From a10f4a23059a2b3d0d45a9528a11510d4f5f49a9 Mon Sep 17 00:00:00 2001 From: pawankhandwe Date: Wed, 9 Aug 2023 12:27:15 +0530 Subject: [PATCH 2/9] Day3 --- week-1/day-3/exercise-1/FactorialApp/Program.cs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/week-1/day-3/exercise-1/FactorialApp/Program.cs b/week-1/day-3/exercise-1/FactorialApp/Program.cs index f116eeca..f4fc9712 100644 --- a/week-1/day-3/exercise-1/FactorialApp/Program.cs +++ b/week-1/day-3/exercise-1/FactorialApp/Program.cs @@ -1,4 +1,6 @@ -namespace FactorialApp +using System; + +namespace FactorialApp { public class Program { @@ -14,6 +16,18 @@ public static void Main() public static long CalculateFactorial(int number) { + long result = number; + int count = 1; + + while (count < number) + { + result = result * count; + count++; + + } + + Console.WriteLine("facorial is " + result); + return result; throw new NotImplementedException(); } } From 70537e075d2b68e7e104ba280618c18f9b30f286 Mon Sep 17 00:00:00 2001 From: pawankhandwe Date: Wed, 9 Aug 2023 15:37:17 +0530 Subject: [PATCH 3/9] Shortestpath --- week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs b/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs index a4ec62d9..8c02d7d6 100644 --- a/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs +++ b/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs @@ -223,7 +223,7 @@ public int[] DijkstraShortestPath(int source) visited[i] = false; } - distances[source] = int.MinValue; + distances[source] = 0; for (int count = 0; count < vertices - 1; count++) { From 3e8d903785c191d96d888472f8b738af722afb30 Mon Sep 17 00:00:00 2001 From: pawankhandwe Date: Thu, 10 Aug 2023 15:59:28 +0530 Subject: [PATCH 4/9] Day4 --- .../day-4/exercise-1/StackApp/CustomStack.cs | 34 +++++++++ .../day-4/exercise-1/StackApp/ICustomStack.cs | 28 +++++++ week-1/day-4/exercise-1/StackApp/Program.cs | 16 +++- .../day-4/exercise-1/StackApp/StackApp.csproj | 4 + .../day-4/exercise-2/IteratorsApp/Program.cs | 20 ++++- .../exercise-3/LinqToObjectsApp/Program.cs | 75 +++++++++++++------ .../day-4/exercise-4/LinqToXmlApp/Program.cs | 23 +++++- .../QueryOptimizationApp/Program.cs | 3 +- .../exercise-6/LinqFilterAndSort/Program.cs | 28 ++++++- .../exercise-7/LinqListNumbers/Program.cs | 38 ++++++++++ .../exercise-8/LinqGroupAggregate/Program.cs | 57 +++++++++++++- 11 files changed, 293 insertions(+), 33 deletions(-) create mode 100644 week-1/day-4/exercise-1/StackApp/CustomStack.cs diff --git a/week-1/day-4/exercise-1/StackApp/CustomStack.cs b/week-1/day-4/exercise-1/StackApp/CustomStack.cs new file mode 100644 index 00000000..380452c7 --- /dev/null +++ b/week-1/day-4/exercise-1/StackApp/CustomStack.cs @@ -0,0 +1,34 @@ +namespace StackApp +{ + using System; + using System.Collections.Generic; + + + internal class CustomStack : ICustomStack + { + bool ICustomStack.IsEmpty() + { + + throw new NotImplementedException(); + } + + int ICustomStack.Pop() + { + + throw new NotImplementedException(); + } + + void ICustomStack.Push(int item) + { + + + + + throw new NotImplementedException(); + } + } + + + + +} \ No newline at end of file diff --git a/week-1/day-4/exercise-1/StackApp/ICustomStack.cs b/week-1/day-4/exercise-1/StackApp/ICustomStack.cs index 55f3936d..3aee51fb 100644 --- a/week-1/day-4/exercise-1/StackApp/ICustomStack.cs +++ b/week-1/day-4/exercise-1/StackApp/ICustomStack.cs @@ -1,5 +1,33 @@ namespace StackApp { + public class CustomStack : ICustomStack + { + private List items = new List(); + + public void Push(T item) + { + items.Add(item); + } + + public T Pop() + { + if (items.Count == 0) + { + throw new InvalidOperationException("Stack is empty"); + } + + int lastIndex = items.Count - 1; + T poppedItem = items[lastIndex]; + items.RemoveAt(lastIndex); + return poppedItem; + } + + public bool IsEmpty() + { + return items.Count == 0; + } + } + internal interface ICustomStack { void Push(T item); diff --git a/week-1/day-4/exercise-1/StackApp/Program.cs b/week-1/day-4/exercise-1/StackApp/Program.cs index e089f665..6e6abc43 100644 --- a/week-1/day-4/exercise-1/StackApp/Program.cs +++ b/week-1/day-4/exercise-1/StackApp/Program.cs @@ -4,13 +4,23 @@ internal class Program { static void Main(string[] args) { + ICustomStack intstack = new CustomStack(); + intstack.Push(1); + Console.WriteLine("pushed 1"); + intstack.Push(2); + Console.WriteLine("pushed 2"); + intstack.Push(3); + + Console.WriteLine("pushed 3"); //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 + + Console.WriteLine("poped "+ intstack.Pop()); + Console.WriteLine("poped "+ intstack.Pop()); + + Console.WriteLine("not empty !"+intstack.IsEmpty()); } } } \ No newline at end of file diff --git a/week-1/day-4/exercise-1/StackApp/StackApp.csproj b/week-1/day-4/exercise-1/StackApp/StackApp.csproj index f02677bf..3f3f08e6 100644 --- a/week-1/day-4/exercise-1/StackApp/StackApp.csproj +++ b/week-1/day-4/exercise-1/StackApp/StackApp.csproj @@ -7,4 +7,8 @@ enable + + + + diff --git a/week-1/day-4/exercise-2/IteratorsApp/Program.cs b/week-1/day-4/exercise-2/IteratorsApp/Program.cs index f3cb1ae8..d15d059b 100644 --- a/week-1/day-4/exercise-2/IteratorsApp/Program.cs +++ b/week-1/day-4/exercise-2/IteratorsApp/Program.cs @@ -5,15 +5,31 @@ internal class Program static void Main(string[] args) { var fibonacci = FibonacciSequence().Take(10); + Console.WriteLine("PROGRAM TO DISPLAY 10 NUMBERS IN THE FIBONACCI SEQUENCE"); foreach (int number in fibonacci) { Console.WriteLine(number); } } - // 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 + //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() { + List fibonacci = new List(); + int a = 0, b = 1; + fibonacci.Add(a); + fibonacci.Add(b); + + + for (int i = 2; i < 10; i++) + { + int c = a + b; + fibonacci.Add(c); + a = b; + b = c; + } + + return fibonacci; throw new NotImplementedException(); } } diff --git a/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs b/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs index 95e8ac84..af2f1281 100644 --- a/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs +++ b/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs @@ -1,31 +1,62 @@ -namespace LinqToObjectsApp -{ - internal class Program - { - static void Main(string[] args) + +using LinqToObjectsApp; + +List people = new List { - List people = new List - { - new Person { Name = "John", Age = 25, Country = "USA" }, - new Person { Name = "Jane", Age = 30, 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 - - } - } + new Person { Name = "Pawan", Age=22 , Country="INDIA"}, + new Person { Name = "John", Age = 25, Country = "USA" }, + new Person { Name = "Nitin", Age=22 , Country="INDIA"}, + new Person { Name = "Divyansh", Age=22 , Country="INDIA"}, + new Person { Name = "Jane", Age = 30, 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 + + + + +List peopleFromINDIA = people.Where(p => p.Country == "INDIA").ToList(); +List peopleAbove25 = people.Where(p => p.Age > 25).ToList(); +List sortedPeopleByName = people.OrderBy(p => p.Name).ToList(); +var nameAndCountry = people.Select(p => new { p.Name, p.Country }); +Console.WriteLine("People from INDIA:"); +foreach (var person in peopleFromINDIA) +{ + Console.WriteLine($"Name: {person.Name}, Country: {person.Country}"); +} + +Console.WriteLine("\nPeople above 25:"); +foreach (var person in peopleAbove25) +{ + Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); +} + +Console.WriteLine("\nPeople sorted by name:"); +foreach (var person in sortedPeopleByName) +{ + Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Country: {person.Country}"); +} + +Console.WriteLine("\nName and Country of all people:"); +foreach (var person in nameAndCountry) +{ + Console.WriteLine($"Name: {person.Name}, Country: {person.Country}"); +} +namespace LinqToObjectsApp +{ public class Person { public string Name { get; set; } public int Age { get; set; } public string Country { get; set; } } + + } \ 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..16d2bc2c 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 { @@ -38,6 +40,25 @@ static void Main(string[] args) // Write the title of all books with genre "Genre 1" to the console + XDocument xdoc = XDocument.Parse(xmlString); + + IEnumerable allTitles = xdoc.Descendants("Title").Select(title => title.Value); + Console.WriteLine("All Titles:"); + foreach (string title in allTitles) + { + Console.WriteLine(title); + } + + IEnumerable genre1Titles = xdoc.Descendants("Book") + .Where(book => book.Element("Genre").Value == "Genre 2") + .Select(book => book.Element("Title").Value); + + Console.WriteLine("\nTitles with Genre 2:"); + foreach (string title in genre1Titles) + { + Console.WriteLine(title); + } + } } } \ No newline at end of file diff --git a/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs b/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs index b18cea78..2d09775c 100644 --- a/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs +++ b/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs @@ -15,7 +15,8 @@ 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..5b57e512 100644 --- a/week-1/day-4/exercise-6/LinqFilterAndSort/Program.cs +++ b/week-1/day-4/exercise-6/LinqFilterAndSort/Program.cs @@ -1,4 +1,6 @@ -namespace LinqFilterAndSort +using System; + +namespace LinqFilterAndSort { internal class Program { @@ -7,6 +9,30 @@ 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 people = new List + { + new Person { Name = "pawan", Age = 22 }, + new Person { Name = "piyush", Age = 10 }, + new Person { Name = "divyansh", Age = 22 }, + new Person { Name = "krishna", Age = 48 }, + new Person { Name = "nitin", Age = 22 } + }; + + List filteredAndSorted = people.Where(person => person.Age > 21) + .OrderBy(person => person.Age).ToList(); + Console.WriteLine("Filtered and Sorted People:"); + foreach (var person in filteredAndSorted) + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); + + } + Console.ResetColor(); } } + class Person + { + public string Name { 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..f74047ed 100644 --- a/week-1/day-4/exercise-7/LinqListNumbers/Program.cs +++ b/week-1/day-4/exercise-7/LinqListNumbers/Program.cs @@ -13,6 +13,44 @@ static void Main(string[] args) // 3. Calculate the sum of all numbers // 4. Calculate the average of all numbers // 5. Find the minimum and maximum values in the list + + List evenNumbers = numbers.Where(num => num % 2 == 0).ToList(); + + int specificValue = 20; + List greaterValue = numbers.Where(num => num > specificValue).ToList(); + + int sum = numbers.Sum(); + + double average = numbers.Average(); + + int minimum = numbers.Min(); + int maximum = numbers.Max(); + + + Console.WriteLine("Even Numbers:"); + + Console.ForegroundColor = ConsoleColor.Blue; + foreach (int num in evenNumbers) + { + Console.Write(num + " "); + } + Console.ResetColor(); + Console.WriteLine("\nNumbers Greater Than " + specificValue + ":"); + + Console.ForegroundColor = ConsoleColor.Blue ; + foreach (int num in greaterValue) + { + Console.Write(num + " "); + } + + Console.WriteLine("\nSum: " + sum); + Console.ForegroundColor = ConsoleColor.Magenta; + Console.WriteLine("Average: " + average); + Console.ResetColor(); + Console.WriteLine("Minimum: " + minimum); + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Maximum: " + maximum); + Console.ResetColor(); } } } \ 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..028c3adf 100644 --- a/week-1/day-4/exercise-8/LinqGroupAggregate/Program.cs +++ b/week-1/day-4/exercise-8/LinqGroupAggregate/Program.cs @@ -1,7 +1,7 @@ namespace LinqGroupAggregate { internal class Program - { + { static void Main(string[] args) { // Create a list of Product objects @@ -14,12 +14,63 @@ static void Main(string[] args) new Product { Name = "Jeans", Category = "Clothing", Price = 60.00M }, new Product { Name = "Sneakers", Category = "Footwear", Price = 100.00M } }; - // Use LINQ to perform the following operations: // 1. Group products by category // 2. Count the number of products in each category // 3. Calculate the total price of products in each category // 4. Find the most expensive product in each category + + + + var productscategory = products.GroupBy(product => product.Category); + + // 2. Count the number of products in each category + var productCounts = productscategory.ToDictionary(group => group.Key, group => group.Count()); + + // 3. Calculate the total price of products in each category + var totalPrices = productscategory.ToDictionary(group => group.Key, group => group.Sum(product => product.Price)); + + // 4. Find the most expensive product in each category + var expensiveProducts = productscategory.ToDictionary(group => group.Key, group => group.OrderByDescending(product => product.Price).FirstOrDefault()); + + + // Print the results + Console.WriteLine("Group products by category:"); + Console.ForegroundColor = ConsoleColor.DarkRed; + foreach (var group in productscategory) + { + Console.WriteLine("Category: " + group.Key); + foreach (var product in group) + { + Console.WriteLine($" Product: {product.Name}, Price: {product.Price}"); + } + } + Console.ResetColor(); + Console.WriteLine("\nProduct Counts by Category:"); + + Console.ForegroundColor = ConsoleColor.DarkYellow; + foreach (var kvp in productCounts) + { + Console.WriteLine($"Category: {kvp.Key}, Count: {kvp.Value}"); + } + + Console.ResetColor(); + Console.WriteLine("\nTotal Prices by Category:"); + + Console.ForegroundColor = ConsoleColor.Green; + foreach (var kvp in totalPrices) + { + Console.WriteLine($"Category: {kvp.Key}, Total Price: {kvp.Value:C}"); + } + Console.ResetColor(); + Console.WriteLine("\nMost Expensive Products by Category:"); + Console.ForegroundColor = ConsoleColor.Magenta; + foreach (var kvp in expensiveProducts) + { + Console.WriteLine($"Category: {kvp.Key}, Product: {kvp.Value?.Name}, Price: {kvp.Value?.Price:C}"); + } + Console.ResetColor(); } } -} \ No newline at end of file + +} From 2f17f080c1a66c7949f96bd4bdadb7be6b1c0fa6 Mon Sep 17 00:00:00 2001 From: pawankhandwe Date: Fri, 11 Aug 2023 15:11:53 +0530 Subject: [PATCH 5/9] day-5 --- .../FileLoggerDisposableApp/Program.cs | 34 ++++++++-- .../Program.cs | 52 +++++++++++---- .../exercise-3/AsyncAwaitBasics/Program.cs | 32 +++++++-- .../AsynAwaitWeatherForcasting.csproj | 4 ++ .../AsynAwaitWeatherForcasting/Program.cs | 65 +++++++++++++++---- 5 files changed, 155 insertions(+), 32 deletions(-) diff --git a/week-1/day-5/exercise-1/FileLoggerDisposableApp/Program.cs b/week-1/day-5/exercise-1/FileLoggerDisposableApp/Program.cs index 30a23ac7..d457068d 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 + using (FileLogger logger = new FileLogger("C:\\Users\\admin\\log.txt")) + { + logger.Log("This is a log entry."); + logger.Log("Another log entry."); + } + } } @@ -14,17 +20,37 @@ class FileLogger : IDisposable public FileLogger(string filePath) { - // Initialize StreamWriter instance + _writer = new StreamWriter(filePath, append: true); } public void Dispose() { - // Implement IDisposable pattern + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (_writer != null) + { + _writer.Dispose(); + _writer = null; + } + } } public void Log(string message) { - // Write message to the file + if (_writer != null) + { + _writer.WriteLine($"{DateTime.Now}: {message}"); + _writer.Flush(); + } } } -} \ 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..a9de90ae 100644 --- a/week-1/day-5/exercise-2/CovariantAndContravariantGenerics/Program.cs +++ b/week-1/day-5/exercise-2/CovariantAndContravariantGenerics/Program.cs @@ -1,32 +1,60 @@ -namespace CovariantAndContravariantGenerics + +namespace CovariantAndContravariantGenerics { interface IProcessor { TResult Process(TInput input); } - class StringToIntProcessor : IProcessor + internal class ObjectToIntProcessor : IProcessor { - // Implement Process method - public int Process(string input) + public int Process(Program input) { - throw new NotImplementedException(); + return Convert.ToInt32(input._input); } } - class DoubleToStringProcessor : IProcessor + public class MyClass { - // Implement Process method - public string Process(double input) + public double inputdouble { get; set; } + public MyClass(double inputDouble) { - throw new NotImplementedException(); + this.inputdouble = inputDouble; + } + + } + + class DoubleToObjectProcessor : IProcessor + { + public MyClass Process(double input) + { + + return new MyClass(input); } } - internal class Program + + internal class Program { + public string _input { get; set; } + static void Main(string[] args) { - // Demonstrate covariance and contravariance with IProcessor interface + + Program program = new Program() + { + _input = "42" + }; + IProcessor objectToIntCovariantProcessor = new ObjectToIntProcessor(); + int intValue = objectToIntCovariantProcessor.Process(program); + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Covariant Processor Output (object to int): " + intValue); + + IProcessor doubleToObjectContravariantProcessor = new DoubleToObjectProcessor(); + + MyClass myobj = doubleToObjectContravariantProcessor.Process(3.14159); + + Console.WriteLine("Contravariant Processor Output (double to Object): " + myobj.inputdouble); + Console.ResetColor(); } } -} \ 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..ca05b248 100644 --- a/week-1/day-5/exercise-3/AsyncAwaitBasics/Program.cs +++ b/week-1/day-5/exercise-3/AsyncAwaitBasics/Program.cs @@ -1,20 +1,42 @@ -namespace AsyncAwaitBasics +using System; +using System.Diagnostics; +using System.Threading.Tasks; + +namespace AsyncAwaitBasics { internal class Program { static async Task Main(string[] args) { - // Call PerformCalculations and measure time taken using Stopwatch + int numberOfTasks = 5; // You can change the number of tasks as needed + + Stopwatch stopwatch = new Stopwatch(); + stopwatch.Start(); + + await PerformCalculations(numberOfTasks); + + stopwatch.Stop(); + + Console.WriteLine($"All tasks completed in {stopwatch.ElapsedMilliseconds} ms"); } static async Task SimulateLongRunningTask(int delayInSeconds) { - // Implement long-running task simulation + Console.WriteLine($"Task with {delayInSeconds} seconds delay started."); + await Task.Delay(delayInSeconds * 1000); + Console.WriteLine($"Task with {delayInSeconds} seconds delay completed."); } static async Task PerformCalculations(int numberOfTasks) { - // Start long-running tasks concurrently and wait for them to complete + Task[] tasks = new Task[numberOfTasks]; + + for (int i = 0; i < numberOfTasks; i++) + { + tasks[i] = SimulateLongRunningTask(i + 1); // Simulate longer delay for each task + } + + await Task.WhenAll(tasks); } } -} \ 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..193a12af 100644 --- a/week-1/day-5/exercise-4/AsynAwaitWeatherForcasting/Program.cs +++ b/week-1/day-5/exercise-4/AsynAwaitWeatherForcasting/Program.cs @@ -1,21 +1,64 @@ -namespace AsynAwaitWeatherForcasting +using Newtonsoft.Json; +using System; +using System.Net.Http; +using System.Threading.Tasks; + +namespace AsynAwaitWeatherForcasting { internal class Program { - static void Main(string[] args) + + static async Task Main(string[] args) { string city = "Vadodara, India"; - // Call the method to fetch weather data - // Display the weather data with city name + string apiKey = "1e4d999bb01f734b6185144802f2b581"; + double latitude = 22.3072; + double longitude = 73.1812; + + string url = $"https://api.openweathermap.org/data/2.5/weather?lat={latitude}&lon={longitude}&appid={apiKey}"; + + WeatherData weatherData = await FetchWeatherDataAsync(url); + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine($"Weather in {city}:"); + Console.BackgroundColor = ConsoleColor.White; + Console.ForegroundColor = ConsoleColor.DarkBlue; + Console.WriteLine("Temperature: "+(int)(weatherData.Main.Temp-273.15)+"°C"); + Console.WriteLine($"Weather: {weatherData.Weather[0].Description}"); + Console.ResetColor(); + } - // 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 json = await response.Content.ReadAsStringAsync(); + WeatherData weatherData = JsonConvert.DeserializeObject(json); + return weatherData; + } + else + { + throw new Exception($"Failed to fetch weather data. Status code: {response.StatusCode}"); + } } } -} \ No newline at end of file + + public class WeatherData + { + public MainData Main { get; set; } + public WeatherDescription[] Weather { get; set; } + } + + public class MainData + { + public float Temp { get; set; } + } + + public class WeatherDescription + { + public string Description { get; set; } + } +} From 8dbf3b867bcbc515a07bb32e53cf0bc0f9a6f7a5 Mon Sep 17 00:00:00 2001 From: pawankhandwe Date: Sat, 12 Aug 2023 18:54:52 +0530 Subject: [PATCH 6/9] firstProject --- .../VehicleManagementSystem/Program.cs | 60 +- .../LibraryManagement/Program.cs | 652 +++++++++++++++++- 2 files changed, 685 insertions(+), 27 deletions(-) diff --git a/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs b/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs index f48a0ffc..eec44fdf 100644 --- a/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs +++ b/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs @@ -42,13 +42,12 @@ static void Main(string[] args) break; case 2: - Console.WriteLine("Enter the ID of the vehicle to remove:"); - Int16 idToRemove = Convert.ToInt16(Console.ReadLine()); - vehicleService.RemoveVehicle(idToRemove); + + vehicleService.RemoveVehicle(); break; case 3: - + vehicleService.ListVehicles(); break; @@ -215,35 +214,54 @@ public void AddVehicle(VehicleFactory factory) vehicleRepository.Add(vehicle); } - public void RemoveVehicle(int id) + public void RemoveVehicle() { - IVehicle vehicle = vehicleRepository.GetById(id); - if (vehicle != null) + IEnumerable vehicles = vehicleRepository.GetAll(); + if (vehicles.Any()) + { + Console.WriteLine("Enter the ID of the vehicle to remove:"); + Int16 id = Convert.ToInt16(Console.ReadLine()); + IVehicle vehicle = vehicleRepository.GetById(id); + if (vehicle != null) + { + vehicleRepository.Delete(vehicle); + } + } + else { - vehicleRepository.Delete(vehicle); + Console.ForegroundColor= ConsoleColor.Red; + Console.WriteLine("no vehicles are available in factory to remove !"); + Console.ResetColor(); } } public void ListVehicles() { IEnumerable vehicles = vehicleRepository.GetAll(); - - foreach (var vehicle in vehicles) + if (vehicles.Any()) { - if (vehicle is Car) - { - Console.ForegroundColor = ConsoleColor.DarkYellow; - Console.WriteLine("Vehicle ID :" + vehicle.Id + " , Vehicle Name : Car "); - Console.ResetColor(); - } - else + foreach (var vehicle in vehicles) { - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("Vehicle ID :" + vehicle.Id + " , Vehicle Name : Truck "); - Console.ResetColor(); - } + if (vehicle is Car) + { + Console.ForegroundColor = ConsoleColor.DarkYellow; + Console.WriteLine("Vehicle ID :" + vehicle.Id + " , Vehicle Name : Car "); + Console.ResetColor(); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Vehicle ID :" + vehicle.Id + " , Vehicle Name : Truck "); + Console.ResetColor(); + } + + } + }else + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("no vehicle is available to show !"); Console.ResetColor(); } } diff --git a/week-1/project/LibraryManagement/LibraryManagement/Program.cs b/week-1/project/LibraryManagement/LibraryManagement/Program.cs index 39a80fab..14001bd1 100644 --- a/week-1/project/LibraryManagement/LibraryManagement/Program.cs +++ b/week-1/project/LibraryManagement/LibraryManagement/Program.cs @@ -1,4 +1,9 @@ -namespace LibraryManagement +using System; +using System.Collections.Generic; +using System.Net; +using static System.Reflection.Metadata.BlobBuilder; + +namespace LibraryManagement { internal class Program { @@ -8,6 +13,7 @@ static void Main(string[] args) List books = new List(); List authors = new List(); List borrowers = new List(); + List borrowersDetail = new List(); // Main program loop while (true) @@ -22,10 +28,84 @@ static void Main(string[] args) // Add cases for each menu option case 1: // Add a book + Book.AddBook(books,authors); + + break; + case 2: + // Add a book + Book.UpdateBook(books); + + break; + case 3: + // Add a book + Book.DeleteBook(books); + + break; + case 4: + // Add a book + Book.ListAllBooks(books); + + break; + case 5: + // Add a book + Author.AddAuthor(authors,books); + + break; + case 6: + // Add a book + Author.UpdateAuthor(authors); + + break; + case 7: + // Add a book + Author.DeleteAuthor(authors); + + break; + case 8: + // Add a book + Author.ListAllAuthor(authors); + + break; + case 9: + // Add a book + Borrower.AddBorrower(borrowers); + + break; + case 10: + // Add a book + Borrower.UpdateBorrower(borrowers); + + break; + case 11: + // Add a book + Borrower.DeleteBorrower(borrowers); + + break; + case 12: + // Add a book + Borrower.ListAllBorrowers(borrowers); + + break; + + case 13: + + Console.WriteLine("Here is Registered borrowers"); + Borrower.ListAllBorrowers(borrowers); + Console.WriteLine("Here is Books"); + Book.ListAllBooks(books); + Borrower.RegisteredBorrowers(borrowers,books, borrowersDetail); + break; + + + case 14: + Borrower.ShowBorrowedBooks(books,borrowersDetail); break; // ... + case 15: + Book.SearchBooks(books); + break; case 16: - // Filter books by status + Book.filterbooks(books); break; default: Console.WriteLine("Invalid option. Please try again."); @@ -42,33 +122,593 @@ static void DisplayMenu() Console.WriteLine("2. Update a book"); Console.WriteLine("3. Delete a book"); Console.WriteLine("4. List all books"); - // ...Add Other options here + Console.WriteLine("5. Add an author"); + Console.WriteLine("6. Update an author"); + Console.WriteLine("7. Delete an author"); + Console.WriteLine("8. List all author"); + Console.WriteLine("9. Add a borrower"); + Console.WriteLine("10. Update a borrower"); + Console.WriteLine("11. Delete a borrower"); + Console.WriteLine("12. List all borrower"); + Console.WriteLine("13. Register a book to a borrower"); + Console.WriteLine("14. Display borrowed books"); + Console.WriteLine("15. Search books"); + Console.WriteLine("16. Filter books by status"); Console.WriteLine("\nEnter the number corresponding to the action you'd like to perform:"); } } // Class definitions - class Book + public class Book { public string Title { get; set; } + + public static int bookIdCounter = 1; + public int BookId { get; set; } public Author Author { get; set; } public int PublicationYear { get; set; } public bool IsAvailable { get; set; } + + + // Add a book + public static void AddBook(List books, List authors) + { + Book newBook = new Book(); + + Console.Write("Enter Title: "); + newBook.Title = Console.ReadLine(); + + Console.Write("Enter Publication Year: "); + newBook.PublicationYear = Convert.ToInt32(Console.ReadLine()); + newBook.IsAvailable = true; + + // Similar code to input Author, PublicationYear, IsAvailable + + + + newBook.BookId = bookIdCounter++; + books.Add(newBook); + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Book Added Sucessfully!"); + Console.ResetColor(); + Author newAuthor = new Author(); + + Console.Write("Enter authors First Name of this book: "); + newAuthor.FirstName = Console.ReadLine(); + Console.Write("Enter authors Last Name of this book: "); + newAuthor.LastName = Console.ReadLine(); + Console.Write("Enter Date of Birth (yyyy-MM-dd): "); + string dobInput = Console.ReadLine(); + DateTime dob; + + if (DateTime.TryParse(dobInput, out dob)) + { + newAuthor.DateOfBirth = dob; + //Console.WriteLine("Date of Birth: " + dob.ToShortDateString()); + } + else + { + Console.WriteLine("Invalid date format. Please enter in yyyy-MM-dd format."); + return; + } + + + newAuthor.authorId = Author.authorIdCounter++; + authors.Add(newAuthor); + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Author Added Sucessfully!"); + Console.ResetColor(); + + } + + public static void UpdateBook(List books) + { + if(books.Any()) { + ListAllBooks(books); + Console.Write("Enter the Id of the book to update: "); + int bookId = Convert.ToInt32(Console.ReadLine()); + + //Book bookToUpdate = books.Find(book => book.BookId == bookId); + Book bookToUpdate = books.FirstOrDefault(book => book.BookId == bookId); + + + if (bookToUpdate != null) + { + Console.Write("Enter Updated Title : "); + bookToUpdate.Title = Console.ReadLine(); + + Console.ForegroundColor = ConsoleColor.DarkYellow; + Console.WriteLine("Book Updated Sucessfully!"); + Console.ResetColor(); + + } + else + { + Console.WriteLine("Book not found."); + } + }else + { + Console.ForegroundColor = ConsoleColor.Blue; + Console.WriteLine("No Books are available please add books first ."); + + Console.ResetColor(); + + } +} + + public static void DeleteBook(List books) + { + if(books.Any()) { + + ListAllBooks(books); + Console.Write("Enter the Id of the book to delete: "); + int bookId = Convert.ToInt32(Console.ReadLine()); + + Book bookIdToDelete = books.Find(book => book.BookId == bookId); + + if (bookIdToDelete != null) + { + books.Remove(bookIdToDelete); + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine("Book Deleted Sucessfully!"); + Console.ResetColor(); + } + else + { + Console.WriteLine("Book not found."); + } + }else + { + Console.ForegroundColor = ConsoleColor.Blue; + Console.WriteLine("No Books are available please add books first ."); + + Console.ResetColor(); + + } + } + + public static void ListAllBooks(List books) + { + if (books.Any()) + { + + Console.ForegroundColor = ConsoleColor.Blue; + Console.WriteLine("List of Books:"); + foreach (Book book in books) + { + Console.WriteLine($"Title: {book.Title} Id :{book.BookId}"); + // Add more properties as needed + } + Console.ResetColor(); + }else + { + Console.ForegroundColor = ConsoleColor.Blue; + Console.WriteLine("No Books are available please add books first ."); + + Console.ResetColor(); + return; + } + } + public static void SearchBooks(List books) + { + if (books.Any()) + { + Console.Write("Enter search keyword: "); + string searchKeyword = Console.ReadLine(); + + //var searchResults = books.Where(book => book.Title.Contains(searchKeyword)); + var searchResults = books.Where(book => book.Title.IndexOf(searchKeyword, StringComparison.OrdinalIgnoreCase) >= 0); + + + Console.ForegroundColor = ConsoleColor.Blue; + if (searchResults.Any()) + { + foreach (var book in searchResults) + { + //Console.WriteLine($"Title: {book.Title}, Author: {book.Author.FirstName} {book.Author.LastName}"); + + Console.WriteLine($"Title: {book.Title} Publication : {book.PublicationYear} Available : {book.IsAvailable}"); + } + + } + else + { + Console.WriteLine("No matching books found."); + } + Console.ResetColor(); + } + else + { + Console.ForegroundColor = ConsoleColor.Blue; + Console.WriteLine("No Books are available please add books first ."); + + Console.ResetColor(); + + } + } + public static void filterbooks(List books) + { + bool desiredStatus = true; + + var filteredBooks = books.Where(book => book.IsAvailable == desiredStatus).ToList(); + Console.ForegroundColor = ConsoleColor.Blue; + if (filteredBooks.Any()) + { + + Console.WriteLine($"Books with availability status IsAvailable = {desiredStatus}:"); + }else + { + desiredStatus = false; + Console.WriteLine($"Books with availability status IsAvailable = {desiredStatus}:"); + } + foreach (var book in filteredBooks) + { + Console.WriteLine($"{book.Title}"); + } + Console.ResetColor(); + } + + + + } - class Author + public class Author { public string FirstName { get; set; } public string LastName { get; set; } + + + public static int authorIdCounter = 1; + public int authorId { get; set; } public DateTime DateOfBirth { get; set; } + + public static void AddAuthor(List authors , Listbooks) + { + Author newAuthor = new Author(); + + + Console.Write("Enter authors First Name: "); + newAuthor.FirstName = Console.ReadLine(); + Console.Write("Enter authors Last Name: "); + newAuthor.LastName = Console.ReadLine(); + Console.Write("Enter Date of Birth (yyyy-MM-dd): "); + string dobInput = Console.ReadLine(); + DateTime dob; + + if (DateTime.TryParse(dobInput, out dob)) + { + newAuthor.DateOfBirth = dob; + //Console.WriteLine("Date of Birth: " + dob.ToShortDateString()); + } + else + { + Console.WriteLine("Invalid date format. Please enter in yyyy-MM-dd format."); + return; + } + + newAuthor.authorId = authorIdCounter++; + authors.Add(newAuthor); + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Author Added Sucessfully!"); + Console.ResetColor(); + Book newBook = new Book(); + + Console.Write("Enter Title to add new book of this author : "); + newBook.Title = Console.ReadLine(); + + Console.Write("Enter Publication Year: "); + newBook.PublicationYear = Convert.ToInt32(Console.ReadLine()); + newBook.IsAvailable = true; + + newBook.BookId = Book.bookIdCounter++; + books.Add(newBook); + + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Book Added Sucessfully!"); + Console.ResetColor(); + + } + + // Update a book + public static void UpdateAuthor(List authors) + { + if (authors.Any()) + { + ListAllAuthor(authors); + + Console.Write("Enter Author ID To Update: "); + int searchAuthorId = Convert.ToInt32(Console.ReadLine()); + //Author NameToUpdate = authors.Find(author => author.authorId == searchAuthorId); + Author NameToUpdate = authors.FirstOrDefault(author => author.authorId == searchAuthorId); + + + if (NameToUpdate != null) + { + + Console.Write("Enter the First Name of the Author to update: "); + NameToUpdate.FirstName = Console.ReadLine(); + Console.Write("Enter the Last Name of the Author to update: "); + NameToUpdate.LastName = Console.ReadLine(); + Console.ForegroundColor = ConsoleColor.DarkYellow; + Console.WriteLine("Author Updated Sucessfully!"); + Console.ResetColor(); + + + } + else + { + Console.WriteLine("Name not found."); + } + }else + { + Console.ForegroundColor = ConsoleColor.Blue; + Console.WriteLine("No Author are available please add author first ."); + + Console.ResetColor(); return; + } + } + + + public static void DeleteAuthor(List authors) + { + if (authors.Any()) + { + Console.Write("Enter the Id of the Author to delete: "); + int AuthorId = Convert.ToInt32(Console.ReadLine()); + + + //Author NameToDelete = authors.Find(author => author.authorId == AuthorId); + Author NameToDelete = authors.FirstOrDefault(author => author.authorId == AuthorId); + + + if (NameToDelete != null) + { + authors.Remove(NameToDelete); + Console.WriteLine("Author deleted."); + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine("Book Deleted Sucessfully!"); + Console.ResetColor(); + } + else + { + Console.WriteLine("Author not found."); + } + } + else + { + Console.ForegroundColor = ConsoleColor.Blue; + Console.WriteLine("No Author are available please add author first ."); + + Console.ResetColor(); return; + } +} + + // List all books + public static void ListAllAuthor(List authors) + { + if (authors.Any()) + { + Console.ForegroundColor = ConsoleColor.Blue; + Console.WriteLine("List of Authors:"); + foreach (Author author in authors) + { + Console.WriteLine($"AuthorID:{author.authorId} FirstName: {author.FirstName}, LastName: {author.LastName} DateOfBirth: {author.DateOfBirth}"); + + } + Console.ResetColor(); + } + else + { + Console.ForegroundColor = ConsoleColor.Blue; + Console.WriteLine("No Author are available please add author first ."); + + Console.ResetColor(); return; + } +} } - class Borrower + public class Borrower { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } + public Book Book { get; set; } + + + public string formattedDueDate { get; set; } + public string formattedborrowedDate { get; set; } + + public static void AddBorrower(List borrowers) + { + Borrower newborrower=new Borrower(); + + Console.Write("Enter Borrowers First Name: "); + newborrower.FirstName = Console.ReadLine(); + Console.Write("Enter Borrowers Last Name: "); + newborrower.LastName = Console.ReadLine(); + Console.Write("Enter Borrowers Email Id: "); + newborrower.Email = Console.ReadLine(); + Console.Write("Enter Borrowers Mob No: "); + newborrower.PhoneNumber = Console.ReadLine(); + + borrowers.Add(newborrower); + + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Borrower Added Sucessfully!"); + Console.ResetColor(); + } + + public static void UpdateBorrower(List borrowers) + { + if (borrowers.Count > 0) + { + ListAllBorrowers(borrowers); + Console.WriteLine("enter Email-Id of borrower to update"); + string EMAIL = Console.ReadLine(); + + Borrower UpdateBorrower = borrowers.Find(borrower => borrower.Email == EMAIL); + + if (UpdateBorrower != null) + { + Console.Write("Enter Borrowers updated First Name: "); + UpdateBorrower.FirstName = Console.ReadLine(); + Console.Write("Enter Borrowers updated Last Name: "); + UpdateBorrower.LastName = Console.ReadLine(); + Console.Write("Enter Borrowers updated Email Id: "); + UpdateBorrower.Email = Console.ReadLine(); + Console.Write("Enter Borrowers updated Mob No: "); + UpdateBorrower.PhoneNumber = Console.ReadLine(); + Console.ForegroundColor = ConsoleColor.DarkYellow; + Console.WriteLine("Borrower Updated Sucessfully!"); + Console.ResetColor(); + } + else + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine("borrower not found."); + Console.ResetColor(); + } + } + else + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine("No borrowers present ."); + Console.ResetColor(); + return; + } + } + + public static void DeleteBorrower(List borrowers) + { + + if (borrowers.Count>0) + { + ListAllBorrowers(borrowers); + Console.WriteLine("enter EMAIL-ID of borrower to delete"); + string EMAIL = Console.ReadLine(); + + Borrower EmailToDelete = borrowers.Find(borrower => borrower.Email == EMAIL ); + + if (EmailToDelete != null) + { + borrowers.Remove(EmailToDelete); + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine("Borrower Deleted Sucessfully!"); + Console.ResetColor(); + } + else + { + Console.WriteLine("borrower not found."); + } + } + else + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine("No borrowers present."); Console.ResetColor(); + return; + } + } + + public static void ListAllBorrowers(List borrowers) + { + if (borrowers.Count == 0) + { + Console.ForegroundColor= ConsoleColor.DarkRed; + Console.WriteLine("No borrowers available."); + Console.ResetColor(); + return; + } + else + { + Console.ForegroundColor = ConsoleColor.Magenta; + Console.WriteLine("List of all borrowers:"); + for (int i = 0; i < borrowers.Count; i++) + { + Console.WriteLine($"{i + 1}. {borrowers[i].FirstName} {borrowers[i].LastName} {borrowers[i].Email} {borrowers[i].PhoneNumber}"); + } + Console.ResetColor (); + } + } + + public static void ShowBorrowedBooks(List books, List borrowersDetail) + { + if (borrowersDetail.Any()) + { + Console.ForegroundColor = ConsoleColor.DarkGreen; + Console.WriteLine("Borrowed Books:"); + + foreach (var book in books) + { + if (!book.IsAvailable) + { + Console.WriteLine($"Book ID: {book.BookId}"); + Console.WriteLine($"Book Title: {book.Title}"); + + } + } + foreach (var borrower in borrowersDetail) + { + Console.WriteLine($"Book borrowers email id is " + + $"{borrower.Email}"); + Console.WriteLine($"Book borrowed date: {borrower.formattedborrowedDate}"); + Console.WriteLine($"Book borrowed due date: {borrower.formattedDueDate}"); + Console.WriteLine(); + + } + + Console.ResetColor(); + }else + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("No Books Borrowed yet !"); + Console.ResetColor(); + + } + } + + internal static void RegisteredBorrowers(List borrowers, List books, List borrowersDetail) + { + if (borrowers.Any()) + { + Console.Write("Enter the Email-Id of the borrower you want to register a book for: "); + string borrowerEmail = Console.ReadLine(); + Borrower borrower = new Borrower(); + Console.Write("Enter tittle of Book "); + String BookName=Console.ReadLine(); + + Book bookToUpdate = books.Find(book => book.Title == BookName); + + if (bookToUpdate != null) + { + borrower.Email = borrowerEmail; + bookToUpdate.IsAvailable = false; + + } + + Console.Write("Enter Borrowed Date (yyyy-mm-dd): "); + DateTime borrowedDate = DateTime.Parse(Console.ReadLine()); + string formattedborrowedDates = borrowedDate.ToString("yyyy-MM-dd"); + borrower.formattedborrowedDate = formattedborrowedDates; + Console.Write("Enter Due Date (yyyy-mm-dd): "); + DateTime dueDate = DateTime.Parse(Console.ReadLine()); + string formattedDueDates = dueDate.ToString("yyyy-MM-dd"); + borrower.formattedborrowedDate = formattedDueDates; + borrowersDetail.Add(borrower); + + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("Book registration successful!"); + Console.ResetColor(); + } + + else + { + Console.ForegroundColor = ConsoleColor.Blue; + Console.WriteLine("No borrower Present Here please add borowwer first ."); + Console.ResetColor(); + } + } } } \ No newline at end of file From 11fd6f457e0232bbfdbd52d79a31d6f557f53e00 Mon Sep 17 00:00:00 2001 From: pawankhandwe Date: Mon, 14 Aug 2023 11:48:23 +0530 Subject: [PATCH 7/9] librarymanagmentsystem --- .../LibraryManagement/Program.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/week-1/project/LibraryManagement/LibraryManagement/Program.cs b/week-1/project/LibraryManagement/LibraryManagement/Program.cs index 14001bd1..1c7dc22b 100644 --- a/week-1/project/LibraryManagement/LibraryManagement/Program.cs +++ b/week-1/project/LibraryManagement/LibraryManagement/Program.cs @@ -420,7 +420,6 @@ public static void UpdateAuthor(List authors) Console.Write("Enter Author ID To Update: "); int searchAuthorId = Convert.ToInt32(Console.ReadLine()); - //Author NameToUpdate = authors.Find(author => author.authorId == searchAuthorId); Author NameToUpdate = authors.FirstOrDefault(author => author.authorId == searchAuthorId); @@ -431,6 +430,20 @@ public static void UpdateAuthor(List authors) NameToUpdate.FirstName = Console.ReadLine(); Console.Write("Enter the Last Name of the Author to update: "); NameToUpdate.LastName = Console.ReadLine(); + Console.Write("Enter Date of Birth of the Author to update (yyyy-MM-dd): "); + string dobInput = Console.ReadLine(); + DateTime dob; + + if (DateTime.TryParse(dobInput, out dob)) + { + NameToUpdate.DateOfBirth = dob; + //Console.WriteLine("Date of Birth: " + dob.ToShortDateString()); + } + else + { + Console.WriteLine("Invalid date format. Please enter in yyyy-MM-dd format."); + return; + } Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Author Updated Sucessfully!"); Console.ResetColor(); @@ -459,7 +472,6 @@ public static void DeleteAuthor(List authors) int AuthorId = Convert.ToInt32(Console.ReadLine()); - //Author NameToDelete = authors.Find(author => author.authorId == AuthorId); Author NameToDelete = authors.FirstOrDefault(author => author.authorId == AuthorId); From ade7de01d479befff65ff7948978eadc46bfdcbf Mon Sep 17 00:00:00 2001 From: pawankhandwe Date: Mon, 14 Aug 2023 16:59:36 +0530 Subject: [PATCH 8/9] week1 --- week-1/day-1/HelloWorldApp | 1 + 1 file changed, 1 insertion(+) create mode 160000 week-1/day-1/HelloWorldApp diff --git a/week-1/day-1/HelloWorldApp b/week-1/day-1/HelloWorldApp new file mode 160000 index 00000000..6bbd865c --- /dev/null +++ b/week-1/day-1/HelloWorldApp @@ -0,0 +1 @@ +Subproject commit 6bbd865c8ecc7f1237bab1ddd55d14e1f1feec2d From 1cdba60dd55db1f2e9212b09f96aa628975005e4 Mon Sep 17 00:00:00 2001 From: pawankhandwe Date: Mon, 14 Aug 2023 18:55:09 +0530 Subject: [PATCH 9/9] project --- .../LibraryManagement/Program.cs | 49 ++++++++++++------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/week-1/project/LibraryManagement/LibraryManagement/Program.cs b/week-1/project/LibraryManagement/LibraryManagement/Program.cs index 1c7dc22b..1708d395 100644 --- a/week-1/project/LibraryManagement/LibraryManagement/Program.cs +++ b/week-1/project/LibraryManagement/LibraryManagement/Program.cs @@ -116,31 +116,42 @@ static void Main(string[] args) static void DisplayMenu() { - // Display the menu options Console.WriteLine("Welcome to the Library Management System!\n"); - Console.WriteLine("1. Add a book"); - Console.WriteLine("2. Update a book"); - Console.WriteLine("3. Delete a book"); - Console.WriteLine("4. List all books"); - Console.WriteLine("5. Add an author"); - Console.WriteLine("6. Update an author"); - Console.WriteLine("7. Delete an author"); - Console.WriteLine("8. List all author"); - Console.WriteLine("9. Add a borrower"); - Console.WriteLine("10. Update a borrower"); - Console.WriteLine("11. Delete a borrower"); - Console.WriteLine("12. List all borrower"); - Console.WriteLine("13. Register a book to a borrower"); - Console.WriteLine("14. Display borrowed books"); - Console.WriteLine("15. Search books"); - - Console.WriteLine("16. Filter books by status"); + + for (int i = 1; i <= 16; i++) + { + Console.ForegroundColor= ConsoleColor.Red; + Console.Write($"{i} "); + Console.ResetColor(); + + switch (i) + { + case 1: Console.WriteLine(". Add a book"); break; + case 2: Console.WriteLine(". Update a book"); break; + case 3: Console.WriteLine(". Delete a book"); break; + case 4: Console.WriteLine(". List all books"); break; + case 5: Console.WriteLine(". Add an author"); break; + case 6: Console.WriteLine(". Update an author"); break; + case 7: Console.WriteLine(". Delete an author"); break; + case 8: Console.WriteLine(". List all authors"); break; + case 9: Console.WriteLine(". Add a borrower"); break; + case 10: Console.WriteLine(". Update a borrower"); break; + case 11: Console.WriteLine(". Delete a borrower"); break; + case 12: Console.WriteLine(". List all borrowers"); break; + case 13: Console.WriteLine(". Register a book to a borrower"); break; + case 14: Console.WriteLine(". Display borrowed books"); break; + case 15: Console.WriteLine(". Search books"); break; + case 16: Console.WriteLine(". Filter books by status"); break; + } + } + Console.WriteLine("\nEnter the number corresponding to the action you'd like to perform:"); } + } // Class definitions - public class Book + public class Book { public string Title { get; set; }