Files
DE70/API/APIModels.cs
T
2024-09-19 06:55:27 +07:00

376 lines
14 KiB
C#

using System.IO;
using System.Net;
using System.Net.Http;
using System.Text.Json.Nodes;
using System.Text;
using System.Net.NetworkInformation;
using System.Linq;
using System;
using System.Windows.Documents;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Serilog;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SafeBagDE70.Model;
namespace SafeBagDE70.API
{
public static class APIModels
{
public static async void SendHealthCheck_old(string? ID=null)
{
try
{
if (ID == null) ID = GetMACAddress();
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
HttpClient httpClient = new HttpClient(clientHandler);
using HttpResponseMessage response = await httpClient.GetAsync(AppData.BaseURL + "HealthCheck?Id=" + ID);
if (response.EnsureSuccessStatusCode().StatusCode == HttpStatusCode.OK)
{
var jsonResponse = await response.Content.ReadAsStringAsync();
}
}
catch(Exception ex)
{
Log.Fatal(ex, "SendHealthCheck");
}
}
public static void SendHealthCheck(DeviceStatus? deviceStatus = null)
{
TaskSendHealthCheck(deviceStatus).ContinueWith(t => {
if (t.IsCompletedSuccessfully)
{
AppData.IsInternetOk = true;
Log.Information("Send HealthCheck Success");
}
else
{
AppData.IsInternetOk = false;
Log.Information("Send HealthCheck Fail");
}
});
}
public static async Task<bool> TaskSendHealthCheck(DeviceStatus? deviceStatus=null)
{
bool bSuccess = false;
try
{
if(deviceStatus != null)
{
var json = JsonConvert.SerializeObject(deviceStatus);
var _deviceStatus = JsonConvert.DeserializeObject<DeviceStatus>(json);
//_deviceStatus.DeviceTime=DateTime.Now;
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
HttpClient httpClient = new HttpClient(clientHandler);
string strJsonObj = JsonConvert.SerializeObject(_deviceStatus);
var content = new StringContent(strJsonObj, Encoding.UTF8, "application/json");
using HttpResponseMessage response = await httpClient.PostAsync(AppData.BaseURL + "HealthCheck_v2", content);
if (response.EnsureSuccessStatusCode().StatusCode == HttpStatusCode.OK)
{
var jsonResponse = await response.Content.ReadAsStringAsync();
bSuccess = true;
}
}
}
catch (Exception ex)
{
Log.Fatal(ex, "SendHealthCheck");
}
return bSuccess;
}
public static void SendEvent(DeviceStatus? deviceStatus = null)
{
try
{
if (deviceStatus == null) return;
DeviceEvent deviceEvent = InsertEventToDB(deviceStatus);
//deviceStatus.DeviceTime = DateTime.Now;
deviceStatus.TransactionCode = AppData.GetTransactionCode();
TaskSendEvent(deviceStatus).ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
{
Log.Information("Send Event Success");
deviceEvent.IsSent = t.Result;
UpdateEventToDB(deviceEvent);
}
else
{
Log.Information("Send Event Fail");
}
});
}
catch(Exception ex)
{
Log.Fatal(ex, "SendEvent");
}
}
private static void UpdateEventToDB(DeviceEvent deviceEvent)
{
try
{
using (var db = new CDMDbContext())
{
db.DeviceEvents.Update(deviceEvent);
db.SaveChanges();
}
}
catch (Exception ex)
{
Log.Fatal(ex, "Fail to Update Event to DB");
}
}
private static DeviceEvent InsertEventToDB(DeviceStatus? deviceStatus)
{
var data = JsonConvert.SerializeObject(deviceStatus);
var deviceEvent = new DeviceEvent
{
Data = data,
IsSent = false,
DeviceTime = DateTime.Now
};
try
{
using (var db = new CDMDbContext())
{
db.DeviceEvents.Add(deviceEvent);
db.SaveChanges();
}
}
catch (Exception ex)
{
Log.Fatal(ex, "Fail to Save Event to DB");
}
return deviceEvent;
}
public static async Task<bool> TaskSendEvent(DeviceStatus? deviceStatus = null)
{
bool bSuccess = false;
try
{
if (deviceStatus != null)
{
var json = JsonConvert.SerializeObject(deviceStatus);
var _deviceStatus = JsonConvert.DeserializeObject<DeviceStatus>(json);
_deviceStatus.DeviceTime = DateTime.Now;
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
HttpClient httpClient = new HttpClient(clientHandler);
string strJsonObj = JsonConvert.SerializeObject(_deviceStatus);
var content = new StringContent(strJsonObj, Encoding.UTF8, "application/json");
using HttpResponseMessage response = await httpClient.PostAsync(AppData.BaseURL + "DeviceEvents", content);
if (response.EnsureSuccessStatusCode().StatusCode == HttpStatusCode.OK)
{
var jsonResponse = await response.Content.ReadAsStringAsync();
bSuccess = true;
}
}
}
catch (Exception ex)
{
Log.Fatal(ex, "SendHealthCheck");
}
return bSuccess;
}
public static async Task<bool> SendCountingData(CountingData2Send data2Send)
{
bool bSuccess=false;
try{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
HttpClient httpClient = new HttpClient(clientHandler);
string strJsonObj = JsonConvert.SerializeObject(data2Send);
var content = new StringContent(strJsonObj, Encoding.UTF8, "application/json");
using HttpResponseMessage response = await httpClient.PostAsync(AppData.BaseURL + "UpdateCountingData", content);
if (response.EnsureSuccessStatusCode().StatusCode == HttpStatusCode.OK)
{
var jsonResponse = await response.Content.ReadAsStringAsync();
bSuccess = true;
}
}
catch(Exception ex)
{
}
return bSuccess;
}
public static async Task<List<AeonMallCustomer>> GetAeonMallCustomers(int tenantId)
{
try
{
var url = AppData.BaseURL + "GetAeonMallCustomers?tenantId="+tenantId;
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
HttpClient client = new HttpClient(clientHandler);
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string jsonResponse = await response.Content.ReadAsStringAsync();
var tenants = JsonConvert.DeserializeObject<List<AeonMallCustomer>>(jsonResponse);
return tenants;
}
else
{
Log.Error($"Error: {response.StatusCode}");
return null;
}
}
catch (Exception ex)
{
Log.Fatal($"Exception: {ex.Message}");
return null;
}
}
public static async Task<DeviceCommand[]?> GetCommands()
{
try
{
string deviceID = Environment.MachineName;
int tenantId = AppData.TenantId;
string url = AppData.BaseURL + $"GetListCommand?Device={deviceID}&TenantId={tenantId}";
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
using (HttpClient client = new HttpClient(clientHandler))
{
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<DeviceCommand[]>(json);
}
else
{
Log.Error("GetCommands: StatusCode=" + response.StatusCode);
return null;
}
}
}
catch (Exception ex)
{
Log.Fatal(ex, "GetCommands");
}
return null;
}
public static async Task<bool> UpdateDeviceCommand(int commandId, int executed)
{
bool bSuccess = false;
try
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
HttpClient httpClient = new HttpClient(clientHandler);
var data = new
{
id = commandId,
executed = executed
};
string strJsonObj = JsonConvert.SerializeObject(data);
var content = new StringContent(strJsonObj, Encoding.UTF8, "application/json");
using HttpResponseMessage response = await httpClient.PostAsync(AppData.BaseURL + $"PostUpdateCommand", content);
if (response.EnsureSuccessStatusCode().StatusCode == HttpStatusCode.OK)
{
var jsonResponse = await response.Content.ReadAsStringAsync();
bSuccess = true;
}
}
catch (Exception ex)
{
}
return bSuccess;
}
private static string GetMACAddress()
{
string? MACAdress = null;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
MACAdress = AddressBytesToString(nic.GetPhysicalAddress().GetAddressBytes());
break;
}
}
if (MACAdress == null) MACAdress = "N/A";
return MACAdress;
}
private static string? AddressBytesToString(byte[] addressBytes)
{
if (addressBytes != null)
{
var str = string.Join(":", (from b in addressBytes
select b.ToString("X2")).ToArray());
return str;
}
else
return null;
}
}
public class AeonMallCustomer
{
public long Id { get; set; }
public DateTime CreationTime { get; set; }
public long? CreatorUserId { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
public bool IsDeleted { get; set; }
public DateTime? LastModificationTime { get; set; }
public long? LastModifierUserId { get; set; }
public int? TenantId { get; set; }
public string? Cards { get; set; }
public string? TenantCode { get; set; }
public string? TenantName { get; set; }
public string? TenantShortName { get; set; }
public string? OpenningDate { get; set; }
public string? Note { get; set; }
public string? Type { get; set; }
public string? TimeTag { get; set; }
}
}