This method receive a CSV file (Sale, Date) POSTed from front-end, cleans a table and inserts csv file record into the table, then gets latest Date and returns it to the front-end. I know the code looks a bit ugly and I have a lot to learn but what I am trying to figure out here is how to create a Helper class from this code since the method is getting too fat I gess?
So I tried to migrate some of the code to a Helper class then I created a static Class but the problem is that I couldn't inject dependencies into its constructor since it was an static Class... then no database service from the Helper class and this is not too "helper".
So in your opinion, is this method too long/ fat? Is there a need for a Helper Class? How can I build it?
Cheers
Here my Controller
private IDataService<Sale> _SaleDataService;
private readonly MyOptions _myOptions;
public DateTime LastWindowDay;
public ForecastApiController(IDataService<Sale> service, IOptions<MyOptions> optionsAccessor)
{
_SaleDataService = service;
_myOptions = optionsAccessor.Value;
}
[HttpPost("api/Sales/uploadFile")]
public async Task<IActionResult> UploadFiles()
{
try
{
//clean table
var all = _SaleDataService.GetAll();
if (all.Count() > 0)
{
foreach (var item in all)
{
_SaleDataService.Delete(item);
}
}
var files = Request.Form.Files;
//Read Request for the unique uploaded file (method can process multiple but frontend will post just one)
foreach (var file in files)
{
using (System.IO.StreamReader sr = new StreamReader(file.OpenReadStream()))
{
//Reads the file one line at a time until its end
String line = await sr.ReadLineAsync();
while (sr.Peek() >= 0)
{
//Split the values on the line and convert them into a propper format
var fileLine = sr.ReadLine();
var lineToArray = fileLine.Split(',').ToArray();
var timeElement = DateTime.Parse(lineToArray[0]);
var saleAmauntElement = float.Parse(lineToArray[1], System.Globalization.CultureInfo.InvariantCulture);
//Discard negative values and store data into database
if (saleAmauntElement >= 0)
{
//Store line into database
Sale sl = new Sale
{
SaleDate = timeElement,
SaleAmount = saleAmauntElement
};
_SaleDataService.Create(sl);
LastWindowDay = sl.SaleDate;
}
}
// Simple Moving Average method will be used and the restriction is that it will calculate only within a week after -
// - last day of historical data.
// Create an array and stores the next 7 days from the last day that there is data
string[] predictionDays = new string[7];
for (int i = 0; i < 7; i++)
{
predictionDays[i] = LastWindowDay.AddDays(i + 1).ToString("dd/MM/yyyy");
}
//returns the array to frontend to let the user select a prediction day
return Json(predictionDays);
}
}
return Json(new { message = "Error trying to process information" });
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { message = ex.Message });
}
}