[성현모] CPMeta 기능 구현 완료

This commit is contained in:
SHM
2025-10-30 16:51:52 +09:00
parent 765f6c6378
commit b78e5a23ea
16 changed files with 518 additions and 80 deletions

View File

@ -248,14 +248,16 @@ PRINT N'테이블 [dbo].[tWbms]을(를) 만드는 중...';
GO GO
CREATE TABLE [dbo].[tWbms] ( CREATE TABLE [dbo].[tWbms] (
[cProductID] NVARCHAR (50) NOT NULL, [cProductID] NVARCHAR (50) NOT NULL,
[cMacAddress] NVARCHAR (50) NULL, [cMacAddress1] NVARCHAR (50) NULL,
[cType] NVARCHAR (20) NULL, [cMacAddress2] NVARCHAR (50) NULL,
[cProductNo] NVARCHAR (50) NULL, [cType] NVARCHAR (20) NULL,
[cSpareValue] NVARCHAR (200) NULL, [cProductNo] NVARCHAR (50) NULL,
[cDateTime] DATETIME2 (7) NOT NULL, [cSpareValue] NVARCHAR (200) NULL,
[cDateTime] DATETIME2 (7) NOT NULL,
CONSTRAINT [PK_cProductKey] PRIMARY KEY CLUSTERED ([cProductID] ASC), CONSTRAINT [PK_cProductKey] PRIMARY KEY CLUSTERED ([cProductID] ASC),
CONSTRAINT [UQ_cMacAddress] UNIQUE NONCLUSTERED ([cMacAddress] ASC) CONSTRAINT [UQ_cMacAddress1] UNIQUE NONCLUSTERED ([cMacAddress1] ASC),
CONSTRAINT [UQ_cMacAddress2] UNIQUE NONCLUSTERED ([cMacAddress2] ASC)
); );

View File

@ -43,19 +43,70 @@ USE [$(DatabaseName)];
GO GO
/* /*
테이블 [dbo].[tWbmsMeta]의 열 [[dbo].[tWbmsMeta].[ctest]]을(를) 추가해야 하지만 해당 열에 기본값이 없으며 NULL 값을 허용하지 않습니다. 테이블에 데이터가 있으면 ALTER 스크립트가 실행되지 않습니다. 이러한 문제를 방지하려면 열에 기본값을 추가 및 해당 열을 NULL 값을 허용하도록 표시하거나 스마트 기본값을 배포 옵션으로서 생성할 수 있도록 하십시오. [dbo].[tWbms].[cMacAddress] 열이 삭제되므로 데이터 손실이 발생할 수 있습니다.
*/ */
IF EXISTS (select top 1 1 from [dbo].[tWbmsMeta]) IF EXISTS (select top 1 1 from [dbo].[tWbms])
RAISERROR (N'행이 발견되었습니다. 데이터가 손실될 수 있으므로 스키마 업데이트가 종료됩니다.', 16, 127) WITH NOWAIT RAISERROR (N'행이 발견되었습니다. 데이터가 손실될 수 있으므로 스키마 업데이트가 종료됩니다.', 16, 127) WITH NOWAIT
GO GO
PRINT N'테이블 [dbo].[tWbmsMeta]을(를) 변경하는 중...'; PRINT N'UNIQUE 제약 조건 [dbo].[UQ_cMacAddress]을(를) 삭제하는 중...';
GO GO
ALTER TABLE [dbo].[tWbmsMeta] ALTER TABLE [dbo].[tWbms] DROP CONSTRAINT [UQ_cMacAddress];
ADD [ctest] DATETIME2 (7) NOT NULL;
GO
PRINT N'[dbo].[tWbms] 테이블 다시 빌드 시작...';
GO
BEGIN TRANSACTION;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET XACT_ABORT ON;
CREATE TABLE [dbo].[tmp_ms_xx_tWbms] (
[cProductID] NVARCHAR (50) NOT NULL,
[cMacAddress1] NVARCHAR (50) NULL,
[cMacAddress2] NVARCHAR (50) NULL,
[cType] NVARCHAR (20) NULL,
[cProductNo] NVARCHAR (50) NULL,
[cSpareValue] NVARCHAR (200) NULL,
[cDateTime] DATETIME2 (7) NOT NULL,
CONSTRAINT [tmp_ms_xx_constraint_PK_cProductKey1] PRIMARY KEY CLUSTERED ([cProductID] ASC),
CONSTRAINT [tmp_ms_xx_constraint_UQ_cMacAddress11] UNIQUE NONCLUSTERED ([cMacAddress1] ASC),
CONSTRAINT [tmp_ms_xx_constraint_UQ_cMacAddress21] UNIQUE NONCLUSTERED ([cMacAddress2] ASC)
);
IF EXISTS (SELECT TOP 1 1
FROM [dbo].[tWbms])
BEGIN
INSERT INTO [dbo].[tmp_ms_xx_tWbms] ([cProductID], [cType], [cProductNo], [cSpareValue], [cDateTime])
SELECT [cProductID],
[cType],
[cProductNo],
[cSpareValue],
[cDateTime]
FROM [dbo].[tWbms]
ORDER BY [cProductID] ASC;
END
DROP TABLE [dbo].[tWbms];
EXECUTE sp_rename N'[dbo].[tmp_ms_xx_tWbms]', N'tWbms';
EXECUTE sp_rename N'[dbo].[tmp_ms_xx_constraint_PK_cProductKey1]', N'PK_cProductKey', N'OBJECT';
EXECUTE sp_rename N'[dbo].[tmp_ms_xx_constraint_UQ_cMacAddress11]', N'UQ_cMacAddress1', N'OBJECT';
EXECUTE sp_rename N'[dbo].[tmp_ms_xx_constraint_UQ_cMacAddress21]', N'UQ_cMacAddress2', N'OBJECT';
COMMIT TRANSACTION;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
GO GO

View File

@ -13,18 +13,18 @@
{ {
"IP": "127.0.0.1", "IP": "127.0.0.1",
"Port": 1433, "Port": 1433,
"DBName": "UniqueKeyDB", "DBName": "CPMeta",
"DBID": 1, "DBID": 1,
"UserID": "SystemX", "UserID": "Alis",
"Password": "X" "Password": "Kefico!@34"
}, },
{ {
"IP": "127.0.0.1", "IP": "127.0.0.1",
"Port": 1433, "Port": 1433,
"DBName": "UniqueKeyDB_DEV", "DBName": "CPMeta_DEV",
"DBID": 2, "DBID": 2,
"UserID": "SystemX", "UserID": "Alis",
"Password": "X" "Password": "Kefico!@34"
} }
] ]
} }

Binary file not shown.

View File

@ -58,9 +58,10 @@
<ItemGroup> <ItemGroup>
<Folder Include="Properties" /> <Folder Include="Properties" />
<Folder Include="dbo" /> <Folder Include="dbo" />
<Folder Include="dbo\Tables" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Build Include="dbo\tWbmsMeta.sql" /> <Build Include="dbo\Tables\tWbmsMeta.sql" />
</ItemGroup> </ItemGroup>
<PropertyGroup> <PropertyGroup>
<PostBuildEvent>xcopy /y $(ProjectDir)$(OutputPath)$(TargetName)_Create.sql $(SolutionDir)..\..\DBPatch\sqlScripts\ <PostBuildEvent>xcopy /y $(ProjectDir)$(OutputPath)$(TargetName)_Create.sql $(SolutionDir)..\..\DBPatch\sqlScripts\

View File

@ -1,7 +1,8 @@
CREATE TABLE [dbo].[tWbms] CREATE TABLE [dbo].[tWbms]
( (
[cProductID] NVARCHAR(50) NOT NULL, [cProductID] NVARCHAR(50) NOT NULL,
[cMacAddress] NVARCHAR(50) NULL, [cMacAddress1] NVARCHAR(50) NULL,
[cMacAddress2] NVARCHAR(50) NULL,
[cType] NVARCHAR(20) NULL, [cType] NVARCHAR(20) NULL,
[cProductNo] NVARCHAR(50) NULL, [cProductNo] NVARCHAR(50) NULL,
@ -9,5 +10,6 @@
[cDateTime] DATETIME2 NOT NULL, [cDateTime] DATETIME2 NOT NULL,
CONSTRAINT PK_cProductKey PRIMARY KEY (cProductID), CONSTRAINT PK_cProductKey PRIMARY KEY (cProductID),
CONSTRAINT UQ_cMacAddress UNIQUE (cMacAddress), CONSTRAINT UQ_cMacAddress1 UNIQUE (cMacAddress1),
CONSTRAINT UQ_cMacAddress2 UNIQUE (cMacAddress2),
) )

View File

@ -21,10 +21,13 @@ public partial class CPMetaContext : DbContext
{ {
entity.HasKey(e => e.cProductID).HasName("PK_cProductKey"); entity.HasKey(e => e.cProductID).HasName("PK_cProductKey");
entity.HasIndex(e => e.cMacAddress, "UQ_cMacAddress").IsUnique(); entity.HasIndex(e => e.cMacAddress1, "UQ_cMacAddress1").IsUnique();
entity.HasIndex(e => e.cMacAddress2, "UQ_cMacAddress2").IsUnique();
entity.Property(e => e.cProductID).HasMaxLength(50); entity.Property(e => e.cProductID).HasMaxLength(50);
entity.Property(e => e.cMacAddress).HasMaxLength(50); entity.Property(e => e.cMacAddress1).HasMaxLength(50);
entity.Property(e => e.cMacAddress2).HasMaxLength(50);
entity.Property(e => e.cProductNo).HasMaxLength(50); entity.Property(e => e.cProductNo).HasMaxLength(50);
entity.Property(e => e.cSpareValue).HasMaxLength(200); entity.Property(e => e.cSpareValue).HasMaxLength(200);
entity.Property(e => e.cType).HasMaxLength(20); entity.Property(e => e.cType).HasMaxLength(20);

View File

@ -7,7 +7,9 @@ public partial class tWbms
{ {
public string cProductID { get; set; } = null!; public string cProductID { get; set; } = null!;
public string? cMacAddress { get; set; } public string? cMacAddress1 { get; set; }
public string? cMacAddress2 { get; set; }
public string? cType { get; set; } public string? cType { get; set; }

View File

@ -264,7 +264,7 @@ namespace AuthApi.Services
private AccountDBContext? GetAccountDBContext(DbContextProvider provider, int dbID) private AccountDBContext? GetAccountDBContext(DbContextProvider provider, int dbID)
{ {
var connectionString = _configService?.GetConfig()?.DataBase?.Find(x => x.DBID == dbID); var connectionString = _configService?.GetConfig()?.DataBase?.Find(x => x.DBID == dbID);
return provider?.GetDBContext<AccountDBContext>($"{connectionString?.DBName}"); return provider?.GetDBContext<AccountDBContext>(Convert.ToInt32(connectionString?.DBID));
} }
} }
} }

View File

@ -10,5 +10,6 @@ namespace WebApi.Library.Enums
{ {
Success = 1, Success = 1,
Failed = 2, Failed = 2,
Update = 3,
} }
} }

View File

