public PlanetResidentsViewModel(string planetName)
        {
            string planetUrl = GetPlanetUrlByName(planetName);

            Residents = new List <ResidentSummary>();

            string     json   = SwApiAccess.ApiGetRequest(planetUrl);
            JsonPlanet planet = JsonConvert.DeserializeObject <JsonPlanet>(json);

            foreach (string residentUrl in planet.Residents)
            {
                json = SwApiAccess.ApiGetRequest(residentUrl);
                JsonResident resident = JsonConvert.DeserializeObject <JsonResident>(json);

                ResidentSummary residentSummary = new ResidentSummary
                {
                    Name      = resident.Name,
                    Height    = resident.Height,
                    Weight    = resident.Mass,
                    Gender    = resident.Gender,
                    HairColor = resident.HairColor,
                    EyeColor  = resident.EyeColor,
                    SkinColor = resident.SkinColor
                };

                Residents.Add(residentSummary);
            }

            Residents = Residents.OrderBy(r => r.Name).ToList();
        }
Пример #2
0
        public SinglePlanetViewModel(string planetId)
        {
            string apiEndpoint = "https://swapi.co/api/planets/" + planetId;

            string     json   = SwApiAccess.ApiGetRequest(apiEndpoint);
            JsonPlanet planet = JsonConvert.DeserializeObject <JsonPlanet>(json);

            this.Name                   = planet.Name;
            this.LengthOfDay            = planet.RotationPeriod;
            this.LengthOfYear           = planet.OrbitalPeriod;
            this.Diameter               = planet.Diameter;
            this.Climate                = planet.Climate;
            this.Gravity                = planet.Gravity;
            this.SurfaceWaterPercentage = planet.SurfaceWater;
            this.Population             = planet.Population;
        }
