Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void ImportDataFromJson(string jsonFilePath)
- {
- try
- {
- string jsonContent = File.ReadAllText(jsonFilePath);
- List<Pharmacy> pharmacies = JsonConvert.DeserializeObject<List<Pharmacy>>(jsonContent);
- foreach (var pharmacy in pharmacies)
- {
- if (IsValidPharmacy(pharmacy))
- {
- _context.Pharmacies.Add(pharmacy);
- foreach (var medicine in pharmacy.Medicines)
- {
- if (IsValidMedicine(medicine, pharmacy.Id))
- {
- _context.Medicines.Add(medicine);
- }
- else
- {
- PrintErrorMessage($"Medicine {medicine.Name} with producer {medicine.Producer} already exists in the current pharmacy.");
- }
- }
- }
- else
- {
- PrintErrorMessage();
- }
- }
- _context.SaveChanges();
- }
- catch (Exception ex)
- {
- Console.WriteLine($"An error occurred while importing data from JSON: {ex.Message}");
- }
- }
- public void ImportDataFromXml(string xmlFilePath)
- {
- try
- {
- XElement root = XElement.Load(xmlFilePath);
- List<Pharmacy> pharmacies = root.Elements("Pharmacy")
- .Select(pharmacyElement => new Pharmacy
- {
- Id = Convert.ToInt32(pharmacyElement.Element("Id").Value),
- Name = pharmacyElement.Element("Name").Value,
- PhoneNumber = pharmacyElement.Element("PhoneNumber").Value,
- IsNonStop = Convert.ToBoolean(pharmacyElement.Element("IsNonStop").Value),
- Medicines = pharmacyElement.Elements("Medicine")
- .Select(medicineElement => new Medicine
- {
- // Map properties accordingly
- })
- .ToList()
- })
- .ToList();
- foreach (var pharmacy in pharmacies)
- {
- if (IsValidPharmacy(pharmacy))
- {
- _context.Pharmacies.Add(pharmacy);
- foreach (var medicine in pharmacy.Medicines)
- {
- if (IsValidMedicine(medicine, pharmacy.Id))
- {
- _context.Medicines.Add(medicine);
- }
- else
- {
- PrintErrorMessage($"Medicine {medicine.Name} with producer {medicine.Producer} already exists in the current pharmacy.");
- }
- }
- }
- else
- {
- PrintErrorMessage();
- }
- }
- _context.SaveChanges();
- }
- catch (Exception ex)
- {
- Console.WriteLine($"An error occurred while importing data from XML: {ex.Message}");
- }
- }
- private bool IsValidMedicine(Medicine medicine, int currentPharmacyId)
- {
- // Check if the medicine already exists in the current pharmacy
- var existingMedicine = _context.Medicines
- .FirstOrDefault(m => m.Name == medicine.Name && m.Producer == medicine.Producer && m.PharmacyId == currentPharmacyId);
- // Check if the medicine exists in another pharmacy with the same name and producer
- var sameMedicineInOtherPharmacy = _context.Medicines
- .Any(m => m.Name == medicine.Name && m.Producer == medicine.Producer && m.PharmacyId != currentPharmacyId);
- return existingMedicine == null || sameMedicineInOtherPharmacy;
- }
- private void PrintErrorMessage(string message)
- {
- Console.WriteLine($"Invalid Data! {message}");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement