add RecipeType and change ctors of Recipes

pull/65/head
Alexandre AGOSTINHO 2 years ago
parent a0e536c9cb
commit 596e699382

@ -39,12 +39,13 @@ namespace ConsoleApp.Menu
Recipe recipe = new Recipe( Recipe recipe = new Recipe(
title: title, title: title,
type: RecipeType.Unspecified,
id: null, id: null,
authorMail: masterMgr.CurrentConnectedUser?.Mail, authorMail: masterMgr.CurrentConnectedUser?.Mail,
picture: "", picture: null)
ingredients: new List<Ingredient>(), {
preparationSteps: steps.ToArray() PreparationSteps = steps
); };
masterMgr.AddRecipe(recipe); masterMgr.AddRecipe(recipe);
return null; return null;

@ -1,118 +1,119 @@
using Model; using Model;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Runtime.Serialization.Json; using System.Runtime.Serialization.Json;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml; using System.Xml;
using System.Xml.Linq; using System.Xml.Linq;
namespace DataPersistence namespace DataPersistence
{ {
/// <summary> /// <summary>
/// Define a serializer to manage JSON files. /// Define a serializer to manage JSON files.
/// </summary> /// </summary>
public class DataContractJSON : IDataManager public class DataContractJSON : IDataManager
{ {
#region Attributes #region Attributes
private string _jsonFolderPath; private string _jsonFolderPath;
private DataContractJsonSerializerSettings _dataContractJsonSerializerSettings; private DataContractJsonSerializerSettings _dataContractJsonSerializerSettings;
#endregion #endregion
#region Constructors #region Constructors
/// <summary> /// <summary>
/// Constructor of the DataContractJSON serializer. /// Constructor of the DataContractJSON serializer.
/// </summary> /// </summary>
/// <param name="jsonFolderPath">Give the default path where to load and save the data (by default is the current execution dir).</param> /// <param name="jsonFolderPath">Give the default path where to load and save the data (by default is the current execution dir).</param>
/// <param name="dataContractJsonSerializerSettings">Give another set of DataContractJson serializer setting to write file</param> /// <param name="dataContractJsonSerializerSettings">Give another set of DataContractJson serializer setting to write file</param>
public DataContractJSON(string jsonFolderPath = "", public DataContractJSON(string jsonFolderPath = "",
DataContractJsonSerializerSettings? dataContractJsonSerializerSettings = null) DataContractJsonSerializerSettings? dataContractJsonSerializerSettings = null)
{ {
_jsonFolderPath = jsonFolderPath; _jsonFolderPath = jsonFolderPath;
if (dataContractJsonSerializerSettings is null) if (dataContractJsonSerializerSettings is null)
_dataContractJsonSerializerSettings = new DataContractJsonSerializerSettings() _dataContractJsonSerializerSettings = new DataContractJsonSerializerSettings()
{ {
KnownTypes = new[] KnownTypes = new[]
{ {
typeof(Recipe), typeof(Recipe),
typeof(Review), typeof(RecipeType),
typeof(User), typeof(Review),
typeof(Ingredient), typeof(User),
typeof(Quantity) typeof(Ingredient),
} typeof(Quantity)
}; }
else };
_dataContractJsonSerializerSettings = dataContractJsonSerializerSettings; else
} _dataContractJsonSerializerSettings = dataContractJsonSerializerSettings;
#endregion }
#endregion
#region IDataManager implementation
public void Export<T>(T obj, string pathToExport) #region IDataManager implementation
where T : class public void Export<T>(T obj, string pathToExport)
{ where T : class
var jsonSerializer = new DataContractJsonSerializer(typeof(T), _dataContractJsonSerializerSettings); {
using (FileStream stream = File.Create(Path.Combine(_jsonFolderPath, pathToExport))) var jsonSerializer = new DataContractJsonSerializer(typeof(T), _dataContractJsonSerializerSettings);
{ using (FileStream stream = File.Create(Path.Combine(_jsonFolderPath, pathToExport)))
using (var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter( {
stream: stream, using (var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(
encoding: System.Text.Encoding.UTF8, stream: stream,
ownsStream: false, encoding: System.Text.Encoding.UTF8,
indent: true)) ownsStream: false,
{ indent: true))
jsonSerializer.WriteObject(jsonWriter, obj); {
} jsonSerializer.WriteObject(jsonWriter, obj);
} }
} }
}
public KeyValuePair<string, T> Import<T>(string pathToImport)
where T : class public KeyValuePair<string, T> Import<T>(string pathToImport)
{ where T : class
T? obj; {
var jsonSerializer = new DataContractJsonSerializer(typeof(T), _dataContractJsonSerializerSettings); T? obj;
using (FileStream stream = File.OpenRead(Path.Combine(_jsonFolderPath, pathToImport))) var jsonSerializer = new DataContractJsonSerializer(typeof(T), _dataContractJsonSerializerSettings);
{ using (FileStream stream = File.OpenRead(Path.Combine(_jsonFolderPath, pathToImport)))
obj = jsonSerializer.ReadObject(stream) as T; {
} obj = jsonSerializer.ReadObject(stream) as T;
}
if (obj is null)
throw new ArgumentNullException("obj"); if (obj is null)
throw new ArgumentNullException("obj");
string typeName = typeof(T).Name;
return new KeyValuePair<string, T>(typeName, obj); string typeName = typeof(T).Name;
} return new KeyValuePair<string, T>(typeName, obj);
}
public Dictionary<string, List<object>> Load()
{ public Dictionary<string, List<object>> Load()
Dictionary<string, List<object>>? elements = new Dictionary<string, List<object>>(); {
var jsonSerializer = new DataContractJsonSerializer(typeof(Dictionary<string, List<object>>), _dataContractJsonSerializerSettings); Dictionary<string, List<object>>? elements = new Dictionary<string, List<object>>();
using (FileStream stream = File.OpenRead(Path.Combine(_jsonFolderPath, "data.json"))) var jsonSerializer = new DataContractJsonSerializer(typeof(Dictionary<string, List<object>>), _dataContractJsonSerializerSettings);
{ using (FileStream stream = File.OpenRead(Path.Combine(_jsonFolderPath, "data.json")))
elements = jsonSerializer.ReadObject(stream) as Dictionary<string, List<object>>; {
} elements = jsonSerializer.ReadObject(stream) as Dictionary<string, List<object>>;
}
if (elements is null)
throw new ArgumentNullException("elements"); if (elements is null)
throw new ArgumentNullException("elements");
return elements;
} return elements;
}
public void Save(Dictionary<string, List<object>> elements)
{ public void Save(Dictionary<string, List<object>> elements)
var jsonSerializer = new DataContractJsonSerializer(typeof(Dictionary<string, List<object>>), _dataContractJsonSerializerSettings); {
using (FileStream stream = File.Create(Path.Combine(_jsonFolderPath, "data.json"))) var jsonSerializer = new DataContractJsonSerializer(typeof(Dictionary<string, List<object>>), _dataContractJsonSerializerSettings);
{ using (FileStream stream = File.Create(Path.Combine(_jsonFolderPath, "data.json")))
using (var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter( {
stream: stream, using (var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(
encoding: System.Text.Encoding.UTF8, stream: stream,
ownsStream: false, encoding: System.Text.Encoding.UTF8,
indent: true)) ownsStream: false,
{ indent: true))
jsonSerializer.WriteObject(jsonWriter, elements); {
} jsonSerializer.WriteObject(jsonWriter, elements);
} }
} }
#endregion }
} #endregion
} }
}

@ -1,123 +1,124 @@
using Model; using Model;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml; using System.Xml;
using System.Xml.Linq; using System.Xml.Linq;
namespace DataPersistence namespace DataPersistence
{ {
/// <summary> /// <summary>
/// Define a serializer to manage XML files. /// Define a serializer to manage XML files.
/// </summary> /// </summary>
public class DataContractXML : IDataManager public class DataContractXML : IDataManager
{ {
#region Attributes #region Attributes
private string _xmlFolderPath; private string _xmlFolderPath;
private XmlWriterSettings _xmlWriterSettings; private XmlWriterSettings _xmlWriterSettings;
private DataContractSerializerSettings _dataContractSerializerSettings; private DataContractSerializerSettings _dataContractSerializerSettings;
#endregion #endregion
#region Constructors #region Constructors
/// <summary> /// <summary>
/// Constructor of a DataContractXML serializer. /// Constructor of a DataContractXML serializer.
/// </summary> /// </summary>
/// <param name="xmlFolderPath">Give the default path where to load and save the data (by default is the current execution dir).</param> /// <param name="xmlFolderPath">Give the default path where to load and save the data (by default is the current execution dir).</param>
/// <param name="xmlWriterSettings">Give another set of XML setting to write file.</param> /// <param name="xmlWriterSettings">Give another set of XML setting to write file.</param>
/// <param name="dataContractSerializerSettings">Give another set of DataContract serializer setting to write file</param> /// <param name="dataContractSerializerSettings">Give another set of DataContract serializer setting to write file</param>
public DataContractXML(string xmlFolderPath = "", public DataContractXML(string xmlFolderPath = "",
XmlWriterSettings? xmlWriterSettings = null, XmlWriterSettings? xmlWriterSettings = null,
DataContractSerializerSettings? dataContractSerializerSettings = null) DataContractSerializerSettings? dataContractSerializerSettings = null)
{ {
_xmlFolderPath = xmlFolderPath; _xmlFolderPath = xmlFolderPath;
if (xmlWriterSettings is null) if (xmlWriterSettings is null)
_xmlWriterSettings = new XmlWriterSettings() { Indent = true }; _xmlWriterSettings = new XmlWriterSettings() { Indent = true };
else else
_xmlWriterSettings = xmlWriterSettings; _xmlWriterSettings = xmlWriterSettings;
if (dataContractSerializerSettings is null) if (dataContractSerializerSettings is null)
_dataContractSerializerSettings = new DataContractSerializerSettings() _dataContractSerializerSettings = new DataContractSerializerSettings()
{ {
KnownTypes = new Type[] KnownTypes = new Type[]
{ {
typeof(Recipe), typeof(Recipe),
typeof(Review), typeof(RecipeType),
typeof(User), typeof(Review),
typeof(Ingredient), typeof(User),
typeof(Quantity), typeof(Ingredient),
typeof(PasswordSHA256) typeof(Quantity),
}, typeof(PasswordSHA256)
PreserveObjectReferences = true },
}; PreserveObjectReferences = true
else };
_dataContractSerializerSettings = dataContractSerializerSettings; else
} _dataContractSerializerSettings = dataContractSerializerSettings;
#endregion }
#endregion
#region IDataManager implementation
public void Export<T>(T obj, string pathToExport) #region IDataManager implementation
where T : class public void Export<T>(T obj, string pathToExport)
{ where T : class
bool restore = _dataContractSerializerSettings.PreserveObjectReferences; {
_dataContractSerializerSettings.PreserveObjectReferences = false; bool restore = _dataContractSerializerSettings.PreserveObjectReferences;
var serializer = new DataContractSerializer(typeof(T), _dataContractSerializerSettings); _dataContractSerializerSettings.PreserveObjectReferences = false;
using (TextWriter textWriter = File.CreateText(Path.Combine(_xmlFolderPath, pathToExport))) var serializer = new DataContractSerializer(typeof(T), _dataContractSerializerSettings);
{ using (TextWriter textWriter = File.CreateText(Path.Combine(_xmlFolderPath, pathToExport)))
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, _xmlWriterSettings)) {
{ using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, _xmlWriterSettings))
serializer.WriteObject(xmlWriter, obj); {
} serializer.WriteObject(xmlWriter, obj);
} }
_dataContractSerializerSettings.PreserveObjectReferences = restore; }
} _dataContractSerializerSettings.PreserveObjectReferences = restore;
}
public KeyValuePair<string, T> Import<T>(string pathToImport)
where T : class public KeyValuePair<string, T> Import<T>(string pathToImport)
{ where T : class
T? obj; {
var serializer = new DataContractSerializer(typeof(T), _dataContractSerializerSettings); T? obj;
using (Stream s = File.OpenRead(Path.Combine(_xmlFolderPath, pathToImport))) var serializer = new DataContractSerializer(typeof(T), _dataContractSerializerSettings);
{ using (Stream s = File.OpenRead(Path.Combine(_xmlFolderPath, pathToImport)))
obj = serializer.ReadObject(s) as T; {
} obj = serializer.ReadObject(s) as T;
}
if (obj is null)
throw new ArgumentNullException("obj"); if (obj is null)
throw new ArgumentNullException("obj");
string typeName = typeof(T).Name;
return new KeyValuePair<string, T>(typeName, obj); string typeName = typeof(T).Name;
} return new KeyValuePair<string, T>(typeName, obj);
}
public Dictionary<string, List<object>> Load()
{ public Dictionary<string, List<object>> Load()
Dictionary<string, List<object>>? elements; {
var serializer = new DataContractSerializer(typeof(Dictionary<string, List<object>>), _dataContractSerializerSettings); Dictionary<string, List<object>>? elements;
using (Stream s = File.OpenRead(Path.Combine(_xmlFolderPath, "data.xml"))) var serializer = new DataContractSerializer(typeof(Dictionary<string, List<object>>), _dataContractSerializerSettings);
{ using (Stream s = File.OpenRead(Path.Combine(_xmlFolderPath, "data.xml")))
elements = serializer.ReadObject(s) as Dictionary<string, List<object>>; {
} elements = serializer.ReadObject(s) as Dictionary<string, List<object>>;
}
if (elements is null)
throw new ArgumentNullException("elements"); if (elements is null)
throw new ArgumentNullException("elements");
return elements;
} return elements;
}
public void Save(Dictionary<string, List<object>> elements)
{ public void Save(Dictionary<string, List<object>> elements)
var serializer = new DataContractSerializer(typeof(Dictionary<string, List<object>>), _dataContractSerializerSettings); {
using (TextWriter textWriter = File.CreateText(Path.Combine(_xmlFolderPath, "data.xml"))) var serializer = new DataContractSerializer(typeof(Dictionary<string, List<object>>), _dataContractSerializerSettings);
{ using (TextWriter textWriter = File.CreateText(Path.Combine(_xmlFolderPath, "data.xml")))
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, _xmlWriterSettings)) {
{ using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, _xmlWriterSettings))
serializer.WriteObject(xmlWriter, elements); {
} serializer.WriteObject(xmlWriter, elements);
} }
} }
#endregion }
} #endregion
} }
}

@ -3,6 +3,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace DataPersistence namespace DataPersistence
@ -21,77 +22,123 @@ namespace DataPersistence
nameof(Recipe), nameof(Recipe),
new List<object>(new[] new List<object>(new[]
{ {
new Recipe( new Recipe("Cookies classiques", RecipeType.Dessert, null, "admin@mctg.fr", "")
title: "Cookies classiques", {
id: 50, Ingredients = new List<Ingredient>
authorMail: "admin@mctg.fr",
picture : "room_service_icon.png",
ingredients: new List<Ingredient>(new[]
{ {
new Ingredient("Patates", new Quantity(23, Unit.unit)), new Ingredient("Patates", new Quantity(23, Unit.unit)),
new Ingredient("Farine", new Quantity(23, Unit.G)) new Ingredient("Farine", new Quantity(23, Unit.G))
}), },
preparationSteps: new[] PreparationSteps = new List<PreparationStep>
{ {
new PreparationStep(1, "Faire cuire."), new PreparationStep(1, "Faire cuire."),
new PreparationStep(2, "Manger.") new PreparationStep(2, "Manger.")
}), },
Reviews = new List<Review>
{
new Review(4, "Bonne recette, je recommande !"),
new Review(3, "Bof bof, mais mangeable...")
}
},
new Recipe( new Recipe(
authorMail: "admin@mctg.fr",
title: "Cookies au chocolat", title: "Cookies au chocolat",
id: null, type: RecipeType.Dessert)
preparationSteps: new[] {
Ingredients = new List<Ingredient>
{
new Ingredient("Farine", new Quantity(200, Unit.G))
},
PreparationSteps = new List<PreparationStep>()
{ {
new PreparationStep(1, "Moulinez la pâte."), new PreparationStep(1, "Moulinez la pâte."),
new PreparationStep(2, "Faire cuire pendant une bonne heure."), new PreparationStep(2, "Faire cuire pendant une bonne heure."),
new PreparationStep(3, "Sortir du four et mettre dans un plat.") new PreparationStep(3, "Sortir du four et mettre dans un plat.")
}), }
},
new Recipe( new Recipe(
title: "Gateau nature", id: null, title: "Gateau nature",
authorMail: "admin@mctg.fr", type: RecipeType.Dessert)
preparationSteps: new[] {
Ingredients = new List<Ingredient>
{
new Ingredient("Farine", new Quantity(200, Unit.G)),
new Ingredient("Lait", new Quantity(2, Unit.L))
},
PreparationSteps = new List<PreparationStep>
{ {
new PreparationStep(1, "Achetez les ingrédients."), new PreparationStep(1, "Achetez les ingrédients."),
new PreparationStep(2, "Préparez le matériel. Ustensiles et tout."), new PreparationStep(2, "Préparez le matériel. Ustensiles et tout."),
new PreparationStep(3, "Pleurez.") new PreparationStep(3, "Pleurez.")
}), },
Reviews = new List<Review>
{
new Review("pedrosamigos@hotmail.com", 5, "C'était vraiment IN-CROY-ABLE !!!")
}
},
new Recipe( new Recipe(
title: "Gateau au pommes", id: null, title: "Gateau au pommes",
authorMail: "admin@mctg.fr", type: RecipeType.Dessert)
preparationSteps: new[] {
PreparationSteps = new List<PreparationStep>
{ {
new PreparationStep(1, "Achetez les légumes."), new PreparationStep(1, "Achetez les légumes."),
new PreparationStep(2, "Préparez le plat. Ustensiles et préchauffez le four."), new PreparationStep(2, "Préparez le plat. Ustensiles et préchauffez le four."),
new PreparationStep(3, "Coupez les pommes en morceaux et disposez-les sur le plat."), new PreparationStep(3, "Coupez les pommes en morceaux et disposez-les sur le plat."),
new PreparationStep(4, "Mettez enfin le plat au four, puis une fois cuit, dégustez !") new PreparationStep(4, "Mettez enfin le plat au four, puis une fois cuit, dégustez !")
}), }
},
new Recipe( new Recipe(
title: "Gateau au chocolat", id: null, title: "Gateau au chocolat",
authorMail: "pedrosamigos@hotmail.com", type: RecipeType.Dessert,
preparationSteps: new[] id: null, authorMail: "pedrosamigos@hotmail.com")
{
Ingredients = new List<Ingredient>
{
new Ingredient("Mais", new Quantity(2, Unit.kG)),
new Ingredient("Sachet pépites de chocolat", new Quantity(1, Unit.unit)),
new Ingredient("Dinde", new Quantity(2, Unit.G))
},
PreparationSteps = new List<PreparationStep>
{ {
new PreparationStep(1, "Ajouter les oeufs."), new PreparationStep(1, "Ajouter les oeufs."),
new PreparationStep(2, "Ajouter la farine."), new PreparationStep(2, "Ajouter la farine."),
new PreparationStep(3, "Ajouter 100g de chocolat fondu."), new PreparationStep(3, "Ajouter 100g de chocolat fondu."),
new PreparationStep(4, "Mélanger le tout."), new PreparationStep(4, "Mélanger le tout."),
new PreparationStep(5, "Faire cuire 45h au four traditionnel.") new PreparationStep(5, "Faire cuire 45h au four traditionnel.")
}), }
},
new Recipe( new Recipe(
title: "Dinde au jambon", title: "Dinde au jambon",
id: null, type: RecipeType.Dish,
authorMail: "pedrosamigos@hotmail.com", id: null, authorMail: "pedrosamigos@hotmail.com")
preparationSteps: new[] {
Ingredients = new List<Ingredient>
{
new Ingredient("Morceaux de bois", new Quantity(2, Unit.unit)),
new Ingredient("Sachet gélatine", new Quantity(1, Unit.unit)),
new Ingredient("Jambon", new Quantity(2, Unit.kG))
},
PreparationSteps = new List<PreparationStep>
{ {
new PreparationStep(1, "Faire une cuisson bien sec de la dinde à la poêle"), new PreparationStep(1, "Faire une cuisson bien sec de la dinde à la poêle"),
new PreparationStep(2, "Mettre la dinde au frigo."), new PreparationStep(2, "Mettre la dinde au frigo."),
new PreparationStep(3, "Mettre le jambon dans le micro-onde."), new PreparationStep(3, "Mettre le jambon dans le micro-onde."),
new PreparationStep(4, "Faire chauffer 3min."), new PreparationStep(4, "Faire chauffer 3min."),
new PreparationStep(5, "Présentez sur un plat la dinde et le jambon : Miam !") new PreparationStep(5, "Présentez sur un plat la dinde et le jambon : Miam !")
}), }
},
new Recipe( new Recipe(
title: "Poulet au curry", id: null, title: "Poulet au curry",
authorMail: "pedrosamigos@hotmail.com", type: RecipeType.Dish,
preparationSteps: new[] id: null, authorMail: "pedrosamigos@hotmail.com")
{
Ingredients = new List<Ingredient>
{
new Ingredient("Pissenlis", new Quantity(200, Unit.unit)),
new Ingredient("Boule de pétanque", new Quantity(10, Unit.unit)),
new Ingredient("Poivre", new Quantity(4, Unit.mG))
},
PreparationSteps = new List<PreparationStep>
{ {
new PreparationStep(1, "Trouvez des épices de curry."), new PreparationStep(1, "Trouvez des épices de curry."),
new PreparationStep(2, "Trouvez maintenant du poulet."), new PreparationStep(2, "Trouvez maintenant du poulet."),
@ -99,7 +146,12 @@ namespace DataPersistence
new PreparationStep(4, "Parsemez d'épices curry la tête de la poule."), new PreparationStep(4, "Parsemez d'épices curry la tête de la poule."),
new PreparationStep(5, "Mettre le tout au four traditionnel 30min."), new PreparationStep(5, "Mettre le tout au four traditionnel 30min."),
new PreparationStep(6, "Dégustez en famille !") new PreparationStep(6, "Dégustez en famille !")
}) },
Reviews = new List<Review>
{
new Review(5, "Meilleure recette que j'ai avalé de tout les temps !!!!!!!")
}
}
}) })
#endregion #endregion
}, },

@ -148,7 +148,7 @@ namespace Model.Managers
/// <returns>The current connected user's personal recipes.</returns> /// <returns>The current connected user's personal recipes.</returns>
public RecipeCollection GetCurrentUserRecipes() public RecipeCollection GetCurrentUserRecipes()
=> new RecipeCollection("User recipes", => new RecipeCollection("User recipes",
DataMgr.GetRecipes().FindAll(r => r.AuthorMail == CurrentConnectedUser?.Mail).ToArray()); DataMgr.GetRecipes().ToList().FindAll(r => r.AuthorMail == CurrentConnectedUser?.Mail).ToArray());
/// <summary> /// <summary>
/// Notify property change handler. /// Notify property change handler.

@ -19,6 +19,9 @@ namespace Model
[DataMember(Name = "image")] [DataMember(Name = "image")]
private string _image = ""; private string _image = "";
[DataMember(Name = "authorMail")]
private string _authorMail = "";
#endregion #endregion
#region Properties #region Properties
@ -32,15 +35,22 @@ namespace Model
/// List of reviews of this recipe. /// List of reviews of this recipe.
/// </summary> /// </summary>
[DataMember(Name = "reviews")] [DataMember(Name = "reviews")]
public List<Review> Reviews { get; private set; } public List<Review> Reviews { get; set; }
/// <summary> /// <summary>
/// AuthorMail's mail of the recipe. /// AuthorMail's mail of the recipe.
/// </summary> /// </summary>
[DataMember(Name = "authorMail")] public string? AuthorMail
public string? AuthorMail { get; private set; } {
get => _authorMail;
public string Toto { get; set; } = "Coucou"; set
{
if (string.IsNullOrEmpty(value))
_authorMail = "admin@mctg.fr";
else
_authorMail = value;
}
}
/// <summary> /// <summary>
/// The Title of the recipe. <br/> /// The Title of the recipe. <br/>
@ -67,12 +77,14 @@ namespace Model
get => _image; get => _image;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (string.IsNullOrWhiteSpace(value))
_image = "room_service_icon.png"; _image = "room_service_icon.png";
_image = value; else
_image = value;
} }
} }
/// <summary>
/// The list of ingredients. /// The list of ingredients.
/// </summary> /// </summary>
[DataMember(Name = "ingredient")] [DataMember(Name = "ingredient")]
@ -84,30 +96,34 @@ namespace Model
/// </summary> /// </summary>
[DataMember(Name = "preparation-steps")] [DataMember(Name = "preparation-steps")]
public List<PreparationStep> PreparationSteps { get; set; } public List<PreparationStep> PreparationSteps { get; set; }
/// <summary>
/// The type of recipe.
/// </summary>
[DataMember(Name = "type")]
public RecipeType Type { get; private set; }
#endregion #endregion
#region Constructors #region Constructors
/// <summary> /// <summary>
/// Construct a new recipe. /// Construct a new recipe.
/// </summary> /// </summary>
/// <param _name="title">The title of the recipe</param> /// <param name="title">The title of the recipe</param>
/// <param _name="id">The id of the recipe. If not given, get a new id.</param> /// <param name="type">The type of the recipe.</param>
/// <param _name="authorMail">The name of the user that create this recipe.</param> /// <param name="id">The id of the recipe. If not given, get a new id.</param>
/// <param _name="picture"> The image that represent the recipe</param> /// <param name="authorMail">The name of the user that create this recipe.</param>
/// <param _name="reviews">Thr list of reviews.</param> /// <param name="picture"> The image that represent the recipe</param>
/// <param _name="ingredients">Thr list of ingredients.</param> public Recipe(string title, RecipeType type, int? id, string? authorMail, string? picture)
/// <param _name="preparationSteps">The steps of the preparation of the meal</param>
public Recipe(string title, int? id, string? authorMail, string? picture,
List<Review> reviews, List<Ingredient> ingredients,
params PreparationStep[] preparationSteps)
{ {
Title = title; Title = title;
Type = type;
Image = picture; Image = picture;
PreparationSteps = new List<PreparationStep>(preparationSteps);
Ingredients = ingredients;
Reviews = reviews;
AuthorMail = authorMail; AuthorMail = authorMail;
PreparationSteps = new List<PreparationStep>();
Ingredients = new List<Ingredient>();
Reviews = new List<Review>();
if (id == null) if (id == null)
{ {
var randomGenerator = RandomNumberGenerator.Create(); var randomGenerator = RandomNumberGenerator.Create();
@ -118,46 +134,20 @@ namespace Model
else Id = (int)id; else Id = (int)id;
} }
public Recipe(string title, RecipeType type, int? id, string? authorMail)
/// <summary> : this(title, type, id, authorMail, null)
/// <inheritdoc cref="Recipe.Recipe(string, int?, List{Review}, PreparationStep[])"/>
/// </summary>
/// <param _name="title">The title of the recipe.</param>
/// <param _name="id">The id of the recipe. If not given, get a new id.</param>
/// <param _name="authorMail">Mail of the user that create the recipe</param>
/// <param _name="preparationSteps">The steps of the preparation of the meal.</param>
public Recipe(string title, int? id, string? authorMail, params PreparationStep[] preparationSteps)
: this(title, id, authorMail, null, new List<Review>(), new List<Ingredient>(), preparationSteps)
{ {
} }
/// <summary> public Recipe(string title, RecipeType type)
/// <inheritdoc cref="Recipe.Recipe(string, int?, List{Review}, PreparationStep[])"/> : this(title, type, null, null)
/// </summary>
/// <param _name="title">The title of the recipe.</param>
/// <param _name="id">The id of the recipe. If not given, get a new id.</param>
/// <param _name="authorMail">Mail of the user that create the recipe</param>
/// <param _name="picture">Mail of the user that create the recipe</param>
/// <param _name="ingredients">List of ingredients that compose the recipe. </param>
/// <param _name="preparationSteps">The steps of the preparation of the meal.</param>
public Recipe(string title, int? id, string? authorMail, string? picture, List<Ingredient> ingredients, params PreparationStep[] preparationSteps)
: this(title, id, authorMail, picture, new List<Review>(), ingredients, preparationSteps)
{ {
} }
/// <summary> public Recipe(string title)
/// <inheritdoc cref="Recipe.Recipe(string, int?, List{Review}, PreparationStep[])"/> : this(title, RecipeType.Unspecified)
/// </summary>
/// <param _name="title">The title of the recipe.</param>
/// <param _name="id">The id of the recipe. If not given, get a new id.</param>
/// <param _name="picture">Image that reppresent the recipe.</param>
/// <param _name="preparationSteps">The steps of the preparation of the meal.</param>
public Recipe()
: this("", null, null, null, new List<Review>(), new List<Ingredient>(),new PreparationStep[0])
{ {
} }
#endregion #endregion
#region Methods #region Methods

@ -8,9 +8,10 @@ namespace Model
{ {
/// <summary> /// <summary>
/// Define a collection of <see cref="Recipe"/>. /// Define a collection of <see cref="Recipe"/>.
/// <br/>This class implement <see cref="IList"/> and <see cref="IEquatable{T}"/>. /// <br/>This class is derived from <see cref="ObservableCollection{Recipe}"/>
/// and implement <see cref="IEquatable{RecipeCollection}"/> and <see cref="ICloneable"/>.
/// </summary> /// </summary>
public class RecipeCollection : List<Recipe>, IEquatable<RecipeCollection> public class RecipeCollection : ObservableCollection<Recipe>, IEquatable<RecipeCollection>, ICloneable
{ {
#region Attributes #region Attributes
private string _description = ""; private string _description = "";
@ -56,7 +57,8 @@ namespace Model
/// <exception cref="ArgumentException"/> /// <exception cref="ArgumentException"/>
public Recipe? GetRecipeById(int id) public Recipe? GetRecipeById(int id)
{ {
Recipe? recipe = this.Find(r => r.Id == id); Recipe? recipe = this.ToList().Find(r => r.Id == id);
if (recipe == null) throw new ArgumentException("No _recipes match the given id."); if (recipe == null) throw new ArgumentException("No _recipes match the given id.");
return recipe; return recipe;
} }
@ -73,7 +75,7 @@ namespace Model
return new RecipeCollection( return new RecipeCollection(
description: $"Results of the research: {str}", description: $"Results of the research: {str}",
recipes: this.FindAll(x => x.Title.ToLower().Contains(str.ToLower())).ToArray()); recipes: this.ToList().FindAll(x => x.Title.ToLower().Contains(str.ToLower())).ToArray());
} }
public virtual bool Equals(RecipeCollection? other) public virtual bool Equals(RecipeCollection? other)
@ -103,7 +105,14 @@ namespace Model
sb.AppendFormat("\t - {0}\n", r.ToString()); sb.AppendFormat("\t - {0}\n", r.ToString());
} }
return sb.ToString(); return sb.ToString();
} }
public object Clone()
{
return new RecipeCollection(
description: this.Description,
recipes: this.ToArray());
}
#endregion #endregion
} }
} }

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public enum RecipeType
{
Unspecified,
Starter,
Dish,
Dessert
}
}

@ -8,9 +8,8 @@ namespace Model_UnitTests
public void TestVoidConstructor() public void TestVoidConstructor()
{ {
Recipe r = new Recipe( Recipe r = new Recipe(
title: "test recipe", title: "test recipe", type: RecipeType.Unspecified);
id: null,
authorMail: "test@test.fr");
Assert.NotNull(r.Title); Assert.NotNull(r.Title);
} }
} }

@ -16,14 +16,17 @@ using System.Runtime.CompilerServices;
namespace Views namespace Views
{ {
public partial class App : Application public partial class App : Application
{ {
private Recipe currentRecipe { get; set; }
/// <summary> /// <summary>
/// Master manager - access to the Model. /// Master manager - access to the Model.
/// </summary> /// </summary>
public MasterManager MasterMgr { get; private set; } = new MasterManager(new Stubs()); public MasterManager MasterMgr { get; private set; } = new MasterManager(new Stubs());
//L'utilisateur courant de l'application
public User CurrentUser { get; set; } /// <summary>
private Recipe currentRecipe { get; set; } /// Current selected recipe.
/// </summary>
public Recipe CurrentRecipe public Recipe CurrentRecipe
{ {
get => currentRecipe; get => currentRecipe;

@ -31,7 +31,8 @@
<Button <Button
Text="Entrées" Text="Entrées"
ImageSource="flatware_icon.png" ImageSource="flatware_icon.png"
Style="{StaticResource button1}"/> Style="{StaticResource button1}"
Clicked="Entrees_Clicked"/>
<Button <Button
Text="Plats" Text="Plats"
ImageSource="room_service_icon.png" ImageSource="room_service_icon.png"
@ -73,7 +74,6 @@
</DataTemplate> </DataTemplate>
</BindableLayout.ItemTemplate> </BindableLayout.ItemTemplate>
</FlexLayout> </FlexLayout>
</StackLayout> </StackLayout>
</ScrollView> </ScrollView>

@ -2,6 +2,7 @@
using DataPersistence; using DataPersistence;
using Model; using Model;
using Model.Managers; using Model.Managers;
using System.Collections.ObjectModel;
using System.ComponentModel; using System.ComponentModel;
namespace Views namespace Views
@ -12,8 +13,8 @@ namespace Views
public User? user => (App.Current as App).CurrentUser; public User? user => (App.Current as App).CurrentUser;
public RecipeCollection AllRecipe => (App.Current as App).AllRecipes; public RecipeCollection AllRecipe => (App.Current as App).AllRecipes;
public RecipeCollection RecipesDisplayed { get; set; } private readonly RecipeCollection _recipesDisplayed;
public ReadOnlyObservableCollection<Recipe> RecipesDisplayed { get; private set; }
public static readonly BindableProperty IsNotConnectedProperty = public static readonly BindableProperty IsNotConnectedProperty =
BindableProperty.Create("IsNotConnected", typeof(bool), typeof(bool)); BindableProperty.Create("IsNotConnected", typeof(bool), typeof(bool));
@ -36,7 +37,8 @@ namespace Views
public Home() public Home()
{ {
RecipesDisplayed = MasterMgr.DataMgr.GetRecipes("Suggestions"); _recipesDisplayed = (RecipeCollection)AllRecipe.Clone();
RecipesDisplayed = new ReadOnlyObservableCollection<Recipe>(_recipesDisplayed);
InitializeComponent(); InitializeComponent();
BindingContext = this; BindingContext = this;
IsNotConnected = true; IsNotConnected = true;
@ -45,24 +47,36 @@ namespace Views
public Home(RecipeCollection recipesDisplayed) public Home(RecipeCollection recipesDisplayed)
{ {
RecipesDisplayed = recipesDisplayed; _recipesDisplayed = recipesDisplayed;
InitializeComponent(); InitializeComponent();
BindingContext = this; BindingContext = this;
IsNotConnected = true; IsNotConnected = true;
NeedReturn = true; NeedReturn = true;
} }
private async void SearchBar_SearchButtonPressed(object sender, EventArgs e) private void ModifyRecipesDisplayed(RecipeCollection recipes)
{
_recipesDisplayed.Clear();
foreach (Recipe recipe in recipes)
{
_recipesDisplayed.Add(recipe);
}
}
private void SearchBar_SearchButtonPressed(object sender, EventArgs e)
{ {
string searchStr = (sender as SearchBar).Text; string searchStr = (sender as SearchBar).Text;
await Navigation.PushModalAsync(new Home(AllRecipe.ResearchByName(searchStr))); ModifyRecipesDisplayed(AllRecipe.ResearchByName(searchStr));
} }
public void OnImageClicked(object sender, EventArgs e) public void OnImageClicked(object sender, EventArgs e)
{ {
(App.Current as App).CurrentRecipe = (Recipe)(sender as ImageButton).BindingContext; (App.Current as App).CurrentRecipe = (Recipe)(sender as ImageButton).BindingContext;
Navigation.PushModalAsync(new ViewRecette()); Navigation.PushModalAsync(new ViewRecette());
} }
private void Entrees_Clicked(object sender, EventArgs e)
{
return;
}
} }
} }

@ -1,106 +1,106 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net7.0-android</TargetFrameworks> <TargetFrameworks>net7.0-android</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net7.0-windows10.0.19041.0</TargetFrameworks> <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net7.0-windows10.0.19041.0</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('ios'))">$(TargetFrameworks);net7.0-ios</TargetFrameworks> <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('ios'))">$(TargetFrameworks);net7.0-ios</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('maccatalyst'))">$(TargetFrameworks);net7.0-maccatalyst</TargetFrameworks> <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('maccatalyst'))">$(TargetFrameworks);net7.0-maccatalyst</TargetFrameworks>
<!-- Uncomment to also build the tizen app. You will need to install tizen by following this: https://github.com/Samsung/Tizen.NET --> <!-- Uncomment to also build the tizen app. You will need to install tizen by following this: https://github.com/Samsung/Tizen.NET -->
<!-- <TargetFrameworks>$(TargetFrameworks);net7.0-tizen</TargetFrameworks> --> <!-- <TargetFrameworks>$(TargetFrameworks);net7.0-tizen</TargetFrameworks> -->
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<RootNamespace>Views</RootNamespace> <RootNamespace>Views</RootNamespace>
<UseMaui>true</UseMaui> <UseMaui>true</UseMaui>
<SingleProject>true</SingleProject> <SingleProject>true</SingleProject>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<!-- Display name --> <!-- Display name -->
<ApplicationTitle>Views</ApplicationTitle> <ApplicationTitle>Views</ApplicationTitle>
<!-- App Identifier --> <!-- App Identifier -->
<ApplicationId>com.companyname.views</ApplicationId> <ApplicationId>com.companyname.views</ApplicationId>
<ApplicationIdGuid>79cbc22d-7cee-47b2-af9f-b25e09cea0af</ApplicationIdGuid> <ApplicationIdGuid>79cbc22d-7cee-47b2-af9f-b25e09cea0af</ApplicationIdGuid>
<!-- Versions --> <!-- Versions -->
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion> <ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
<ApplicationVersion>1</ApplicationVersion> <ApplicationVersion>1</ApplicationVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">11.0</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">11.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'">13.1</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'">13.1</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</SupportedOSPlatformVersion>
<TargetPlatformMinVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</TargetPlatformMinVersion> <TargetPlatformMinVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</TargetPlatformMinVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion>
<Configurations>Debug;Release</Configurations> <Configurations>Debug;Release</Configurations>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<!-- App Icon --> <!-- App Icon -->
<MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#512BD4" /> <MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#512BD4" />
<!-- Splash Screen --> <!-- Splash Screen -->
<MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#512BD4" BaseSize="128,128" /> <MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#512BD4" BaseSize="128,128" />
<!-- Images --> <!-- Images -->
<MauiImage Include="Resources\Images\*" /> <MauiImage Include="Resources\Images\*" />
<MauiImage Update="Resources\Images\dotnet_bot.svg" BaseSize="168,208" /> <MauiImage Update="Resources\Images\dotnet_bot.svg" BaseSize="168,208" />
<!-- Custom Fonts --> <!-- Custom Fonts -->
<MauiFont Include="Resources\Fonts\*" /> <MauiFont Include="Resources\Fonts\*" />
<!-- Raw Assets (also remove the "Resources\Raw" prefix) --> <!-- Raw Assets (also remove the "Resources\Raw" prefix) -->
<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" /> <MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CommunityToolkit.Maui" Version="5.0.0" /> <PackageReference Include="CommunityToolkit.Maui" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\DataPersistence\DataPersistence.csproj" /> <ProjectReference Include="..\DataPersistence\DataPersistence.csproj" />
<ProjectReference Include="..\Model\Model.csproj" /> <ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<MauiXaml Update="AddRecipe.xaml"> <MauiXaml Update="AddRecipe.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="ContainerBase.xaml"> <MauiXaml Update="ContainerBase.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="ContainerFlyout.xaml"> <MauiXaml Update="ContainerFlyout.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="CustomHeader.xaml"> <MauiXaml Update="CustomHeader.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="Login.xaml"> <MauiXaml Update="Login.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="MiniHeader.xaml"> <MauiXaml Update="MiniHeader.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="MyPosts.xaml"> <MauiXaml Update="MyPosts.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="MyProfil.xaml"> <MauiXaml Update="MyProfil.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="RecipeCase.xaml"> <MauiXaml Update="RecipeCase.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="RecipeReviews.xaml"> <MauiXaml Update="RecipeReviews.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="ReturnButton.xaml"> <MauiXaml Update="ReturnButton.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="UserReview.xaml"> <MauiXaml Update="UserReview.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
<MauiXaml Update="ViewRecette.xaml"> <MauiXaml Update="ViewRecette.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</MauiXaml> </MauiXaml>
</ItemGroup> </ItemGroup>
</Project> </Project>

Loading…
Cancel
Save