Пример #3
0
        public VehicleSummaryViewModel()
        {
            Details = new List <VehicleStatsViewModel>();

            bool   continueLoop    = true;
            string nextApiEndpoint = "https://swapi.co/api/vehicles";

            Dictionary <string, Manufacturer> manufacturerDictionary = new Dictionary <string, Manufacturer>();

            // Continue looping api calls
            while (continueLoop)
            {
                string          json        = SwApiAccess.ApiGetRequest(nextApiEndpoint);
                JsonAllVehicles allVehicles = JsonConvert.DeserializeObject <JsonAllVehicles>(json);

                foreach (JsonVehicle jsonVehicle in allVehicles.Results)
                {
                    // Ignore vehicles without a known cost
                    if (!jsonVehicle.CostInCredits.Equals("unknown"))
                    {
                        // Increment vehicle count property
                        this.VehicleCount++;

                        // Create a new manufacturer obj if new, otherwise increment count and cost for manufacturer
                        if (!manufacturerDictionary.ContainsKey(jsonVehicle.Manufacturer))
                        {
                            Manufacturer manufacturer = new Manufacturer
                            {
                                Name         = jsonVehicle.Manufacturer,
                                VehicleCount = 1,
                                TotalCost    = Convert.ToDouble(jsonVehicle.CostInCredits)
                            };

                            manufacturerDictionary.Add(jsonVehicle.Manufacturer, manufacturer);
                        }
                        else
                        {
                            Manufacturer manufacturer = manufacturerDictionary[jsonVehicle.Manufacturer];
                            manufacturer.VehicleCount++;
                            manufacturer.TotalCost += Convert.ToDouble(jsonVehicle.CostInCredits);
                        }
                    }
                }

                // Break loop if the api returns null for next field
                if (allVehicles.Next == null)
                {
                    continueLoop = false;
                }
                else
                {
                    nextApiEndpoint = allVehicles.Next;
                }
            }

            // Loop through manufacturers and massage into VehicleStatsViewModel
            foreach (KeyValuePair <string, Manufacturer> manufacturerItem in manufacturerDictionary)
            {
                Manufacturer manufacturer = manufacturerItem.Value;

                VehicleStatsViewModel vehicleStatsViewModel = new VehicleStatsViewModel
                {
                    ManufacturerName = manufacturer.Name,
                    VehicleCount     = manufacturer.VehicleCount,
                    AverageCost      = manufacturer.TotalCost / manufacturer.VehicleCount
                };

                // Add to details property
                Details.Add(vehicleStatsViewModel);
            }

            // Set manufacturerCount based on unique manufacturers in dictionary
            this.ManufacturerCount = manufacturerDictionary.Count();

            // Sort by vehicle count desc and then by avg cost desc
            Details = Details.OrderByDescending(d => d.VehicleCount).ThenByDescending(d => d.AverageCost).ToList();
        }
        public AllPlanetsViewModel()
        {
            Planets = new List <PlanetDetailsViewModel>();

            bool continueLoop = true;
            // Setup endpoint for first api call
            string nextApiEndpoint   = "https://swapi.co/api/planets";
            int    summedDiameter    = 0;
            int    totalValidPlanets = 0;

            // Continue looping api calls
            while (continueLoop)
            {
                string         json       = SwApiAccess.ApiGetRequest(nextApiEndpoint);
                JsonAllPlanets allPlanets = JsonConvert.DeserializeObject <JsonAllPlanets>(json);

                foreach (JsonPlanet jsonPlanet in allPlanets.Results)
                {
                    // Set 1:1 properties
                    PlanetDetailsViewModel planetDetailsViewModel = new PlanetDetailsViewModel
                    {
                        Name         = jsonPlanet.Name,
                        Population   = jsonPlanet.Population,
                        Terrain      = jsonPlanet.Terrain,
                        LengthOfYear = jsonPlanet.OrbitalPeriod,
                        Url          = jsonPlanet.Url
                    };

                    // Display 0 if the diameter is unknown but don't include this planet in average
                    if (jsonPlanet.Diameter.Equals("unknown"))
                    {
                        jsonPlanet.Diameter = "0";
                    }
                    else
                    {
                        totalValidPlanets++;
                        summedDiameter += Convert.ToInt32(jsonPlanet.Diameter);
                    }

                    // Set diameter
                    planetDetailsViewModel.Diameter = Convert.ToInt32(jsonPlanet.Diameter);

                    // Add current planet view to list
                    Planets.Add(planetDetailsViewModel);
                }

                // Break loop if the api returns null for next field
                if (allPlanets.Next == null)
                {
                    continueLoop = false;
                }
                else
                {
                    nextApiEndpoint = allPlanets.Next;
                }
            }

            // Calculate average diameter
            AverageDiameter = summedDiameter / totalValidPlanets;

            // Sort by diameter desc
            Planets = Planets.OrderByDescending(p => p.Diameter).ToList();
        }
