Advertisement
Galina841130

Deserializer

Aug 6th, 2022
872
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.14 KB | None | 0 0
  1. namespace Footballers.DataProcessor
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.ComponentModel.DataAnnotations;
  6.     using System.Globalization;
  7.     using System.IO;
  8.     using System.Linq;
  9.     using System.Text;
  10.     using System.Xml.Serialization;
  11.     using Data;
  12.     using Footballers.Data.Models;
  13.     using Footballers.Data.Models.Enums;
  14.     using Footballers.DataProcessor.ImportDto;
  15.     using Newtonsoft.Json;
  16.  
  17.     public class Deserializer
  18.     {
  19.         private const string ErrorMessage = "Invalid data!";
  20.  
  21.         private const string SuccessfullyImportedCoach
  22.             = "Successfully imported coach - {0} with {1} footballers.";
  23.  
  24.         private const string SuccessfullyImportedTeam
  25.             = "Successfully imported team - {0} with {1} footballers.";
  26.  
  27.         public static string ImportCoaches(FootballersContext context, string xmlString)
  28.         {
  29.             const string rootElement = "Coaches";
  30.             var serializer = new XmlSerializer(typeof(List<CoachXmlImportModel>), new XmlRootAttribute(rootElement));
  31.             var textReader = new StringReader(xmlString);
  32.             var coachesDtos = serializer.Deserialize(textReader) as List<CoachXmlImportModel>;
  33.  
  34.             var validCoaches = new List<Coach>();
  35.             StringBuilder sb = new StringBuilder();
  36.  
  37.             foreach (var coachDto in coachesDtos)
  38.             {
  39.                 if (!IsValid(coachDto) || string.IsNullOrEmpty(coachDto.Nationality))
  40.                 {
  41.                     sb.AppendLine(ErrorMessage);
  42.                     continue;
  43.                 }
  44.  
  45.                 var currentCoach = new Coach
  46.                 {
  47.                     Name = coachDto.Name,
  48.                     Nationality = coachDto.Nationality
  49.                 };
  50.                 foreach (var footballerDto in coachDto.Footballers)
  51.                 {
  52.                     DateTime currentFootballerContractStartDate;
  53.                     var isCurrentFootballerContractStartDateValid = DateTime.TryParseExact(footballerDto.ContractStartDate, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out currentFootballerContractStartDate);
  54.  
  55.                     DateTime currentFootballerContractEndDate;
  56.                     var isCurrentFootballerContractEndDateValid = DateTime.TryParseExact(footballerDto.ContractEndDate, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out currentFootballerContractEndDate);
  57.  
  58.                     bool isCurrentDTOBestSkillTypeValid = Enum.TryParse(footballerDto.BestSkillType, out BestSkillType bestSkillType);
  59.                     bool isCurrentDTOPositionTypeValid = Enum.TryParse(footballerDto.PositionType, out PositionType positionType);
  60.  
  61.                     if (!IsValid(footballerDto)
  62.                         || !isCurrentFootballerContractStartDateValid
  63.                         || !isCurrentFootballerContractEndDateValid
  64.                         || !isCurrentDTOBestSkillTypeValid
  65.                         || !isCurrentDTOPositionTypeValid
  66.                         || currentFootballerContractStartDate > currentFootballerContractEndDate)
  67.                     {
  68.                         sb.AppendLine(ErrorMessage);
  69.                         continue;
  70.                     }
  71.                     currentCoach.Footballers.Add(new Footballer
  72.                     {
  73.                         Name = footballerDto.Name,
  74.                         ContractStartDate = currentFootballerContractStartDate,
  75.                         ContractEndDate = currentFootballerContractEndDate,
  76.                         PositionType = positionType,
  77.                         BestSkillType = bestSkillType,
  78.                         CoachId = currentCoach.Id
  79.                     });
  80.                 }
  81.                 validCoaches.Add(currentCoach);
  82.                 sb.AppendLine(string.Format(SuccessfullyImportedCoach, currentCoach.Name, currentCoach.Footballers.Count));
  83.  
  84.             }
  85.             context.Coaches.AddRange(validCoaches);
  86.             context.SaveChanges();
  87.             return sb.ToString().TrimEnd();
  88.         }
  89.         public static string ImportTeams(FootballersContext context, string jsonString)
  90.         {
  91.             var teamsDtos = JsonConvert.DeserializeObject<IEnumerable<TeamJsonImportModel>>(jsonString);
  92.            
  93.             var validTeams = new List<Team>();
  94.             StringBuilder sb = new StringBuilder();
  95.  
  96.             foreach (var teamDto in teamsDtos)
  97.             {
  98.                 if (!IsValid(teamDto) || teamDto.Trophies < 1)
  99.                 {
  100.                     sb.AppendLine(ErrorMessage);
  101.                     continue;
  102.                 }
  103.                 var currentTeam = new Team
  104.                 {
  105.                     Name = teamDto.Name,
  106.                     Nationality = teamDto.Nationality,
  107.                     Trophies = teamDto.Trophies
  108.                 };
  109.  
  110.                 var footballersIdsInDatabase = context.Footballers.Select(x => x.Id).ToList();
  111.                
  112.                 foreach (var uniqueFootballerId in teamDto.FootballersIds.Distinct())
  113.                 {
  114.                    
  115.                     if (!footballersIdsInDatabase.Contains(uniqueFootballerId))
  116.                     {
  117.                         sb.AppendLine(ErrorMessage);
  118.                         continue;
  119.                     }
  120.                     currentTeam.TeamsFootballers.Add(new TeamFootballer
  121.                     {
  122.                         Team = currentTeam,
  123.                         FootballerId = uniqueFootballerId
  124.                     });
  125.                 }
  126.                 validTeams.Add(currentTeam);
  127.                 sb.AppendLine(string.Format(SuccessfullyImportedTeam, currentTeam.Name, currentTeam.TeamsFootballers.Count));
  128.             }
  129.             context.AddRange(validTeams);
  130.             context.SaveChanges();
  131.             return sb.ToString().TrimEnd();
  132.         }
  133.  
  134.         private static bool IsValid(object dto)
  135.         {
  136.             var validationContext = new ValidationContext(dto);
  137.             var validationResult = new List<ValidationResult>();
  138.  
  139.             return Validator.TryValidateObject(dto, validationContext, validationResult, true);
  140.         }
  141.     }
  142. }
  143.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement