diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..43aee7b2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +#*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/CashRegister/CashRegister/CashRegister.csproj b/CashRegister/CashRegister/CashRegister.csproj new file mode 100644 index 00000000..4168e0e2 --- /dev/null +++ b/CashRegister/CashRegister/CashRegister.csproj @@ -0,0 +1,59 @@ + + + + + Debug + AnyCPU + {A0E97303-9B1D-40E3-8567-5C3FCEDF7B8E} + Library + Properties + CashRegister + CashRegister + v4.6.1 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + 7 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + 7 + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CashRegister/CashRegister/Core/ChangeMaker.cs b/CashRegister/CashRegister/Core/ChangeMaker.cs new file mode 100644 index 00000000..1239ceb4 --- /dev/null +++ b/CashRegister/CashRegister/Core/ChangeMaker.cs @@ -0,0 +1,185 @@ +using System.Collections.Generic; +using CashRegister.Core.Denominations; +using CashRegister.Generators; + +namespace CashRegister.Core +{ + public static class ChangeMaker + { + #region Private Members + + //Instructions say for values divisible by 3 to use the random change. + private const int RandomnessDivisor = 3; + + //List of all denominations of coins to be used for change. + //In order from smallest to largest. + private static readonly List AllDenominations = new List + { + new Penny(), + new Nickel(), + new Dime(), + new Quarter(), + new Dollar() + }; + #endregion + + #region Public Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Determines whether to return "perfect" change or "random" change. + /// + /// Int for amount owed in cents. + /// Int for amount of change needed in cents. + /// Returns a CoinPurse object containing the denominations comprising the correct change. + public static CoinPurse GetChange(int amountOwedInCents, int amountOfChangeInCents) + { + //Check to see if we need to randomize change given back + var returnValue = amountOwedInCents % RandomnessDivisor == 0 ? + GetRandomChange(amountOfChangeInCents) : + GetPerfectChange(amountOfChangeInCents); + + return returnValue; + } + #endregion + + #region Private Methods + + #region Methods for Random Change + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Generates the proper change required with random coins chosen. + /// + /// The total amount of change required, in cents. + /// Returns a CoinPurse containing proper change in random denominations. + private static CoinPurse GetRandomChange(int amountOfChange) + { + //With random, on each pass, pick a single coin of a random value and subtract from total until complete. + //Do checks for new ranges of randomness so we don't have wasted passes. + //We don't want be able to select a coin that is higher than the change left to give out. + var returnedCoins = new Dictionary(); + var currentChangeAmount = amountOfChange; + + //There is still change to be given out, so... + while (currentChangeAmount > 0) + { + var currentCoin = GetRandomCoin(currentChangeAmount); + var currentCoinCount = 1; //Returning a single coin of random type + if (returnedCoins.ContainsKey(currentCoin)) + { + returnedCoins[currentCoin] = returnedCoins[currentCoin] + currentCoinCount; + } + else + { + returnedCoins.Add(currentCoin, currentCoinCount); + } + //We don't allow the ability to pick coins with values higher than the change remaining, so this will never be negative. + currentChangeAmount = currentChangeAmount - (currentCoinCount * currentCoin.CentValue); + } + return new CoinPurse(returnedCoins); + } + + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Returns the maximum upper bound for the amount of change remaining. + /// For example, there is no point to potentially randomly select dollars, + /// if the total change left is less than 100 cents. + /// + /// The remaining amount of change required, in cents. + /// + private static int GetDenominationUpperBound(int currentChangeAmount) + { + //This is the default selection that will get replaced from the loop later + Coin holdCoin = new Penny(); + + //Start with largest denomination and work the way down the chain + for (var i = AllDenominations.Count - 1; i >= 0; i--) + { + var currentCoin = AllDenominations[i]; + + if (currentChangeAmount >= currentCoin.CentValue) + { + holdCoin = currentCoin; + break; + } + } + + //We are adding +1 for passing to the randomness method, + //because the upper bound is exclusive, + //meaning that it will never pick that number randomly. + var returnValue = AllDenominations.LastIndexOf(holdCoin) + 1; + + return returnValue; + } + + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Get a random coin, based on how much change remains to be paid. + /// We want to avoid trying to pick a coin that is higher than the remaining amount. + /// + /// Current amount of change to be paid. + /// Returns a Coin object representing a random coin denomination. + private static Coin GetRandomCoin(int currentChangeAmount) + { + //Pick a random number in the valid range (current valid denominations) + //Determine upper bound of random range + var upperBound = GetDenominationUpperBound(currentChangeAmount); + var lowerBound = 0; //Always 0, which is the lowest index in the collection + + var randomCoinIndex = RandomIntegerGenerator.GetRandomNumber(lowerBound, upperBound); + var currentCoin = AllDenominations[randomCoinIndex]; + return currentCoin; + } + + #endregion + + #region Methods for Perfect Change + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Generates the proper change required with the most efficient coins chosen. + /// + /// The total amount of change required, in cents. + /// Returns a CoinPurse containing proper change using least amount of possible coins. + private static CoinPurse GetPerfectChange(int amountOfChange) + { + var returnedCoins = new Dictionary(); + var currentChangeAmount = amountOfChange; + + //Start with largest denomination and work the way down the chain + for (int i = AllDenominations.Count - 1; i >= 0; i--) + { + var currentCoin = AllDenominations[i]; + var currentCoinCount = GetCountOfCoins(currentCoin, currentChangeAmount); + returnedCoins.Add(currentCoin, currentCoinCount); + currentChangeAmount = currentChangeAmount - (currentCoinCount * currentCoin.CentValue); + } + return new CoinPurse(returnedCoins); + } + + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Returns the most amount of coins possible to be returned for a particular denomination. + /// + /// The desired denomination. + /// The remaining amount of change required, in cents. + /// + private static int GetCountOfCoins(Coin currentCoin, int currentChangeAmount) + { + var coinsToReturn = 0; + + if (currentChangeAmount > currentCoin.CentValue) + { + coinsToReturn = currentChangeAmount / currentCoin.CentValue; + } + return coinsToReturn; + } + #endregion + + #endregion + } +} diff --git a/CashRegister/CashRegister/Core/Coin.cs b/CashRegister/CashRegister/Core/Coin.cs new file mode 100644 index 00000000..208b7391 --- /dev/null +++ b/CashRegister/CashRegister/Core/Coin.cs @@ -0,0 +1,78 @@ +using System; + +namespace CashRegister.Core +{ + public abstract class Coin : IComparable + { + #region Protected Members + protected string VerboseSingular { get; } + protected string VerbosePlural { get; } + #endregion + + #region Public Members + public int CentValue { get; set; } + #endregion + + #region Constructors / Factory Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Constructor that requires a value (in cents), + /// the text for a singular coin descriptor, + /// and the text for the plural coin descriptor. + /// + /// Value of coin in cents. + /// String text for singular descriptor. + /// String text for plural descriptor. + protected Coin(int centValue, string singular, string plural) + { + CentValue = centValue; + VerboseSingular = singular; + VerbosePlural = plural; + } + #endregion + + #region Private Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Checks to see if quantity is higher than one. + /// + /// Int for quantity of coins to check. + /// Returns whether there is more than one coin. + private bool IsPlural(int quantity) + { + return quantity > 1; + } + #endregion + + #region Public Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Creates descriptor string for the coin. + /// + /// Int for amount of coins for determining descriptor. + /// Returns a string describing quantity of coins. + public string ToVerboseString(int quantity) + { + if (quantity == 0) + { + return ""; + } + if (IsPlural(quantity)) + { + return $"{quantity} {VerbosePlural}"; + } + return $"{quantity} {VerboseSingular}"; + } + #endregion + + #region Interface Implementations + public int CompareTo(Coin coin) + { + return CentValue.CompareTo(coin.CentValue); + } + #endregion + } +} diff --git a/CashRegister/CashRegister/Core/CoinPurse.cs b/CashRegister/CashRegister/Core/CoinPurse.cs new file mode 100644 index 00000000..f03377b6 --- /dev/null +++ b/CashRegister/CashRegister/Core/CoinPurse.cs @@ -0,0 +1,98 @@ +using System.Collections.Generic; +using System.Text; + +namespace CashRegister.Core +{ + public class CoinPurse + { + #region Private Members + private readonly IDictionary _coinCollection; + #endregion + + #region Constructors / Factory Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Constructor for CoinPurse which forces a IDictionary to be sent to populate the internal _coinCollection. + /// + /// Dictionary representing a collection of coins and their respective counts. + public CoinPurse(IDictionary coinCollection) + { + _coinCollection = coinCollection; + } + + /// + /// Keep this one private so we can only use in this class. + /// + private CoinPurse() + { + } + #endregion + + #region Public Methods + + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Method that returns CoinPurse containing change from string inputs for amount owed and amount paid. + /// + /// String representing amount of owed. + /// String representing amount paid. + /// Returns a CoinPurse containing change for the specified amounts. + public static CoinPurse GetChangePurse(string amountOwed, string amountPaid) + { + var returnValue = new CoinPurse(); + var owedSuccess = int.TryParse(amountOwed.Replace(".", ""), out var amountOwedInCents); + var paidSuccess = int.TryParse(amountPaid.Replace(".", ""), out var amountPaidInCents); + + if (owedSuccess && paidSuccess) + { + //If change is a positive number, get the change. + //If expecting 0 change, return an empty coin purse. + //Example shows that denominations with 0 are ignored. + var amountOwedInChange = amountPaidInCents - amountOwedInCents; + if (amountOwedInChange > 0) + { + returnValue = ChangeMaker.GetChange(amountOwedInCents, amountPaidInCents - amountOwedInCents); + } + } + return returnValue; + } + + + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Get a nicely printed string describing contents of CoinPurse. + /// + /// Returns a string representing the quantities of coins in the current CoinPurse in plain English. + public string GetCollectionVerboseString() + { + var returnValue = string.Empty; + + if (_coinCollection != null) + { + //Ensure collection is sorted biggest to smallest + var returnBuilder = new StringBuilder(); + var allKeys = new List(_coinCollection.Keys); + + allKeys.Sort(); //Put in order from smallest to largest (random collection not guaranteed to be in order) + allKeys.Reverse(); //Reverse that order so it becomes largest to smallest + + foreach (var currentCoin in allKeys) + { + var verboseStringToAdd = currentCoin.ToVerboseString(_coinCollection[currentCoin]); + + if (!string.IsNullOrEmpty(verboseStringToAdd)) + { + returnBuilder.Append($",{verboseStringToAdd}"); + } + } + //Remove starting comma + returnValue = returnBuilder.ToString().Substring(1); + } + return returnValue; + } + #endregion + } +} diff --git a/CashRegister/CashRegister/Core/Denominations.cs b/CashRegister/CashRegister/Core/Denominations.cs new file mode 100644 index 00000000..609cc883 --- /dev/null +++ b/CashRegister/CashRegister/Core/Denominations.cs @@ -0,0 +1,40 @@ +namespace CashRegister.Core +{ + namespace Denominations + { + public class Penny : Coin + { + public Penny() : base(1, "penny", "pennies") + { + } + } + + public class Nickel : Coin + { + public Nickel() : base(5, "nickel", "nickels") + { + } + } + + public class Dime : Coin + { + public Dime() : base(10, "dime", "dimes") + { + } + } + + public class Quarter : Coin + { + public Quarter() : base(25, "quarter", "quarters") + { + } + } + + public class Dollar : Coin + { + public Dollar() : base(100, "dollar", "dollars") + { + } + } + } +} diff --git a/CashRegister/CashRegister/Exceptions/CashRegisterExceptions.cs b/CashRegister/CashRegister/Exceptions/CashRegisterExceptions.cs new file mode 100644 index 00000000..ff1faeee --- /dev/null +++ b/CashRegister/CashRegister/Exceptions/CashRegisterExceptions.cs @@ -0,0 +1,29 @@ +using System; +using System.Diagnostics; + +namespace CashRegister.Exceptions +{ + public static class CashRegisterExceptions + { + /// + /// Author: Brian Sabotta + /// Date: 10/31/2019 + /// Notes: Since this is a small scale console app for now, + /// we will just write out errors to the console. + /// Log files could be swapped in for a bigger UI-based app. + /// + /// The thrown exception we are writing to the console. + public static void HandleException(Exception ex) + { + //If running in debugger, write out to output window, since we don't see console. + if (Debugger.IsAttached) + { + Debug.Print(ex.Message + Environment.NewLine + ex.StackTrace); + } + else + { + Console.WriteLine(ex); + } + } + } +} diff --git a/CashRegister/CashRegister/Generators/RandomIntegerGenerator.cs b/CashRegister/CashRegister/Generators/RandomIntegerGenerator.cs new file mode 100644 index 00000000..969d293f --- /dev/null +++ b/CashRegister/CashRegister/Generators/RandomIntegerGenerator.cs @@ -0,0 +1,30 @@ +namespace CashRegister.Generators +{ + public static class RandomIntegerGenerator + { + #region Private Members + private static System.Random _randomNumbers; + #endregion + + #region Public Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Uses a System.Random object to generate random numbers. + /// + /// Int for lower bound of random range. + /// Int for upper bound of random range. + /// Must be 1 higher than desired highest possible value. + /// Returns a random int in the specified range. + public static int GetRandomNumber(int lowerBound, int upperBound) + { + if (_randomNumbers == null) + { + _randomNumbers = new System.Random(); + } + var returnValue = _randomNumbers.Next(lowerBound, upperBound); + return returnValue; + } + #endregion + } +} diff --git a/CashRegister/CashRegister/IO/FileOperations.cs b/CashRegister/CashRegister/IO/FileOperations.cs new file mode 100644 index 00000000..1e8c0f4d --- /dev/null +++ b/CashRegister/CashRegister/IO/FileOperations.cs @@ -0,0 +1,47 @@ +using System.IO; +using System.Collections.Generic; + +namespace CashRegister.IO +{ + public static class FileOperations + { + #region Public Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Gets all lines from a text file and returns them in a collection. + /// + /// String specifying full path to source file. + /// Returns a collection of strings for data in source file. + public static IEnumerable GetTextLinesFromFile(string inputFilePath) + { + var allLines = File.ReadAllLines(inputFilePath); + return new List(allLines); + } + + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Write all text to the specified file. Overwrites any pre-existing file. + /// + /// String for full file path to write to. + /// String data to write to file. + /// Returns a boolean indicating success or failure of the write attempt. + public static void WriteTextToFile(string filePath, string data) + { + //Create the directory if it doesn't exist. + var directoryToMake = Path.GetDirectoryName(filePath); + + if (directoryToMake != null && !Directory.Exists(directoryToMake)) + { + Directory.CreateDirectory(directoryToMake); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + File.WriteAllText(filePath, data); + } + #endregion + } +} diff --git a/CashRegister/CashRegister/Processors/CashRegisterProcessor.cs b/CashRegister/CashRegister/Processors/CashRegisterProcessor.cs new file mode 100644 index 00000000..fd7f6d74 --- /dev/null +++ b/CashRegister/CashRegister/Processors/CashRegisterProcessor.cs @@ -0,0 +1,34 @@ +using CashRegister.IO; +using CashRegister.Validators; + +namespace CashRegister.Processors +{ + public static class CashRegisterProcessor + { + #region Public Methods + + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Validates existence of input files, + /// and processes all data passed to it, + /// writing output data to specified file. + /// + public static void ProcessData(string inputFilePath, string outputFilePath) + { + //Check validity of inputs. + //If invalid, throw exceptions to be caught for display in console + InputValidator.ValidateInputs(inputFilePath, outputFilePath); + + //Get data from file + var inputData = FileOperations.GetTextLinesFromFile(inputFilePath); + + //Process the data + var output = InputDataProcessor.ProcessData(inputData); + + //Write output to file + FileOperations.WriteTextToFile(outputFilePath, output); + } + #endregion + } +} diff --git a/CashRegister/CashRegister/Processors/InputDataProcessor.cs b/CashRegister/CashRegister/Processors/InputDataProcessor.cs new file mode 100644 index 00000000..56568cf9 --- /dev/null +++ b/CashRegister/CashRegister/Processors/InputDataProcessor.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Text; +using CashRegister.Core; + +namespace CashRegister.Processors +{ + public static class InputDataProcessor + { + #region Private Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Gets a descriptor string for CoinPurses which contain change details for each line in the source file. + /// + /// A collection of lines of text, representing source data to be processed. + /// Returns a descriptor string of all CoinPurses generated for every line in the source file. + private static string GetAllCoinPurseDescriptors(IEnumerable sourceData) + { + var returnValue = new StringBuilder(); + + foreach (var currentLine in sourceData) + { + //Break up each line by splitting on the comma delimiter + var dataRow = currentLine.Split(','); + if (dataRow.Length > 1) + { + var currentPurse = CoinPurse.GetChangePurse(dataRow[0], dataRow[1]); + //Example output has double-spacing, so we'll do the same for ease of reading. + returnValue.AppendLine($"{currentPurse.GetCollectionVerboseString()}{Environment.NewLine}"); + } + } + return returnValue.ToString(); + } + #endregion + + #region Public Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Processes contents of source file to generate final descriptive output. + /// + /// A collection of strings containing all source data from file. + /// Returns a string representing all contents of all change for all transactions. + public static string ProcessData(IEnumerable sourceDataLines) + { + return GetAllCoinPurseDescriptors(sourceDataLines); + } + #endregion + } +} diff --git a/CashRegister/CashRegister/Properties/AssemblyInfo.cs b/CashRegister/CashRegister/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..11bda049 --- /dev/null +++ b/CashRegister/CashRegister/Properties/AssemblyInfo.cs @@ -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("CashRegister")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CashRegister")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[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("a0e97303-9b1d-40e3-8567-5c3fcedf7b8e")] + +// 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")] diff --git a/CashRegister/CashRegister/Validators/InputValidator.cs b/CashRegister/CashRegister/Validators/InputValidator.cs new file mode 100644 index 00000000..1ba264f9 --- /dev/null +++ b/CashRegister/CashRegister/Validators/InputValidator.cs @@ -0,0 +1,60 @@ +using System.IO; + +namespace CashRegister.Validators +{ + public static class InputValidator + { + #region Private Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Validates that provided paths are not empty. + /// + /// String for input file path. + /// String for output file path. + private static void CheckFilePaths(string inputFilePath, string outputFilePath) + { + //Validate inputs - make sure they are not empty or null + //Throw exceptions so that log file gets updated. + if (string.IsNullOrEmpty(inputFilePath)) + throw new System.ArgumentNullException(nameof(inputFilePath)); + + if (string.IsNullOrEmpty(outputFilePath)) + throw new System.ArgumentNullException(nameof(outputFilePath)); + } + + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Validates that provided file paths actually exist. + /// + /// String for full path to input file. + private static void DoesFileExist(string inputFilePath) + { + //Path to source text file + if (!File.Exists(inputFilePath)) + { + throw new FileNotFoundException($"Specified file does not exist: {inputFilePath}", inputFilePath); + } + } + #endregion + + #region Public Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Validates that all inputs are valid. + /// + /// String for input file path. + /// String for output file path. + public static void ValidateInputs(string inputFilePath, string outputFilePath) + { + //Make sure inputs are not blank + CheckFilePaths(inputFilePath, outputFilePath); + + //Make sure inputs exist + DoesFileExist(inputFilePath); + } + #endregion + } +} diff --git a/CashRegister/CashRegisterSabotta/App.config b/CashRegister/CashRegisterSabotta/App.config new file mode 100644 index 00000000..bae5d6d8 --- /dev/null +++ b/CashRegister/CashRegisterSabotta/App.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/CashRegister/CashRegisterSabotta/CashRegisterManager.cs b/CashRegister/CashRegisterSabotta/CashRegisterManager.cs new file mode 100644 index 00000000..4a94eb70 --- /dev/null +++ b/CashRegister/CashRegisterSabotta/CashRegisterManager.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using CashRegister.Exceptions; +using CashRegister.Processors; + +namespace CashRegisterSabotta +{ + public static class CashRegisterManager + { + #region Private Members + //Set up a friendly error message to ensure proper usage of exe + //Warn user about passing input/output file paths, if not provided at command line. + private const string UsageError = "{2}{0} must be specified. Usage = {1} [input file path] [output file path] {2}"; + #endregion + + #region Private Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Gets the desired parameter value by index. + /// + /// The collection of arguments to choose from. + /// The index of the argument to get. + /// The name of the argument for error message, if not provided. + /// Returns the value of the parameter at the index specified. + private static string GetParameterByIndex(IReadOnlyList args, int index, string argName) + { + string returnValue; + if (args.Count > index) + { + returnValue = args[index]; + } + else + { + //If we're running debugger, put text in the output window, otherwise write out to console. + if (Debugger.IsAttached) + { + Debug.Print(UsageError, argName, AppDomain.CurrentDomain.FriendlyName, Environment.NewLine); + } + else + { + Console.Write(UsageError, argName, AppDomain.CurrentDomain.FriendlyName, Environment.NewLine); + } + + returnValue = string.Empty; + } + return returnValue; + } + #endregion + + #region Public Methods + /// + /// Author: Brian Sabotta + /// Created: 10/30/2019 + /// Notes: Checks parameters and starts running the cash register process. + /// + /// Collection of args passed in from command line. + public static void RunCashRegisterProcessor(string[] args) + { + try + { + //arg[0] - inputFile + var inputFile = GetParameterByIndex(args, 0, "Input file"); + + //Exit out if not provided + if (string.IsNullOrEmpty(inputFile)) + return; + + //arg[1] - outputFile + var outputFile = GetParameterByIndex(args, 1, "Output file"); + + //Exit out if not provided + if (string.IsNullOrEmpty(outputFile)) + return; + + //Call the processing method + CashRegisterProcessor.ProcessData(inputFile, outputFile); + + } + catch (Exception ex) + { + CashRegisterExceptions.HandleException(ex); + } + } + #endregion + } +} diff --git a/CashRegister/CashRegisterSabotta/CashRegisterSabotta.csproj b/CashRegister/CashRegisterSabotta/CashRegisterSabotta.csproj new file mode 100644 index 00000000..c9ffd0e4 --- /dev/null +++ b/CashRegister/CashRegisterSabotta/CashRegisterSabotta.csproj @@ -0,0 +1,62 @@ + + + + + Debug + AnyCPU + {0F86B7AF-F482-4FF1-A2B5-46BA7E719959} + Exe + CashRegisterSabotta + CashRegisterSabotta + v4.6.1 + 512 + true + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + 7 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + 7 + + + + + + + + + + + + + + + + + + + + + + {a0e97303-9b1d-40e3-8567-5c3fcedf7b8e} + CashRegister + + + + \ No newline at end of file diff --git a/CashRegister/CashRegisterSabotta/CashRegisterSabotta.csproj.user b/CashRegister/CashRegisterSabotta/CashRegisterSabotta.csproj.user new file mode 100644 index 00000000..28824f81 --- /dev/null +++ b/CashRegister/CashRegisterSabotta/CashRegisterSabotta.csproj.user @@ -0,0 +1,6 @@ + + + + ..\..\..\inputFile.txt ..\..\..\outputFile.txt + + \ No newline at end of file diff --git a/CashRegister/CashRegisterSabotta/CashRegisterSabotta.sln b/CashRegister/CashRegisterSabotta/CashRegisterSabotta.sln new file mode 100644 index 00000000..a3b73923 --- /dev/null +++ b/CashRegister/CashRegisterSabotta/CashRegisterSabotta.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26403.3 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CashRegisterSabotta", "CashRegisterSabotta.csproj", "{0F86B7AF-F482-4FF1-A2B5-46BA7E719959}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CashRegister", "..\CashRegister\CashRegister.csproj", "{A0E97303-9B1D-40E3-8567-5C3FCEDF7B8E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0F86B7AF-F482-4FF1-A2B5-46BA7E719959}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0F86B7AF-F482-4FF1-A2B5-46BA7E719959}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0F86B7AF-F482-4FF1-A2B5-46BA7E719959}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0F86B7AF-F482-4FF1-A2B5-46BA7E719959}.Release|Any CPU.Build.0 = Release|Any CPU + {A0E97303-9B1D-40E3-8567-5C3FCEDF7B8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A0E97303-9B1D-40E3-8567-5C3FCEDF7B8E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A0E97303-9B1D-40E3-8567-5C3FCEDF7B8E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A0E97303-9B1D-40E3-8567-5C3FCEDF7B8E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/CashRegister/CashRegisterSabotta/Program.cs b/CashRegister/CashRegisterSabotta/Program.cs new file mode 100644 index 00000000..e055ac1d --- /dev/null +++ b/CashRegister/CashRegisterSabotta/Program.cs @@ -0,0 +1,15 @@ +namespace CashRegisterSabotta +{ + /// + /// Author: Brian Sabotta + /// Created: 10/29/2019 + /// Notes: Created a separate project for application so that CashRegister dll can be easily referenced in other projects, as desired. + /// + class Program + { + static void Main(string[] args) + { + CashRegisterManager.RunCashRegisterProcessor(args); + } + } +} diff --git a/CashRegister/CashRegisterSabotta/Properties/AssemblyInfo.cs b/CashRegister/CashRegisterSabotta/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..161c5f74 --- /dev/null +++ b/CashRegister/CashRegisterSabotta/Properties/AssemblyInfo.cs @@ -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("CashRegisterSabotta")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CashRegisterSabotta")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[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("0f86b7af-f482-4ff1-a2b5-46ba7e719959")] + +// 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")] diff --git a/CashRegister/inputFile.txt b/CashRegister/inputFile.txt new file mode 100644 index 00000000..30acbd03 --- /dev/null +++ b/CashRegister/inputFile.txt @@ -0,0 +1,19 @@ +2.12,3.00 + +1.97,2.00 + +3.33,5.00 + +8.65,10.00 + +1.86,20.00 + +asdflkasd,asdfasdf + +234234,adsfadfa + +sdfgsdfgs,345345345 + +2.00,2.00 + +14.55,18.00 \ No newline at end of file diff --git a/README.md b/README.md index 06a2101e..42c3d2f2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,38 @@ +UPDATED: 4/28/2021 by Brian Sabotta + +CashRegisterSabotta C# Console Application +========================================== + +Author: Brian Sabotta +Created: 11/1/2019 +Purpose: Code Test for SoftWriters +Tools Used: Visual Studio 2017 + Resharper (for easy refactoring) +.NET Info: C# 7.0 + .NET 4.6.1 + +As per the specifications of the code test, the application will take an input file, process all the lines, and write out to an output file. + +The input and output files are passed via command line in the following manner: + +CashRegisterSabotta.exe [input file path] [output file path] + +Default paths have been set in the solution for `..\..\..\inputFile.txt` and `..\..\..\outputFile.txt`, but these can be altered to suit testing. + +If any errors occur during the operation of the program through a command window, error information will be printed to the console for easy debugging. +If errors occur while debugging in Visual Studio, error information will be printed to the output window for easy debugging. + +Based on the example data given, the following choices were made: + + 1) an empty space will exist between every line in the output file. + + 2) transactions that require no change will be represented by empty lines in the output file (since 0 coin counts are excluded from output) + + 3) transactions containing garbage data will be represented by empty lines in the output file + + 4) processing of garbage files (that do not contain any valid data) will generate an output file of empty lines + +================================= + + Cash Register ============