Пример #5
0
        public MostAverageFilmViewModel(string sortBy)
        {
            Films          = new List <FilmDetailsViewModel>();
            FilmProperties = new List <FilmPropertyViewModel>();

            string apiEndpoint = "https://swapi.co/api/films";

            string       json     = SwApiAccess.ApiGetRequest(apiEndpoint);
            JsonAllFilms allFilms = JsonConvert.DeserializeObject <JsonAllFilms>(json);

            int filmCount = 0;

            // List of properties that we are intersted in
            List <string> filmProperties = new List <string>()
            {
                "Characters",
                "Planets",
                "Starships",
                "Vehicles",
                "Species"
            };

            // Build our dictionary of filmPropertyViewModels, and set the properties we can right now
            Dictionary <string, FilmPropertyViewModel> filmPropertyDictionary = new Dictionary <string, FilmPropertyViewModel>();

            foreach (string filmProperty in filmProperties)
            {
                FilmPropertyViewModel filmPropertyViewModel = new FilmPropertyViewModel()
                {
                    PropertyName = filmProperty,
                    Count        = 0,
                    MinimumDifferenceFromAverage = int.MaxValue
                };

                filmPropertyDictionary.Add(filmProperty, filmPropertyViewModel);
            }

            // Loop through api film data
            foreach (JsonFilm jsonFilm in allFilms.Results)
            {
                filmCount++;

                // Populate films list for summary
                FilmDetailsViewModel filmDetailsViewModel = new FilmDetailsViewModel
                {
                    Title      = jsonFilm.Title,
                    Characters = jsonFilm.Characters.Count(),
                    Planets    = jsonFilm.Planets.Count(),
                    Starships  = jsonFilm.Starships.Count(),
                    Vehicles   = jsonFilm.Vehicles.Count(),
                    Species    = jsonFilm.Species.Count()
                };

                Films.Add(filmDetailsViewModel);

                // Populate our filmPropertyViewModels total property counts
                foreach (PropertyInfo propertyInfo in jsonFilm.GetType().GetProperties())
                {
                    string propertyName = propertyInfo.Name;

                    // This only applies to the properties that we are interested in from filmProperties list
                    if (filmProperties.Contains(propertyName))
                    {
                        List <string> jsonFilmPropertyValue = (List <string>)propertyInfo.GetValue(jsonFilm);
                        filmPropertyDictionary[propertyName].Count += jsonFilmPropertyValue.Count();
                    }
                }
            }

            // Calculate averages for each filmPropertyViewModel
            foreach (KeyValuePair <string, FilmPropertyViewModel> filmPropertyItem in filmPropertyDictionary)
            {
                FilmPropertyViewModel filmPropertyViewModel = filmPropertyItem.Value;
                filmPropertyViewModel.CalculatedAverage = filmPropertyViewModel.Count / filmCount;
            }

            // Calculate the film that is closest to the average for each filmPropertyViewModel
            foreach (FilmDetailsViewModel film in Films)
            {
                foreach (KeyValuePair <string, FilmPropertyViewModel> filmPropertyItem in filmPropertyDictionary)
                {
                    FilmPropertyViewModel filmPropertyViewModel = filmPropertyItem.Value;

                    // Get the film.Property value that matches the filmPropertViewModel.PropertyName. i.e. the film.Characters value
                    int filmCountForProperty = (int)film.GetType().GetProperty(filmPropertyViewModel.PropertyName).GetValue(film);

                    // Calculate how close the film.Property is to the filmPropertyViewModel.CalculatedAverage
                    double differenceFromAverage = Math.Abs(filmCountForProperty - filmPropertyViewModel.CalculatedAverage);

                    // If this is the closest to average film then update our minDiff and the film title
                    if (differenceFromAverage < filmPropertyViewModel.MinimumDifferenceFromAverage)
                    {
                        filmPropertyViewModel.FilmClosestToAverage         = film.Title;
                        filmPropertyViewModel.MinimumDifferenceFromAverage = differenceFromAverage;
                    }
                }
            }

            // TODO figure out how to do this correctly with reflection
            // Sort film summary by given param
            switch (sortBy)
            {
            case "Characters":
                Films = Films.OrderByDescending(f => f.Characters).ToList();
                break;

            case "Planets":
                Films = Films.OrderByDescending(f => f.Planets).ToList();
                break;

            case "Starships":
                Films = Films.OrderByDescending(f => f.Starships).ToList();
                break;

            case "Vehicles":
                Films = Films.OrderByDescending(f => f.Vehicles).ToList();
                break;

            case "Species":
                Films = Films.OrderByDescending(f => f.Species).ToList();
                break;

            default:
                Films = Films.OrderByDescending(f => f.Characters).ToList();
                break;
            }

            // Calcuate the most average film by finding the film with the most closest avg occurences
            List <string> closestToAveragesList = new List <string>();

            foreach (KeyValuePair <string, FilmPropertyViewModel> filmPropertyItem in filmPropertyDictionary)
            {
                FilmPropertyViewModel filmPropertyViewModel = filmPropertyItem.Value;
                closestToAveragesList.Add(filmPropertyViewModel.FilmClosestToAverage);

                FilmProperties.Add(filmPropertyViewModel);
            }

            MostAverageFilm = closestToAveragesList.GroupBy(c => c).OrderByDescending(group => group.Count()).Select(group => group.Key).First();
        }