AdminUserCheckService.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Data;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Microsoft.Extensions.Hosting;
  6. using ResfullApi.Models;
  7. using ResfullApi.Models.balance;
  8. using log4net;
  9. namespace ApiProcess.Process
  10. {
  11. public class AdminUserCheckService : BackgroundService
  12. {
  13. private static readonly ILog logger = LogManager.GetLogger(typeof(AdminUserCheckService));
  14. private const int INTERVAL_MINUTES = 5;
  15. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  16. {
  17. logger.Info($"AdminUserCheckService started. Will check database every {INTERVAL_MINUTES} minutes.");
  18. while (!stoppingToken.IsCancellationRequested)
  19. {
  20. try
  21. {
  22. bool result = CheckAdminUser();
  23. logger.Info($"AdminUserCheckService: Check result = {result}");
  24. await Task.Delay(TimeSpan.FromMinutes(INTERVAL_MINUTES), stoppingToken);
  25. }
  26. catch (OperationCanceledException)
  27. {
  28. logger.Info("AdminUserCheckService: Service is stopping.");
  29. break;
  30. }
  31. catch (Exception ex)
  32. {
  33. logger.Error($"AdminUserCheckService: Error occurred: {ex.ToString()}");
  34. // Wait 1 minute before retrying on error
  35. await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
  36. }
  37. }
  38. logger.Info("AdminUserCheckService: Service stopped.");
  39. }
  40. private bool CheckAdminUser()
  41. {
  42. try
  43. {
  44. DataSet ds = balanceDataAccess.callCheckDB();
  45. // Check if DataSet is valid and has data
  46. if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
  47. {
  48. logger.Info("AdminUserCheckService: No data returned. Result = false");
  49. return false;
  50. }
  51. // If we have data, consider it as success (true)
  52. logger.Info("AdminUserCheckService: Data returned successfully. Result = true");
  53. return true;
  54. }
  55. catch (Exception ex)
  56. {
  57. logger.Error($"AdminUserCheckService: Exception in CheckAdminUser: {ex.ToString()}");
  58. return false;
  59. }
  60. }
  61. }
  62. }