Commit 8aa56ab0 authored by Charles Still's avatar Charles Still
Browse files

Fix merging logfile + main

parents c7ec7087 b9095f86
......@@ -9,12 +9,10 @@
namespace BeeWeatherPollenTracker
{
using MySql.Data.EntityFramework;
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public partial class delmeEntities1 : DbContext
{
public delmeEntities1()
......
// La génération de code T4 est activée pour le modèle 'C:\CNAM\2A\Darmstadt\bee-weather\BeeWeatherPollenTracker\BeesWeatherModel.edmx'.
// La génération de code T4 est activée pour le modèle 'C:\CNAM\2A\Darmstadt\Genie_logiciel\bee-weather\BeeWeatherPollenTracker\BeesWeatherModel.edmx'.
// Pour activer la génération de code héritée, définissez la valeur de la propriété
// du concepteur 'Stratégie de génération de code' sur 'ObjectContext hérité'. Cette propriété est disponible dans la fenêtre Propriétés lorsque le modèle
// est ouvert dans le concepteur.
......
......@@ -24,13 +24,14 @@
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="Input_date" Type="date" Nullable="false" />
<Property Name="Forecast_date" Type="date" Nullable="false" />
<Property Name="Input_date" Type="datetime" Precision="0" Nullable="false" />
<Property Name="Forecast_date" Type="datetime" Precision="0" Nullable="false" />
<Property Name="Temperature" Type="double" Nullable="false" />
<Property Name="Wind" Type="double" Nullable="false" />
<Property Name="Humidity" Type="double" Nullable="false" />
<Property Name="Cloudiness" Type="varchar" MaxLength="256" Nullable="false" />
<Property Name="Location" Type="varchar" MaxLength="256" Nullable="false" />
<Property Name="Icon" Type="varchar" MaxLength="5" Nullable="false" />
</EntityType>
<EntityType Name="ref_beehive_poll_forecast">
<Key>
......@@ -142,6 +143,7 @@
<Property Name="Humidity" Type="Double" Nullable="false" />
<Property Name="Cloudiness" Type="String" Nullable="false" MaxLength="256" FixedLength="false" Unicode="false" />
<Property Name="Location" Type="String" Nullable="false" MaxLength="256" FixedLength="false" Unicode="false" />
<Property Name="Icon" Type="String" Nullable="false" MaxLength="5" FixedLength="false" Unicode="false" />
</EntityType>
<EntityType Name="ref_beehive_poll_forecast">
<Key>
......@@ -189,7 +191,7 @@
</Dependent>
</ReferentialConstraint>
</Association>
</Schema>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
......@@ -213,6 +215,7 @@
<EntitySetMapping Name="beehive_weather_forecast">
<EntityTypeMapping TypeName="delmeModel.beehive_weather_forecast">
<MappingFragment StoreEntitySet="beehive_weather_forecast">
<ScalarProperty Name="Icon" ColumnName="Icon" />
<ScalarProperty Name="Location" ColumnName="Location" />
<ScalarProperty Name="Cloudiness" ColumnName="Cloudiness" />
<ScalarProperty Name="Humidity" ColumnName="Humidity" />
......
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BeeWeatherPollenTracker
{
public class LoggerManager
{
private static LoggerManager Logger = null;
private String Path = "";
private FileStream fs = null;
public LoggerManager()
{
Path = ".\\logfile.txt";
if (!File.Exists(Path)) // Check if the file is existing and create him if not.
{
fs = File.Create(Path);
}
else
{
fs = File.OpenWrite(Path);
}
// define type of log
public enum DataForcastType {
WEATHER,
POLL
}
// Instance of class
private static LoggerManager Logger = null;
/// <summary>
/// Create new instance of logger manager
/// </summary>
public LoggerManager() {}
/// <summary>
/// Get unique instance of logger manager
/// </summary>
/// <returns></returns>
public static LoggerManager GetInstance()
{
if (Logger == null)
......@@ -35,13 +33,49 @@ namespace BeeWeatherPollenTracker
return Logger;
}
/// <summary>
/// Write execption in log file
/// </summary>
/// <param name="type">type of log</param>
/// <param name="e"></param>
public void WriteInFile(Exception e)
{
// retreive current datetime
DateTime dt = DateTime.Now;
string res = dt.ToString() + " : "+ e.Message + " \n\t" + e.StackTrace ;
string path = String.Format(".\\LOG_{0}.txt", dt.ToString("yyyy-MM-dd"));
// initialize file stream
FileStream fs = new FileStream(path, FileMode.Append);
// write content in file
string res = dt.ToString() + " : "+ e.Message ;
byte[] data = Encoding.UTF8.GetBytes(res);
fs.Write(data, 0, data.Length);
fs.Close();
}
/// <summary>
/// Write data in log file
/// </summary>
/// <param name="json">data to write</param>
public void WriteBackup(DataForcastType type, string json)
{
// define backup file
string path = String.Format(".\\BACKUP_{0}_{1}.json", type.ToString(), DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
// initialize file stream
FileStream fs = new FileStream(path, FileMode.Append);
// write content in file
byte[] d = Encoding.UTF8.GetBytes(json);
fs.Write(d, 0, d.Length);
fs.Close();
}
}
}
}
\ No newline at end of file

using MySql.Data.EntityFramework;
using MySql.Data.EntityFramework;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Threading;
using WeatherNet;
......@@ -13,6 +13,11 @@ namespace BeeWeatherPollenTracker
{
internal static class Program
{
#region Constantes
private const string POLLEN_FORECAST_URL = "https://opendata.dwd.de/climate_environment/health/alerts/s31fg.json";
#endregion
private static LoggerManager logs = null;
private static void Main(string[] args)
......@@ -42,8 +47,12 @@ namespace BeeWeatherPollenTracker
catch (Exception e)
{
logs.WriteInFile(e);
logs.WriteBackup(LoggerManager.DataForcastType.POLL, pollenJson);
}
#endregion Pollen
t.Join();
}
}
}
}
\ No newline at end of file
using MySql.Data.EntityFramework;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using WeatherNet;
using WeatherNet.Clients;
namespace BeeWeatherPollenTracker
{
public class WeatherForecast
{
#region Constantes
private const string OPEN_WEATHER_MAP_API_KEY = "3f80e65ed0609e7e52737e65d522aed8";
private const double FORECAST_LENGTH = 3.0;
#endregion
#region Attributes
// Weather forecast data
private List<beehive_weather_forecast> _weather_forecast_list;
private static LoggerManager logs = null;
#endregion
/// <summary>
/// Create new instance of weatherforcase
/// </summary>
public WeatherForecast()
{
// Initialize weather forecast list
this._weather_forecast_list = new List<beehive_weather_forecast>();
// Set up API KEY
ClientSettings.SetApiKey(OPEN_WEATHER_MAP_API_KEY);
// Set up the logger manager
logs = LoggerManager.GetInstance();
}
public void Process()
{
RetreiveData();
PushForecastToDatabase();
}
/// <summary>
/// Retreive Data from API
/// </summary>
private void RetreiveData()
{
// Retrieve forecast data from from OWM API
var cityId = int.Parse(ConfigurationManager.AppSettings["CityId"]);
var apiResults = FiveDaysForecast.GetByCityId(cityId);
if (!apiResults.Success)
{
throw new ApplicationException(apiResults.Message);
}
// Filter: keep only 3 next days forecast
var forecast = apiResults.Items
.Where(x => x.Date < DateTime.Now.AddDays(FORECAST_LENGTH))
.ToList();
foreach (var item in forecast)
{
beehive_weather_forecast w = new beehive_weather_forecast();
w.Input_date = DateTime.Now;
w.Forecast_date = item.Date;
w.Temperature = item.Temp;
w.Humidity = item.Humidity;
w.Wind = item.WindSpeed;
w.Cloudiness = item.Description;
w.Location = item.City;
_weather_forecast_list.Add(w);
}
}
/// <summary>
/// Push weather forecast to database
/// </summary>
private void PushForecastToDatabase()
{
try
{
// Entity context
var context = new delmeEntities1();
// Add weather forecast to context
foreach (var item in this._weather_forecast_list)
context.beehive_weather_forecast.Add(item);
// Push data in databse
context.SaveChanges();
}
catch (Exception ex)
{
logs.WriteInFile(ex);
}
finally
{
// Clear weather data
this._weather_forecast_list.Clear();
}
}
}
}
using MySql.Data.EntityFramework;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using WeatherNet;
using WeatherNet.Clients;
namespace BeeWeatherPollenTracker
{
public class WeatherForecast
{
#region Constantes
private const string OPEN_WEATHER_MAP_API_KEY = "3f80e65ed0609e7e52737e65d522aed8";
private const double FORECAST_LENGTH = 3.0;
#endregion
#region Attributes
// Weather forecast data
private List<beehive_weather_forecast> _weather_forecast_list;
private static LoggerManager logs = null;
#endregion
/// <summary>
/// Create new instance of weatherforcase
/// </summary>
public WeatherForecast()
{
// Initialize weather forecast list
this._weather_forecast_list = new List<beehive_weather_forecast>();
// Set up API KEY
ClientSettings.SetApiKey(OPEN_WEATHER_MAP_API_KEY);
// Set up the logger manager
logs = LoggerManager.GetInstance();
}
public void Process()
{
RetreiveData();
PushForecastToDatabase();
}
/// <summary>
/// Retreive Data from API
/// </summary>
private void RetreiveData()
{
// Retrieve forecast data from from OWM API
var cityId = int.Parse(ConfigurationManager.AppSettings["CityId"]);
var apiResults = FiveDaysForecast.GetByCityId(cityId);
if (!apiResults.Success)
{
throw new ApplicationException(apiResults.Message);
}
// Filter: keep only 3 next days forecast
var forecast = apiResults.Items
.Where(x => x.Date < DateTime.Now.AddDays(FORECAST_LENGTH))
.ToList();
foreach (var item in forecast)
{
beehive_weather_forecast w = new beehive_weather_forecast();
w.Input_date = DateTime.Now;
w.Forecast_date = item.Date;
w.Temperature = item.Temp;
w.Humidity = item.Humidity;
w.Wind = item.WindSpeed;
w.Cloudiness = item.Description;
w.Location = item.City;
w.Icon = item.Icon;
_weather_forecast_list.Add(w);
}
}
/// <summary>
/// Push weather forecast to database
/// </summary>
private void PushForecastToDatabase()
{
try
{
// Entity context
using (var context = new delmeEntities1())
{
// Add weather forecast to context
foreach (var item in this._weather_forecast_list)
context.beehive_weather_forecast.Add(item);
// Push data in databse
context.SaveChanges();
}
}
catch (Exception ex)
{
// write
logs.WriteInFile(ex);
// write data backup
logs.WriteBackup(LoggerManager.DataForcastType.WEATHER, JsonConvert.SerializeObject(_weather_forecast_list));
}
finally
{
// Clear weather data
this._weather_forecast_list.Clear();
}
}
}
}
......@@ -22,5 +22,6 @@ namespace BeeWeatherPollenTracker
public double Humidity { get; set; }
public string Cloudiness { get; set; }
public string Location { get; set; }
public string Icon { get; set; }
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment