- Sponsor
-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enhance Geographical Data Access with State and City Information #28
Open
donprecious
wants to merge
2
commits into
egbakou:main
Choose a base branch
from
donprecious:feat/24-23_support-for-states-and-cities
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+256
−0
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
using System.Collections.Generic; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace RESTCountries.NET.Models | ||
{ | ||
/// <summary> | ||
/// Represents a state or region within a country, including its cities. | ||
/// </summary> | ||
public class State | ||
{ | ||
/// <summary> | ||
/// Gets or sets the ISO country code. | ||
/// </summary> | ||
[JsonPropertyName("countryCode")] | ||
public string CountryCode { get; set; } | ||
|
||
/// <summary> | ||
/// Gets or sets the name of the state or region. | ||
/// </summary> | ||
[JsonPropertyName("name")] | ||
public string Name { get; set; } | ||
|
||
/// <summary> | ||
/// Gets or sets the state or region code. | ||
/// </summary> | ||
[JsonPropertyName("code")] | ||
public string Code { get; set; } | ||
|
||
/// <summary> | ||
/// Gets or sets the list of cities within the state or region. | ||
/// </summary> | ||
[JsonPropertyName("cities")] | ||
public List<City> Cities { get; set; } | ||
} | ||
|
||
/// <summary> | ||
/// Represents a city within a state or region. | ||
/// </summary> | ||
public class City | ||
{ | ||
/// <summary> | ||
/// Gets or sets the name of the city. | ||
/// </summary> | ||
[JsonPropertyName("name")] | ||
public string Name { get; set; } | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Reflection; | ||
using System.Text.Json; | ||
using RESTCountries.NET.Models; | ||
|
||
namespace RESTCountries.NET.Services | ||
{ | ||
/// <summary> | ||
/// Serves as a static repository for geographical data, specifically states and cities, within applications. This class provides efficient, read-only access to structured geographical information, making it ideal for applications that require reliable and quick access to such data without the overhead of dynamic data loading or external database dependencies. | ||
/// | ||
/// Functionality: | ||
/// - Retrieves lists of states within a specified country, identified by ISO2 country codes. | ||
/// - Retrieves lists of cities within a specified state, supporting both state-only and state-country queries. | ||
/// | ||
/// Designed to be used as part of a larger library, RestStateService abstracts away the complexities of geographical data management, offering straightforward methods for accessing the data. This approach allows developers to incorporate geographical information into their applications seamlessly, with minimal setup or configuration. | ||
/// | ||
/// Example Usage: | ||
/// var statesInUS = RestStateService.GetStatesInCountry("US"); | ||
/// var citiesInCalifornia = RestStateService.GetCitiesInState("CA"); | ||
/// | ||
/// Note: | ||
/// The geographical data is preloaded from an embedded JSON resource, ensuring fast access times and consistency across application instances. As such, no external data loading or initialization is required from the consumer's side. | ||
/// </summary> | ||
internal static class RestStateService | ||
{ | ||
private static readonly Dictionary<string, IEnumerable<State>> statesByCountry; | ||
private static readonly Dictionary<string, State> statesByCountryAndStateCode; | ||
|
||
/// <summary> | ||
/// Instantiates the RestStateService by loading state and city location data embedded within the assembly. | ||
/// This constructor attempts to locate and deserialize the JSON data from an embedded resource, organizing it into | ||
/// useful structures for quick access. It ensures the service is ready to use immediately after instantiation by | ||
/// pre-loading all necessary data. | ||
/// The data is organized into two primary dictionaries for efficient retrieval: one mapping country codes to their | ||
/// corresponding states, and another mapping state codes to their detailed state information. This organization | ||
/// facilitates rapid lookup operations for states and cities by their respective codes. | ||
/// Exception Handling: | ||
/// If the JSON data file cannot be found or an error occurs during deserialization, the constructor throws an | ||
/// exception, | ||
/// preventing the instantiation of the class with invalid or incomplete data. This approach ensures that any instance | ||
/// of RestStateService is fully operational and contains all necessary location data upon creation. | ||
/// Usage Note: | ||
/// Ensure the JSON data file is correctly embedded within the assembly and accessible via the specified resource path. | ||
/// Incorrect file paths or missing resources will result in exceptions, indicating initialization failures. | ||
/// </summary> | ||
static RestStateService() | ||
{ | ||
IEnumerable<State> allStates; | ||
try | ||
{ | ||
var assembly = Assembly.GetExecutingAssembly(); | ||
using var stream = assembly.GetManifestResourceStream("RESTCountries.NET.Services.states.json"); | ||
allStates = stream != null | ||
? JsonSerializer.Deserialize<IEnumerable<State>>(new StreamReader(stream).ReadToEnd()) | ||
: throw new Exception("Unable to load data source."); | ||
|
||
|
||
// Organizes states by country code for efficient retrieval. | ||
if (allStates != null) | ||
{ | ||
statesByCountry = allStates.GroupBy(s => s.CountryCode) | ||
.ToDictionary(g => g.Key, g => g.AsEnumerable()); | ||
|
||
// Organizes states by concatenating country code and state code for unique access. | ||
statesByCountryAndStateCode = allStates | ||
.ToDictionary(s => $"{s.CountryCode}:{s.Code}", s => s); | ||
} | ||
} | ||
catch (Exception ex) | ||
{ | ||
statesByCountry = new Dictionary<string, IEnumerable<State>>(); | ||
statesByCountryAndStateCode = new Dictionary<string, State>(); | ||
allStates = new List<State>(); | ||
throw new Exception($"An error occurred while initializing state location data: {ex.Message}"); | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Retrieves all states within a given country, identified by its ISO2 country code. | ||
/// </summary> | ||
/// <param name="countryCode">The ISO2 country code of the country.</param> | ||
/// <returns>A list of State objects within the specified country. Returns an empty list if no states are found.</returns> | ||
public static IEnumerable<State> GetStatesInCountry(string countryCode) | ||
{ | ||
return statesByCountry.TryGetValue(countryCode, out var states) ? states : new List<State>(); | ||
} | ||
|
||
/// <summary> | ||
/// Retrieves all cities within a given state, identified by its state code and country code. | ||
/// </summary> | ||
/// <param name="stateCode">The code of the state.</param> | ||
/// <param name="countryCode">The ISO2 code of the country.</param> | ||
/// <returns> | ||
/// A list of City objects within the specified state. Returns an empty list if no cities are found or the state | ||
/// does not exist. | ||
/// </returns> | ||
public static IEnumerable<City> GetCitiesInState(string stateCode, string countryCode) | ||
{ | ||
var key = $"{countryCode}:{stateCode}"; | ||
if (statesByCountryAndStateCode.TryGetValue(key, out var state)) | ||
{ | ||
return state.Cities; | ||
} | ||
|
||
return new List<City>(); | ||
} | ||
} | ||
} |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The dataset is significantly large, causing the NuGet package to exceed 3MB. It's uncertain whether users would appreciate downloading a package of this size just to obtain countries and states data.