AdminUserCheckService.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 = 1;
  15. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  16. {
  17. logger.Info($"AdminUserCheckService started. Will check every {INTERVAL_MINUTES} minutes.");
  18. while (!stoppingToken.IsCancellationRequested)
  19. {
  20. try
  21. {
  22. bool result = CheckAdminUser();
  23. logger.Info($"AdminUserCheckService: Check result = {result}");
  24. // Wait for 10 minutes before next check
  25. await Task.Delay(TimeSpan.FromMinutes(INTERVAL_MINUTES), stoppingToken);
  26. }
  27. catch (OperationCanceledException)
  28. {
  29. logger.Info("AdminUserCheckService: Service is stopping.");
  30. break;
  31. }
  32. catch (Exception ex)
  33. {
  34. logger.Error($"AdminUserCheckService: Error occurred: {ex.ToString()}");
  35. // Wait 1 minute before retrying on error
  36. await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
  37. }
  38. }
  39. logger.Info("AdminUserCheckService: Service stopped.");
  40. }
  41. private bool CheckAdminUser()
  42. {
  43. try
  44. {
  45. DataSet ds = balanceDataAccess.callCheckDB();
  46. // Check if DataSet is valid and has data
  47. if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
  48. {
  49. logger.Info("AdminUserCheckService: No data returned. Result = false");
  50. return false;
  51. }
  52. // If we have data, consider it as success (true)
  53. logger.Info("AdminUserCheckService: Data returned successfully. Result = true");
  54. return true;
  55. }
  56. catch (Exception ex)
  57. {
  58. logger.Error($"AdminUserCheckService: Exception in CheckAdminUser: {ex.ToString()}");
  59. return false;
  60. }
  61. }
  62. }
  63. }