Initial commit

This commit is contained in:
Mark J Price 2022-03-04 08:34:29 +00:00
parent 17ad36d6ad
commit 3d241b2154
44 changed files with 1619 additions and 0 deletions

View file

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Using Include="System.Console" Static="true" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,14 @@
namespace Packt.Shared;
public class Circle : Shape
{
public override double Area
{
get
{
return Math.PI * Radius * Radius;
}
}
public double Radius { get; set; }
}

View file

@ -0,0 +1,50 @@
using Packt.Shared; // Circle, Rectangle, Shape
using System.Xml.Serialization; // XmlSerializer
using static System.Environment;
using static System.IO.Path;
// create a file path to write to
string path = Combine(CurrentDirectory, "shapes.xml");
// create a list of Shape objects to serialize
List<Shape> listOfShapes = new()
{
new Circle { Colour = "Red", Radius = 2.5 },
new Rectangle { Colour = "Blue", Height = 20.0, Width = 10.0 },
new Circle { Colour = "Green", Radius = 8 },
new Circle { Colour = "Purple", Radius = 12.3 },
new Rectangle { Colour = "Blue", Height = 45.0, Width = 18.0 }
};
// create an object that knows how to serialize and deserialize
// a list of Shape objects
XmlSerializer serializerXml = new(listOfShapes.GetType());
WriteLine("Saving shapes to XML file:");
using (FileStream fileXml = File.Create(path))
{
serializerXml.Serialize(fileXml, listOfShapes);
}
WriteLine("Loading shapes from XML file:");
List<Shape>? loadedShapesXml = null;
using (FileStream fileXml = File.Open(path, FileMode.Open))
{
loadedShapesXml =
serializerXml.Deserialize(fileXml) as List<Shape>;
}
if (loadedShapesXml == null)
{
WriteLine($"{nameof(loadedShapesXml)} is empty.");
}
else
{
foreach (Shape item in loadedShapesXml)
{
WriteLine($"{item.GetType().Name} is {item.Colour} and has an area of {item.Area:N2}");
}
}

View file

@ -0,0 +1,15 @@
namespace Packt.Shared;
public class Rectangle : Shape
{
public override double Area
{
get
{
return Height * Width;
}
}
public double Height { get; set; }
public double Width { get; set; }
}

View file

@ -0,0 +1,11 @@
using System.Xml.Serialization;
namespace Packt.Shared;
[XmlInclude(typeof(Circle))]
[XmlInclude(typeof(Rectangle))]
public abstract class Shape
{
public string? Colour { get; set; }
public abstract double Area { get; }
}