This commit is contained in:
Mguy13 2023-01-04 23:32:29 +01:00
parent 1170c76e3f
commit 06332d76eb
5 changed files with 416 additions and 124 deletions

265
.gitignore vendored
View file

@ -1,3 +1,6 @@
# Created by https://www.toptal.com/developers/gitignore/api/csharp,dotnetcore,visualstudiocode,visualstudio,rider
# Edit at https://www.toptal.com/developers/gitignore?templates=csharp,dotnetcore,visualstudiocode,visualstudio,rider
### Csharp ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
@ -405,6 +408,85 @@ obj/
/node_modules
/wwwroot/node_modules
### Rider ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### VisualStudioCode ###
!.vscode/*.code-snippets
@ -418,4 +500,185 @@ obj/
.history
.ionide
# End of https://www.toptal.com/developers/gitignore/api/csharp,visualstudiocode,dotnetcore
### VisualStudio ###
# User-specific files
# User-specific files (MonoDevelop/Xamarin Studio)
# Mono auto generated files
# Build results
# Visual Studio 2015/2017 cache/options directory
# Uncomment if you have tasks that create the project's static files in wwwroot
# Visual Studio 2017 auto generated files
# MSTest test Results
# NUnit
# Build Results of an ATL Project
# Benchmark Results
# .NET Core
# ASP.NET Scaffolding
# StyleCop
# Files built by Visual Studio
# Chutzpah Test files
# Visual C++ cache files
# Visual Studio profiler
# Visual Studio Trace Files
# TFS 2012 Local Workspace
# Guidance Automation Toolkit
# ReSharper is a .NET coding add-in
# TeamCity is a build add-in
# DotCover is a Code Coverage Tool
# AxoCover is a Code Coverage Tool
# Coverlet is a free, cross platform Code Coverage Tool
# Visual Studio code coverage results
# NCrunch
# MightyMoose
# Web workbench (sass)
# Installshield output folder
# DocProject is a documentation generator add-in
# Click-Once directory
# Publish Web Output
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
# 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
# NuGet Packages
# NuGet Symbol Packages
# The packages folder can be ignored because of Package Restore
# except build/, which is used as an MSBuild target.
# Uncomment if necessary however generally it will be regenerated when needed
# NuGet v3's project.json files produces more ignorable files
# Microsoft Azure Build Output
# Microsoft Azure Emulator
# Windows Store app package directories and files
# Visual Studio cache files
# files ending in .cache can be ignored
# but keep track of directories ending in .cache
# Others
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
# RIA/Silverlight projects
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
# SQL Server files
# Business Intelligence projects
# Microsoft Fakes
# GhostDoc plugin setting file
# Node.js Tools for Visual Studio
# Visual Studio 6 build log
# Visual Studio 6 workspace options file
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
# Paket dependency manager
# FAKE - F# Make
# CodeRush personal settings
# Python Tools for Visual Studio (PTVS)
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
# Telerik's JustMock configuration file
# BizTalk build output
# OpenCover UI analysis results
# Azure Stream Analytics local run output
# MSBuild Binary and Structured Log
# NVidia Nsight GPU debugger configuration file
# MFractors (Xamarin productivity tool) working folder
# Local History for Visual Studio
# Visual Studio History (VSHistory) files
# BeatPulse healthcheck temp database
# Backup folder for Package Reference Convert tool in Visual Studio 2017
# Ionide (cross platform F# VS Code tools) working folder
# Fody - auto-generated XML schema
# VS Code files for those working on multiple tools
# Local History for Visual Studio Code
# Windows Installer files from build outputs
# JetBrains Rider
### VisualStudio Patch ###
# Additional files built by Visual Studio
# End of https://www.toptal.com/developers/gitignore/api/csharp,dotnetcore,visualstudiocode,visualstudio,rider

27
Problems.md Normal file
View file

@ -0,0 +1,27 @@
## Code explanation
This is a program manages the processing of orders in the following way: when an order is registered with the `RegisterOrder` method, the order is first deleted using the `DeleteOrder` method. Then, the order is converted to a list of `ReviewExportLine` objects using the `ConvertOrderToExportLines` method and added to a queue of lists of `ReviewExportLine` objects. There is a separate thread running in the background which was mentioend in the assignment itself. This service continuously checks the queue and processes the review export lines when the queue is not empty and the review folder is empty. When the review folder is not empty, the thread waits for 2 seconds and checks the queue again. The processing of review export lines involves opening a file in the review folder with a random 7 character string as the file name, writing the review export lines to the file, and then closing the file.
## Problems with the code
1. The `ProcessReviewExportLines` method runs in an infinite loop, which means that it will run indefinitely until the program is terminated. This may not be desirable behavior, especially if the program is intended to run for a fixed amount of time or in response to specific user input. Also, this seems hacky: a better practice would be to use some sort of a listener or a state observer (with observer pattern).
2. Possible race-conditions: the `ProcessReviewExportLines` method checks whether the review folder is empty before processing the review export lines. However, it is possible that other processes or threads may be writing to the review folder at the same time, which could cause the program to skip processing the review export lines even if the folder is not actually empty.
3. The `ProcessReviewExportLines` method writes to the review folder using a randomly generated file name. This may cause problems if the program needs to read the contents of the review folder at a later time, as it will be difficult to determine which file corresponds to which order.
4. The `FilterString` method replaces semicolons (;) with colons (:). This may cause problems if the input strings contain colons that are not intended to be replaced. If it is such a simple operation, then it should be done locally.
5. The `DeleteOrder` method enqueues a single ReviewExportLine object with a Type field value of "9" to the queue. It is not clear what the purpose of this line is, or how it is related to the process of deleting an order.
6. `GenerateRandomString` method does not check the validity of the returned path: Since it generates these characters randomly, there could be a chaater that is considered illegal to be used as in a system-path. Additionally, 7 characters (which are very bounded) might not prove to be enough to prevent collisions.
## How to solve them
1. Add a condition to the loop to terminate it after a certain number of iterations or after a certain amount of time has passed Alternatively, a cancellation token to the method and pass it a token that can be used to cancel the loop. Or used better design-patterns
2. Use a locking-mechanism to syncronize access to a shared resource, in this case, this folder.
3. Use an incrementative / more predictable file name. Such as using timestamps.
4. Move the operation upwards, or use the method better, to actually filter-out invalid characters.
5. Add proper useful logic. Or add comments explaining it.

View file

@ -15,7 +15,9 @@ namespace OrderParser
foreach (var jsonFile in filesInfoConfig.JsonFilesInfo)
{
var orderModel = new OrderModel(Newtonsoft.Json.JsonConvert.DeserializeObject<OrderDto>(File.ReadAllText(jsonFile.FullName)));
var orderDTO = Newtonsoft.Json.JsonConvert.DeserializeObject<OrderDto>(File.ReadAllText(jsonFile.FullName));
var orderModel = new OrderModel(orderDTO);
csvFileWriter.writeOutRow(orderModel);
}

0
README.md Normal file
View file

244
review.cs
View file

@ -1,144 +1,144 @@
// using SollicitantReview.Models;
// using SollicitantReview.Services;
// using Microsoft.Extensions.Options;
// using System;
// using System.Collections.Generic;
// using System.IO;
// using System.Linq;
// using System.Text;
// using System.Threading;
// using System.Threading.Tasks;
using SollicitantReview.Models;
using SollicitantReview.Services;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
// namespace SollicitantReview
// {
// public class SollicitantReview
// {
// private SollicitantReviewSettings options;
// private IWriter writer;
// private Queue<List<ReviewExportLine>> exportLineQueue;
namespace SollicitantReview
{
public class SollicitantReview
{
private SollicitantReviewSettings options;
private IWriter writer;
private Queue<List<ReviewExportLine>> exportLineQueue;
// public SollicitantReview(IOptions<SollicitantReviewSettings> options, IWriter writer)
// {
// this.options = options.Value;
// this.writer = writer;
// this.exportLineQueue = new Queue<List<ReviewExportLine>>();
public SollicitantReview(IOptions<SollicitantReviewSettings> options, IWriter writer)
{
this.options = options.Value;
this.writer = writer;
this.exportLineQueue = new Queue<List<ReviewExportLine>>();
// var processExportLinesThread = new Thread(new ThreadStart(ProcessReviewExportLines));
// processExportLinesThread.Start();
// }
var processExportLinesThread = new Thread(new ThreadStart(ProcessReviewExportLines));
processExportLinesThread.Start();
}
// public void RegisterOrder(Order order)
// {
// DeleteOrder(order);
// exportLineQueue.Enqueue(ConvertOrderToExportLines(order));
// }
public void RegisterOrder(Order order)
{
DeleteOrder(order);
exportLineQueue.Enqueue(ConvertOrderToExportLines(order));
}
// private string FilterString(string value)
// {
// return value.Replace(";", ":");
// }
private string FilterString(string value)
{
return value.Replace(";", ":");
}
// private void DeleteOrder(Order order)
// {
// var exportLines = new List<ReviewExportLine>()
// {
// new ReviewExportLine()
// {
// Type = "9",
// OrderNumber = FilterString(order.OrderNumber),
// Amount = "1",
// UserId = FilterString(order.User),
// JournalPostIndication = "Y"
// }
// };
private void DeleteOrder(Order order)
{
var exportLines = new List<ReviewExportLine>()
{
new ReviewExportLine()
{
Type = "9",
OrderNumber = FilterString(order.OrderNumber),
Amount = "1",
UserId = FilterString(order.User),
JournalPostIndication = "Y"
}
};
// exportLineQueue.Enqueue(exportLines);
// }
exportLineQueue.Enqueue(exportLines);
}
// private List<ReviewExportLine> ConvertOrderToExportLines(Order order, string userId = null)
// {
// var exportLines = new List<ReviewExportLine>();
private List<ReviewExportLine> ConvertOrderToExportLines(Order order, string userId = null)
{
var exportLines = new List<ReviewExportLine>();
// foreach (var orderLine in order.OrderLines)
// {
// exportLines.Add(new ReviewExportLine()
// {
// OrderNumber = FilterString(order.OrderNumber),
// Name = FilterString(orderLine.Name),
// Amount = FilterString(orderLine.Amount),
// ProductNumber = FilterString(orderLine.Number),
// ProductDescription = FilterString(orderLine.Description),
// UserId = userId == null ? FilterString(order.User) : userId,
// Location = FilterString(orderLine.Location),
// JournalPostIndication = "Y"
// });
// }
foreach (var orderLine in order.OrderLines)
{
exportLines.Add(new ReviewExportLine()
{
OrderNumber = FilterString(order.OrderNumber),
Name = FilterString(orderLine.Name),
Amount = FilterString(orderLine.Amount),
ProductNumber = FilterString(orderLine.Number),
ProductDescription = FilterString(orderLine.Description),
UserId = userId == null ? FilterString(order.User) : userId,
Location = FilterString(orderLine.Location),
JournalPostIndication = "Y"
});
}
// return exportLines;
// }
return exportLines;
}
// private void ProcessReviewExportLines()
// {
// while(true)
// {
// if (exportLineQueue.Any() && IsFolderEmpty(options.ReviewFolderPath))
// {
// var exportLines = exportLineQueue.Dequeue();
// var randomStringLength = 7;
private void ProcessReviewExportLines()
{
while(true)
{
if (exportLineQueue.Any() && IsFolderEmpty(options.ReviewFolderPath))
{
var exportLines = exportLineQueue.Dequeue();
var randomStringLength = 7;
// writer.OpenFile($"{options.ReviewFolderPath}\\{GenerateRandomString(randomStringLength)}.txt");
writer.OpenFile($"{options.ReviewFolderPath}\\{GenerateRandomString(randomStringLength)}.txt");
// foreach (var exportLine in exportLines)
// {
// writer.WriteLine($"{exportLine.Type};" +
// $"{exportLine.OrderNumber};" +
// $"{exportLine.Name};" +
// $"{exportLine.Amount};" +
// $"{exportLine.ProductNumber};" +
// $"{exportLine.ProductDescription};" +
// $"{exportLine.UserId};" +
// $"{exportLine.Location};" +
// $"{exportLine.JournalPostIndication};" +
// $"{exportLine.Info2}");
// }
foreach (var exportLine in exportLines)
{
writer.WriteLine($"{exportLine.Type};" +
$"{exportLine.OrderNumber};" +
$"{exportLine.Name};" +
$"{exportLine.Amount};" +
$"{exportLine.ProductNumber};" +
$"{exportLine.ProductDescription};" +
$"{exportLine.UserId};" +
$"{exportLine.Location};" +
$"{exportLine.JournalPostIndication};" +
$"{exportLine.Info2}");
}
// writer.CloseFile();
// }
writer.CloseFile();
}
// Thread.Sleep(2000);
// }
// }
Thread.Sleep(2000);
}
}
// private bool IsFolderEmpty(string path)
// {
// DirectoryInfo dirInfo = new DirectoryInfo(path);
private bool IsFolderEmpty(string path)
{
DirectoryInfo dirInfo = new DirectoryInfo(path);
// if (!dirInfo.Exists)
// {
// throw new CouldNotFindReviewDirectory();
// }
if (!dirInfo.Exists)
{
throw new CouldNotFindReviewDirectory();
}
// return !dirInfo.GetFiles("*.txt").Any();
// }
return !dirInfo.GetFiles("*.txt").Any();
}
// private string GenerateRandomString(int length)
// {
// StringBuilder stringBuilder = new StringBuilder();
// Random random = new Random();
// var ASCIIOffset = 65;
// var ASCIIRange = 25;
private string GenerateRandomString(int length)
{
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
var ASCIIOffset = 65;
var ASCIIRange = 25;
// char letter;
char letter;
// for (int i = 0; i < length; i++)
// {
// double randomDouble = random.NextDouble();
// int shift = Convert.ToInt32(Math.Floor(ASCIIRange * randomDouble));
// letter = Convert.ToChar(shift + ASCIIOffset);
// stringBuilder.Append(letter);
// }
for (int i = 0; i < length; i++)
{
double randomDouble = random.NextDouble();
int shift = Convert.ToInt32(Math.Floor(ASCIIRange * randomDouble));
letter = Convert.ToChar(shift + ASCIIOffset);
stringBuilder.Append(letter);
}
// return stringBuilder.ToString();
// }
// }
// }
return stringBuilder.ToString();
}
}
}