Browse Source

update to master commit 58a36

Robert 1 year ago
parent
commit
caaf6b6a03

+ 2 - 0
Dockerfile

@@ -1,6 +1,8 @@
 #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
 
 FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
+EXPOSE 80
+
 RUN sed -i 's/TLSv1.2/TLSv1/g' /etc/ssl/openssl.cnf
 RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf
 WORKDIR /app

+ 0 - 1
EVCB_OCPP.TaskScheduler/EVCB_OCPP.TaskScheduler.csproj

@@ -12,7 +12,6 @@
   </ItemGroup>
   <ItemGroup>
     <PackageReference Include="Dapper" Version="2.0.123" />
-    <PackageReference Include="Dapper.Transaction" Version="2.0.123" />
     <PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
     <PackageReference Include="Microsoft.Data.SqlClient" Version="5.0.1" />
     <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />

+ 7 - 0
EVCB_OCPP.TaskScheduler/Helper/AddPortalDbContext.cs

@@ -130,6 +130,13 @@ public class SqlConnectionFactory<T> where T : DbContext
         sqlConnection.Open();
         return sqlConnection;
     }
+
+    public async Task<SqlConnection> CreateAsync()
+    {
+        var sqlConnection = new SqlConnection(ConnectionString);
+        await sqlConnection.OpenAsync();
+        return sqlConnection;
+    }
 }
 
 /// <summary>

+ 29 - 33
EVCB_OCPP.TaskScheduler/Jobs/CheckEVSEOnlineJob.cs

@@ -47,7 +47,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
             logger.LogDebug(this.ToString() + " :Starting........");
             try
             {
-                List<EVSECurrentStatus> _EVSEs = GetEVSEs();
+                List<EVSECurrentStatus> _EVSEs = await GetEVSEs();
                 var checktime = DateTime.UtcNow.AddDays(-3);
                 _EVSEs = _EVSEs.Where(x => x.HeartbeatUpdatedOn > checktime).ToList();
 
@@ -60,7 +60,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
                         if (!evse.Online)
                         { //off - on                           
 
-                            UpdateEVSECurrentStatus(evse.CustomerId.ToString(), evse.ChargeBoxId, true, DefaultSetting.DefaultNullTime);
+                            await UpdateEVSECurrentStatus(evse.CustomerId.ToString(), evse.ChargeBoxId, true, DefaultSetting.DefaultNullTime);
                             await UpdateOnlineRecords(evse.ChargeBoxId, true, evse.HeartbeatUpdatedOn, null);
                         }
                     }
@@ -71,7 +71,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
                         {
                             //on -off                        
 
-                            UpdateEVSECurrentStatus(evse.CustomerId.ToString(), evse.ChargeBoxId, false, evse.HeartbeatUpdatedOn);
+                            await UpdateEVSECurrentStatus(evse.CustomerId.ToString(), evse.ChargeBoxId, false, evse.HeartbeatUpdatedOn);
                             var online_row = await GetOnlineRecord(evse.ChargeBoxId);
                             if (online_row != null)
                             {
@@ -95,19 +95,20 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
         }
 
 
-        private List<EVSECurrentStatus> GetEVSEs()
+        private async Task<List<EVSECurrentStatus>> GetEVSEs()
         {
             List<EVSECurrentStatus> result = new List<EVSECurrentStatus>();
             try
             {
-                using (var dbConn = mainDbConnectionFactory.Create())
-                {
-                    string sqlstring = "SELECT m.CustomerId,m.Id,m.ChargeBoxId,m.Online,m.HeartbeatUpdatedOn,MachineConfigurations.ConfigureSetting HeartbeatInterval"
-                   + "  FROM [dbo].[Machine]  m  left join [dbo].[MachineConfigurations]  MachineConfigurations  on m.ChargeBoxId = MachineConfigurations.ChargeBoxId"
-                   + " where MachineConfigurations.ConfigureName = 'HeartbeatInterval'  and MachineConfigurations.ConfigureSetting!=''";
-                    result = dbConn.Query<EVSECurrentStatus>(sqlstring).ToList();
-                }
-
+                using var dbConn = await mainDbConnectionFactory.CreateAsync();
+
+                string sqlstring =
+                    """
+                    SELECT m.CustomerId,m.Id,m.ChargeBoxId,m.Online,m.HeartbeatUpdatedOn,MachineConfigurations.ConfigureSetting HeartbeatInterval
+                    FROM [dbo].[Machine] m left join [dbo].[MachineConfigurations] MachineConfigurations  on m.ChargeBoxId = MachineConfigurations.ChargeBoxId
+                    WHERE MachineConfigurations.ConfigureName = 'HeartbeatInterval'  and MachineConfigurations.ConfigureSetting!=''
+                    """;
+                result = (await dbConn.QueryAsync<EVSECurrentStatus>(sqlstring)).ToList();
             }
             catch (Exception ex)
             {
@@ -118,27 +119,22 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
             return result;
         }
 
-        private void UpdateEVSECurrentStatus(string customerId, string ChargeBoxId, bool turnOn, DateTime offlineTime)
+        private async Task UpdateEVSECurrentStatus(string customerId, string ChargeBoxId, bool turnOn, DateTime offlineTime)
         {
             try
             {
-                string sqlString = string.Format("UPDATE [dbo].[Machine] SET Online=@Online {0} WHERE chargeBoxId=@chargeBoxId ", turnOn ? "" : " ,OfflineOn=@OfflineOn");
-                using (var dbConn = mainDbConnectionFactory.Create())
-                {
-                    var parameters = new DynamicParameters();
-                    parameters.Add("@Online", turnOn, System.Data.DbType.Boolean);
-                    parameters.Add("@chargeBoxId", ChargeBoxId, System.Data.DbType.String);
+                string sqlString = string.Format("UPDATE dbo.Machine SET Online=@Online {0} WHERE chargeBoxId=@chargeBoxId ", turnOn ? "" : " ,OfflineOn=@OfflineOn");
+                using var dbConn = await mainDbConnectionFactory.CreateAsync();
+                var parameters = new DynamicParameters();
+                parameters.Add("@Online", turnOn, System.Data.DbType.Boolean);
+                parameters.Add("@chargeBoxId", ChargeBoxId, System.Data.DbType.String);
 
-                    if (!turnOn)
-                    {
-                        parameters.Add("@OfflineOn", offlineTime, System.Data.DbType.DateTime);
-                    }
-
-
-
-                    dbConn.Execute(sqlString, parameters);
+                if (!turnOn)
+                {
+                    parameters.Add("@OfflineOn", offlineTime, System.Data.DbType.DateTime);
                 }
 
+                await dbConn.ExecuteAsync(sqlString, parameters);
             }
             catch (Exception ex)
             {
@@ -147,15 +143,15 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
         }
 
 
-        async private Task UpdateOnlineRecords(string chargeBoxId, bool online, DateTime hearbeatDt, Int64? rowId)
+        private async Task UpdateOnlineRecords(string chargeBoxId, bool online, DateTime hearbeatDt, Int64? rowId)
         {
             try
             {
                 if (online)
                 {
-                    string sqlString = "INSERT INTO [dbo].[EVSEOnlineRecord] (\"ChargeBoxId\",\"OnlineTime\",\"OfflineTime\")" +
+                    string sqlString = "INSERT INTO dbo.EVSEOnlineRecord (\"ChargeBoxId\",\"OnlineTime\",\"OfflineTime\")" +
                        "VALUES( @ChargeBoxId,@OnlineTime,@OfflineTime); ";
-                    using (var dbConn = onlineLogDbConnectionFactory.Create())
+                    using var dbConn = await onlineLogDbConnectionFactory.CreateAsync();
                     {
                         var parameters = new DynamicParameters();
                         parameters.Add("@ChargeBoxId", chargeBoxId, System.Data.DbType.String);
@@ -169,8 +165,8 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
                 {
                     if (rowId.HasValue)
                     {
-                        string sqlString = "UPDATE [dbo].[EVSEOnlineRecord] SET OfflineTime=@OfflineTime  WHERE Id=@Id";
-                        using (var dbConn = mainDbConnectionFactory.Create())
+                        string sqlString = "UPDATE dbo.EVSEOnlineRecord SET OfflineTime=@OfflineTime  WHERE Id=@Id";
+                        using (var dbConn = await onlineLogDbConnectionFactory.CreateAsync())
                         {
                             var parameters = new DynamicParameters();
                             parameters.Add("@OfflineTime", hearbeatDt, System.Data.DbType.DateTime);
@@ -203,7 +199,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
             EVSEOnlineRecord lastrow = new EVSEOnlineRecord();
             try
             {
-                string sqlString = string.Format("SELECT Id FROM [dbo].[EVSEOnlineRecord] WHERE chargeBoxId=@chargeBoxId Order by OnlineTime desc");
+                string sqlString = string.Format("SELECT Id FROM dbo.EVSEOnlineRecord WHERE chargeBoxId=@chargeBoxId Order by OnlineTime desc");
                 using (var dbConn = onlineLogDbConnectionFactory.Create())
                 {
                     var parameters = new DynamicParameters();

+ 1 - 1
EVCB_OCPP.TaskScheduler/Jobs/CheckExecutionCmdJob.cs

@@ -32,7 +32,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
             List<Task> tList = new List<Task>();
 
             //ICustomersService cs = serviceProvider.GetService<ICustomersService>();//new CommonCustomerService();
-            var cList = customersService.GetCallPartnerCustomers();
+            var cList = await customersService.GetCallPartnerCustomers();
 
             foreach (var customerId in cList)
             {

+ 75 - 0
EVCB_OCPP.TaskScheduler/Jobs/ConnectionStatisticsJob.cs

@@ -0,0 +1,75 @@
+using EVCB_OCPP.TaskScheduler.Models;
+using EVCB_OCPP.TaskScheduler.Services;
+using Microsoft.Extensions.Logging;
+using Quartz;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.TaskScheduler.Jobs
+{
+    [DisallowConcurrentExecution]
+    internal class ConnectionStatisticsJob : IJob
+    {
+        public ConnectionStatisticsJob(DatabaseService databaseService, ILogger<ConnectionStatisticsJob> logger)
+        {
+            this.database = databaseService;
+            this.logger = logger;
+        }
+        private readonly DatabaseService database;
+        private readonly ILogger<ConnectionStatisticsJob> logger;
+
+        public async Task Execute(IJobExecutionContext context)
+        {
+            logger.LogTrace(this.ToString() + " :Starting........");
+
+            List<ConnectionStatistics> connectionStatistics = new List<ConnectionStatistics>();
+            var customers = await database.GetCustomerInfos();
+            var storagedChargers = await database.GetChargerAmount(connected: false);
+            var connectedChargers = await database.GetChargerAmount(connected: true);
+            var connectedConnectors = await database.GetConnectorAmount();
+            foreach (var customer in customers)
+            {
+                if (customer.Name == "PHT") continue;
+                connectionStatistics.Add(new ConnectionStatistics()
+                {
+                    CustomerName = customer.Name,
+                    StationName = customer.Name,
+                    StoragedChargerAmount = storagedChargers.Where(x => x.CustomerName == customer.Name).Select(x => x.Charger_Count).FirstOrDefault(),
+                    UsedChargerAmount = connectedChargers.Where(x => x.CustomerName == customer.Name).Select(x => x.Charger_Count).FirstOrDefault(),
+                    UsedConnectorAmount = connectedConnectors.Where(x => x.CustomerName == customer.Name).Select(x => x.Charger_Count).FirstOrDefault(),
+                    CreatedOn = DateTime.UtcNow
+                });
+
+                //ignore customer
+
+                connectionStatistics.RemoveAll(x => x.StoragedChargerAmount == 0);
+            }
+            connectionStatistics.Add(new ConnectionStatistics()
+            {
+                CustomerName = "PHT",
+                StationName = "PHT",
+                StoragedChargerAmount = (await database.GetPHTChargerAmount(false, true)).Where(x => x.CustomerName == "PHT").Select(x => x.Charger_Count).FirstOrDefault(),
+                UsedChargerAmount = (await database.GetPHTChargerAmount(true, true)).Where(x => x.CustomerName == "PHT").Select(x => x.Charger_Count).FirstOrDefault(),
+                UsedConnectorAmount = (await database.GetPHTConnectorAmount(true)).Where(x => x.CustomerName == "PHT").Select(x => x.Charger_Count).FirstOrDefault(),
+                CreatedOn = DateTime.UtcNow
+            });
+
+            connectionStatistics.Add(new ConnectionStatistics()
+            {
+                CustomerName = "PHT",
+                StationName = "Electric Avenue",
+                StoragedChargerAmount = (await database.GetPHTChargerAmount(false, false)).Where(x => x.CustomerName == "PHT").Select(x => x.Charger_Count).FirstOrDefault(),
+                UsedChargerAmount = (await database.GetPHTChargerAmount(true, false)).Where(x => x.CustomerName == "PHT").Select(x => x.Charger_Count).FirstOrDefault(),
+                UsedConnectorAmount = (await database.GetPHTConnectorAmount(false)).Where(x => x.CustomerName == "PHT").Select(x => x.Charger_Count).FirstOrDefault(),
+                CreatedOn = DateTime.UtcNow
+            });
+
+            await database.SaveConnectionStatistics(connectionStatistics);
+            logger.LogTrace(this.ToString() + " :Finished........");
+
+        }
+    }
+}

+ 47 - 0
EVCB_OCPP.TaskScheduler/Jobs/DeleteServerMessageJob.cs

@@ -0,0 +1,47 @@
+using Dapper;
+using EVCB_OCPP.Domain;
+using EVCB_OCPP.TaskScheduler.Helper;
+using Microsoft.Data.SqlClient;
+using Microsoft.Extensions.Logging;
+using Quartz;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.TaskScheduler.Jobs
+{
+    [DisallowConcurrentExecution]
+    public class DeleteServerMessageJob : IJob
+    {
+        public DeleteServerMessageJob(ILogger<DeleteServerMessageJob> logger, SqlConnectionFactory<MainDBContext> mainDBConnectionFactory)
+        {
+            this.logger = logger;
+            this.mainDBConnectionFactory = mainDBConnectionFactory;
+        }
+
+        private readonly ILogger<DeleteServerMessageJob> logger;
+        private readonly SqlConnectionFactory<MainDBContext> mainDBConnectionFactory;
+
+        public async Task Execute(IJobExecutionContext context)
+        {
+
+            logger.LogDebug(this.ToString() + " :Start........");
+            int counter = 0;
+
+            while (counter < 5)
+            {
+                counter++;
+                using (var dbConn = await mainDBConnectionFactory.CreateAsync())
+                {
+                    dbConn.Open();
+                    string sqlstring = "Delete Top(10000) from ServerMessage";
+                    await dbConn.ExecuteAsync(sqlstring);
+                }
+            }
+
+            logger.LogDebug(this.ToString() + " :Finished........");
+        }
+    }
+}

+ 1 - 1
EVCB_OCPP.TaskScheduler/Jobs/ExecutionCmdReportJob.cs

@@ -31,7 +31,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
 
             List<Task> tList = new List<Task>();
 
-            var cList = customersService.GetCallPartnerCustomers();
+            var cList = await customersService.GetCallPartnerCustomers();
 
             foreach (var customerId in cList)
             {

+ 15 - 1
EVCB_OCPP.TaskScheduler/Jobs/JobScheduler.cs

@@ -49,7 +49,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
                     .WithIdentity("CheckExecutionCmdJobTrigger")
                     .StartNow()
                     .WithSimpleSchedule(x => x
-                        .WithIntervalInSeconds(10)
+                        .WithIntervalInSeconds(5)
                         .RepeatForever())
                 );
 
@@ -61,6 +61,20 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
                         .WithIntervalInSeconds(10)
                         .RepeatForever())
                 );
+
+                q.ScheduleJob<ConnectionStatisticsJob>(trigger =>
+                    trigger
+                    .WithIdentity("ConnectionStatisticsJobTrigger")
+                    .StartNow()
+                    .WithCronSchedule("0 59 23 L * ?")
+                );
+
+                q.ScheduleJob<DeleteServerMessageJob>(trigger =>
+                    trigger
+                    .WithIdentity("ConnectionStatisticsJobTrigger")
+                    .StartNow()
+                    .WithCronSchedule("0 15 17 * * ? *")
+                );
             });
 
             services.AddQuartzHostedService(configure => {

+ 1 - 1
EVCB_OCPP.TaskScheduler/Jobs/StartTransacionReportJob.cs

@@ -30,7 +30,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
 
             List<Task> tList = new List<Task>();
 
-            var cList = customersService.GetCallPartnerCustomers();
+            var cList = await customersService.GetCallPartnerCustomers();
 
             foreach (var customerId in cList)
             {

+ 1 - 1
EVCB_OCPP.TaskScheduler/Jobs/StopTransacionReportJob.cs

@@ -31,7 +31,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
 
             List<Task> tList = new List<Task>();
 
-            var cList = customersService.GetNotifyStopTransactionCustomers();
+            var cList = await customersService.GetNotifyStopTransactionCustomers();
 
             foreach (var customerId in cList)
             {

+ 16 - 0
EVCB_OCPP.TaskScheduler/Models/ChargerAmountDto.cs

@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.TaskScheduler.Models
+{
+    public class ChargerAmountDto
+    {
+        public int Charger_Count { set; get; }
+
+
+        public string CustomerName { set; get; }
+    }
+}

+ 24 - 0
EVCB_OCPP.TaskScheduler/Models/ConnectionStatistics.cs

@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.TaskScheduler.Models
+{
+    public class ConnectionStatistics
+    {
+        public string CustomerName { set; get; }
+
+        public string StationName { set; get; }
+
+        public int StoragedChargerAmount { set; get; }
+
+        public int UsedChargerAmount { set; get; }
+
+
+        public int UsedConnectorAmount { set; get; }
+
+        public DateTime CreatedOn { set; get; }
+    }
+}

+ 16 - 0
EVCB_OCPP.TaskScheduler/Models/CustomerInfoDto.cs

@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.TaskScheduler.Models
+{
+    public class CustomerInfoDto
+    {
+        public Guid Id { set; get; }
+
+        public string Name { set; get; }
+
+    }
+}

+ 2 - 2
EVCB_OCPP.TaskScheduler/Services/CommonCustomerService.cs

@@ -39,7 +39,7 @@ namespace EVCB_OCPP.TaskScheduler.Services
 
             customerName = await _dbService.GetCustomerName(this.customerId);
             //_dbService.GetCustomerName(this.customerId);
-            var connectionInfo = _dbService.GetAPIConnectionInfo(customerId);
+            var connectionInfo = await _dbService.GetAPIConnectionInfo(customerId);
             _saltkey = connectionInfo.ApiKey;
             _partnerAPIRoot = connectionInfo.ApiUrl;
         }
@@ -309,7 +309,7 @@ namespace EVCB_OCPP.TaskScheduler.Services
 
         async public Task ReportExecutionofRemoteCommand()
         {
-            var items = _dbService.GetNeedReportExecution(customerId, 1000);
+            var items = await _dbService.GetNeedReportExecution(customerId, 1000);
 
             Stopwatch watch = new Stopwatch();
             watch.Start();

+ 6 - 6
EVCB_OCPP.TaskScheduler/Services/CustomersService.cs

@@ -9,11 +9,11 @@ namespace EVCB_OCPP.TaskScheduler.Services;
 
 public interface ICustomersService
 {
-    Task<ICustomerService> GetCustomerService(Guid guid); 
-    
-    List<Guid> GetNotifyStopTransactionCustomers();
+    Task<ICustomerService> GetCustomerService(Guid guid);
 
-    List<Guid> GetCallPartnerCustomers();
+    Task<List<Guid>> GetNotifyStopTransactionCustomers();
+
+    Task<List<Guid>> GetCallPartnerCustomers();
 }
 
 public class CustomersService : ICustomersService
@@ -34,12 +34,12 @@ public class CustomersService : ICustomersService
         return service;
     }
 
-    public List<Guid> GetCallPartnerCustomers()
+    public Task<List<Guid>> GetCallPartnerCustomers()
     {
         return _dbService.GetCallParterAPICustomers();
     }
 
-    public List<Guid> GetNotifyStopTransactionCustomers()
+    public Task<List<Guid>> GetNotifyStopTransactionCustomers()
     {
         return _dbService.GetNotifyStopTransactionCustomers();
     }

+ 243 - 50
EVCB_OCPP.TaskScheduler/Services/DatabaseService.cs

@@ -1,23 +1,15 @@
 using Dapper;
-using Dapper.Transaction;
 using EVCB_OCPP.Domain;
 using EVCB_OCPP.TaskScheduler.Helper;
 using EVCB_OCPP.TaskScheduler.Models;
 using Microsoft.Data.SqlClient;
-using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.Logging;
 using Polly;
-using Polly.Retry;
 using System;
 using System.Collections.Generic;
-using System.Configuration;
 using System.Data;
-using System.Data.Common;
-using System.Diagnostics;
 using System.Linq;
-using System.Text;
 using System.Threading.Tasks;
-using System.Transactions;
 using Transaction = EVCB_OCPP.TaskScheduler.Models.Transaction;
 
 namespace EVCB_OCPP.TaskScheduler.Services
@@ -27,6 +19,7 @@ namespace EVCB_OCPP.TaskScheduler.Services
         private readonly ILogger logger;
         private readonly SqlConnectionFactory<MainDBContext> mainDbConnectionFactory;
         private readonly SqlConnectionFactory<OnlineLogDBContext> onlineLogDbConnectionFactory;
+        private readonly SqlConnectionFactory<WebDBConetext> webDbConnectionFactory;
 
         //private readonly string mainDBConnectString;
         //private readonly string onlineDBConnectString;
@@ -34,11 +27,13 @@ namespace EVCB_OCPP.TaskScheduler.Services
         public DatabaseService(
             ILogger<DatabaseService> logger,
             SqlConnectionFactory<MainDBContext> mainDbConnectionFactory,
-            SqlConnectionFactory<OnlineLogDBContext> onlineLogDbConnectionFactory)
+            SqlConnectionFactory<OnlineLogDBContext> onlineLogDbConnectionFactory,
+            SqlConnectionFactory<WebDBConetext> webDbConnectionFactory)
         {
             this.logger = logger;
             this.mainDbConnectionFactory = mainDbConnectionFactory;
             this.onlineLogDbConnectionFactory = onlineLogDbConnectionFactory;
+            this.webDbConnectionFactory = webDbConnectionFactory;
 
             //mainDBConnectString = configuration.GetConnectionString("MainDBContext");
             //onlineDBConnectString = configuration.GetConnectionString("OnlineLogDBContext");
@@ -90,31 +85,31 @@ namespace EVCB_OCPP.TaskScheduler.Services
 
         }
 
-        internal CustomerConnectionDto GetAPIConnectionInfo(Guid partnerId)
+        internal async Task<CustomerConnectionDto> GetAPIConnectionInfo(Guid partnerId)
         {
             CustomerConnectionDto result = new CustomerConnectionDto();
             string key = string.Empty;
             var parameters = new DynamicParameters();
             parameters.Add("@Id", partnerId, DbType.Guid, ParameterDirection.Input);
-            using (SqlConnection conn = mainDbConnectionFactory.Create())
+            using (SqlConnection conn = await mainDbConnectionFactory.CreateAsync())
             {
                 string strSql = "Select ApiKey, ApiUrl from [dbo].[Customer] where Id=@Id; ";
-                result = conn.Query<CustomerConnectionDto>(strSql, parameters).FirstOrDefault();
+                result = await conn.QueryFirstOrDefaultAsync<CustomerConnectionDto>(strSql, parameters);
             }
             return result;
 
         }
 
 
-        internal List<Guid> GetCallParterAPICustomers()
+        internal async Task<List<Guid>> GetCallParterAPICustomers()
         {
             List<Guid> result = new List<Guid>();
             try
             {
-                using (var dbConn = mainDbConnectionFactory.Create())
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
                 {
                     //dbConn.Open();
-                    result = dbConn.Query<Guid>("SELECT Id FROM [dbo].[Customer] where CallPartnerApiOnSchedule=1").ToList();
+                    result = (await dbConn.QueryAsync<Guid>("SELECT Id FROM [dbo].[Customer] where CallPartnerApiOnSchedule=1")).ToList();
                 }
 
             }
@@ -126,15 +121,15 @@ namespace EVCB_OCPP.TaskScheduler.Services
             return result;
         }
 
-        internal List<Guid> GetNotifyStopTransactionCustomers()
+        internal async Task<List<Guid>> GetNotifyStopTransactionCustomers()
         {
             List<Guid> result = new List<Guid>();
             try
             {
-                using (var dbConn = mainDbConnectionFactory.Create())
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
                 {
                     //dbConn.Open();
-                    result = dbConn.Query<Guid>("SELECT Id FROM [dbo].[Customer] where CallPartnerApiOnSchedule=1 and InstantStopTxReport=0").ToList();
+                    result = (await dbConn.QueryAsync<Guid>("SELECT Id FROM [dbo].[Customer] where CallPartnerApiOnSchedule=1 and InstantStopTxReport=0")).ToList();
                 }
 
             }
@@ -188,12 +183,12 @@ namespace EVCB_OCPP.TaskScheduler.Services
             return result;
         }
 
-        internal List<MachineOperateRecord> GetNeedReportExecution(Guid customerId, int size)
+        internal async Task<List<MachineOperateRecord>> GetNeedReportExecution(Guid customerId, int size)
         {
             List<MachineOperateRecord> result = new List<MachineOperateRecord>();
             try
             {
-                using (var dbConn = mainDbConnectionFactory.Create())
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
                 {
                     //dbConn.Open();
                     var parameters = new DynamicParameters();                  
@@ -203,7 +198,7 @@ namespace EVCB_OCPP.TaskScheduler.Services
                     sqlString = "SELECT Top(" + size + ") Machine.CustomerId, record.Id, record.ChargeBoxId,record.Action,record.SerialNo,record.Status,record.EVSE_Value,record.EVSE_Status FROM[dbo].[MachineOperateRecord] record" +
                         " left join[dbo].[Machine]   on record.ChargeBoxId = Machine.ChargeBoxId " +
                         "  where Machine.CustomerId =@CustomerId and Status!= 0 and RequestType = 1 and ReportedOn = '1991/01/01'";
-                    result = dbConn.Query<MachineOperateRecord>(sqlString, parameters).ToList();
+                    result = (await dbConn.QueryAsync<MachineOperateRecord>(sqlString, parameters)).ToList();
                 }
             }
             catch (Exception ex)
@@ -220,7 +215,7 @@ namespace EVCB_OCPP.TaskScheduler.Services
 
             try
             {
-                using (var dbConn = mainDbConnectionFactory.Create())
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
                 {
                     foreach (var kv in reportResults)
                     {
@@ -247,24 +242,22 @@ namespace EVCB_OCPP.TaskScheduler.Services
 
             try
             {
-                using (var dbConn = mainDbConnectionFactory.Create())
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
+                using (var trans = await dbConn.BeginTransactionAsync())
                 {
-                    //await dbConn.OpenAsync();
-                    using (var trans = await dbConn.BeginTransactionAsync())
-                    {
-                        //dbConn.Open();
-
-                        foreach (var kv in reportResults)
-                        {
-                            var parameters = new DynamicParameters();
-                            parameters.Add("@Id", kv.Key, DbType.Int32, ParameterDirection.Input);
-                            parameters.Add("@StopTransactionReportedOn", kv.Value.StopTransactionReportedOn, DbType.DateTime, ParameterDirection.Input);
-                            parameters.Add("@ErrorMsg", kv.Value.ErrorMsg, DbType.String, ParameterDirection.Input, -1);
-                            await trans.ExecuteAsync("UPDATE [dbo].[TransactionRecord] set StopTransactionReportedOn=@StopTransactionReportedOn, ErrorMsg=@ErrorMsg  where Id=@Id", parameters);
-                        }
+                    //dbConn.Open();
 
-                        await trans.CommitAsync();
+                    foreach (var kv in reportResults)
+                    {
+                        var parameters = new DynamicParameters();
+                        parameters.Add("@Id", kv.Key, DbType.Int32, ParameterDirection.Input);
+                        parameters.Add("@StopTransactionReportedOn", kv.Value.StopTransactionReportedOn, DbType.DateTime, ParameterDirection.Input);
+                        parameters.Add("@ErrorMsg", kv.Value.ErrorMsg, DbType.String, ParameterDirection.Input, -1);
+                        await dbConn.ExecuteAsync("UPDATE [dbo].[TransactionRecord] set StopTransactionReportedOn=@StopTransactionReportedOn, ErrorMsg=@ErrorMsg  where Id=@Id", parameters, trans);
+                        //await trans.ExecuteAsync("UPDATE [dbo].[TransactionRecord] set StopTransactionReportedOn=@StopTransactionReportedOn, ErrorMsg=@ErrorMsg  where Id=@Id", parameters);
                     }
+
+                    await trans.CommitAsync();
                 }
             }
             catch (Exception ex)
@@ -300,31 +293,231 @@ namespace EVCB_OCPP.TaskScheduler.Services
         {
             try
             {
-                using (var dbConn = mainDbConnectionFactory.Create())
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
+                using (var trans = await dbConn.BeginTransactionAsync())
                 {
-                    //await dbConn.OpenAsync();
-                    using (var trans = await dbConn.BeginTransactionAsync())
+                    //dbConn.Open();
+
+                    foreach (var kv in reportResults)
                     {
-                        //dbConn.Open();
+                        var parameters = new DynamicParameters();
+                        parameters.Add("@Id", kv.Key, DbType.Int32, ParameterDirection.Input);
+                        parameters.Add("@ReportedOn", kv.Value.ReportedOn, DbType.DateTime, ParameterDirection.Input);
 
-                        foreach (var kv in reportResults)
-                        {
-                            var parameters = new DynamicParameters();
-                            parameters.Add("@Id", kv.Key, DbType.Int32, ParameterDirection.Input);
-                            parameters.Add("@ReportedOn", kv.Value.ReportedOn, DbType.DateTime, ParameterDirection.Input);
+                        await dbConn.ExecuteAsync("UPDATE [dbo].[MachineOperateRecord] set ReportedOn=@ReportedOn where Id=@Id", parameters, trans);
+                    }
 
-                            await trans.ExecuteAsync("UPDATE [dbo].[MachineOperateRecord] set ReportedOn=@ReportedOn where Id=@Id", parameters);
-                        }
+                    await trans.CommitAsync();
+                }
+            }
+            catch (Exception ex)
+            {
+                logger.LogError("ReportExecution Error " + ex.ToString());
+            }
+
+        }
 
-                        await trans.CommitAsync();
+        internal async Task<List<CustomerInfoDto>> GetCustomerInfos()
+        {
+            List<CustomerInfoDto> result = new List<CustomerInfoDto>();
+            try
+            {
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
+                {
+                    result = (await dbConn.QueryAsync<CustomerInfoDto>("SELECT Id , Name  FROM [dbo].[Customer] where  IsShow =1 "))
+                        .ToList();
+                }
+
+            }
+            catch (Exception ex)
+            {
+                logger.LogError("GetCustomerInfos Error " + ex.ToString());
+            }
+
+            //add PHT Electric Avenue
+
+            return result;
+        }
+
+        internal async Task<List<ChargerAmountDto>> GetChargerAmount(bool connected)
+        {
+            List<ChargerAmountDto> result = new List<ChargerAmountDto>();
+            try
+            {
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
+                {
+                    if (connected)
+                    {
+                        var parameters = new DynamicParameters();
+                        parameters.Add("@HeartbeatUpdatedOn", new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), DbType.DateTime, ParameterDirection.Input);
+                        var quertResult = await dbConn.QueryAsync<ChargerAmountDto>("""
+                            SELECT  count(ChargeBoxId) as Charger_Count , Customer.Name as CustomerName  FROM [dbo].[Machine] 
+                            inner join Customer on Customer.id =[Machine].CustomerId 
+                            WHERE IsDelete=0 and HeartbeatUpdatedOn>=@HeartbeatUpdatedOn 
+                            group by  CustomerId,Customer.Name
+                            """, parameters);
+                        result = quertResult.ToList();
+                    }
+                    else
+                    {
+                        var queryResult = await dbConn.QueryAsync<ChargerAmountDto>("""
+                            SELECT  count(ChargeBoxId) as Charger_Count , Customer.Name as CustomerName  FROM [dbo].[Machine] 
+                            inner join Customer on Customer.id =[Machine].CustomerId 
+                            where IsDelete=0 
+                            group by  CustomerId,Customer.Name
+                            """);
+                        result = queryResult.ToList();
                     }
+
                 }
+
             }
             catch (Exception ex)
             {
-                logger.LogError("ReportExecution Error " + ex.ToString());
+                logger.LogError("GetChargerAmount Error " + ex.ToString());
             }
 
+            //add PHT Electric Avenue
+
+            return result;
+        }
+
+        internal async Task<List<ChargerAmountDto>> GetConnectorAmount()
+        {
+            List<ChargerAmountDto> result = new List<ChargerAmountDto>();
+            try
+            {
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
+                {
+                    var parameters = new DynamicParameters();
+                    parameters.Add("@HeartbeatUpdatedOn", new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), DbType.DateTime, ParameterDirection.Input);
+                    var queryResult = await dbConn.QueryAsync<ChargerAmountDto>("""
+                        SELECT  sum(GunAmt) as Charger_Count , Customer.Name as CustomerName  FROM [dbo].[Machine]
+                        inner join Customer on Customer.id =[Machine].CustomerId 
+                        where IsDelete=0 and HeartbeatUpdatedOn>=@HeartbeatUpdatedOn
+                        group by CustomerId,Customer.Name
+                        """, parameters);
+                    result = queryResult.ToList();
+                }
+
+            }
+            catch (Exception ex)
+            {
+                logger.LogError("GetConnectorAmount Error " + ex.ToString());
+            }
+
+            //add PHT Electric Avenue
+
+            return result;
+        }
+
+        internal async Task<List<ChargerAmountDto>> GetPHTChargerAmount(bool connected, bool inner)
+        {
+            List<ChargerAmountDto> result = new List<ChargerAmountDto>();
+            try
+            {
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
+                {
+                    if (connected)
+                    {
+                        var parameters = new DynamicParameters();
+                        parameters.Add("@HeartbeatUpdatedOn", new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), DbType.DateTime, ParameterDirection.Input);
+                        var requestResult = await dbConn.QueryAsync<ChargerAmountDto>($"""
+                            SELECT  count(ChargeBoxId) as Charger_Count , Customer.Name as CustomerName 
+                            FROM [dbo].[Machine]
+                            inner join Customer on Customer.id =[Machine].CustomerId 
+                            where IsDelete=0 and Customer.Name='PHT' 
+                            {(inner ? "and [ChargePointVendor]!='Electric Avenue'" : "and [ChargePointVendor]='Electric Avenue'")}
+                            and HeartbeatUpdatedOn>=@HeartbeatUpdatedOn group by  CustomerId,Customer.Name
+                            """, parameters);
+                        result = requestResult.ToList();
+                    }
+                    else
+                    {
+                        var requestResult = await dbConn.QueryAsync<ChargerAmountDto>($"""
+                            SELECT count(ChargeBoxId) as Charger_Count , Customer.Name as CustomerName 
+                            FROM [dbo].[Machine]
+                            inner join Customer on Customer.id =[Machine].CustomerId where IsDelete=0
+                            {(inner ? "and [ChargePointVendor]!='Electric Avenue'" : "and [ChargePointVendor]='Electric Avenue'")}
+                            and Customer.Name='PHT' group by  CustomerId,Customer.Name
+                            """);
+                        result = requestResult.ToList();
+                    }
+
+                }
+
+            }
+            catch (Exception ex)
+            {
+                logger.LogError("GetChargerAmount Error " + ex.ToString());
+            }
+
+            //add PHT Electric Avenue
+
+            return result;
+        }
+
+        internal async Task<List<ChargerAmountDto>> GetPHTConnectorAmount(bool inner)
+        {
+            List<ChargerAmountDto> result = new List<ChargerAmountDto>();
+            try
+            {
+                using (var dbConn = await mainDbConnectionFactory.CreateAsync())
+                {
+                    var parameters = new DynamicParameters();
+                    parameters.Add("@HeartbeatUpdatedOn", new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), DbType.DateTime, ParameterDirection.Input);
+                    var queryResult = await dbConn.QueryAsync<ChargerAmountDto>($"""
+                        SELECT  sum(GunAmt) as Charger_Count , Customer.Name as CustomerName  FROM [dbo].[Machine]
+                        inner join Customer on Customer.id =[Machine].CustomerId where IsDelete=0 and Customer.Name='PHT' 
+                        {(inner ? "and [ChargePointVendor]!='Electric Avenue'" : "and [ChargePointVendor]='Electric Avenue'")}
+                        and HeartbeatUpdatedOn>=@HeartbeatUpdatedOn group by  CustomerId,Customer.Name
+                        """, parameters);
+                    result = queryResult.ToList();
+                }
+            }
+            catch (Exception ex)
+            {
+                logger.LogError("GetConnectorAmount Error " + ex.ToString());
+            }
+
+            //add PHT Electric Avenue
+
+            return result;
+        }
+
+        internal async Task SaveConnectionStatistics(List<ConnectionStatistics> connectionStatistics)
+        {
+            try
+            {
+                using (var dbConn = await webDbConnectionFactory.CreateAsync())
+                using (var trans = await dbConn.BeginTransactionAsync())
+                {
+                    foreach (var connection in connectionStatistics)
+                    {
+                        var parameters = new DynamicParameters();
+                        parameters.Add("@CustomerName", connection.CustomerName, DbType.String, ParameterDirection.Input);
+                        parameters.Add("@StationName", connection.StationName, DbType.String, ParameterDirection.Input);
+                        parameters.Add("@StoragedChargerAmount", connection.StoragedChargerAmount, DbType.Int32, ParameterDirection.Input);
+                        parameters.Add("@UsedChargerAmount", connection.UsedChargerAmount, DbType.Int32, ParameterDirection.Input);
+                        parameters.Add("@UsedConnectorAmount", connection.UsedConnectorAmount, DbType.Int32, ParameterDirection.Input);
+                        parameters.Add("@CreatedOn", connection.CreatedOn, DbType.DateTime, ParameterDirection.Input);
+
+                        await dbConn.ExecuteAsync("""
+                            INSERT INTO [dbo].[ConnectionStatistics]
+                            ([CustomerName],[StationName],[StoragedChargerAmount],[UsedChargerAmount],[UsedConnectorAmount],[CreatedOn]) 
+                            VALUES(@CustomerName,@StationName,@StoragedChargerAmount,@UsedChargerAmount,@UsedConnectorAmount,@CreatedOn)
+                            """, parameters);
+                    }
+
+                    await trans.CommitAsync();
+                }
+            }
+            catch (Exception ex)
+            {
+                logger.LogError("ReportStartTx Error " + ex.ToString());
+            }
+
+
         }
     }
 }

+ 6 - 2
EVCB_OCPP.TaskScheduler/Services/TestService.cs

@@ -13,22 +13,26 @@ namespace EVCB_OCPP.TaskScheduler.Services
     public class TestService : IHostedService
     {
         private readonly IServiceProvider serviceProvider;
+        private WebApplication app;
 
         public TestService(IServiceProvider serviceProvider) {
             this.serviceProvider = serviceProvider;
 
             var appBuilder = WebApplication.CreateBuilder();
+            app = appBuilder.Build();
+            app.MapGet("/", () => "");
+            app.Urls.Add("http://*:80");
         }
 
         public Task StartAsync(CancellationToken cancellationToken)
         {
             serviceProvider.GetService<DatabaseService>().GetCallParterAPICustomers();
-            return Task.CompletedTask;
+            return app.StartAsync();
         }
 
         public Task StopAsync(CancellationToken cancellationToken)
         {
-            return Task.CompletedTask;
+            return app.StopAsync();
         }
     }
 }

+ 2 - 0
EVCB_OCPP.TaskScheduler/appsettings.json

@@ -1,8 +1,10 @@
 {
   "NLog": {
     "targets": {
+      "async": true,
       "f": {
         "type": "File",
+        "keepFileOpen": false,
         "fileName": "${basedir}/logs/task/${shortdate}.log",
         "layout": "${longdate} ${uppercase:${level}} ${message}"
       },

+ 1 - 1
build.bat

@@ -1,5 +1,5 @@
 for /f %%i in ('git rev-parse --short HEAD') do set ssha=%%i
 docker build ./ -t 172.1.2.214:5000/task:test --label "git-commit=%ssha%"
-docker push 172.1.2.214:5000/task:test
+::docker push 172.1.2.214:5000/task:test
 docker tag 172.1.2.214:5000/task:test evdevcontainerregistry.azurecr.io/task:test
 docker push evdevcontainerregistry.azurecr.io/task:test