@ -0,0 +1,70 @@
using Microsoft.AspNetCore.Mvc;
using SystemX.Core.Controller;
using WebApi.Project.UniqueKeyApi.Models;
using WebApi.Project.UniqueKeyApi.Services;
namespace WebApi.Project.UniqueKeyApi.Controllers
{
[ApiController]
[Route("[controller]/[action]")]
public class CPMetaController : CommonController<UniqueKeyApiConfig>
{
private readonly CPMetaService _cpMetaService;
public CPMetaController(IServiceProvider serviceProvider, IHttpContextAccessor httpContextAccessor, CPMetaService cpMetaService)
: base(serviceProvider, httpContextAccessor)
{
_cpMetaService = cpMetaService;
}
[HttpGet("health")]
public async Task<IResult> Health()
{
LogXnet.WriteLine($"[{GetRequestMethod()}:{GetMethodName()}] [Client IP:{GetClientIP()}] [RequestUrl:{GetRequestUrl()}]{Environment.NewLine}", LogXLabel.CONTROLLER);
await Task.CompletedTask;
return Results.Ok("Healthy");
}
[HttpPost]
public async Task<IResult> SetWbmsMeta([FromBody]Request_SetWbmsMeta request)
{
Guid guid = Guid.NewGuid();
LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} {request.ToJson()}", LogXLabel.CONTROLLER);
Response_SetWbmsMeta response = await _cpMetaService.SetWbmsMeta(request, guid.ToString());
LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER);
return Results.Ok(response);
}
[HttpGet]
public async Task<IResult> GetWbmsMetaByProductID([FromQuery] string ProductID, int? ShardID = 1)
{
Guid guid = Guid.NewGuid();
LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} key:{ProductID}", LogXLabel.CONTROLLER);
Response_GetWbms response = await _cpMetaService.GetWbmsMeta(new Request_GetWbmsMetaByProductID() { ProductID = ProductID, ShardID = (int)ShardID }, guid.ToString());
LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER);
return Results.Ok(response);
}
[HttpGet]
public async Task<IResult> GetWbmsMetaByMacAddress([FromQuery] string MacAddress, int? ShardID = 1)
{
Guid guid = Guid.NewGuid();
LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} key:{MacAddress}", LogXLabel.CONTROLLER);
Response_GetWbms response = await _cpMetaService.GetWbmsMeta(new Request_GetWbmsMetaByMacAddress() { MacAddress = MacAddress, ShardID = (int)ShardID }, guid.ToString());
LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER);
return Results.Ok(response);
}
}
}

View File

