Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text.Json;
- using System.Xml.Linq;
- public class Deserializer
- {
- private readonly MedicinesContext _context;
- public Deserializer(MedicinesContext context)
- {
- _context = context;
- }
- public void ImportDataFromJson(string jsonFilePath)
- {
- try
- {
- string jsonContent = File.ReadAllText(jsonFilePath);
- List<Pharmacy> pharmacies = JsonSerializer.Deserialize<List<Pharmacy>>(jsonContent);
- foreach (var pharmacy in pharmacies)
- {
- if (IsValidPharmacy(pharmacy))
- {
- _context.Pharmacies.Add(pharmacy);
- }
- else
- {
- Console.WriteLine("Error message: Invalid Data!");
- }
- }
- _context.SaveChanges();
- }
- catch (Exception ex)
- {
- Console.WriteLine($"An error occurred while importing data from JSON: {ex.Message}");
- }
- }
- public void ImportDataFromXml(string xmlFilePath)
- {
- try
- {
- XDocument xmlDoc = XDocument.Load(xmlFilePath);
- List<Medicine> medicines = xmlDoc.Descendants("Medicine")
- .Select(m => new Medicine
- {
- Id = int.Parse(m.Element("Id").Value),
- })
- .ToList();
- foreach (var medicine in medicines)
- {
- if (IsValidMedicine(medicine))
- {
- _context.Medicines.Add(medicine);
- }
- else
- {
- Console.WriteLine("Error message: Invalid Data!");
- }
- }
- _context.SaveChanges();
- }
- catch (Exception ex)
- {
- Console.WriteLine($"An error occurred while importing data from XML: {ex.Message}");
- }
- }
- private bool IsValidPharmacy(Pharmacy pharmacy)
- {
- // Пример:
- // if (pharmacy.Name.Length < 2 || pharmacy.Name.Length > 50)
- // {
- // return false;
- // }
- // Аналогично добавям валидация за лекарствата в IsValidMedicine метода.
- return true;
- }
- private bool IsValidMedicine(Medicine medicine)
- {
- // Добавям валидация за лекарството тук, спрямо изискванията от първата секция
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement