Skip to content

Commit

Permalink
Feature branch1 (#5)
Browse files Browse the repository at this point in the history
* update weather.cs

* updated README

* added some updates to html and path

* updated output, html, added functions

* added image

* updatet readme

* changed button

* Feature branch2 (#4)

* edit1

* setting up style css

* arraning items in css

* last changes for the day

* links in readme

* readme edit

* aligning text

---------

Co-authored-by: bax082024 <bax082024@gmail.com>
  • Loading branch information
Amaliebra and bax082024 authored Oct 9, 2024
1 parent b0155fb commit 530a8a4
Show file tree
Hide file tree
Showing 9 changed files with 156 additions and 166 deletions.
12 changes: 5 additions & 7 deletions Controller/WeatherController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,9 @@ public WeatherController(WeatherService weatherService)
}

[HttpGet]
public async Task<IActionResult> GetWeather()
{
var weatherInfo = await _weatherService.GetWeatherForBergenAsync();

// Assuming your service fetches data, return it as a JSON object
return Ok(new { temperature = "14°C", windspeed = "23 km/h" });
}
public async Task<IActionResult> GetWeather() // Use IActionResult for HTTP response
{
var weatherInfo = await _weatherService.GetWeatherForBergenAsync(); // Call WeatherService
return weatherInfo; // Return the result directly
}
}
17 changes: 5 additions & 12 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Expand All @@ -7,7 +6,8 @@

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

var app = builder.Build();

Expand All @@ -17,17 +17,10 @@
app.UseDeveloperExceptionPage();
}

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

// Map controller routes and fallback to index.html for any non-API request
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // Map controller routes
// Fallback to index.html for SPA or static files
endpoints.MapFallbackToFile("index.html");

});
app.MapControllers();

app.Run();
55 changes: 24 additions & 31 deletions Services/WeatherService.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Mvc;

public class WeatherService
public class WeatherService : ControllerBase
{
private readonly HttpClient _httpClient;
private readonly ILogger<WeatherService> _logger;
Expand All @@ -15,57 +15,50 @@ public WeatherService(HttpClient httpClient, ILogger<WeatherService> logger)
_logger = logger;
}

public async Task<string> GetWeatherForBergenAsync()
public async Task<IActionResult> 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";
// API request
string requestUri = "https://api.open-meteo.com/v1/forecast?latitude=60.393&longitude=5.3242&hourly=temperature_2m,precipitation,rain,showers,weather_code,wind_speed_10m";
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)

if (weatherData?.Hourly != null)
{
return $"Temperature in Bergen: {weatherData.CurrentWeather.Temperature}°C, Windspeed: {weatherData.CurrentWeather.Windspeed} km/h";
// Check if the first element in the lists exist and use them, otherwise return "undefined"
float? temperature = weatherData.Hourly.Temperature2M?.Count > 0 ? weatherData.Hourly.Temperature2M[0] : (float?)null;
float? windspeed = weatherData.Hourly.WindSpeed10M?.Count > 0 ? weatherData.Hourly.WindSpeed10M[0] : (float?)null;
int? weatherCode = weatherData.Hourly.WeatherCode?.Count > 0 ? weatherData.Hourly.WeatherCode[0] : (int?)null;

return Ok(new
{
temperature = temperature.HasValue ? $"{temperature}°C" : "undefined",
windspeed = windspeed.HasValue ? $"{windspeed} km/h" : "undefined",
condition = weatherCode.HasValue && weatherCode.Value == 3 ? "Cloudy" : "Clear"
});
}
else
{
_logger.LogError("Weather data or CurrentWeather is null.");
return "Weather data is not available.";
_logger.LogError("Hourly weather data is null.");
return StatusCode(500, "Weather data is not available.");
}
}
else
{
_logger.LogError("Failed to fetch weather data. Status Code: {StatusCode}", response.StatusCode);
return "Unable to retrieve weather data.";
return StatusCode((int)response.StatusCode, "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.";
_logger.LogError(ex, "Error occurred while fetching weather data.");
return StatusCode(500, "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; }
}
}

29 changes: 13 additions & 16 deletions classes/WeatherData.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
using System.Collections.Generic;
using System.Text.Json.Serialization;

// This class represents the weather data returned by the Open-Meteo API
public class WeatherData
{
[JsonPropertyName("current_weather")]
public CurrentWeatherData CurrentWeather { get; set;}
[JsonPropertyName("hourly")]
public HourlyData Hourly { get; set; }
}
// we dont use all the functions
public class CurrentWeatherData
{
[JsonPropertyName("temperature")]
public float Temperature { get; set; }

[JsonPropertyName("windspeed")]
public float Windspeed { get; set; }
public class HourlyData
{
[JsonPropertyName("temperature_2m")]
public List<float> Temperature2M { get; set; }

[JsonPropertyName("weathercode")]
public int WeatherCode { get; set; }
[JsonPropertyName("wind_speed_10m")]
public List<float> WindSpeed10M { get; set; }

[JsonPropertyName("winddirection")]
public int WindDirection { get; set; }
[JsonPropertyName("weather_code")]
public List<int> WeatherCode { get; set; }

[JsonPropertyName("is_day")]
public int IsDay { get; set; }
// Add other fields like precipitation, rain, etc. if needed
}

File renamed without changes.
Binary file added images/bryggen.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 9 additions & 14 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,23 @@
# Weather App for Bergen



## Introduction
- This is school project me and Amalie made together.
- we made a weather app to show the weather in our city


- This is school project Bax and Amalie made together.
- We made a weather app to show the weather in our city

### How to use
### How to use

**Run the app**

- dotnet run

**Use the app**

- http://localhost:5000
- http://localhost:5000/api/weather

**Navigate to files**




A small app for looking up the weather in Bergen, NO.

-[HTML](/wwwroot/index.html)


|[HTML](/wwwroot/index.html)|[CSS](/wwwroot/styles.css)|[Figma](documentation/Figma-design.pdf)
|[Program.cs](/Program.cs)|[WheatherData.cs](/classes/WeatherData.cs)
|[WeatherController.cs](/Controller/WeatherController.cs)|[WheatherService.cs](/Services/WeatherService.cs)
35 changes: 24 additions & 11 deletions wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,52 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Weather Network</title>
<title>Bax Weather Network</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<header>
<h1 class="logo">Bax Weather Network</h1>
<p class="local-only">Local weather ONLY</p>
</header>

<div class="divider-line"></div>
<main>
<div class="weather-container">
<h1 class="bergen">Bergen</h1>
<p>Current weather in Bergen, Norway.</p>
<button id="getWeather">Click this!</button>
<p id="weatherInfo"></p>
<p id="temperature">Temperature: Loading...</p>
<p id="windspeed">Windspeed: Loading...</p>
<p id="condition">Condition: Loading...</p>
</div>
</main>

<script>
document.getElementById("getWeather").addEventListener("click", async () => {
async function fetchWeather() {
try {
const response = await fetch("/api/weather");
if (!response.ok) {
throw new Error("Failed to fetch weather data");
}

const weatherData = await response.json();
console.log("Received Weather Data: ", weatherData);

// Update the HTML elements with the fetched data
document.getElementById("temperature").innerText = `Temperature: ${weatherData.temperature}`;
document.getElementById("windspeed").innerText = `Windspeed: ${weatherData.windspeed}`;
document.getElementById("condition").innerText = `Condition: ${weatherData.condition}`;

// Use response.json() to parse JSON
const weatherInfo = await response.json();

// Assuming weatherInfo contains properties like 'temperature' and 'windspeed'
document.getElementById("weatherInfo").innerText = `Temperature: ${weatherInfo.temperature}, Windspeed: ${weatherInfo.windspeed}`;
} catch (error) {
document.getElementById("weatherInfo").innerText = "Error: " + error.message;
console.error("Error: ", error.message);
document.getElementById("temperature").innerText = "Temperature: Error";
document.getElementById("windspeed").innerText = "Windspeed: Error";
document.getElementById("condition").innerText = "Condition: Error";
}
});
}

// Call the function when the page loads
window.onload = fetchWeather;
</script>
</body>
</html>
Loading

0 comments on commit 530a8a4

Please sign in to comment.