Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
strauss_d_getting_started_with_visual_studio_2022_learning_a.pdf
Скачиваний:
124
Добавлен:
26.06.2023
Размер:
17.04 Mб
Скачать

Chapter 2 Working with Visual Studio 2022

can remove the targets for the platforms you don’t need. Optionally, you can also remove the supported version information for the platforms you removed. Lastly, you can delete the removed platforms’ directories under the Platforms folder.

The Required NuGet Package

Figure 2-22 shows that the project contains a folder for models, services, and view models. We will be using an MVVM (Model View ViewModel) approach, and for this, be sure to include the CommunityToolkit.Mvvm NuGet package by Microsoft, as seen in Figure 2-23.

Figure 2-23.  The CommunityToolkit.Mvvm NuGet package

The Weather Models

The application uses two classes to model the weather data. You will need to create a folder called Model in your project to add these classes. The WeatherResults class contains the deserialized JSON data from the Weather Service API, and the

CurrentWeather class takes what it needs from the WeatherResults class to display the forecast information. The code for the CurrentWeather class can be seen in Listing 2-1.

Listing 2-1.  The CurrentWeather Class

namespace HelloMAUI.Model

{

public class ForecastDay

{

public string DayOfWeek { get; set; } public string ImageUrl { get; set; } public int MinTemp { get; set; } public int MaxTemp { get; set; }

}

}

83

Chapter 2 Working with Visual Studio 2022

The WeatherResults class was generated by copying the returned JSON data from the Weather Service API and using Paste JSON as Classes option, as discussed in Chapter 1, to create an object to deserialize the returned JSON.

I won’t list the code for the WeatherResults class here because the code is generated from the JSON data returned from the Weather API and is relatively large. Your class will most likely differ from mine if you use a different

API. Remember, the complete code is available on GitHub at the following link: github.com/apress/getting-started-vs2022.

With these two models in place, we can now proceed to create the weather service.

The WeatherService

To consume the weather data from the Weather API, we need to create a Weather Service class under the Services folder. Create a folder called Services in your project, and add an Interface called IWeatherService and its implementation in a class called WeatherService.

Listing 2-2.  The IWeatherService Interface

using HelloMAUI.Model;

namespace HelloMAUI.Services

{

public interface IWeatherService

{

bool CanConnectToInternet();

Task<WeatherResults> GetCurrentWeather();

}

}

The Interface can be seen in Listing 2-2 and allows us to avoid tight coupling to the WeatherService class. This way, we can provide a contract for consuming entities to adhere to. The benefits of the Interface become apparent when we use dependency injection in our ViewModel. The Interface here specifies that any implementing class

84

Chapter 2 Working with Visual Studio 2022

must provide an implementation for checking the Internet connection and getting the current weather. The Interface does not care about the actual implementation (the code you write to check for Internet connection and get the weather). The WeatherService class can be seen in Listing 2-3.

Listing 2-3.  The WeatherService Class

using System.Net.Http.Json; using HelloMAUI.Model;

namespace HelloMAUI.Services

{

public class WeatherService : IWeatherService

{

IConnectivity _connectivity; WeatherResults weather = new(); HttpClient httpClient;

public WeatherService(IConnectivity connectivity)

{

_connectivity = connectivity; httpClient = new HttpClient();

}

public bool CanConnectToInternet()

{

return _connectivity?.NetworkAccess == NetworkAccess.Internet;

}

public async Task<WeatherResults> GetCurrentWeather()

{

var baseUrl = "https://api.weatherapi.com/v1"; var endP = "forecast.json";

var key = "91e3647d6ece446d969130840220309"; var city = "Los Angeles";

var url = $"{baseUrl}/{endP}?key={key}&q={city}&days=10&aqi=no& alerts=no";

85

Chapter 2 Working with Visual Studio 2022

var response = await httpClient.GetAsync(url);

if (response.IsSuccessStatusCode)

{

weather = await response.Content.ReadFromJsonAsync<Weather Results>();

}

return weather;

}

}

}

The WeatherService class implements the IWeatherService Interface as seen in the class declaration public class WeatherService : IWeatherService. Because we do this, we now must satisfy the implementations for checking to see if we can connect to the Internet and get the current weather in our WeatherService class. The constructor for the class uses the IConnectivity Interface passed to it via dependency injection. It then uses this to allow the WeatherService to provide an implementation in the CanConnectToInternet method for checking to see if the application is currently connected to the Internet. The GetCurrentWeather method then provides the implementation for calling the API to get the current weather data.

It is important to note that if you use a different API, your GetCurrentWeather method will be different.

The first thing we need to do is provide the service with a URL to get the data. In this case, the Weather API service URL is defined along with the end point, auth key, and other data that I have just hard-coded here. In reality, you would want to keep things such as auth keys and other secrets in Azure Key Vault or similar to secure your secrets and keep those out of source control. My API call is for Los Angeles, but you would probably want to be more dynamic and get the users’ current location to pass to the Weather API service. For simplicity’s sake, I have just hard-coded the data and used that to construct the URL to call the correct end point for the API.

86