@ -8,78 +8,78 @@ using WebApi.Project.UniqueKeyApi.Services;
namespace WebApi.Project.UniqueKeyApi.Controllers namespace WebApi.Project.UniqueKeyApi.Controllers
{ {
[ApiController] //[ApiController]
[Route("[controller]/[action]")] //[Route("[controller]/[action]")]
public class UniqueKeyController : CommonController<UniqueKeyApiConfig> //public class UniqueKeyController : CommonController<UniqueKeyApiConfig>
{ //{
private readonly UniqueKeyService _uniqueKeyService; // private readonly UniqueKeyService _uniqueKeyService;
public UniqueKeyController(IServiceProvider serviceProvider, IHttpContextAccessor httpContextAccessor, UniqueKeyService uniqueKeyService) // public UniqueKeyController(IServiceProvider serviceProvider, IHttpContextAccessor httpContextAccessor, UniqueKeyService uniqueKeyService)
: base(serviceProvider, httpContextAccessor) // : base(serviceProvider, httpContextAccessor)
{ // {
_uniqueKeyService = uniqueKeyService; // _uniqueKeyService = uniqueKeyService;
} // }
[HttpGet("health")] // [HttpGet("health")]
public async Task<IResult> Health() // public async Task<IResult> Health()
{ // {
LogXnet.WriteLine($"[{GetRequestMethod()}:{GetMethodName()}] [Client IP:{GetClientIP()}] [RequestUrl:{GetRequestUrl()}]{Environment.NewLine}", LogXLabel.CONTROLLER); // LogXnet.WriteLine($"[{GetRequestMethod()}:{GetMethodName()}] [Client IP:{GetClientIP()}] [RequestUrl:{GetRequestUrl()}]{Environment.NewLine}", LogXLabel.CONTROLLER);
await Task.CompletedTask; // await Task.CompletedTask;
return Results.Ok("Healthy"); // return Results.Ok("Healthy");
} // }
[HttpPost] // [HttpPost]
public async Task<IResult> InsertUniqueKey(Request_InsertUniqueKey request) // public async Task<IResult> InsertUniqueKey(Request_InsertUniqueKey request)
{ // {
Guid guid = Guid.NewGuid(); // Guid guid = Guid.NewGuid();
LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} {request.ToJson()}", LogXLabel.CONTROLLER); // LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} {request.ToJson()}", LogXLabel.CONTROLLER);
Response_InsertUniqueKy response = await _uniqueKeyService.Request_InsertUniqueKey(request); // Response_InsertUniqueKy response = await _uniqueKeyService.Request_InsertUniqueKey(request);
LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER); // LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER);
return Results.Ok(response); // return Results.Ok(response);
} // }
[HttpPost] // [HttpPost]
public async Task<IResult> SelectUniqueKey([FromBody]Request_SelectUniqueKey request) // public async Task<IResult> SelectUniqueKey([FromBody]Request_SelectUniqueKey request)
{ // {
Guid guid = Guid.NewGuid(); // Guid guid = Guid.NewGuid();
LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} {request.ToJson()}", LogXLabel.CONTROLLER); // LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} {request.ToJson()}", LogXLabel.CONTROLLER);
Response_SelectUniqueKy response = await _uniqueKeyService.Request_SelectUniqueKey(request); // Response_SelectUniqueKy response = await _uniqueKeyService.Request_SelectUniqueKey(request);
LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER); // LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER);
return Results.Ok(response); // return Results.Ok(response);
} // }
[HttpGet] // [HttpGet]
public async Task<IResult> SelectUniqueKeyGet([FromQuery] string key) // public async Task<IResult> SelectUniqueKeyGet([FromQuery] string key)
{ // {
Guid guid = Guid.NewGuid(); // Guid guid = Guid.NewGuid();
LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} key:{key}", LogXLabel.CONTROLLER); // LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} key:{key}", LogXLabel.CONTROLLER);
Response_SelectUniqueKy response = await _uniqueKeyService.Request_SelectUniqueKey(new Request_SelectUniqueKey { Identity = key }); // Response_SelectUniqueKy response = await _uniqueKeyService.Request_SelectUniqueKey(new Request_SelectUniqueKey { Identity = key });
LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER); // LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER);
return Results.Ok(response); // return Results.Ok(response);
} // }
[HttpPost] // [HttpPost]
public async Task<IResult> UpdateUniqueKey(Request_UpdateUniqueKey request) // public async Task<IResult> UpdateUniqueKey(Request_UpdateUniqueKey request)
{ // {
Guid guid = Guid.NewGuid(); // Guid guid = Guid.NewGuid();
LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} {request.ToJson()}", LogXLabel.CONTROLLER); // LogXnet.WriteLine($"[Request][{GetRequestMethod()}:{GetMethodName()}][Client IP:{GetClientIP()}][RequestUrl:{GetRequestUrl()}]::({guid}){Environment.NewLine} {request.ToJson()}", LogXLabel.CONTROLLER);
Response_UpdateUniqueKy response = await _uniqueKeyService.Request_UpdateUniqueKey(request); // Response_UpdateUniqueKy response = await _uniqueKeyService.Request_UpdateUniqueKey(request);
LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER); // LogXnet.WriteLine($"[Response]::({guid}){Environment.NewLine} {response.ToJson()}", LogXLabel.CONTROLLER);
return Results.Ok(response); // return Results.Ok(response);
} // }
} //}
} }

View File

