Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Text;
- using Castle.Core.Internal;
- using Trucks.Data.Models;
- using Trucks.Data.Models.Enums;
- using Trucks.DataProcessor.ImportDto;
- namespace Trucks.DataProcessor
- {
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using Data;
- public class Deserializer
- {
- private const string ErrorMessage = "Invalid data!";
- private const string SuccessfullyImportedDespatcher
- = "Successfully imported despatcher - {0} with {1} trucks.";
- private const string SuccessfullyImportedClient
- = "Successfully imported client - {0} with {1} trucks.";
- public static string ImportDespatcher(TrucksContext context, string xmlString)
- {
- var sb = new StringBuilder();
- var despatcherDto = XmlConverter.Deserializer<ImportDespatchersXML>(xmlString, "Despatchers");
- var valiDespatchers = new List<Despatcher>();
- foreach (var dDto in despatcherDto)
- {
- if (!IsValid(dDto))
- {
- sb.AppendLine(ErrorMessage);
- continue;
- }
- if (dDto.Position.IsNullOrEmpty())
- {
- sb.AppendLine(ErrorMessage);
- continue;
- }
- var trucks = new List<Truck>();
- foreach (var tDto in dDto.Trucks)
- {
- if (!IsValid(tDto))
- {
- sb.AppendLine(ErrorMessage);
- continue;
- }
- if (tDto.VinNumber.IsNullOrEmpty())
- {
- sb.AppendLine(ErrorMessage);
- continue;
- }
- trucks.Add(new Truck()
- {
- RegistrationNumber = tDto.RegistrationNumber,
- VinNumber = tDto.VinNumber,
- TankCapacity = tDto.TankCapacity,
- CargoCapacity = tDto.CargoCapacity,
- CategoryType = (CategoryType)tDto.CategoryType,
- MakeType = (MakeType)tDto.MakeType
- });
- }
- Despatcher despatcher = new Despatcher()
- {
- Name = dDto.Name,
- Position = dDto.Position,
- Trucks = trucks
- };
- valiDespatchers.Add(despatcher);
- sb.AppendLine(string.Format(SuccessfullyImportedDespatcher, despatcher.Name, trucks.Count()));
- }
- context.Despatchers.AddRange(valiDespatchers);
- context.SaveChanges();
- return sb.ToString().TrimEnd();
- }
- public static string ImportClient(TrucksContext context, string jsonString)
- {
- throw new NotImplementedException();
- }
- private static bool IsValid(object dto)
- {
- var validationContext = new ValidationContext(dto);
- var validationResult = new List<ValidationResult>();
- return Validator.TryValidateObject(dto, validationContext, validationResult, true);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement