Skip to content

Commit

Permalink
Feature branch1 (#2)
Browse files Browse the repository at this point in the history
* Added some stuff for Amalie to fix

* added adjustments

* updated weatherservice.cs

* fixed bug

---------

Co-authored-by: bax082024 <bax082024@gmail.com>
  • Loading branch information
Amaliebra and bax082024 authored Oct 8, 2024
1 parent 45c1633 commit 3dca0dc
Show file tree
Hide file tree
Showing 7 changed files with 169 additions and 49 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
/obj
/bin
/bin
wwwroot/


21 changes: 21 additions & 0 deletions Controller/WeatherController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class WeatherController : ControllerBase
{
private readonly WeatherService _weatherService;

public WeatherController(WeatherService weatherService)
{
_weatherService = weatherService;
}

[HttpGet]
public async Task<IActionResult> GetWeather()
{
var weatherInfo = await _weatherService.GetWeatherForBergenAsync();
return Ok(weatherInfo);
}
}
59 changes: 15 additions & 44 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -1,62 +1,33 @@
using System.IO;
using System.Net.Http;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;

public class WeatherData
{
public Current Current { get; set; }
}
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Current
{
public double temperature_2m { get; set; }
public double Rain { get; set; }
}
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddHttpClient<WeatherService>(); // Registers HttpClient for WeatherService

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

string htmlPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "index.html");
string htmlContent = File.ReadAllText(htmlPath);

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();

app.UseDeveloperExceptionPage();
}

app.UseStaticFiles(); // Serve static files from wwwroot folder
app.UseHttpsRedirection();
app.UseRouting();

app.UseStaticFiles();
app.UseDefaultFiles();


app.MapGet("/", async () =>
// Map controller routes and fallback to index.html for any non-API request
app.UseEndpoints(endpoints =>
{
string url = $"https://api.open-meteo.com/v1/forecast?latitude=60.393&longitude=5.3242&current=temperature_2m,rain,weather_code&hourly=temperature_2m&forecast_days=3";
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var responseString = await response.Content.ReadAsStringAsync();
var weatherData = JsonSerializer.Deserialize<WeatherData>(responseString);
htmlContent = htmlContent.Replace("", weatherData.Current.temperature_2m.ToString());
htmlContent = htmlContent.Replace("", weatherData.Current.Rain.ToString());

return Results.Content(htmlContent, "text/html");
}
else
{
return Results.StatusCode((int)response.StatusCode);
}
}
endpoints.MapControllers(); // Map controller routes
// Fallback to index.html for SPA or static files
endpoints.MapFallbackToFile("index.html");

});

app.Run();

15 changes: 12 additions & 3 deletions Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "/",
"applicationUrl": "http://localhost:5000"
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
71 changes: 71 additions & 0 deletions Services/WeatherService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization; // Add this line
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

public class WeatherService
{
private readonly HttpClient _httpClient;
private readonly ILogger<WeatherService> _logger;

public WeatherService(HttpClient httpClient, ILogger<WeatherService> logger)
{
_httpClient = httpClient;
_logger = logger;
}

public async Task<string> GetWeatherForBergenAsync()
{
try
{
// Open-Meteo API endpoint for Bergen, Norway
string requestUri = "https://api.open-meteo.com/v1/forecast?latitude=60.393&longitude=5.3242&current_weather=true";
var response = await _httpClient.GetAsync(requestUri);

if (response.IsSuccessStatusCode)
{
var jsonResponse = await response.Content.ReadAsStringAsync();

// Attempt to deserialize the JSON response
var weatherData = JsonSerializer.Deserialize<WeatherData>(jsonResponse);

// Ensure that the deserialized object is not null
if (weatherData?.CurrentWeather != null)
{
return $"Temperature in Bergen: {weatherData.CurrentWeather.Temperature}°C, Windspeed: {weatherData.CurrentWeather.Windspeed} km/h";
}
else
{
_logger.LogError("Weather data or CurrentWeather is null.");
return "Weather data is not available.";
}
}
else
{
_logger.LogError("Failed to fetch weather data. Status Code: {StatusCode}", response.StatusCode);
return "Unable to retrieve weather data.";
}
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while fetching weather data.");
return "An error occurred while fetching weather data.";
}
}

private class WeatherData
{
[JsonPropertyName("current_weather")] // Map the JSON property "current_weather" to the C# property
public CurrentWeatherData CurrentWeather { get; set; }
}

private class CurrentWeatherData
{
[JsonPropertyName("temperature")] // Map the JSON property "temperature" to the C# property
public float Temperature { get; set; }

[JsonPropertyName("windspeed")] // Map the JSON property "windspeed" to the C# property
public float Windspeed { get; set; }
}
}
26 changes: 26 additions & 0 deletions classes/WeatherData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Text.Json.Serialization;

public class WeatherData
{
[JsonPropertyName("current_weather")]
public CurrentWeatherData CurrentWeather { get; set;}
}

public class CurrentWeatherData
{
[JsonPropertyName("temperature")]
public float Temperature { get; set; }

[JsonPropertyName("windspeed")]
public float Windspeed { get; set; }

[JsonPropertyName("weathercode")]
public int WeatherCode { get; set; }

[JsonPropertyName("winddirection")]
public int WindDirection { get; set; }

[JsonPropertyName("is_day")]
public int IsDay { get; set; }
}

21 changes: 20 additions & 1 deletion wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,30 @@
<header>
<h1>Weather Network</h1>
</header>
<main>
<main>
<div class="weather-container">
<h1>{{ temperature }}</h1>
<h1>{{ rain }}</h1>
<button id="getWeather">Get Weather for Bergen</button>
<p id="weatherInfo"></p>
</div>
</main>
<button id="getWeather">Get Weather for Bergen</button>
<p id="weatherInfo"></p>

<script>
document.getElementById("getWeather").addEventListener("click", async () => {
try {
const response = await fetch("/api/weather");
if (!response.ok) {
throw new Error("Failed to fetch weather data");
}
const weatherInfo = await response.text();
document.getElementById("weatherInfo").innerText = weatherInfo;
} catch (error) {
document.getElementById("weatherInfo").innerText = "Error: " + error.message;
}
});
</script>
</body>
</html>

0 comments on commit 3dca0dc

Please sign in to comment.