@ -1,7 +1,54 @@
using WebApi.Library.Enums; using SystemX.Core.DB;
using WebApi.Library.Enums;
namespace WebApi.Project.UniqueKeyApi.Models namespace WebApi.Project.UniqueKeyApi.Models
{ {
#region CPMeta Wbms
//Wbms Meta Insert or Update
public class Request_SetWbmsMeta
{
//pk
public string ProductID { get; set; } = string.Empty;
//uk
public string? MacAddress1 { get; set; } = string.Empty;
public string? MacAddress2 { get; set; } = string.Empty;
//value
public string? Type { get; set; } = string.Empty;
public string? ProductNo { get; set; } = string.Empty;
public string? SpareValue { get; set; } = string.Empty;
public int ShardID { get; set; } = 1;
}
public class Response_SetWbmsMeta
{
public string ProductID { get; set; } = string.Empty;
public string Result { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
}
//Wbms Meta Select
public class Request_GetWbmsMetaByProductID
{
public string ProductID { get; set; } = string.Empty;
public int ShardID { get; set; } = 1;
}
public class Request_GetWbmsMetaByMacAddress
{
public string MacAddress { get; set; } = string.Empty;
public int ShardID { get; set; } = 1;
}
public class Response_GetWbms
{
public List<tWbms> Wbms { get; set; }
public string Result { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
}
#endregion
#region Unique Key #region Unique Key
//Insert //Insert
public class Request_InsertUniqueKey public class Request_InsertUniqueKey

View File

@ -26,6 +26,7 @@ builder.Services.AddSingleton<ConfigService<UniqueKeyApiConfig>>();
//scoped //scoped
builder.Services.AddSingleton<UniqueKeyService>(); builder.Services.AddSingleton<UniqueKeyService>();
builder.Services.AddSingleton<CPMetaService>();
//db //db
builder.Services.AddSingleton<DbContextProvider>(); // Generic <20><><EFBFBD><EFBFBD> builder.Services.AddSingleton<DbContextProvider>(); // Generic <20><><EFBFBD><EFBFBD>

View File

@ -0,0 +1,258 @@
using Microsoft.EntityFrameworkCore;
using System.Data;
using SystemX.Core.DB;
using SystemX.Core.Services;
using WebApi.Library.Enums;
using WebApi.Project.UniqueKeyApi.Models;
namespace WebApi.Project.UniqueKeyApi.Services
{
public class CPMetaService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ConfigService<UniqueKeyApiConfig>? _configService;
public CPMetaService(IServiceProvider serviceProvider, IServiceScopeFactory scopeFactory, ConfigService<UniqueKeyApiConfig> configSerice)
{
_scopeFactory = scopeFactory;
_configService = configSerice;
}
public async Task<Response_SetWbmsMeta> SetWbmsMeta(Request_SetWbmsMeta request, string guid = "")
{
Response_SetWbmsMeta response = new Response_SetWbmsMeta();
if (request != null)
{
response.ProductID = request.ProductID;
bool transactionResult = true;
using (var scope = _scopeFactory.CreateScope())
{
int shardId = request.ShardID;
if (shardId <= 0)
shardId = 1;
var provider = scope.ServiceProvider.GetRequiredService<DbContextProvider>();
using (var context = GetCPMetaDBContext(provider, shardId))
{
if (context is not null)
{
var data = await context.tWbms.AsNoTracking().Where(x => x.cProductID == request.ProductID)?.FirstOrDefaultAsync();
if (data is not null) //update
{
var selected = await context.tWbms.FirstOrDefaultAsync(x => x.cProductID == request.ProductID);
if (selected != null)
{
selected.cMacAddress1 = request.MacAddress1;
selected.cMacAddress2 = request.MacAddress2;
selected.cType = request.Type;
selected.cProductNo = request.ProductNo;
selected.cSpareValue = request.SpareValue;
selected.cDateTime = DateTime.Now;
using (var transaction = await context.CreateTransactionAsync())
{
context.Update(selected);
transactionResult = await context.CloseTransactionAsync(transaction);
}
}
LogXnet.WriteLine($"Update::{guid}", LogXLabel.DB);
response.Result = WebApiResult.Update.ToString();
}
else //insert
{
var row = new tWbms
{
cProductID = request.ProductID,
cMacAddress1 = request.MacAddress1,
cMacAddress2 = request.MacAddress2,
cType = request.Type,
cProductNo = request.ProductNo,
cSpareValue = request.SpareValue,
cDateTime = DateTime.Now
};
using (var transaction = await context.CreateTransactionAsync())
{
await context.AddAsync(row);
transactionResult = await context.CloseTransactionAsync(transaction);
}
LogXnet.WriteLine($"Insert::{guid}", LogXLabel.DB);
response.Result = WebApiResult.Success.ToString();
}
//db error
if (transactionResult == false)
{
LogXnet.WriteLine($"Transaction Error::{guid}", LogXLabel.Error);
response.Result = WebApiResult.Failed.ToString();
response.Message = "Duplicate Mac Address";
}
}
else //invalid shard id
{
LogXnet.WriteLine($"ShardID Error::{guid}", LogXLabel.Error);
response.Result = WebApiResult.Failed.ToString();
response.Message = "Invalid shard id";
}
}
}
}
return response;
}
public async Task<Response_GetWbms> GetWbmsMeta(Request_GetWbmsMetaByProductID request, string guid = "")
{
Response_GetWbms response = new Response_GetWbms();
response.Wbms = new List<tWbms>();
if (request != null)
{
using (var scope = _scopeFactory.CreateScope())
{
int shardId = request.ShardID;
if (shardId <= 0)
shardId = 1;
var provider = scope.ServiceProvider.GetRequiredService<DbContextProvider>();
using (var context = GetCPMetaDBContext(provider, shardId))
{
if (context is not null)
{
try
{
using (var transaction = await context.CreateTransactionAsync(IsolationLevel.ReadUncommitted))
{
var data = await context.tWbms.AsNoTracking().FirstOrDefaultAsync(x => x.cProductID.ToLower() == request.ProductID.ToLower());
await context.CloseTransactionAsync(transaction);
if (data != null)
{
if(response.Wbms is not null)
{
response.Wbms.Add(data);
}
response.Result = WebApiResult.Success.ToString();
}
else
{
response.Wbms = null;
response.Result = WebApiResult.Failed.ToString();
response.Message = $"Not exist productID: {request.ProductID}";
}
}
}
catch (Exception e)
{
response.Wbms = null;
response.Result = WebApiResult.Failed.ToString();
response.Message = $"Not exist productID: {request.ProductID}";
LogXnet.WriteLine($"GetWbmsMeta By ProductID Transaction Error::{guid}", LogXLabel.Error);
LogXnet.WriteLine(e);
}
}
else //invalid shard id
{
LogXnet.WriteLine($"ShardID Error::{guid}", LogXLabel.Error);
response.Result = WebApiResult.Failed.ToString();
response.Message = "Invalid shard id";
}
}
}
}
return response;
}
public async Task<Response_GetWbms> GetWbmsMeta(Request_GetWbmsMetaByMacAddress request, string guid = "")
{
Response_GetWbms response = new Response_GetWbms();
response.Wbms = new List<tWbms>();
if (request != null)
{
using (var scope = _scopeFactory.CreateScope())
{
int shardId = request.ShardID;
if (shardId <= 0)
shardId = 1;
var provider = scope.ServiceProvider.GetRequiredService<DbContextProvider>();
using (var context = GetCPMetaDBContext(provider, shardId))
{
if (context is not null)
{
try
{
using (var transaction = await context.CreateTransactionAsync(IsolationLevel.ReadUncommitted))
{
var mac1 = await context.tWbms.AsNoTracking().FirstOrDefaultAsync(x => x.cMacAddress1.ToLower() == request.MacAddress.ToLower());
var mac2 = await context.tWbms.AsNoTracking().FirstOrDefaultAsync(x => x.cMacAddress2.ToLower() == request.MacAddress.ToLower());
await context.CloseTransactionAsync(transaction);
if (mac1 is not null)
{
if(response.Wbms is not null)
{
response.Wbms.Add(mac1);
}
response.Result = WebApiResult.Success.ToString();
}
if(mac2 is not null)
{
if (response.Wbms is not null)
{
response.Wbms.Add(mac2);
}
response.Result = WebApiResult.Success.ToString();
}
if(response.Wbms?.Count <= 0)
{
response.Wbms = null;
response.Result = WebApiResult.Failed.ToString();
response.Message = $"Not exist MacAddress: {request.MacAddress}";
}
}
}
catch (Exception e)
{
response.Wbms = null;
response.Result = WebApiResult.Failed.ToString();
response.Message = $"Not exist MacAddrss: {request.MacAddress}";
LogXnet.WriteLine($"GetWbmsMeta By MacAddress Transaction Error::{guid}", LogXLabel.Error);
LogXnet.WriteLine(e);
}
}
else //invalid shard id
{
LogXnet.WriteLine($"ShardID Error::{guid}", LogXLabel.Error);
response.Result = WebApiResult.Failed.ToString();
response.Message = "Invalid shard id";
}
}
}
}
return response;
}
private CPMetaContext? GetCPMetaDBContext(DbContextProvider provider, int dbID)
{
var connectionString = _configService?.GetConfig()?.DataBase?.Find(x => x.DBID == dbID);
if(connectionString is not null)
return provider?.GetDBContext<CPMetaContext>((int)connectionString?.DBID);
return null;
}
}
}