Exemplo n.º 1
0
        private static bool IsValidTrip(Trip trip, StationsDbContext db)
        {
            if (trip.ArrivalTime == null || trip.DepartureTime == null || trip.DepartureTime > trip.ArrivalTime)
            {
                return(false);
            }

            if (!db.Trains.Any(t => t.TrainNumber == trip.Train.TrainNumber) ||
                !db.Stations.Any(st => st.Name == trip.OriginStation.Name) ||
                !db.Stations.Any(st => st.Name == trip.DestinationStation.Name))
            {
                return(false);
            }

            if (trip.Status.ToString() == null)
            {
                trip.Status = TripStatus.OnTime;
            }

            TimeSpan timeDifference;

            if (trip.TimeDifference != null && !TimeSpan.TryParseExact(trip.TimeDifference.ToString(), @"hh\:mm", CultureInfo.InvariantCulture, out timeDifference))
            {
                return(false);
            }
            //to do •	Arrival/Departure date may be null or in format “dd/MM/yyyy HH:mm”


            return(true);
        }
Exemplo n.º 2
0
        public static string ExportDelayedTrains(StationsDbContext context, string dateAsString)
        {
            DateTime date = DateTime.ParseExact(dateAsString, "dd/MM/yyyy", CultureInfo.InvariantCulture);

            TrainDto[] delayed = context
                                 .Trains
                                 .Where(tr => tr.Trips.Any(t => t.Status == TripStatus.Delayed && t.DepartureTime <= date))
                                 .Select(t => new
            {
                t.TrainNumber,
                DelayedTrips = t.Trips
                               .Where(tr => tr.Status == TripStatus.Delayed && tr.DepartureTime <= date)
                               // if i dont make it to array it will throw error - reducible node
                               .ToArray()
                               //.Count(),
                               //MaxDelayedTime = t.Trips
                               //.Where(tr => tr.Status == TripStatus.Delayed && tr.DepartureTime <= date)
                               //.Max(tr=>tr.TimeDifference)
            })
                                 .Select(t => new TrainDto
            {
                TrainNumber    = t.TrainNumber,
                DelayedCount   = t.DelayedTrips.Count(),
                MaxDelayedTime = t.DelayedTrips.Max(tr => tr.TimeDifference).ToString(),
            })
                                 .OrderByDescending(t => t.DelayedCount)
                                 .ThenByDescending(t => t.MaxDelayedTime)
                                 .ThenByDescending(t => t.TrainNumber)
                                 .ToArray();

            string json = JsonConvert.SerializeObject(delayed, Newtonsoft.Json.Formatting.Indented);

            return(json);
        }
        public static string ExportDelayedTrains(StationsDbContext context, string dateAsString)
        {
            var date   = DateTime.ParseExact(dateAsString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            var trains = context.Trains
                         .Where(t =>
                                t.Trips.Any(tr => tr.Status == TripStatus.Delayed &&
                                            tr.DepartureTime <= date))
                         .Select(t => new
            {
                t.TrainNumber,
                DelayedTrips = t.Trips.Where(tr => tr.Status == TripStatus.Delayed && tr.DepartureTime <= date).ToArray()
            })
                         .Select(t => new DelayedTrainDto
            {
                TrainNumber    = t.TrainNumber,
                DelayedTimes   = t.DelayedTrips.Length,
                MaxDelayedTime = t.DelayedTrips.Max(tr => tr.TimeDifference).Value.ToString()
            })
                         .OrderByDescending(t => t.DelayedTimes)
                         .ThenByDescending(t => t.MaxDelayedTime)
                         .ThenBy(t => t.TrainNumber)
                         .ToArray();

            return(JsonConvert.SerializeObject(trains, Formatting.Indented));
        }
Exemplo n.º 4
0
        public static string ImportClasses(StationsDbContext context, string jsonString)
        {
            var sb = new StringBuilder();

            var deserializedClass = JsonConvert.DeserializeObject <SeatingClassDto[]>(jsonString);

            var validClasses = new List <SeatingClass>();

            foreach (var dto in deserializedClass)
            {
                if (!IsValid(dto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var classAlreadyExists = validClasses
                                         .Any(c => c.Name == dto.Name || c.Abbreviation == dto.Abbreviation);

                if (classAlreadyExists)
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var seatingClass = Mapper.Map <SeatingClass>(dto);

                validClasses.Add(seatingClass);
                sb.AppendLine(String.Format(SuccessMessage, seatingClass.Name));
            }

            context.SeatingClasses.AddRange(validClasses);
            context.SaveChanges();
            return(sb.ToString());
        }
Exemplo n.º 5
0
        public static string ImportStations(StationsDbContext context, string jsonString)
        {
            var sb            = new StringBuilder();
            var stations      = JsonConvert.DeserializeObject <StationDto[]>(jsonString);
            var stationsToAdd = new List <Station>();

            foreach (var stationDto in stations)
            {
                if (stationDto.Town == null && stationDto.Name != null)
                {
                    stationDto.Town = stationDto.Name;
                }

                if (stationDto.Name == null || stationDto.Name.Length > 50 || stationDto.Town.Length > 50 ||
                    stationsToAdd.Any(s => s.Name == stationDto.Name))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var stationToAdd = Mapper.Map <Station>(stationDto);
                stationsToAdd.Add(stationToAdd);
                sb.AppendLine(string.Format(SuccessMessage, stationDto.Name));
            }
            context.Stations.AddRange(stationsToAdd);
            context.SaveChanges();

            return(sb.ToString().TrimEnd());
        }
Exemplo n.º 6
0
        private static void ResetDatabase(StationsDbContext context, bool shouldDeleteDatabase = false)
        {
            if (shouldDeleteDatabase)
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
            }

            context.Database.EnsureCreated();

            var disableIntegrityChecksQuery = "EXEC sp_MSforeachtable @command1='ALTER TABLE ? NOCHECK CONSTRAINT ALL'";

            context.Database.ExecuteSqlCommand(disableIntegrityChecksQuery);

            var deleteRowsQuery = "EXEC sp_MSforeachtable @command1='DELETE FROM ?'";

            context.Database.ExecuteSqlCommand(deleteRowsQuery);

            var enableIntegrityChecksQuery = "EXEC sp_MSforeachtable @command1='ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL'";

            context.Database.ExecuteSqlCommand(enableIntegrityChecksQuery);

            var reseedQuery = "EXEC sp_MSforeachtable @command1='DBCC CHECKIDENT(''?'', RESEED, 0)'";

            try
            {
                context.Database.ExecuteSqlCommand(reseedQuery);
            }
            catch (SqlException)             // OrderItems table has no identity column, which isn't a problem
            {
            }
        }
Exemplo n.º 7
0
        public static string ImportCards(StationsDbContext context, string xmlString)
        {
            var sb = new StringBuilder();

            var serializer       = new XmlSerializer(typeof(CardDto[]), new XmlRootAttribute("Cards"));
            var deserializedCard = (CardDto[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));

            var validCards = new List <CustomerCard>();

            foreach (var dto in deserializedCard)
            {
                if (!IsValid(dto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var cardType = Enum.TryParse <CardType>(dto.CardType, out var cardT) ? cardT : CardType.Normal;

                var card = new CustomerCard
                {
                    Name = dto.Name,
                    Type = cardType,
                    Age  = dto.Age
                };

                validCards.Add(card);
                sb.AppendLine(String.Format(SuccessMessage, $"{card.Name}"));
            }

            context.Cards.AddRange(validCards);
            context.SaveChanges();
            return(sb.ToString());
        }
Exemplo n.º 8
0
        public static string ImportCards(StationsDbContext context, string xmlString)
        {
            StringBuilder       sb                = new StringBuilder();
            var                 serializer        = new XmlSerializer(typeof(CustomerCard), new XmlRootAttribute("cards"));
            var                 deserializedCards = (CustomerCard[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));
            List <CustomerCard> cards             = new List <CustomerCard>();

            foreach (var card in deserializedCards)
            {
                if (!IsValid(card))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }
                var cardType   = Enum.TryParse <CardType>(card.Type.ToString(), out var card1) ? card1 : CardType.Normal;
                var customCard = new CustomerCard()
                {
                    Name = card.Name,
                    Type = cardType,
                    Age  = card.Age
                };
                cards.Add(customCard);
                sb.AppendLine(string.Format(SuccessMessage, customCard.Name));
            }
            context.Cards.AddRange(cards);
            context.SaveChanges();
            return(sb.ToString());
        }
Exemplo n.º 9
0
        public static string ImportClasses(StationsDbContext context, string jsonString)
        {
            StringBuilder       sb = new StringBuilder();
            var                 deserializedClasses = JsonConvert.DeserializeObject <SeatingClass[]>(jsonString);
            List <SeatingClass> classes             = new List <SeatingClass>();

            foreach (var clas in deserializedClasses)
            {
                if (!IsValid(clas))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }
                var seatingClassAlreadyExists = classes
                                                .Any(sc => sc.Name == clas.Name || sc.Abbreviation == clas.Abbreviation);
                if (seatingClassAlreadyExists)
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }
                var seatClass = new SeatingClass()
                {
                    Name         = clas.Name,
                    Abbreviation = clas.Abbreviation
                };
                classes.Add(seatClass);
                sb.AppendLine(String.Format(SuccessMessage, seatClass.Name));
            }
            context.SeatingClasses.AddRange(classes);
            context.SaveChanges();
            return(sb.ToString());
        }
Exemplo n.º 10
0
        public static string ImportStations(StationsDbContext context, string jsonString)
        {
            var result = new List <string>();

            var objects          = JsonConvert.DeserializeObject <StationDto[]>(jsonString);
            var stationsToImport = new List <Station>();

            foreach (var o in objects)
            {
                if (o.Town == null)
                {
                    o.Town = o.Name;
                }

                if (o.Name == null || o.Name.Length > 50 || o.Town.Length > 50 || stationsToImport.Any(s => s.Name == o.Name))
                {
                    result.Add(FailureMessage);
                    continue;
                }

                stationsToImport.Add(new Station {
                    Name = o.Name, Town = o.Town
                });
                result.Add(String.Format(SuccessMessage, o.Name));
            }

            context.Stations.AddRange(stationsToImport);
            context.SaveChanges();
            return(String.Join(Environment.NewLine, result));
        }
Exemplo n.º 11
0
        public static string ImportClasses(StationsDbContext context, string jsonString)
        {
            var result          = new List <string>();
            var classesToImport = new List <SeatingClass>();

            var objects = JsonConvert.DeserializeAnonymousType(jsonString, new[] { new { Name = String.Empty, Abbreviation = String.Empty } });

            foreach (var o in objects)
            {
                if (classesToImport.Any(c => c.Name == o.Name) || classesToImport.Any(c => c.Abbreviation == o.Abbreviation) || o.Abbreviation == null || o.Name == null || o.Name.Length > 30 || o.Abbreviation.Length != 2)
                {
                    result.Add(FailureMessage);
                    continue;
                }

                classesToImport.Add(new SeatingClass {
                    Name = o.Name, Abbreviation = o.Abbreviation
                });
                result.Add(String.Format(SuccessMessage, o.Name));
            }

            context.SeatingClasses.AddRange(classesToImport);
            context.SaveChanges();
            return(String.Join(Environment.NewLine, result));
        }
        public static string ImportClasses(StationsDbContext context, string jsonString)
        {
            List <SeatingClass> seatingClasses      = JsonConvert.DeserializeObject <List <SeatingClass> >(jsonString);
            HashSet <string>    seatingClassNames   = new HashSet <string>();
            HashSet <string>    abbreviations       = new HashSet <string>();
            List <SeatingClass> validSeatingClasses = new List <SeatingClass>();
            StringBuilder       sb = new StringBuilder();

            foreach (var seatingClass in seatingClasses)
            {
                if (!IsValid(seatingClass) ||
                    seatingClassNames.Contains(seatingClass.Name) ||
                    abbreviations.Contains(seatingClass.Abbreviation))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                abbreviations.Add(seatingClass.Abbreviation);
                seatingClassNames.Add(seatingClass.Name);
                validSeatingClasses.Add(seatingClass);
                sb.AppendLine(string.Format(SuccessMessage, seatingClass.Name));
            }

            context.SeatingClasses.AddRange(validSeatingClasses);
            context.SaveChanges();
            return(sb.ToString().TrimEnd());
        }
        public static string ImportStations(StationsDbContext context, string jsonString)
        {
            List <Station>   stations      = JsonConvert.DeserializeObject <List <Station> >(jsonString);
            HashSet <string> stationNames  = new HashSet <string>();
            List <Station>   validStations = new List <Station>();
            StringBuilder    sb            = new StringBuilder();

            foreach (var station in stations)
            {
                if (station.Town == null)
                {
                    station.Town = station.Name;
                }

                if (!IsValid(station) || stationNames.Contains(station.Name))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                stationNames.Add(station.Name);
                validStations.Add(station);
                sb.AppendLine(string.Format(SuccessMessage, station.Name));
            }

            context.Stations.AddRange(validStations);
            context.SaveChanges();
            return(sb.ToString().TrimEnd());
        }
        public static string ImportCards(StationsDbContext context, string xmlString)
        {
            XmlSerializer       serializer = new XmlSerializer(typeof(CardImportDto[]), new XmlRootAttribute("Cards"));
            var                 cards      = (CardImportDto[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));
            List <CustomerCard> validCards = new List <CustomerCard>();
            StringBuilder       sb         = new StringBuilder();

            foreach (var card in cards)
            {
                if (!IsValid(card))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                CardType type = CardType.Normal;
                if (card.CardType != null)
                {
                    type = Enum.Parse <CardType>(card.CardType);
                }

                CustomerCard customerCard = new CustomerCard(card.Name, card.Age, type);

                validCards.Add(customerCard);
                sb.AppendLine(string.Format(SuccessMessage, card.Name));
            }

            context.Cards.AddRange(validCards);
            context.SaveChanges();
            return(sb.ToString().TrimEnd());
        }
Exemplo n.º 15
0
        public static string ImportCards(StationsDbContext context, string xmlString)
        {
            var serializer = new XmlSerializer(typeof(ImportDto.CardDto[]), new XmlRootAttribute("Cards"));

            ImportDto.CardDto[] deserializedCards = (ImportDto.CardDto[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));

            StringBuilder sb = new StringBuilder();

            List <CustomerCard> cards = new List <CustomerCard>();

            foreach (var cardDto in deserializedCards)
            {
                if (!IsValid(cardDto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                CustomerCard card = new CustomerCard()
                {
                    Name = cardDto.Name,
                    Age  = cardDto.Age,
                    Type = cardDto.CardType,
                };

                cards.Add(card);
                sb.AppendLine(string.Format(SuccessMessage, cardDto.Name));
            }

            context.AddRange(cards);
            context.SaveChanges();
            return(sb.ToString().Trim());
        }
Exemplo n.º 16
0
        public static string ImportCards(StationsDbContext context, string xmlString)
        {
            var sb = new StringBuilder();

            var serializer        = new XmlSerializer(typeof(CardDto[]), new XmlRootAttribute("Cards"));
            var deserializedCards = (CardDto[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));

            var validCards = new List <CustomerCard>();

            foreach (var cardDto in deserializedCards)
            {
                if (!IsValid(cardDto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var customerCard = Mapper.Map <CustomerCard>(cardDto);

                validCards.Add(customerCard);
                sb.AppendLine(string.Format(SuccessMessage, customerCard.Name));
            }

            context.Cards.AddRange(validCards);
            context.SaveChanges();

            var result = sb.ToString();

            return(result);
        }
Exemplo n.º 17
0
        public static string ImportClasses(StationsDbContext context, string jsonString)
        {
            var seatingClassDtos = JsonConvert.DeserializeObject <List <SeatingClassImportDto> >(jsonString);
            var sb = new StringBuilder();
            var seatingClassesToAdd = new List <SeatingClass>();

            foreach (var seatingClassDto in seatingClassDtos)
            {
                if (!IsValid(seatingClassDto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                if (seatingClassesToAdd.Any(sc => sc.Name == seatingClassDto.Name ||
                                            sc.Abbreviation == seatingClassDto.Abbreviation))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var seatingClass = Mapper.Map <SeatingClass>(seatingClassDto);
                seatingClassesToAdd.Add(seatingClass);
                sb.AppendLine(string.Format(SuccessMessage, seatingClass.Name));
            }

            context.SeatingClasses.AddRange(seatingClassesToAdd);
            context.SaveChanges();

            var result = sb.ToString().Trim();

            return(result);
        }
Exemplo n.º 18
0
        public static string ExportDelayedTrains(StationsDbContext context, string dateAsString)
        {
            var date   = DateTime.ParseExact(dateAsString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            var result = new List <Train>();

            var delayedTrains = context.Trains
                                .Where(t => t.Trips.Any(tr => tr.Status == TripStatus.Delayed && tr.DepartureTime <= date))
                                .Select(t => new
            {
                t.TrainNumber,
                DelayedTrips = t.Trips
                               .Where(tr => tr.Status == TripStatus.Delayed && tr.DepartureTime <= date)
                               .ToArray()
            })
                                .Select(t => new TrainDto
            {
                TrainNumber    = t.TrainNumber,
                DelayedTimes   = t.DelayedTrips.Count(),
                MaxDelayedTime = t.DelayedTrips.Max(d => d.TimeDifference).ToString()
            })
                                .OrderByDescending(t => t.DelayedTimes)
                                .ThenByDescending(t => t.MaxDelayedTime)
                                .ThenByDescending(t => t.TrainNumber)
                                .ToArray();

            var jsonString = JsonConvert.SerializeObject(delayedTrains, Newtonsoft.Json.Formatting.Indented);

            return(jsonString);
        }
Exemplo n.º 19
0
        private static void ImportEntities(StationsDbContext context, string baseDir = @".\..\..\..\Datasets\")
        {
            const string exportDir = @".\..\..\..\ImportResults\";

            var stations = DataProcessor.Deserializer.ImportStations(context, File.ReadAllText(baseDir + "stations.json"));

            PrintAndExportEntityToFile(stations, exportDir + "Stations.txt");

            var classes = DataProcessor.Deserializer.ImportClasses(context, File.ReadAllText(baseDir + "classes.json"));

            PrintAndExportEntityToFile(classes, exportDir + "Classes.txt");

            var trains = DataProcessor.Deserializer.ImportTrains(context, File.ReadAllText(baseDir + "trains.json"));

            PrintAndExportEntityToFile(trains, exportDir + "Trains.txt");

            var trips = DataProcessor.Deserializer.ImportTrips(context, File.ReadAllText(baseDir + "trips.json"));

            PrintAndExportEntityToFile(trips, exportDir + "Trips.txt");

            var cards = DataProcessor.Deserializer.ImportCards(context, File.ReadAllText(baseDir + "cards.xml"));

            PrintAndExportEntityToFile(cards, exportDir + "Cards.txt");

            var tickets = DataProcessor.Deserializer.ImportTickets(context, File.ReadAllText(baseDir + "tickets.xml"));

            PrintAndExportEntityToFile(tickets, exportDir + "Tickets.txt");
        }
Exemplo n.º 20
0
        public static string ImportClasses(StationsDbContext context, string jsonString)
        {
            var seatinClasses = JsonConvert.DeserializeObject <SeatingClass[]>(jsonString);

            StringBuilder sb = new StringBuilder();

            List <SeatingClass> validSeatingClasses = new List <SeatingClass>();

            foreach (var seatingClass in seatinClasses)
            {
                if (!IsValid(seatingClass))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var iSeatingClassExist = context.SeatingClasses.Any(x => x.Name == seatingClass.Name || x.Abbreviation == seatingClass.Abbreviation);

                if (iSeatingClassExist || validSeatingClasses.Any(x => x.Name == seatingClass.Name || x.Abbreviation == seatingClass.Abbreviation))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                validSeatingClasses.Add(seatingClass);
                sb.AppendLine(string.Format(SuccessMessage, seatingClass.Name));
            }

            context.SeatingClasses.AddRange(validSeatingClasses);
            context.SaveChanges();

            return(sb.ToString().TrimEnd());
        }
Exemplo n.º 21
0
        public static string ImportStations(StationsDbContext context, string jsonString)
        {
            var sb = new StringBuilder();

            var deserializedStations = JsonConvert.DeserializeObject <StationDto[]>(jsonString);

            var validStations = new List <Station>();

            foreach (var dto in deserializedStations)
            {
                if (!IsValid(dto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }
                if (dto.Town == null)
                {
                    dto.Town = dto.Name;
                }

                var alreadyExists = validStations.Any(s => s.Name == dto.Name);

                if (alreadyExists)
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }
                var station = Mapper.Map <Station>(dto);
                validStations.Add(station);
                sb.AppendLine(string.Format(SuccessMessage, dto.Name));
            }
            context.Stations.AddRange(validStations);
            context.SaveChanges();
            return(sb.ToString());
        }
        public static string ExportDelayedTrains(StationsDbContext context, string dateAsString)
        {
            var inputdate = DateTime.ParseExact(dateAsString, "dd/MM/yyyy", CultureInfo.InvariantCulture);

            var delayedTrains = context.Trains
                                .Where(t => t.Trips.Any(tr => tr.DepartureTime <= inputdate && tr.Status == Models.Enum.TripStatus.Delayed))
                                .Select(t => new
            {
                t.TrainNumber,
                DelayedTimes   = t.Trips.Where(tr => tr.Status == TripStatus.Delayed && tr.ArrivalTime <= inputdate).Count(),
                MaxDelayedTime = t.Trips
                                 .Where(tr => tr.Status == TripStatus.Delayed)
                                 .OrderByDescending(tr => tr.TimeDifference)
                                 .Select(tr => tr.TimeDifference)
                                 .First()
            })
                                .OrderByDescending(o => o.DelayedTimes)
                                .ThenByDescending(o => o.MaxDelayedTime)
                                .ThenBy(o => o.TrainNumber)
                                .ToArray();


            var json = JsonConvert.SerializeObject(delayedTrains, Newtonsoft.Json.Formatting.Indented);

            return(json);
        }
Exemplo n.º 23
0
        public static string ExportDelayedTrains(StationsDbContext context, string dateAsString)
        {
            DateTime parsedDepDate = DateTime.ParseExact(dateAsString, "dd/MM/yyyy", CultureInfo.InvariantCulture);

            var trains = context.Trains
                         .Where(x => x.Trips.Any(y => y.Status == TripStatus.Delayed &&
                                                 y.DepartureTime <= parsedDepDate))
                         .Select(t => new
            {
                t.TrainNumber,
                DelayedTimes = t.Trips.Where(x => x.Status == TripStatus.Delayed &&
                                             x.DepartureTime <= parsedDepDate).ToArray()
            })
                         .Select(x => new ExportTrainDto
            {
                TrainNumber    = x.TrainNumber,
                DelayedTimes   = x.DelayedTimes.Length,
                MaxDelayedTime = x.DelayedTimes.Max(y => y.TimeDifference).ToString()
            })
                         .OrderByDescending(x => x.DelayedTimes)
                         .ThenByDescending(x => x.MaxDelayedTime)
                         .ThenBy(x => x.TrainNumber);



            var jsonString = JsonConvert.SerializeObject(trains, Formatting.Indented);

            return(jsonString);
        }
        public static string ImportCards(StationsDbContext context, string xmlString)
        {
            var serializer   = new XmlSerializer(typeof(CardDto[]), new XmlRootAttribute("Cards"));
            var cardsFromXml = (CardDto[])serializer.Deserialize(new StringReader(xmlString));
            var sb           = new StringBuilder();
            var resultCards  = new List <CustomerCard>();

            foreach (var cardDto in cardsFromXml)
            {
                if (!IsValid(cardDto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var type = Enum.Parse <CardType>(cardDto.CardType);

                var currentCard = new CustomerCard
                {
                    Name = cardDto.Name,
                    Age  = cardDto.Age,
                    Type = type
                };

                resultCards.Add(currentCard);
                sb.AppendLine(string.Format(SuccessMessage, currentCard.Name));
            }

            context.Cards.AddRange(resultCards);
            context.SaveChanges();

            return(sb.ToString().Trim());
        }
Exemplo n.º 25
0
        public static string ImportClasses(StationsDbContext context, string jsonString)
        {
            var sb         = new StringBuilder();
            var classesDto = JsonConvert.DeserializeObject <ClassesDto[]>(jsonString);
            var classes    = new List <SeatingClass>();

            foreach (var dto in classesDto)
            {
                if (dto.Abbreviation == null || dto.Name == null ||
                    dto.Name.Length > 30 || dto.Abbreviation.Length != 2)
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                if (classes.Any(x => x.Name == dto.Name ||
                                x.Abbreviation == dto.Abbreviation))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var classToAdd = Mapper.Map <SeatingClass>(dto);
                classes.Add(classToAdd);
                sb.AppendLine(string.Format(SuccessMessage, dto.Name));
            }

            context.SeatingClasses.AddRange(classes);
            context.SaveChanges();

            return(sb.ToString().TrimEnd());
        }
        public static string ImportStations(StationsDbContext context, string jsonString)
        {
            var sb = new StringBuilder();

            var stationDtos = JsonConvert.DeserializeObject <StationDto[]>(jsonString);

            var validStations = new List <Station>();

            foreach (var stationDto in stationDtos)
            {
                if (!IsValid(stationDto) || validStations.Any(s => s.Name.Equals(stationDto.Name)))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                if (string.IsNullOrWhiteSpace(stationDto.Town))
                {
                    stationDto.Town = stationDto.Name;
                }

                var station = Mapper.Map <Station>(stationDto);
                validStations.Add(station);
                sb.AppendLine(string.Format(SuccessMessage, station.Name));
            }

            context.Stations.AddRange(validStations);
            context.SaveChanges();
            return(sb.ToString().Trim());
        }
Exemplo n.º 27
0
        public static string ExportCardsTicket(StationsDbContext context, string cardType)
        {
            var cardTypeParsed = Enum.Parse <CardType>(cardType);

            StringBuilder sb = new StringBuilder();

            CardDto[] cards = context
                              .Cards
                              .Where(c => c.Type == cardTypeParsed && c.BoughtTickets.Any())
                              .Select(c => new CardDto
            {
                Name    = c.Name,
                Type    = c.Type.ToString(),
                Tickets = c.BoughtTickets.Select(t => new TicketDto
                {
                    OriginStation      = t.Trip.OriginStation.Name,
                    DestinationStation = t.Trip.DestinationStation.Name,
                    DepartureTime      = t.Trip.DepartureTime.ToString(string.Format("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture))
                }).ToArray()
            })
                              .OrderBy(c => c.Name)
                              .ToArray();
            XmlSerializer serializer = new XmlSerializer(typeof(CardDto[]), new XmlRootAttribute("Cards"));


            serializer.Serialize(new StringWriter(sb), cards, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
            string result = sb.ToString();

            return(result);
        }
        public static string ImportClasses(StationsDbContext context, string jsonString)
        {
            var sb = new StringBuilder();

            var seatingClassDtos = JsonConvert.DeserializeObject <SeatingClassDto[]>(jsonString);
            var validClasses     = new List <SeatingClass>();

            foreach (var seatingClassDto in seatingClassDtos)
            {
                if (!IsValid(seatingClassDto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                if (validClasses.Any(c => c.Name.Equals(seatingClassDto.Name)) ||
                    validClasses.Any(c => c.Abbreviation.Equals(seatingClassDto.Abbreviation)))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var validCLass = Mapper.Map <SeatingClass>(seatingClassDto);
                validClasses.Add(validCLass);
                sb.AppendLine(string.Format(SuccessMessage, validCLass.Name));
            }

            context.SeatingClasses.AddRange(validClasses);
            context.SaveChanges();

            return(sb.ToString().Trim());
        }
        public static string ExportCardsTicket(StationsDbContext context, string cardType)
        {
            var cardT = Enum.Parse <CardType>(cardType);
            var cards = context.Cards
                        .Where(c => c.Type == cardT && c.BoughtTickets.Any())
                        .OrderBy(c => c.Name)
                        .Select(c => new CardExportDto
            {
                Name    = c.Name,
                Type    = c.Type.ToString(),
                Tickets = c.BoughtTickets.Select(t => new TicketExportDto
                {
                    OriginStation      = t.Trip.OriginStation.Name,
                    DestinationStation = t.Trip.DestinationStation.Name,
                    DepartureTime      = t.Trip.DepartureTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
                }).ToArray()
            })
                        .ToArray();

            var serializer = new XmlSerializer(typeof(CardExportDto[]), new XmlRootAttribute("Cards"));

            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, cards, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
                return(writer.ToString());
            }
        }
Exemplo n.º 30
0
        public static string ImportStations(StationsDbContext context, string jsonString)
        {
            IEnumerable <Station> stations = JsonConvert.DeserializeObject <IEnumerable <Station> >(jsonString);

            var result = new StringBuilder();

            foreach (Station station in stations)
            {
                if (string.IsNullOrEmpty(station.Town) || string.IsNullOrWhiteSpace(station.Town))
                {
                    station.Town = station.Name;
                }

                if (!IsValidStation(station, context))
                {
                    result.AppendLine(FailureMessage);
                }
                else
                {
                    context.Stations.Add(station);
                    context.SaveChanges();

                    result.AppendLine(String.Format(SuccessMessage, station.Name));
                }
            }

            // context.SaveChanges();

            return(result.ToString());
        }