Added Tutorial 9

This commit is contained in:
Brychan Dempsey 2021-09-21 20:07:08 +12:00
parent e9e107e3d3
commit 2fa6a798a5
19 changed files with 696 additions and 69 deletions

View File

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31515.178
# Visual Studio Version 17
VisualStudioVersion = 17.0.31710.8
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "158326 Week 7 Singletons", "158326 Week 7 Singletons\158326 Week 7 Singletons.csproj", "{DDB32161-79F3-4CCF-9CCC-44CCD562B15E}"
EndProject
@ -23,6 +23,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tutorial 5", "Tutorial 5\Tu
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tutorial 6", "Tutorial 6\Tutorial 6.csproj", "{00702453-3AD5-4822-A38C-2859B52C3E4C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tutorial 9", "Tutorial 9\Tutorial 9.csproj", "{38781F4C-0A86-42F7-8912-D17CF5E0FDED}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tutorial 9 Tests", "Tutorial 9 Tests\Tutorial 9 Tests.csproj", "{5198ABA9-CBE2-4AEF-95D5-F14705697294}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -69,6 +73,14 @@ Global
{00702453-3AD5-4822-A38C-2859B52C3E4C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00702453-3AD5-4822-A38C-2859B52C3E4C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00702453-3AD5-4822-A38C-2859B52C3E4C}.Release|Any CPU.Build.0 = Release|Any CPU
{38781F4C-0A86-42F7-8912-D17CF5E0FDED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{38781F4C-0A86-42F7-8912-D17CF5E0FDED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{38781F4C-0A86-42F7-8912-D17CF5E0FDED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{38781F4C-0A86-42F7-8912-D17CF5E0FDED}.Release|Any CPU.Build.0 = Release|Any CPU
{5198ABA9-CBE2-4AEF-95D5-F14705697294}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5198ABA9-CBE2-4AEF-95D5-F14705697294}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5198ABA9-CBE2-4AEF-95D5-F14705697294}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5198ABA9-CBE2-4AEF-95D5-F14705697294}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace _158326_Week_7_Singletons
@ -10,6 +11,58 @@ namespace _158326_Week_7_Singletons
Console.WriteLine("158.326 Software Architecture");
Console.WriteLine("\tWeek 7 - Singleton Design Pattern");
Console.WriteLine("\tSingletons are instanced classes that can have only 0 or 1 instances of that class in existance in the application (Multitons are a variant that restricts the maximum number of instances)");
Console.WriteLine("\nCompany:");
for (int i = 0; i < 10; i++)
{
try
{
Company instanceOfCompany = Company.GetCompany();
Console.WriteLine(instanceOfCompany.ShowDetails());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Console.WriteLine("\nFileSingleton:");
for (int i = 0; i < 10; i++)
{
try
{
FileSingleton instanceOfCompany = FileSingleton.GetInstance(i);
Console.WriteLine(instanceOfCompany.ShowDetails());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
for (int i = 100; i < 110; i++)
{
try
{
FileSingleton instanceOfCompany = FileSingleton.GetInstance(i);
Console.WriteLine(instanceOfCompany.ShowDetails());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Console.WriteLine("\nCompany:");
for (int i = 0; i < 10; i++)
{
try
{
Company instanceOfCompany = Company.GetCompany();
Console.WriteLine(instanceOfCompany.ShowDetails());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
@ -23,14 +76,15 @@ namespace _158326_Week_7_Singletons
/// Store the instance in a private, static variable
/// </summary>
private static FileSingleton instance;
private string _name;
/// <summary>
/// Path of the file to open
/// </summary>
public static Uri FilePath { get; set; } = new Uri("\\log.txt", UriKind.Relative); // Opens exactly one file stream on log.txt and will always return that stream
//public static Uri FilePath { get; set; } = new Uri("\\log.txt", UriKind.Relative); // Opens exactly one file stream on log.txt and will always return that stream
// We can define instance variables here:
public FileStream OpenedFileStream { get; set; } // Calling FileSingleton.GetInstance().OpenedFileStream will always return this object
// public FileStream OpenedFileStream { get; set; } // Calling FileSingleton.GetInstance().OpenedFileStream will always return this object
// We can also define
@ -40,20 +94,68 @@ namespace _158326_Week_7_Singletons
/// This restricts the creation of this instance to local methods, so by restricting constructor calls
/// to GetInstance(), we can ensure that only one instance is created
/// </summary>
private FileSingleton() { }
private FileSingleton(int i)
{
_name = i.ToString();
}
/// <summary>
/// Gets the initialised instance of FileSingleton
/// </summary>
/// <returns></returns>
public static FileSingleton GetInstance()
public static FileSingleton GetInstance(int i)
{
if (instance is null)
{
instance = new FileSingleton(i);
}
return instance;
}
public string ShowDetails()
{
if (instance is null)
return _name;
}
}
public sealed class Company
{
private string _name;
private static Company _company;
private bool _legalInstance;
private List<string> _listEmployee;
private Company()
{
if (_company == null)
{
instance = new FileSingleton();
_company = this;
_name = "test";
_legalInstance = true;
}
else
{
_legalInstance = false;
}
}
public static Company GetCompany()
{
return new Company();
}
public string ShowDetails()
{
if (_legalInstance)
{
return _name;
}
else
{
throw new ApplicationException("Null Object");
}
return instance;
}
}
}

View File

@ -13,13 +13,20 @@ namespace Tutorial_5
public partial class CurrentConditionsDisplay : Form, IWeatherObserver, IDisplay
{
ISubject subject;
WeatherData weatherData;
//WeatherData_old weatherData;
private void RegisterButton_Click(object sender, EventArgs e)
{
subject.RegisterObserver(this);
}
double temperature = default, humidity = default, pressure = default;
/// <summary>
/// Push technique
/// </summary>
/// <param name="temperature"></param>
/// <param name="humidity"></param>
/// <param name="pressure"></param>
public void Update(double temperature, double humidity, double pressure)
{
this.temperature = temperature;
@ -30,9 +37,9 @@ namespace Tutorial_5
public void UpdateOther()
{
this.temperature = weatherData.GetTemperature();
this.humidity = weatherData.GetHumidity();
this.pressure = weatherData.GetPressure();
//this.temperature = weatherData.GetTemperature();
//this.humidity = weatherData.GetHumidity();
//this.pressure = weatherData.GetPressure();
}
public void Display()

98
Tutorial 5/ForecastDisplay.Designer.cs generated Normal file
View File

@ -0,0 +1,98 @@

namespace Tutorial_5
{
partial class ForecastDisplay
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.ConditionLabel = new System.Windows.Forms.Label();
this.RegisterButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(100, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(96, 26);
this.label1.TabIndex = 0;
this.label1.Text = "Forecast";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(14, 106);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(104, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Expected Conditions";
//
// ConditionLabel
//
this.ConditionLabel.AutoSize = true;
this.ConditionLabel.Location = new System.Drawing.Point(124, 106);
this.ConditionLabel.Name = "ConditionLabel";
this.ConditionLabel.Size = new System.Drawing.Size(139, 13);
this.ConditionLabel.TabIndex = 2;
this.ConditionLabel.Text = "______________________";
//
// RegisterButton
//
this.RegisterButton.Location = new System.Drawing.Point(85, 231);
this.RegisterButton.Name = "RegisterButton";
this.RegisterButton.Size = new System.Drawing.Size(136, 23);
this.RegisterButton.TabIndex = 3;
this.RegisterButton.Text = "Register Observer";
this.RegisterButton.UseVisualStyleBackColor = true;
//
// ForecastDisplay
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(304, 450);
this.Controls.Add(this.RegisterButton);
this.Controls.Add(this.ConditionLabel);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "ForecastDisplay";
this.Text = "ForecastDisplay";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label ConditionLabel;
private System.Windows.Forms.Button RegisterButton;
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tutorial_5
{
public partial class ForecastDisplay : Form
{
public ForecastDisplay()
{
InitializeComponent();
}
}
}

View File

@ -1,43 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tutorial_5
{
public partial class Form1 : Form
{
ISubject subject;
public Form1()
{
InitializeComponent();
this.subject = new WeatherData();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void SliderChanged(object sender, EventArgs e)
{
subject.NotifyObservers();
TemperatureLabel.Text = TemperatureSlider.Value.ToString() + " ℃";
HumidityLabel.Text = HumiditySlider.Value.ToString() + " %";
PressureLabel.Text = PressureSlider.Value.ToString() + " kPa";
}
private void Form1_Load_1(object sender, EventArgs e)
{
CurrentConditionsDisplay ccd = new CurrentConditionsDisplay(this.subject);
ccd.Show();
}
}
}

View File

@ -16,7 +16,7 @@ namespace Tutorial_5
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Application.Run(new WeatherData());
}
}

View File

@ -51,11 +51,17 @@
<Compile Include="CurrentConditionsDisplay.Designer.cs">
<DependentUpon>CurrentConditionsDisplay.cs</DependentUpon>
</Compile>
<Compile Include="Form1.cs">
<Compile Include="ForecastDisplay.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
<Compile Include="ForecastDisplay.Designer.cs">
<DependentUpon>ForecastDisplay.cs</DependentUpon>
</Compile>
<Compile Include="WeatherData.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="WeatherData.Designer.cs">
<DependentUpon>WeatherData.cs</DependentUpon>
</Compile>
<Compile Include="IDisplay.cs" />
<Compile Include="IObserver.cs" />
@ -63,12 +69,14 @@
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ThirdPartyDisplay.cs" />
<Compile Include="WeatherData.cs" />
<EmbeddedResource Include="CurrentConditionsDisplay.resx">
<DependentUpon>CurrentConditionsDisplay.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
<EmbeddedResource Include="ForecastDisplay.resx">
<DependentUpon>ForecastDisplay.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="WeatherData.resx">
<DependentUpon>WeatherData.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>

View File

@ -1,7 +1,7 @@

namespace Tutorial_5
{
partial class Form1
partial class WeatherData
{
/// <summary>
/// Required designer variable.

View File

@ -1,12 +1,16 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tutorial_5
{
class WeatherData : ISubject
public partial class WeatherData : Form, ISubject
{
List<IWeatherObserver> observers;
public void DeregisterObserver(IWeatherObserver observer)
@ -15,6 +19,9 @@ namespace Tutorial_5
else Console.Error.WriteLine("{0} does not exist in the observers list.", observer.ToString());
}
/// <summary>
/// 'Push' method
/// </summary>
public void NotifyObservers()
{
double t = GetTemperature();
@ -23,7 +30,7 @@ namespace Tutorial_5
foreach (var observer in observers)
{
observer.Update(t,h,p);
observer.Update(t, h, p);
}
}
@ -35,17 +42,17 @@ namespace Tutorial_5
public double GetTemperature()
{
return 0.0;
return TemperatureSlider.Value;
}
public double GetHumidity()
{
return 0.0;
return HumiditySlider.Value;
}
public double GetPressure()
{
return 0.0;
return PressureSlider.Value;
}
void MeasurementChanged()
@ -55,7 +62,33 @@ namespace Tutorial_5
public WeatherData()
{
InitializeComponent();
observers = new List<IWeatherObserver>();
}
private void Form1_Load(object sender, EventArgs e)
{
}
/// <summary>
/// Analagous to the Update() method in Excercise 1
/// Pushes data to observers via Subject.NotifyObservers
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SliderChanged(object sender, EventArgs e)
{
NotifyObservers();
TemperatureLabel.Text = TemperatureSlider.Value.ToString() + " ℃";
HumidityLabel.Text = HumiditySlider.Value.ToString() + " %";
PressureLabel.Text = PressureSlider.Value.ToString() + " kPa";
}
private void Form1_Load_1(object sender, EventArgs e)
{
CurrentConditionsDisplay ccd = new CurrentConditionsDisplay(this);
ccd.Show();
}
}
}

120
Tutorial 5/WeatherData.resx Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,20 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Tutorial 9 Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tutorial 9 Tests")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("5198aba9-cbe2-4aef-95d5-f14705697294")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\MSTest.TestAdapter.2.1.2\build\net45\MSTest.TestAdapter.props" Condition="Exists('..\packages\MSTest.TestAdapter.2.1.2\build\net45\MSTest.TestAdapter.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{5198ABA9-CBE2-4AEF-95D5-F14705697294}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Tutorial_9_Tests</RootNamespace>
<AssemblyName>Tutorial 9 Tests</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\MSTest.TestFramework.2.1.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\MSTest.TestFramework.2.1.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="UnitTest1.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Tutorial 9\Tutorial 9.csproj">
<Project>{38781f4c-0a86-42f7-8912-d17cf5e0fded}</Project>
<Name>Tutorial 9</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\MSTest.TestAdapter.2.1.2\build\net45\MSTest.TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.2.1.2\build\net45\MSTest.TestAdapter.props'))" />
<Error Condition="!Exists('..\packages\MSTest.TestAdapter.2.1.2\build\net45\MSTest.TestAdapter.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.2.1.2\build\net45\MSTest.TestAdapter.targets'))" />
</Target>
<Import Project="..\packages\MSTest.TestAdapter.2.1.2\build\net45\MSTest.TestAdapter.targets" Condition="Exists('..\packages\MSTest.TestAdapter.2.1.2\build\net45\MSTest.TestAdapter.targets')" />
</Project>

View File

@ -0,0 +1,28 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Tutorial_9;
namespace Tutorial_9_Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void SedanNoDiscountTest()
{
Sedan sedan = new Sedan();
Assert.AreEqual(0, sedan.PriceAfterDays(0));
Assert.AreEqual(80, sedan.PriceAfterDays(1));
Assert.AreEqual(320, sedan.PriceAfterDays(4));
}
[TestMethod]
public void TestCarTest()
{
TestCar sedan = new TestCar();
Assert.AreEqual(0, sedan.PriceAfterDays(0));
Assert.AreEqual(0, sedan.PriceAfterDays(1));
Assert.AreEqual(0, sedan.PriceAfterDays(4));
}
}
}

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MSTest.TestAdapter" version="2.1.2" targetFramework="net472" />
<package id="MSTest.TestFramework" version="2.1.2" targetFramework="net472" />
</packages>

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tutorial 9")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tutorial 9")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("38781f4c-0a86-42f7-8912-d17cf5e0fded")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

59
Tutorial 9/Rental.cs Normal file
View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tutorial_9
{
public abstract class Car
{
protected abstract decimal Price { get; }
public decimal PriceAfterDays(decimal numDays)
{
decimal result;
if (numDays < 0 || numDays >= 90) throw new ArgumentOutOfRangeException("Provided number of days is invalid");
if (numDays < 5)
{
result = Price * numDays;
}
else if (numDays < 10)
{
result = Price * numDays * 0.9M;
}
else if (numDays < 20)
{
result = Price * numDays * 0.85M;
}
else
{
result = Price * numDays * 0.8M;
}
return result;
}
}
public class Hatchback : Car
{
protected override decimal Price => 50;
}
public class Sedan : Car
{
protected override decimal Price => 80;
}
public class Convertible : Car
{
protected override decimal Price => 100;
}
public class Saloon : Car
{
protected override decimal Price => 120;
}
public class Motorcycle : Car
{
protected override decimal Price => 20;
}
}

View File

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{38781F4C-0A86-42F7-8912-D17CF5E0FDED}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Tutorial_9</RootNamespace>
<AssemblyName>Tutorial 9</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Rental.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>