Skip to content

Commit

Permalink
added thread name to logs
Browse files Browse the repository at this point in the history
added check in case service thread is aborted
re-create the http client each api call
  • Loading branch information
Vlad Somai authored and Vlad Somai committed Jul 27, 2022
1 parent c1ece71 commit fd1700b
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 42 deletions.
10 changes: 6 additions & 4 deletions Necta/API/API.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace Necta.API
{
public class API_Handler
{
private static readonly HttpClient client = new HttpClient();
private const string updateReceiptID_Prefix = "&row=";

#region Configuration_variables
Expand Down Expand Up @@ -49,7 +49,6 @@ public static int API_REQUEST_INTERVAL
public static List<Receipt> FetchReceipts(string uri)
{
var result = Task.Run(async () => await MakeGetHTTP_request(uri)).Result;

try
{
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
Expand All @@ -58,8 +57,8 @@ public static List<Receipt> FetchReceipts(string uri)
}
catch (Exception)
{
NectaLogService.WriteLog("The received data from the API is not a valid JSON!", LogLevels.ERROR);
NectaLogService.WriteLog("The following data was received: " + result, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "The received data from the API is not a valid JSON!", LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "The following data was received: " + result, LogLevels.ERROR);
return new List<Receipt>();
}
}
Expand All @@ -82,6 +81,7 @@ public static void SendPrinterErrorInfo(PrinterError printerError, string printe

private static async Task<string> MakeGetHTTP_request(string uri)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetStringAsync(uri);
Expand All @@ -90,6 +90,8 @@ private static async Task<string> MakeGetHTTP_request(string uri)

private static async Task<HttpResponseMessage> MakePostHTTP_request(string uri, string data)
{
HttpClient client = new HttpClient();

StringContent stringContent = new StringContent(data);

client.DefaultRequestHeaders.Accept.Clear();
Expand Down
47 changes: 25 additions & 22 deletions Necta/NectaApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using PuppeteerSharp;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;

namespace Necta
{
Expand All @@ -29,6 +30,8 @@ public static bool printingInProgress

public NectaApp()
{
Thread.CurrentThread.Name = "Main thread";

InitializeComponent();
var materialSkinManager = MaterialSkinManager.Instance;
materialSkinManager.AddFormToManage(this);
Expand All @@ -49,7 +52,7 @@ public NectaApp()
}
catch (Exception ex)
{
NectaLogService.WriteLog(ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, ex.Message, LogLevels.ERROR);
}

SetTextboxesToVisible(false);
Expand All @@ -74,7 +77,7 @@ private void SetDataFromConfig()

private void SaveAndValidateURI(bool isFirstPaint = false)
{
NectaLogService.WriteLog("Saving new uri links..", LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Saving new uri links..", LogLevels.INFO);
try
{
Uri getURI = new Uri(ApiGetUri_textBox.Text);
Expand All @@ -89,21 +92,21 @@ private void SaveAndValidateURI(bool isFirstPaint = false)
NectaConfigService.SaveNewConfig();

if (API_Handler.API_REQUEST_INTERVAL < 3000)
NectaLogService.WriteLog("The request interval value is too low, please enter a value greater than 3000ms!", LogLevels.WARNING);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "The request interval value is too low, please enter a value greater than 3000ms!", LogLevels.WARNING);

NectaLogService.WriteLog("The following new URI links will now be used to send and receive data through HTTP requests from the API!", LogLevels.INFO);
NectaLogService.WriteLog("GET URI: " + API_Handler.API_GET_URI.ToString(), LogLevels.INFO);
NectaLogService.WriteLog("UPDATE URI: " + API_Handler.API_UPDATE_URI.ToString(), LogLevels.INFO);
NectaLogService.WriteLog("PRINTER INFO URI: " + API_Handler.API_PRINTER_INFO_URI.ToString(), LogLevels.INFO);
NectaLogService.WriteLog("Request interval: " + API_Handler.API_REQUEST_INTERVAL.ToString(), LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "The following new URI links will now be used to send and receive data through HTTP requests from the API!", LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "GET URI: " + API_Handler.API_GET_URI.ToString(), LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "UPDATE URI: " + API_Handler.API_UPDATE_URI.ToString(), LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "PRINTER INFO URI: " + API_Handler.API_PRINTER_INFO_URI.ToString(), LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Request interval: " + API_Handler.API_REQUEST_INTERVAL.ToString(), LogLevels.INFO);

if (!isFirstPaint)
MessageBox.Show(this, "Data has been succesfully saved!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
catch (Exception ex)
{
NectaLogService.WriteLog(ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog("Please enter a valid URI in the GET, UPDATE and PRINTER INFO URI text boxes!", LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Please enter a valid URI in the GET, UPDATE and PRINTER INFO URI text boxes!", LogLevels.ERROR);

API_Handler.API_GET_URI = null;
API_Handler.API_UPDATE_URI = null;
Expand All @@ -116,42 +119,42 @@ private void SaveAndValidateURI(bool isFirstPaint = false)

public static async void PrintReceipt(Receipt receipt)
{
NectaLogService.WriteLog("Setting default printer", LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Setting default printer", LogLevels.INFO);
bool defaultPrinterResult = WinPrinter.SetDefaultPrinter(receipt.PrinterName);

if (defaultPrinterResult)
{
NectaLogService.WriteLog("**************** Printing in progress ****************", LogLevels.INFO);
NectaLogService.WriteLog("Receipt ID: " + receipt.ID, LogLevels.INFO);
NectaLogService.WriteLog("Receipt will be printed on printer: " + receipt.PrinterName + " with ID: " + receipt.Printer, LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "**************** Printing in progress ****************", LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Receipt ID: " + receipt.ID, LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Receipt will be printed on printer: " + receipt.PrinterName + " with ID: " + receipt.Printer, LogLevels.INFO);

try
{
await ChromeConvertHtmlToPdf(receipt.HTML);
}
catch (Exception ex)
{
NectaLogService.WriteLog(ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog(ex.InnerException?.Message, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, ex.InnerException?.Message, LogLevels.ERROR);

if (browserForConverting != null)
await browserForConverting.CloseAsync();

if (ex.Message == "Failed to launch browser! path to executable does not exist")
{
NectaLogService.WriteLog("You must stop Necta.exe and add the corect path to the chrome executable in C:/Necta/Config/Config.json!", LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "You must stop Necta.exe and add the corect path to the chrome executable in C:/Necta/Config/Config.json!", LogLevels.ERROR);
}
printingInProgress = false;
return;
}

API_Handler.UpdateReceipt(receipt.ID, API_Handler.API_UPDATE_URI.ToString());
NectaLogService.WriteLog("Printing done!", LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Printing done!", LogLevels.INFO);
printingInProgress = false;
}
else
{
NectaLogService.WriteLog("Invalid printer name for receipt ID: " + receipt.ID, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Invalid printer name for receipt ID: " + receipt.ID, LogLevels.ERROR);
}
}

Expand Down Expand Up @@ -192,16 +195,16 @@ private static async Task<int> ChromeConvertHtmlToPdf(string html)
Args = args1,
});

NectaLogService.WriteLog("Starting new page", LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Starting new page", LogLevels.INFO);
using (var page = await browserForConverting.NewPageAsync())
{
var navigtionOptions = new NavigationOptions();
WaitUntilNavigation[] waitUntilNavigations = { WaitUntilNavigation.Load };
navigtionOptions.WaitUntil = waitUntilNavigations;
NectaLogService.WriteLog("Setting HTML content on page", LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Setting HTML content on page", LogLevels.INFO);
await page.SetContentAsync(html, navigtionOptions);
await page.WaitForTimeoutAsync(1000);
NectaLogService.WriteLog("Saving the page as PDF", LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Saving the page as PDF", LogLevels.INFO);
await page.PdfAsync(PathToReceipt, new PdfOptions() { PrintBackground = true, OmitBackground = false });
}
await browserForConverting.CloseAsync();
Expand Down
5 changes: 2 additions & 3 deletions Necta/NectaServices/NectaLogService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,18 @@ public static void RunService()
File.WriteAllLines(currentLogFile, logFileContentAfterDeletion);
}
}

}
}

public static void WriteLog(string log, string logLevel)
public static void WriteLog(string source, string log, string logLevel)
{
lock (lockFile)
{
if (serviceInstance == null) return;
using (StreamWriter file = new StreamWriter(currentLogFile, append: true))

{
file.WriteLine(DateTime.Now.ToString() + " | " + logLevel + " | " + log);
file.WriteLine(DateTime.Now.ToString() + " | " + source + " | " + logLevel + " | " + log);
}
}
}
Expand Down
38 changes: 25 additions & 13 deletions Necta/NectaServices/NectaService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class NectaService

public static void RunService()
{
Thread.CurrentThread.Name = "Service thread";
PrintReceiptDelegate PRdel = new PrintReceiptDelegate(NectaApp.PrintReceipt);

List<Receipt> receipts = null;
Expand All @@ -25,25 +26,36 @@ public static void RunService()

if (API_Handler.API_GET_URI == null || API_Handler.API_UPDATE_URI == null)
{
NectaLogService.WriteLog("Fetching data not possible because GET / UPDATE / INFO URIs are not valid, please set valid URIs!", LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Fetching data not possible because GET / UPDATE / INFO URIs are not valid, please set valid URIs!", LogLevels.ERROR);
continue;
}

try
{
NectaLogService.WriteLog("Fetching new receipts from address: " + API_Handler.API_GET_URI.ToString(), LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Fetching new receipts from address: " + API_Handler.API_GET_URI.ToString(), LogLevels.INFO);
receipts = API_Handler.FetchReceipts(API_Handler.API_GET_URI.ToString());
}
catch (Exception ex)
{
NectaLogService.WriteLog(ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog(ex.InnerException?.Message, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, ex.InnerException?.Message, LogLevels.ERROR);

try
{
Thread.ResetAbort();
}
catch(Exception exe)
{
NectaLogService.WriteLog(Thread.CurrentThread.Name, exe.Message, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, exe.InnerException?.Message, LogLevels.ERROR);
}

continue;
}

if (receipts.Count == 0)
{
NectaLogService.WriteLog("No receipts received from API", LogLevels.INFO);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "No receipts received from API", LogLevels.INFO);
continue;
}

Expand All @@ -64,9 +76,9 @@ public static void RunService()
}
catch (Exception ex)
{
NectaLogService.WriteLog("The Printer's info could not be fetched because: ", LogLevels.ERROR);
NectaLogService.WriteLog(ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog("The Printer's info must be fetched before sending a printing command, please solve the issue.", LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "The Printer's info could not be fetched because: ", LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "The Printer's info must be fetched before sending a printing command, please solve the issue.", LogLevels.ERROR);
}

if (printer == null)
Expand All @@ -86,13 +98,13 @@ public static void RunService()

if (API_Handler.API_PRINTER_INFO_URI == null)
{
NectaLogService.WriteLog("Cannot send printer info because PRINTER_INFO_URI is not valid.", LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Cannot send printer info because PRINTER_INFO_URI is not valid.", LogLevels.ERROR);
}
else
{
NectaLogService.WriteLog("Printer has an error, please check the printer info below:", LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, "Printer has an error, please check the printer info below:", LogLevels.ERROR);
var options = new JsonSerializerOptions { WriteIndented = true };
NectaLogService.WriteLog(JsonSerializer.Serialize(printerError, options), LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, JsonSerializer.Serialize(printerError, options), LogLevels.ERROR);
API_Handler.SendPrinterErrorInfo(printerError, API_Handler.API_PRINTER_INFO_URI.ToString());
}

Expand All @@ -111,8 +123,8 @@ public static void RunService()
}
catch (Exception ex)
{
NectaLogService.WriteLog(ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog(ex.InnerException?.Message, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, ex.Message, LogLevels.ERROR);
NectaLogService.WriteLog(Thread.CurrentThread.Name, ex.InnerException?.Message, LogLevels.ERROR);
}
}
}
Expand Down

0 comments on commit fd1700b

Please sign in to comment.