firts commit

This commit is contained in:
2025-10-24 10:25:29 +09:00
commit ec77d8bc29
49 changed files with 134191 additions and 0 deletions

406
.gitignore vendored Normal file
View File

@@ -0,0 +1,406 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
# but not Directory.Build.rsp, as it configures directory-level build defaults
!Directory.Build.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# JetBrains
.idea/*
#CFG
CFG/

25
KART_API.sln Normal file
View File

@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34616.47
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KART_API", "KART_API\KART_API.csproj", "{B9261B6C-B795-4EDF-97EC-E4D4821B62F7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B9261B6C-B795-4EDF-97EC-E4D4821B62F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B9261B6C-B795-4EDF-97EC-E4D4821B62F7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B9261B6C-B795-4EDF-97EC-E4D4821B62F7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B9261B6C-B795-4EDF-97EC-E4D4821B62F7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7FCA2E0E-3E1A-4E8F-998B-A293230C6A5E}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "8.0.2",
"commands": [
"dotnet-ef"
]
}
}
}

View File

@@ -0,0 +1,179 @@
using Microsoft.AspNetCore.Mvc;
using KART_API.Services;
using KART_API.Utils;
using KART_API.Dto;
using System;
using System.Net;
using System.Data;
using System.Collections.Generic;
namespace KART_API.Controllers
{
[Route("api/v2/export")]
[ApiController]
public class ExportController : ControllerBase
{
[Route("excel/table")] //확인
[HttpPost]
[DisableRequestSizeLimit]
public IActionResult ExportExcelTable([FromHeader] string token, [FromBody] ExportExcelParam excelParam)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null && String.IsNullOrEmpty(excelParam.ExportTable) == false && excelParam.ExportTable != "[]")
{
MakeExcelService makeExcel = new MakeExcelService();
string fileName = token + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xlsx";
string fileType = "application/vnd.ms-excel";
byte[] excelFile = makeExcel.getTableExcel(excelParam.ExportTable, excelParam.Turn);
Response.StatusCode = (int)HttpStatusCode.OK;
return File(excelFile, fileType, fileName);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("excel/quota")] //확인
[HttpPost]
[DisableRequestSizeLimit]
public IActionResult ExportExcelQuota([FromHeader] string token, [FromBody] ExportExcelParam excelParam)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null && String.IsNullOrEmpty(excelParam.ExportTable) == false && excelParam.ExportTable != "[]")
{
MakeExcelService makeExcel = new MakeExcelService();
string fileName = token + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xlsx";
string fileType = "application/vnd.ms-excel";
byte[] excelFile = makeExcel.getQuotaExcel(excelParam.ExportTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return File(excelFile, fileType, fileName);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("form/data")] //확인
[HttpGet]
public IActionResult ExportDataForm([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable headerTable = project.getExportHeader(projectCodeInfo.projectCode, userInfo.IsAdmin);
DataTable exportTable = project.makeExportTable(headerTable);
Response.StatusCode = (int)HttpStatusCode.OK;
string fileName = "(Header)" + projectCodeInfo.projectCode + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xlsx";
byte[] fileByteArray = Common.DataTableToExcel(exportTable);
return File(fileByteArray, "application/octet-stream", fileName);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("form/question")] //확인
[HttpGet]
public IActionResult ExportQuestionForm([FromHeader] string token)
{
//UserInfo userInfo = Security.ValidateToken(token);
//if (userInfo != null)
//{
// Response.StatusCode = (int)HttpStatusCode.OK;
// byte[] fileByteArray = System.IO.File.ReadAllBytes(Common.MapPath("file_forms/새싹 문항 등록 양식.xlsx"));
// return File(fileByteArray, "application/octet-stream", "새싹 문항 등록 양식.xlsx");
//}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("form/title")] //확인
[HttpGet]
[DisableRequestSizeLimit]
public IActionResult ExportTitleForm([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable titleTable = project.getExportExplain(projectCodeInfo.projectCode);
Response.StatusCode = (int)HttpStatusCode.OK;
string fileName = "(Explain)" + projectCodeInfo.projectCode + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xlsx";
byte[] fileByteArray = Common.DataTableToExcel(titleTable);
return File(fileByteArray, "application/octet-stream", fileName);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("data")] //확인
[HttpGet]
public IActionResult ExportData([FromHeader] string token, [FromHeader] string skey, [FromHeader] string type, [FromHeader] string isTest = "")
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable headerTable = project.getExportHeader(projectCodeInfo.projectCode, userInfo.IsAdmin);
DataTable bodyTable = project.getProjectData(projectCodeInfo.projectCode, "", "", "", "", 1, isTest, "", type);
DataTable exportTable = project.makeExportTable(headerTable, bodyTable);
DataTable guideTable = project.makeGuideTable(projectCodeInfo.projectCode, userInfo.IsAdmin);
List<DataTabelToExcelSheet> excelDataList =
[
new DataTabelToExcelSheet(exportTable, "DATA"),
new DataTabelToExcelSheet(guideTable, "GUIDE")
];
string fileName = "(DATA)" + projectCodeInfo.projectCode + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xlsx";
byte[] fileByteArray = Common.DataTableToExcel(excelDataList);
Response.StatusCode = (int)HttpStatusCode.OK;
return File(fileByteArray, "application/octet-stream", fileName);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("guide")] //확인
[HttpGet]
public IActionResult ExportGuide([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable guideTable = project.makeGuideTable(projectCodeInfo.projectCode, userInfo.IsAdmin);
string fileName = "(GUIDE)" + projectCodeInfo.projectCode + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xlsx";
byte[] fileByteArray = Common.DataTableToExcel(guideTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return File(fileByteArray, "application/octet-stream", fileName);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
}
}

View File

@@ -0,0 +1,135 @@
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using KART_API.Services;
using KART_API.Dto;
using KART_API.Utils;
using System.Net;
using System.Collections.Generic;
namespace KART_API.Controllers
{
[Route("api/v2/import")]
[ApiController]
public class ImportController : ControllerBase
{
//ToDo : 해야해
[Route("data")]
[HttpPost]
[DisableRequestSizeLimit]
public IActionResult ImportData([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
if (Request.Form.Files.Count > 0)
{
/*
string returnString = "업로드 성공";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
var file = Request.Form.Files[0];
string extension = System.IO.Path.GetExtension(file.FileName);
string fileName = "DATA_" + projectCodeInfo.projectCode + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + extension;
LogService.InsertSiteLog(userInfo.ID, projectCodeInfo.projectCode, "Upload File", "{\"Type\":\"DATA\", \"Origin\": \"" + file.FileName + "\", \"FileName\":\"" + fileName + "\"}");
fileName = Common.uploadFile(fileName, file);
returnString = project.uploadProjectData(projectCodeInfo.projectCode, fileName, extension);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
*/
Response.StatusCode = (int)HttpStatusCode.OK;
return Content("새싹은 미지원");
}
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
//ToDo : 해야해
[Route("question")]
[HttpPost]
[DisableRequestSizeLimit]
public IActionResult ImportQuestion([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
if (Request.Form.Files.Count > 0)
{/*
string returnString = "업로드 성공";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
var file = Request.Form.Files[0];
string extension = System.IO.Path.GetExtension(file.FileName);
string fileName = "QUESTION_" + projectCodeInfo.projectCode + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + extension;
LogService.InsertSiteLog(userInfo.ID, projectCodeInfo.projectCode, "Upload File", "{\"Type\":\"QUESTION\", \"Origin\": \"" + file.FileName + "\", \"FileName\":\"" + fileName + "\"}");
fileName = Common.uploadFile(fileName, file);
returnString = project.resetQuestion(projectCodeInfo.projectCode);
if (String.IsNullOrEmpty(returnString))
{
returnString = project.uploadQuestion(projectCodeInfo.projectCode, fileName, extension);
}
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
*/
Response.StatusCode = (int)HttpStatusCode.OK;
return Content("새싹은 미지원");
}
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
//ToDo : 해야해
[Route("title")]
[HttpPost]
[DisableRequestSizeLimit]
public IActionResult ImportTitle([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
if (Request.Form.Files.Count > 0)
{
/*
string returnString = "업로드 성공";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
var file = Request.Form.Files[0];
string extension = System.IO.Path.GetExtension(file.FileName);
string fileName = "TITLE_" + projectCodeInfo.projectCode + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + extension;
LogService.InsertSiteLog(userInfo.ID, projectCodeInfo.projectCode, "Upload File", "{\"Type\":\"TITLE\", \"Origin\": \"" + file.FileName + "\", \"FileName\":\"" + fileName + "\"}");
fileName = Common.uploadFile(fileName, file);
returnString = project.resetExplain(projectCodeInfo.projectCode);
if (String.IsNullOrEmpty(returnString))
{
returnString = project.uploadExplain(projectCodeInfo.projectCode, fileName, extension);
}
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
*/
Response.StatusCode = (int)HttpStatusCode.OK;
return Content("새싹은 미지원");
}
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
}
}

View File

@@ -0,0 +1,59 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Data;
using System.Net;
using System.Text;
using System.Web;
using KART_API.Services;
using KART_API.Dto;
using KART_API.Utils;
using System.Net.Http;
namespace KART_API.Controllers
{
[Route("api/v2/log")]
[ApiController]
public class LogController : ControllerBase
{
[Route("visit")] //확인
[HttpPost]
public IActionResult visitLog([FromHeader] string token ,[FromBody] VisitLogParam visitLog, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if(userInfo != null)
{
projectCodeInfo projectCodeInfo = new projectCodeInfo();
if (String.IsNullOrEmpty(skey) == false)
{
projectCodeInfo = new projectCodeInfo(skey);
}
LogService.InsertVisitLog(userInfo.ID, projectCodeInfo.projectCode, visitLog.LogContent);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content("PASS");
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("site")] //확인
[HttpPost]
public IActionResult siteLog([FromHeader] string token, [FromBody] SiteLogParam siteLog, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
LogService.InsertSiteLog(userInfo.ID, projectCodeInfo.projectCode, siteLog.LogTitle, siteLog.LogContent);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content("PASS");
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
}
}

View File

@@ -0,0 +1,512 @@
using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.Net;
using KART_API.Services;
using KART_API.Utils;
using KART_API.Dto;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Logical;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using OfficeOpenXml.Style;
using System.Collections.Generic;
namespace KART_API.Controllers
{
[Route("api/v2/project")]
[ApiController]
public class ProjectController : ControllerBase
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
[Route("list")] //확인
[HttpGet]
public IActionResult GetProjectList([FromHeader] string token)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
DataTable resultTable = project.getProjectList(userInfo.Team, userInfo.ID, userInfo.IsAdmin);
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("assign")] //확인
[HttpGet]
public IActionResult GetAssignList([FromHeader] string token)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "text/plain";
ProjectService project = new ProjectService();
string returnString = project.getAssignCount(userInfo.ID).ToString();
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("last")] //확인
[HttpGet]
public IActionResult GetStateCount([FromHeader] string token)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
DataTable resultTable = project.lastProjectCount(userInfo.Team, userInfo.ID, userInfo.IsAdmin, 6);
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("progress/type")] //확인
[HttpGet]
public IActionResult GetTypeByState([FromHeader] string token, [FromHeader] string skey, [FromHeader] string selectDate)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable resultTable = project.getTypeByState(projectCodeInfo.projectCode, selectDate);
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("progress/loi")] //확인
[HttpGet]
public IActionResult GetLOI([FromHeader] string token, [FromHeader] string skey, [FromHeader] string selectDate)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable resultTable = project.getLOI(projectCodeInfo.projectCode, selectDate);
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("progress/day")] //확인
[HttpGet]
public IActionResult GetDayByState([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable resultTable = project.getDayByState(projectCodeInfo.projectCode);
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("progress/screen")] //확인
[HttpGet]
public IActionResult GetQidByScreen([FromHeader] string token, [FromHeader] string skey, [FromHeader] string selectDate)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable resultTable = project.getQidByScreen(projectCodeInfo.projectCode, selectDate);
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("question/{qid}")] //확인
[HttpGet]
public IActionResult GetQuestionListWithQID([FromHeader] string token, [FromHeader] string skey, string qid)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable resultTable = project.getQuestionList(projectCodeInfo.projectCode, qid);
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("question")] //확인
[HttpGet]
public IActionResult GetQuestionList([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable resultTable = project.getQuestionList(projectCodeInfo.projectCode, "");
resultTable = resultTable.AsEnumerable().Where(dr => dr.Field<string>("QTYPE").ToLower() != "file").CopyToDataTable();
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("quota")] //확인
[HttpGet]
public IActionResult GetQuotaList([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable resultTable = project.getQuotaList(projectCodeInfo.projectCode);
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("bookmark/{page}")] //확인
[HttpGet]
public IActionResult GetBookmarkList([FromHeader] string token, [FromHeader] string skey, string page)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable resultTable = project.getBookmark(projectCodeInfo.projectCode, page, userInfo.Team, userInfo.ID);
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("bookmark/create")] //확인
[HttpPost]
public IActionResult CreateBookmark([FromHeader] string token, [FromBody] BookmarkParam bookmarkParam, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "text/plain";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
string returnString = project.insertBookmark(projectCodeInfo.projectCode, bookmarkParam, userInfo.Team, userInfo.ID);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("bookmark/update")] //확인
[HttpPost]
public IActionResult UpdateBookmark([FromHeader] string token, [FromBody] BookmarkParam bookmarkParam, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "text/plain";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
string returnString = project.updateBookmark(projectCodeInfo.projectCode, bookmarkParam, userInfo.Team, userInfo.ID);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("bookmark/delete/{bookmarkID}")] //확인
[HttpPost]
public IActionResult DeleteBookmark([FromHeader] string token, [FromHeader] string skey, string bookmarkID)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "text/plain";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
string returnString = project.deleteBookmark(projectCodeInfo.projectCode, bookmarkID, userInfo.ID);
if (returnString.IndexOf("오류") > -1)
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
else
{
Response.StatusCode = (int)HttpStatusCode.OK;
}
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("derived")] //확인
[HttpGet]
public IActionResult GetDerivedList([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "application/json";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
DataTable resultTable = project.getOnlyDerivedList(projectCodeInfo.projectCode, userInfo.Team, userInfo.IsAdmin);
string returnString = Common.GetJsonFromObject(resultTable);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
/* Response.StatusCode = (int)HttpStatusCode.OK;
return Content("새싹은 미지원");*/
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("derived/all")] //확인
[HttpPost]
public IActionResult UpdateAllDerivedVariable([FromHeader] string token, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "text/plain";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
string returnString = project.updateAllDerived(projectCodeInfo.projectCode, userInfo.ID);
if(returnString.IndexOf("오류") > -1)
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
else
{
Response.StatusCode = (int)HttpStatusCode.OK;
}
return Content(returnString);
/* Response.StatusCode = (int)HttpStatusCode.OK;
return Content("새싹은 미지원");*/
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("derived/create")] //확인
[HttpPost]
public IActionResult CreateDerivedVariable([FromHeader] string token, [FromBody] DerivedParam derivedParam, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "text/plain";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
string returnString = project.insertDerivedVariable(projectCodeInfo.projectCode, derivedParam, userInfo.Team, userInfo.ID);
if (returnString.IndexOf("오류") > -1)
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
else
{
Response.StatusCode = (int)HttpStatusCode.OK;
}
return Content(returnString);
/* Response.StatusCode = (int)HttpStatusCode.OK;
return Content("새싹은 미지원");*/
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("derived/update")] //확인
[HttpPost]
public IActionResult UpdateDerivedVariable([FromHeader] string token, [FromBody] DerivedParam derivedParam, [FromHeader] string skey)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "text/plain";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
string returnString = project.updateDerivedVariable(projectCodeInfo.projectCode, derivedParam, userInfo.Team, userInfo.ID);
if (returnString.IndexOf("오류") > -1)
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
else
{
Response.StatusCode = (int)HttpStatusCode.OK;
}
return Content(returnString);
/* Response.StatusCode = (int)HttpStatusCode.OK;
return Content("새싹은 미지원");*/
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("derived/delete/{variableID}")] //확인
[HttpPost]
public IActionResult DeleteDerived([FromHeader] string token, [FromHeader] string skey, string variableID)
{
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
hcAccessor.HttpContext.Response.ContentType = "text/plain";
ProjectService project = new ProjectService();
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
variableID = variableID.Split('_')[0].ToUpper();
string returnString = project.deleteDerivedVariable(projectCodeInfo.projectCode, variableID, userInfo.ID);
if (returnString.IndexOf("오류") > -1)
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
else
{
Response.StatusCode = (int)HttpStatusCode.OK;
}
return Content(returnString);
/* Response.StatusCode = (int)HttpStatusCode.OK;
return Content("새싹은 미지원");*/
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
//kon에서 문항 완료시 Derived 변수 만드는 거 새싹을 위해 준비해 놓도록 하자
[Route("derived/{projectCode}/{answerID}")] //확인
[HttpPost]
public IActionResult CreateDerivedData(string projectCode, string answerID)
{
hcAccessor.HttpContext.Response.ContentType = "text/plain";
/* Response.StatusCode = (int)HttpStatusCode.OK;
return Content("새싹은 미지원");*/
ProjectService project = new ProjectService();
string returnString = project.updateAllDerived(projectCode, "NEWSSAK", answerID);
if (returnString.IndexOf("오류") > -1)
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
else
{
Response.StatusCode = (int)HttpStatusCode.OK;
}
return Content(returnString);
}
}
}

View File

@@ -0,0 +1,195 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using KART_API.Services;
using KART_API.Dto;
using KART_API.Utils;
namespace KART_API.Controllers
{
[Route("api/v2/report")]
[ApiController]
public class ReportController : ControllerBase
{
[Route("result")] //확인
[HttpPost]
public IActionResult Result([FromHeader] string token, [FromBody] ReportParam reportParam, [FromHeader] string skey)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
var context = hcAccessor.HttpContext;
hcAccessor.HttpContext.Response.ContentType = "text/plain";
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
Security security = new Security();
ReportService report = new ReportService();
string returnString = string.Empty;
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
string mkey = userInfo.ID;
#region data, param 정리
try
{
//"index":"1"
string indexString = reportParam.IndexParam.ToUpper().Replace(" ", "");
//"banner":"2,3|4" ','옆으로 붙이기 / '|'단으로 쌓기
string bannerString = reportParam.BannerParam.ToUpper().Replace(" ", "");
//filter 새싹 로직 참조
string filterString = reportParam.FilterParam;
JObject options = Common.GetJObjectFromString(reportParam.OptionParam);
//"0" ~ "14"
string pointerStr = Common.GetNullString(options["POINTER"]);
string mPointerStr = Common.GetNullString(options["MPOINTER"]);
//"1" -> cell은 N만 Total은 N 만/ "2" -> cell은 %,N Total은 %,N / default -> cell은 %만 Total은 N 만
string prtModeStr = Common.GetNullString(options["PRTMODE"]);
//ex) {"카테고리1":"1,2,3", "카테고리2":"4,5,6", "카테고리3":"7,8,9"}
string valueGroupStr = Common.GetNullString(options["VGROUP"]);
#region 옵션 파라미터
ReportService.ReportOptions reportOptions = new ReportService.ReportOptions();
//Tabulation 표본특성, Banner By Banner
reportOptions.mode = Common.GetNullString(options["MODE"]);
//ex) "2022-01-25"
reportOptions.startDate = Common.GetNullString(options["SDATE"]);
reportOptions.endDate = Common.GetNullString(options["EDATE"]);
// 쿼터 표 번호(QSORDER)
reportOptions.isQuota = Common.GetNullString(options["QUOTA"]);
// "TEST" 테스트 데이터 사용, ALL TEST와 실제 데이터 같이 사용 이외의 문자열 테스트 데이터 사용X
reportOptions.isTest = Common.GetNullString(options["TEST"]);
// "1" 행 열 전환 이외의 문자열 행 열 전환X
reportOptions.isTurn = Common.GetNullString(options["TURN"]);
//출력 default -> cell은 %만 Total은 N 만
reportOptions.prtTotalCase = 1;
reportOptions.prtTotalPercent = 0;
reportOptions.prtCase = 0;
reportOptions.prtPercent = 1;
//소수점 default -> 14자리
reportOptions.roundPointer = 14;
reportOptions.mRoundPointer = 14;
// "0" 헤더 출력 안함 이외의 문자열 헤더 출력
// "GPT" 추가 GPT용 Table에는 머지가 되지 않은 헤더를 붙임
reportOptions.prtHeader = Common.GetNullString(options["PRTHEAD"]);
// "0" sub total 출력 안함 이외의 문자열 sub total 출력
reportOptions.prtSubTotal = Common.GetNullString(options["PRTSUB"]);
// "1" 인덱스 레이블 출력 안함 이외의 문자열 인덱스 레이블 출력
reportOptions.prtIndexValue = Common.GetNullString(options["PRTIV"]);
// "1" Numeric문항 Sum값 출력 이외의 문자열 Numeric문항 Sum값 출력 안함
reportOptions.prtNumericSum = Common.GetNullString(options["PRTNS"]);
if (String.IsNullOrWhiteSpace(pointerStr) == false && Common.IsNumeric(pointerStr))
{
if (Convert.ToInt32(pointerStr) < 14)
{
reportOptions.roundPointer = Convert.ToInt32(pointerStr);
}
}
if (String.IsNullOrWhiteSpace(mPointerStr) == false && Common.IsNumeric(mPointerStr))
{
if (Convert.ToInt32(mPointerStr) < 14)
{
reportOptions.mRoundPointer = Convert.ToInt32(mPointerStr);
}
}
if (String.IsNullOrWhiteSpace(reportOptions.isQuota) == false)//쿼터표는 옵션이 특별
{
//쿼터표는 N만
reportOptions.prtCase = 1;
reportOptions.prtPercent = 0;
//쿼터표는 SubTotal X
reportOptions.prtSubTotal = "0";
}
else
{
if (prtModeStr == "1")
{
//출력 1 -> cell은 N만 Total은 N 만
reportOptions.prtCase = 1;
reportOptions.prtPercent = 0;
}
else if (prtModeStr == "2")
{
//출력 2 -> cell은 %,N Total은 %,N
reportOptions.prtTotalCase = 1;
reportOptions.prtTotalPercent = 1;
reportOptions.prtCase = 1;
reportOptions.prtPercent = 1;
}
}
if (Common.IsJson(valueGroupStr))
{
reportOptions.valueGroup = Common.GetJObjectFromString(valueGroupStr);
}
#endregion
if (Request.Headers["Referer"].ToString().IndexOf(context.Request.Host.ToString()) < 0)
{
JObject logJson = new JObject();
logJson["INDEX"] = indexString;
logJson["BANNER"] = bannerString;
logJson["FILTER"] = filterString;
JObject optionJson = new JObject();
optionJson["MODE"] = reportOptions.mode;
optionJson["SDATE"] = reportOptions.startDate;
optionJson["EDATE"] = reportOptions.endDate;
optionJson["TEST"] = reportOptions.isTest;
optionJson["TURN"] = reportOptions.isTurn;
optionJson["POINTER"] = pointerStr;
optionJson["MPOINTER"] = mPointerStr;
optionJson["PRTMODE"] = prtModeStr;
optionJson["PRTHEAD"] = reportOptions.prtHeader;
optionJson["PRTSUB"] = reportOptions.prtSubTotal;
optionJson["PRTIV"] = reportOptions.prtIndexValue;
optionJson["PRTNS"] = reportOptions.prtNumericSum;
optionJson["VGROUP"] = valueGroupStr;
List<string> keyList = optionJson.Properties().Select(x => x.Name).Distinct().ToList<string>();
for (int ki = 0; ki < keyList.Count; ki++)
{
if (optionJson[keyList[ki]].ToString() == "")
{
optionJson.Property(keyList[ki]).Remove();
}
}
logJson["OPTION"] = optionJson;
if (String.IsNullOrEmpty(mkey))
{
mkey = context.Request.Host.ToString();
}
LogService.InsertSiteLog(mkey, projectCodeInfo.projectCode, "Get Report Data", logJson.ToString());
}
#endregion
context.Response.ContentType = "application/json";
returnString = report.getResult(projectCodeInfo.projectCode, indexString, bannerString, filterString, reportOptions);
}
catch (Exception ex)
{
returnString = ex.Message.ToString();
}
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
}
}

View File

@@ -0,0 +1,145 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using KART_API.Services;
using KART_API.Utils;
using KART_API.Dto;
using System.Data;
using System;
using System.Net;
namespace KART_API.Controllers
{
[Route("api/v2/encrypt")]
[ApiController]
public class SecurityController : ControllerBase
{
[Route("pkey")]//확인
[HttpGet]
public IActionResult EncryptString([FromHeader] string token, [FromHeader]string pkey)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
hcAccessor.HttpContext.Response.ContentType = "text/plain";
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
ProjectService project = new ProjectService();
if (project.getProjectInfo(pkey).Rows.Count > 0)
{
Security security = new Security();
string returnString = WebUtility.UrlEncode(security.encryptString(pkey));
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("login")]//확인
[HttpPost]
public IActionResult Login([FromBody] LoginParam login)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
hcAccessor.HttpContext.Response.ContentType = "application/json";
UserService user = new UserService();
DataTable userTable = user.userLogin(login.ID, login.Password);
if (userTable.Rows.Count > 0)
{
string returnString = "";
string userID = userTable.Rows[0]["mail"].ToString();
string userPNO = userTable.Rows[0]["p_no"].ToString();
string userName = userTable.Rows[0]["member_name"].ToString();
string userTeam = userTable.Rows[0]["team"].ToString();
string isKri = userTable.Rows[0]["is_kri"].ToString();
// isAdmin - 0 : Admin, 1:DCO, 4:BC 팀, 5:타부서, 6:외부인 인데 파생변수까지 접근, 7:클라이언트, 9:외부 링크
string isAdmin = "7";
if (userID == "jspark@kric.com")
{
isAdmin = "0";
}
else if (userTeam == "S301" || userTeam == "S401" || userTeam == "S501" || userPNO == "20191201")//온라인 사업, 데이터 사업, 개발팀 + 서지원 상무
{
isAdmin = "1";
}
else if (isKri == "1")
{
isAdmin = "4";
}
else if (isKri == "2")
{
isAdmin = "5";
}
else if (isKri == "3")
{
isAdmin = "6";
}
LogService.insertLoginLog(userID);
Security security = new Security();
string token = security.GenerateToken(userID, userName, userTeam, isAdmin);
Authentication authentication = new Authentication(token, userName, isAdmin);
returnString = Common.GetJsonFromObject(authentication);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("authentication")]//확인
[HttpGet]
public IActionResult Authentication([FromHeader] string token)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
hcAccessor.HttpContext.Response.ContentType = "text/plain";
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(null);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("external")]//확인
[HttpPost]
public IActionResult External([FromBody] ExternalParam externalParam)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
hcAccessor.HttpContext.Response.ContentType = "text/plain";
if (externalParam.External == "NS" || externalParam.External == "KON" || externalParam.External == "KIWI" || externalParam.External == "CLIENT")
{
string returnString = "";
LogService.insertLoginLog(externalParam.External);
Security security = new Security();
string tempID = externalParam.External + "_" + Common.GetRandomString();
string token = security.GenerateToken(tempID, externalParam.External, externalParam.External, "9");
Authentication authentication = new Authentication(token, externalParam.External, "9");
returnString = Common.GetJsonFromObject(authentication);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
}
}

View File

@@ -0,0 +1,78 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Data;
using System.Net;
using System.Text;
using System.Web;
using KART_API.Services;
using KART_API.Utils;
using KART_API.Dto;
namespace KART_API.Controllers
{
[Route("api/v2/uri")]
[ApiController]
public class UriController : ControllerBase
{
[Route("short")]//확인
[HttpPost]
public IActionResult ShortURL([FromHeader] string token, [FromBody] ShortURLParam shortURLParam, [FromHeader] string skey)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
hcAccessor.HttpContext.Response.ContentType = "text/plain";
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
string okey = "REPORT";
if(userInfo.ID == "KON" || userInfo.ID == "KIWI" || userInfo.ID == "NEWSSAK")
{
okey = userInfo.ID;
}
projectCodeInfo projectCodeInfo = new projectCodeInfo(skey);
ProjectService project = new ProjectService();
DataTable proejctInfo = project.getProjectInfo(projectCodeInfo.projectCode);
if(proejctInfo.Rows.Count > 0)
{
int mode = shortURLParam.Mode == "P" ? 1 : 0;
string returnString = "https://kart.kric.com/External/" + URIService.GetURIKey(shortURLParam.RealURI, mode, skey, proejctInfo.Rows[0]["IN_TT"].ToString(), okey);
string cLogContent = "{ \"REAL_URI\": \"" + shortURLParam.RealURI + "\",\"MODE\": \"" + shortURLParam.Mode + "\", \"COPY_URI\": \"" + returnString + "\" }";
LogService.InsertSiteLog(userInfo.ID, projectCodeInfo.projectCode, "URL Copy", cLogContent);
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(returnString);
}
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
[Route("short/{urikey}")]//확인
[HttpGet]
public IActionResult ShortURL([FromHeader] string token, string urikey)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
hcAccessor.HttpContext.Response.ContentType = "application/json";
UserInfo userInfo = Security.ValidateToken(token);
if (userInfo != null)
{
DataTable realUritable = URIService.GetRealURL(urikey, true);
if (realUritable.Rows.Count > 0)
{
Response.StatusCode = (int)HttpStatusCode.OK;
return Content(Common.GetJsonFromObject(realUritable));
}
}
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Content(null);
}
}
}

View File

@@ -0,0 +1,22 @@
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using KART_API.Utils;
namespace SwaggerFilter.Filters
{
public class CustomSwaggerFilter : IDocumentFilter
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(CustomSwaggerFilter));
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext contextt)
{
var remoteIP = Common.GetRemoteIP();
logger.Info("remote ip : " + remoteIP);
if (remoteIP != "::1" && remoteIP.StartsWith("211.254.145.") == false)
{
var nonMobileRoutes = swaggerDoc.Paths.ToList();
nonMobileRoutes.ForEach(x => { swaggerDoc.Paths.Remove(x.Key); });
}
}
}
}

16
KART_API/Dto/CommonDto.cs Normal file
View File

@@ -0,0 +1,16 @@
using System.Data;
namespace KART_API.Dto
{
public class DataTabelToExcelSheet
{
public DataTable ExcelData { get; set; } = new DataTable();
public string SheetName { get; set; } = string.Empty;
public DataTabelToExcelSheet(DataTable excelData, string sheetName)
{
ExcelData = excelData;
SheetName = sheetName;
}
public DataTabelToExcelSheet() { }
}
}

34
KART_API/Dto/ExportDto.cs Normal file
View File

@@ -0,0 +1,34 @@
namespace KART_API.Dto
{
public class ExportFormParam
{
public string FormName { get; set; } = string.Empty;
public ExportFormParam(string formName)
{
FormName = formName;
}
public ExportFormParam() { }
}
public class ExportExcelParam
{
public string ExportTable { get; set; } = string.Empty;
public string Turn { get; set; } = string.Empty;
public ExportExcelParam( string exportTable, string turn)
{
ExportTable = exportTable;
Turn = turn;
}
public ExportExcelParam() { }
}
public class ExportQuotaParam
{
public string ExportTable { get; set; } = string.Empty;
public ExportQuotaParam(string exportTable)
{
ExportTable = exportTable;
}
public ExportQuotaParam() { }
}
}

26
KART_API/Dto/LogDto.cs Normal file
View File

@@ -0,0 +1,26 @@
namespace KART_API.Dto
{
public class VisitLogParam
{
public string LogContent { get; set; }
public VisitLogParam(string logContent)
{
LogContent = logContent;
}
public VisitLogParam() { }
}
public class SiteLogParam
{
public string LogTitle { get; set; }
public string LogContent { get; set; }
public SiteLogParam(string logTitle, string logContent)
{
LogTitle = logTitle;
LogContent = logContent;
}
public SiteLogParam() { }
}
}

199
KART_API/Dto/ProjectDto.cs Normal file
View File

@@ -0,0 +1,199 @@
using System.Net;
using Newtonsoft.Json.Linq;
using KART_API.Utils;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using System.Text.RegularExpressions;
using KART_API.Services;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using OfficeOpenXml.Style;
namespace KART_API.Dto
{
public class projectCodeInfo
{
public string SecurityKey { get; set; } = string.Empty;
public string projectCode { get; set; } = string.Empty;
public string ver { get; set; } = string.Empty;
public projectCodeInfo(string securityKey)
{
Security security = new Security();
SecurityKey = securityKey;
projectCode = security.decryptString(WebUtility.UrlDecode(securityKey));
if (projectCode.IndexOf("|K|W|") > -1)
{
projectCode = projectCode.Replace("|K|W|", "");
ver = "KIWI";
}
else if(projectCode.IndexOf("|N|S|") > -1)
{
projectCode = projectCode.Replace("|N|S|", "");
ver = "NEWSSAK";
}
else
{
ver = "KON";
}
}
public projectCodeInfo() { }
}
/// <summary>
/// KON Question 정보
/// 문항 등록시에 사용
/// </summary>
public class QuestionInfo
{
public string variableName { get; set; } = string.Empty;
public string explain { get; set; } = string.Empty;
public string structureType { get; set; } = string.Empty;
public string questionType { get; set; } = string.Empty;
public string itemType { get; set; } = string.Empty;
public string variableType { get; set; } = string.Empty;
public string maxCount { get; set; } = string.Empty;
public string questionTitle { get; set; } = string.Empty;
public JObject attrJson { get; set; } = new JObject();
public JObject itemJson { get; set; } = new JObject();
public JObject optionJson { get; set; } = new JObject();
public QuestionInfo() { }
}
public class DataStructure
{
public string questionId { get; set; } = string.Empty;
public string l { get; set; } = "-1";
public string t { get; set; } = "0";
public string m { get; set; } = "0";
public string r { get; set; } = "0";
public string s { get; set; } = "0";
public bool isEtc { get; set; } = false;
public DataStructure() { }
public DataStructure(string[] fixHeader, string inString)
{
if(Array.IndexOf(fixHeader, inString) > -1)
{
questionId = inString;
}
else
{
Regex qidRegex = new Regex(@"^[A-Za-z0-9_]+(?=_[0-9]#|_ETC)");//알파벳으로 시작하고 숫자 또는 언더바
if (qidRegex.IsMatch(inString))
{
questionId = qidRegex.Match(inString).Value;
var tempArray = inString.Replace(questionId+"_", "").Split('_');
if(tempArray[tempArray.Length-1].ToUpper() == "ETC")
{
isEtc = true;
}
for (int i = 0; i < tempArray.Length; i++)
{
string keyString = tempArray[i].Substring(0, tempArray[i].Length - 2);
switch (tempArray[i].ToUpper().Substring(tempArray[i].Length - 1))
{
case "L":
l = keyString;
break;
case "T":
t = keyString;
break;
case "M":
m = keyString;
break;
case "R":
r = keyString;
break;
case "S":
s = keyString;
break;
}
}
}
else
{
questionId = inString;
}
}
}
}
public class DerivedParam
{
public string VariableID { get; set; } = string.Empty;
public string OriginID { get; set; } = string.Empty;
public string VariableType { get; set; } = string.Empty;
public string VariableTitle { get; set; } = string.Empty;
public string VariableInfo { get; set; } = string.Empty;
/// <summary>
/// DerivedParam 설정
/// </summary>
/// <param name="variableID">파생 변수명</param>
/// <param name="originID">수정 전 변수명</param>
/// <param name="variableType">파생변수 타입</param>
/// <param name="variableTitle">파생변수 제목</param>
/// <param name="variableInfo">파생변수 정보</param>
public DerivedParam(string variableID, string originID, string variableType, string variableTitle, string variableInfo)
{
VariableID = variableID;
OriginID = originID;
VariableType = variableType;
VariableTitle = variableTitle;
VariableInfo = variableInfo;
}
public DerivedParam() { }
}
public class BookmarkParam
{
public string BookmarkPage { get; set; }
public string BookmarkID { get; set; }
public string BookmarkTitle { get; set; }
public string BookmarkInfo { get; set; }
public string BookmarkJson { get; set; }
public string IsOpen { get; set; }
/// <summary>
/// BookmarkParam 설정
/// </summary>
/// <param name="bookmarkPage">TABULATION, CROSSTAB</param>
/// <param name="bookmarkID">북마크 ID</param>
/// <param name="bookmarkTitle">북마크 제목</param>
/// <param name="bookmarkInfo">북마크 설명</param>
/// <param name="bookmarkJson">북마크 정보</param>
/// <param name="isOpen">공개/비공개</param>
public BookmarkParam(string bookmarkPage, string bookmarkID, string bookmarkTitle, string bookmarkInfo, string bookmarkJson, string isOpen)
{
BookmarkPage = bookmarkPage;
BookmarkID = bookmarkID;
BookmarkTitle = bookmarkTitle;
BookmarkInfo = bookmarkInfo;
BookmarkJson = bookmarkJson;
IsOpen = isOpen;
}
public BookmarkParam() { }
}
public class LabelInfo
{
public string Value { get; set; }
public string Label { get; set; }
public LabelInfo(string value, string label)
{
Value = value;
Label = label;
}
public LabelInfo() { }
}
}

19
KART_API/Dto/ReportDto.cs Normal file
View File

@@ -0,0 +1,19 @@
namespace KART_API.Dto
{
public class ReportParam
{
public string IndexParam { get; set; } = string.Empty;
public string BannerParam { get; set; } = string.Empty;
public string FilterParam { get; set; } = string.Empty;
public string OptionParam { get; set; } = string.Empty;
public ReportParam(string indexParam, string bannerParam, string filterParam, string optionParam)
{
IndexParam = indexParam;
BannerParam = bannerParam;
FilterParam = filterParam;
OptionParam = optionParam;
}
public ReportParam() { }
}
}

View File

@@ -0,0 +1,33 @@
using System.Text.Json.Serialization;
namespace KART_API.Dto
{
public class LoginParam
{
public string ID { get; set; }
public string Password { get; set; }
public LoginParam(string id, string pw) { ID = id; Password = pw; }
public LoginParam() { }
}
public class ExternalParam
{
public string External { get; set; }
public ExternalParam(string external) { External = external; }
public ExternalParam() { }
}
public class Authentication
{
public string Token { get; set; }
public string Name { get; set; }
public string IsAdmin { get; set; }
public Authentication(string token, string name, string isAdmin)
{
Token = token;
Name = name;
IsAdmin = isAdmin;
}
public Authentication() { }
}
}

15
KART_API/Dto/UriDto.cs Normal file
View File

@@ -0,0 +1,15 @@
namespace KART_API.Dto
{
public class ShortURLParam
{
public string RealURI { get; set; }
public string Mode { get; set; }
public ShortURLParam(string realUri, string mode)
{
RealURI = realUri;
Mode = mode;
}
public ShortURLParam() { }
}
}

12
KART_API/Dto/UserDto.cs Normal file
View File

@@ -0,0 +1,12 @@
namespace KART_API.Dto
{
public class UserInfo
{
public string ID { get; set; }
public string Name { get; set; }
public string Team { get; set; }
public string IsAdmin { get; set; }
public UserInfo(string id, string name, string team, string isAdmin) { ID = id; Name = name; Team = team; IsAdmin = isAdmin;}
public UserInfo() { }
}
}

Binary file not shown.

29
KART_API/KART_API.csproj Normal file
View File

@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Accord" Version="3.8.0" />
<PackageReference Include="Accord.Math" Version="3.8.0" />
<PackageReference Include="Accord.Statistics" Version="3.8.0" />
<PackageReference Include="EPPlus" Version="4.5.3.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="8.0.0" />
<PackageReference Include="MySqlConnector" Version="2.3.5" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Svg" Version="3.4.6" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="System.Data.OleDb" Version="8.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.3.1" />
</ItemGroup>
<ItemGroup>
<Folder Include="UploadData\" />
</ItemGroup>
</Project>

3
KART_API/KART_API.http Normal file
View File

@@ -0,0 +1,3 @@
@KART_API_HostAddress = http://localhost:5179
###

View File

@@ -0,0 +1,171 @@
PI E
르 어 르)(러
VV E
^푸 어 퍼
따르 어 따(라)
^치르 어 치(러)
^다다르 어 다다(라)
^우러르 어 우러(러)
^들르 어 들(러)
^돕 어 도)(와
어쩌 어 어(째)
V,XSV,XSA E
^하 어 해,하)(여
^하 다$ 타-1.1,)다-1
^하 도록$ 토)록-0.1,)도록-3
^하 게$ 케)-0.1,)게-3
^하 지$ 치)-0.1,)지-3
^하 건대$ 컨)대-0.1,)건대-3
VX E
ᆯ [ᆫᆸᆺᆯ나-니바-비사-시오] )\2 +IgnoreRCond
ᆯ ᆷ$ ᆱ +IgnoreRCond
[가나] 어 \1
보 어 봐
오 어 와
두 어 둬
주 어 줘
리 [어여] 려
시 [어여] 셔
지 [어여] 져
내 어 내
대 어 대
놓 어 놔
^말 어$ 마
^말 어요$ 마)(요
^말 어라$ 마)(라
VA E
곱 어 고)(와
XSV E
리 [어여] 려
키 [어여] 켜
되 어 돼
XSA E
되 어 돼
XSA-I E
스럽 [ᆫᆷ] 스러)(\2-3 +IgnoreRCond
ᆸ 어 워,버-5
ᆸ 으 우,브-5
NP J
^나 가$ 내)(가
^너 가$ 네)(가
^저 가$ 제)(가
^나 의$ 내
^너 의$ 네
^저 의$ 제
^나 에게$ 내)(게
^너 에게$ 네)(게
^저 에게$ 제)(게
^것 이$ 게-1
^누구 가$ 누)(가
NNB VCP,JK
^터 이 테-1
^것 이 게-1
NP VCP,JK
터 이 테-1
것 이 게-1
VCP E
이 ([ᆨ-ᆶᆸ-ᇂ].+|어([^ᆻ].*)?|[^ᆨ-ᇂ어].*)$ )\2 -Coda
VC E
ㅣ 아 ㅑ -Coda
ㅣ 어 ㅕ -Coda
ㅣ 에 ㅖ -Coda
ㅣ 오 ㅛ -Coda
PA-I E
스럽 [ᆫᆷ] 스러)(\2-3 +IgnoreRCond
PA-I E
렇 어 래
떻 어 때
갛 어 개
랗 어 래
맣 어 매
겋 어 게
렇 어 레
멓 어 메
얗 어 얘
옇 어 예
ᇂ [ᆫᆯᆷ나-니라-리마-미시] )(\2 +IgnoreRCond
ᇂ 으 )(
PR E
르 어 ᆯ)(라 +Positive
르 어 ᆯ)(러 -Positive
르 이 ᆯ)(리
P E
하 어 해,하)(여
[가까나따라사싸자짜차카타파] 어 \1
[너러서쩌허] 어 \1
[켜펴혀] 어 \1
고 어 과
꼬 어 꽈
로 어 롸
모 어 뫄
보 어 봐
쏘 어 쏴
오 어 와
쪼 어 쫘
구 어 궈
꾸 어 꿔
누 어 눠
두 어 둬
루 어 뤄
수 어 숴
쑤 어 쒀
우 어 워
주 어 줘
쭈 어 쭤
추 어 춰
투 어 퉈
ㅡ 어 ㅏ +Positive
ㅡ 어 ㅓ -Positive
ㅣ [어여] ㅕ
괴 어 괘
꾀 어 꽤
뇌 어 놰
되 어 돼
뢰 어 뢔
뵈 어 봬
쇠 어 쇄
쐬 어 쐐
외 어 왜
죄 어 좨
쬐 어 쫴
[개깨내대때래매배빼새쌔애재째채캐태패] 어 \1
[네데떼레메베세헤] 어 \1
ᆯ [ᆫᆸᆺᆯ나-니바-비사-시오] )\2 +IgnoreRCond
ᆯ ᆷ$ ᆱ +IgnoreRCond
PI E
ᆮ 어 ᆯ)(아 +Positive
ᆮ 어 ᆯ)(어 -Positive
ᆮ [아-얘에-이] ᆯ)\2
#ᆮ [라-리] ᆯ\2
ᆸ 어 워,버-5
ᆸ 으 우,브-5
ㅂ [아-얘에-유의-이] )\2
ᆺ 어 아 +Positive
ᆺ 어 어 -Positive
ᆺ [아-얘에-이] )\2
EP E
시 었 셨
시 엇 셧
#시 어 세,셔
E E
리 어 려
시 어 셔

121908
KART_API/NlpModel/default.dict Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

BIN
KART_API/NlpModel/sj.knlm Normal file

Binary file not shown.

BIN
KART_API/NlpModel/sj.morph Normal file

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,17 @@
# 인터넷에서 자주 쓰이는 변형 어미 등재
ᆸ니다$ ᆷ니다/EF -5
ᆸ니다$ ᆷ다/EF -5
습니다$ 슴니다/EF -5
습니다$ 슴다/EF -5
요$ 여/EF -5
기$ 긔/ETN -5
# 자주 발생하는 오타에 대해 이형태로 등재
엇 었/EP -5
겟 겠/EP -5
괜찬 괜찮/VA -5
편찬 편찮/VA -5
귀찬 귀찮/VA -5
하찬 하찮/VA -5

97
KART_API/Program.cs Normal file
View File

@@ -0,0 +1,97 @@
using Microsoft.Extensions.WebEncoders;
using Microsoft.OpenApi.Models;
using SwaggerFilter.Filters;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Unicode;
var log4netRepository = log4net.LogManager.GetRepository(Assembly.GetEntryAssembly());
log4net.Config.XmlConfigurator.Configure(log4netRepository, new FileInfo("log4net.config"));
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
// Add services to the container.
services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
services.AddEndpointsApiExplorer();
//HttpContext <20><><EFBFBD><EFBFBD>
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSwaggerGen(gen =>
{
gen.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Version = "v1",
Title = "KART API NET 8.0",
Description = "KART API NET 8.0"
});
gen.AddSecurityDefinition("token", new OpenApiSecurityScheme
{
Description = "Custom header for token",
Name = "token",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
});
gen.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "token"
},
Name = "token",
In = ParameterLocation.Header,
},
new List<string>()
}
});
gen.DocumentFilter<CustomSwaggerFilter>();
gen.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
});
services.Configure<WebEncoderOptions>(options =>
{
options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All); // <20>ѱ<EFBFBD><D1B1><EFBFBD> <20><><EFBFBD>ڵ<EFBFBD><DAB5>Ǵ<EFBFBD> <20><><EFBFBD><EFBFBD> <20>ذ<EFBFBD>
});
services.AddCors(options => {
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.WithExposedHeaders(new string[] { "Content-Disposition" });
});
});
//Server Path<74><68><EFBFBD><EFBFBD>
AppDomain.CurrentDomain.SetData("ContentRootPath", Environment.CurrentDirectory);
var app = builder.Build();
app.UseCors();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Showing API V1");
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:1848",
"sslPort": 44372
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5179",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7042;http://localhost:5179",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,743 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
using System.Collections.Generic;
namespace KART_API.Services
{
using CString = IntPtr;
using KiwiHandle = IntPtr;
using KiwiBuilderHandle = IntPtr;
using KiwiResHandle = IntPtr;
using KiwiWsHandle = IntPtr;
using KiwiTypoHandle = IntPtr;
using KiwiJoinerHandle = IntPtr;
internal class Utf8String : IDisposable
{
IntPtr iPtr;
public IntPtr IntPtr { get { return iPtr; } }
public int BufferLength { get { return iBufferSize; } }
int iBufferSize;
public Utf8String(string aValue)
{
if (aValue == null)
{
iPtr = IntPtr.Zero;
}
else
{
byte[] bytes = Encoding.UTF8.GetBytes(aValue);
iPtr = Marshal.AllocHGlobal(bytes.Length + 1);
Marshal.Copy(bytes, 0, iPtr, bytes.Length);
Marshal.WriteByte(iPtr, bytes.Length, 0);
iBufferSize = bytes.Length + 1;
}
}
public void Dispose()
{
if (iPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(iPtr);
iPtr = IntPtr.Zero;
}
}
}
internal class Utf16String : IDisposable
{
IntPtr iPtr;
public IntPtr IntPtr { get { return iPtr; } }
public int BufferLength { get { return iBufferSize; } }
int iBufferSize;
public Utf16String(string aValue)
{
if (aValue == null)
{
iPtr = IntPtr.Zero;
}
else
{
byte[] bytes = new UnicodeEncoding().GetBytes(aValue);
iPtr = Marshal.AllocHGlobal(bytes.Length + 2);
Marshal.Copy(bytes, 0, iPtr, bytes.Length);
Marshal.WriteByte(iPtr, bytes.Length, 0);
Marshal.WriteByte(iPtr, bytes.Length + 1, 0);
iBufferSize = bytes.Length + 2;
}
}
public void Dispose()
{
if (iPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(iPtr);
iPtr = IntPtr.Zero;
}
}
}
internal class Utf8StringArray : IDisposable
{
IntPtr iPtr, bPtr;
public IntPtr IntPtr { get { return bPtr; } }
public Utf8StringArray(string[] aValue)
{
if (aValue == null)
{
iPtr = IntPtr.Zero;
}
else
{
int totalLength = 0;
byte[][] pool = new byte[aValue.Length][];
for (int i = 0; i < aValue.Length; i++)
{
pool[i] = Encoding.UTF8.GetBytes(aValue[i]);
totalLength += pool[i].Length + 1;
}
iPtr = Marshal.AllocHGlobal(totalLength);
bPtr = Marshal.AllocHGlobal(IntPtr.Size * pool.Length);
int offset = 0;
for (int i = 0; i < aValue.Length; i++)
{
Marshal.Copy(pool[i], 0, iPtr + offset, pool[i].Length);
Marshal.WriteByte(iPtr, pool[i].Length, 0);
Marshal.WriteIntPtr(bPtr, IntPtr.Size * i, iPtr + offset);
offset += pool[i].Length + 1;
}
}
}
public void Dispose()
{
if (iPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(iPtr);
Marshal.FreeHGlobal(bPtr);
iPtr = IntPtr.Zero;
bPtr = IntPtr.Zero;
}
}
}
public class KiwiException : Exception
{
public KiwiException()
{
}
public KiwiException(string message) : base(message)
{
}
public KiwiException(string message, Exception inner) : base(message, inner)
{
}
}
public struct Result
{
public Token[] morphs;
public float prob;
}
public struct ExtractedWord
{
public string word;
public float score, posScore;
public int freq;
}
internal class KiwiCAPI
{
private const string dll_name = "kiwi.dll";
public static IntPtr LoadDll(string path)
{
var is64 = IntPtr.Size == 8;
var subfolder = "\\bin_" + (is64 ? "x64\\" : "x86\\");
return LoadLibrary(path + subfolder + dll_name);
}
[StructLayout(LayoutKind.Sequential)]
public struct TokenInfo
{
public uint chrPosition; /* 시작 위치(UTF16 문자 기준) */
public uint wordPosition; /* 어절 번호(공백 기준)*/
public uint sentPosition; /* 문장 번호*/
public uint lineNumber; /* 줄 번호*/
public ushort length; /* 길이(UTF16 문자 기준) */
public byte _tag; /* 품사 태그 */
public byte senseId; /* 의미 번호 */
public float score; /* 해당 형태소의 언어모델 점수 */
public float typoCost; /* 오타가 교정된 경우 오타 비용. 그렇지 않은 경우 0 */
public uint typoFormId; /* 교정 전 오타의 형태에 대한 정보 (typoCost가 0인 경우 의미 없음) */
public uint pairedToken; /* SSO, SSC 태그에 속하는 형태소의 경우 쌍을 이루는 반대쪽 형태소의 위치(-1인 경우 해당하는 형태소가 없는 것을 뜻함) */
public uint subSentPosition; /* 인용부호나 괄호로 둘러싸인 하위 문장의 번호. 1부터 시작. 0인 경우 하위 문장이 아님을 뜻함 */
}
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int CReader(int id, IntPtr buf, IntPtr userData);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int CReceiver(int id, IntPtr kiwi_res, IntPtr userData);
// global functions
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern CString kiwi_version();
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern CString kiwi_error();
// builder functions
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern KiwiBuilderHandle kiwi_builder_init(CString modelPath, int maxCache, int options);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_builder_close(KiwiBuilderHandle handle);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_builder_add_word(KiwiBuilderHandle handle, CString word, CString pos, float score);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_builder_load_dict(KiwiBuilderHandle handle, CString dictPath);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern KiwiWsHandle kiwi_builder_extract_words_w(KiwiBuilderHandle handle, CReader reader, IntPtr userData, int minCnt, int maxWordLen, float minScore, float posThreshold);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern KiwiWsHandle kiwi_builder_extract_add_words_w(KiwiBuilderHandle handle, CReader reader, IntPtr userData, int minCnt, int maxWordLen, float minScore, float posThreshold);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern KiwiHandle kiwi_builder_build(KiwiBuilderHandle handle, KiwiTypoHandle typos, float typo_cost_threshold);
// analyzer functions
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_get_option(KiwiHandle handle, int option);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern void kiwi_set_option(KiwiHandle handle, int option, int value);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern float kiwi_get_option_f(KiwiHandle handle, int option);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern void kiwi_set_option_f(KiwiHandle handle, int option, float value);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern KiwiResHandle kiwi_analyze_w(KiwiHandle handle, IntPtr text, int topN, int matchOptions);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern KiwiResHandle kiwi_analyze(KiwiHandle handle, IntPtr text, int topN, int matchOptions);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_analyze_mw(KiwiHandle handle, CReader reader, CReceiver receiver, IntPtr userData, int topN, int matchOptions);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_analyze_m(KiwiHandle handle, CReader reader, CReceiver receiver, IntPtr userData, int topN, int matchOptions);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_close(KiwiHandle handle);
// result management functions
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_res_size(KiwiResHandle result);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern float kiwi_res_prob(KiwiResHandle result, int index);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_res_word_num(KiwiResHandle result, int index);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr kiwi_res_form_w(KiwiResHandle result, int index, int num);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr kiwi_res_tag_w(KiwiResHandle result, int index, int num);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr kiwi_res_form(KiwiResHandle result, int index, int num);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr kiwi_res_tag(KiwiResHandle result, int index, int num);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_res_position(KiwiResHandle result, int index, int num);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_res_length(KiwiResHandle result, int index, int num);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_res_word_position(KiwiResHandle result, int index, int num);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_res_sent_position(KiwiResHandle result, int index, int num);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern ref TokenInfo kiwi_res_token_info(KiwiResHandle result, int index, int num);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_res_close(KiwiResHandle result);
// word management functions
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_ws_size(KiwiWsHandle result);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr kiwi_ws_form_w(KiwiWsHandle result, int index);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern float kiwi_ws_score(KiwiWsHandle result, int index);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_ws_freq(KiwiWsHandle result, int index);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern float kiwi_ws_pos_score(KiwiWsHandle result, int index);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_ws_close(KiwiWsHandle result);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern KiwiTypoHandle kiwi_typo_init();
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern KiwiTypoHandle kiwi_typo_get_basic();
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_typo_add(KiwiTypoHandle typo, IntPtr orig, int origSize, IntPtr error, int errorSize, float cost, int condition);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_typo_close(KiwiTypoHandle typo);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern KiwiJoinerHandle kiwi_new_joiner(KiwiHandle handle, int lmSearch);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_joiner_add(KiwiJoinerHandle handle, CString form, CString tag, int option);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern CString kiwi_joiner_get(KiwiJoinerHandle handle);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern CString kiwi_joiner_get_w(KiwiJoinerHandle handle);
[DllImport(dll_name, CallingConvention = CallingConvention.Cdecl)]
public static extern int kiwi_joiner_close(KiwiJoinerHandle handle);
public static Result[] ToResult(KiwiResHandle kiwiresult)
{
int resCount = kiwi_res_size(kiwiresult);
if (resCount < 0) throw new KiwiException(Marshal.PtrToStringAnsi(kiwi_error()));
Result[] ret = new Result[resCount];
for (int i = 0; i < resCount; ++i)
{
int num = kiwi_res_word_num(kiwiresult, i);
ret[i].morphs = new Token[num];
for (int j = 0; j < num; ++j)
{
ret[i].morphs[j].form = Marshal.PtrToStringUni(kiwi_res_form_w(kiwiresult, i, j));
ret[i].morphs[j].tag = Marshal.PtrToStringUni(kiwi_res_tag_w(kiwiresult, i, j));
var ti = kiwi_res_token_info(kiwiresult, i, j);
ret[i].morphs[j].chrPosition = ti.chrPosition;
ret[i].morphs[j].wordPosition = ti.wordPosition;
ret[i].morphs[j].sentPosition = ti.sentPosition;
ret[i].morphs[j].lineNumber = ti.lineNumber;
ret[i].morphs[j].length = ti.length;
ret[i].morphs[j].senseId = ti.senseId;
ret[i].morphs[j].score = ti.score;
ret[i].morphs[j].typoCost = ti.typoCost;
ret[i].morphs[j].typoFormId = ti.typoFormId;
ret[i].morphs[j].pairedToken = ti.pairedToken;
ret[i].morphs[j].subSentPosition = ti.subSentPosition;
}
ret[i].prob = kiwi_res_prob(kiwiresult, i);
}
return ret;
}
public static ExtractedWord[] ToExtractedWord(KiwiWsHandle kiwiresult)
{
int resCount = kiwi_ws_size(kiwiresult);
if (resCount < 0) throw new KiwiException(Marshal.PtrToStringAnsi(kiwi_error()));
ExtractedWord[] ret = new ExtractedWord[resCount];
for (int i = 0; i < resCount; ++i)
{
ret[i].word = Marshal.PtrToStringUni(kiwi_ws_form_w(kiwiresult, i));
ret[i].score = kiwi_ws_score(kiwiresult, i);
ret[i].posScore = kiwi_ws_pos_score(kiwiresult, i);
ret[i].freq = kiwi_ws_freq(kiwiresult, i);
}
return ret;
}
}
public struct Token
{
public string form;
public string tag;
public uint chrPosition; /* 시작 위치(UTF16 문자 기준) */
public uint wordPosition; /* 어절 번호(공백 기준)*/
public uint sentPosition; /* 문장 번호*/
public uint lineNumber; /* 줄 번호*/
public ushort length; /* 길이(UTF16 문자 기준) */
public byte senseId; /* 의미 번호 */
public float score; /* 해당 형태소의 언어모델 점수 */
public float typoCost; /* 오타가 교정된 경우 오타 비용. 그렇지 않은 경우 0 */
public uint typoFormId; /* 교정 전 오타의 형태에 대한 정보 (typoCost가 0인 경우 의미 없음) */
public uint pairedToken; /* SSO, SSC 태그에 속하는 형태소의 경우 쌍을 이루는 반대쪽 형태소의 위치(-1인 경우 해당하는 형태소가 없는 것을 뜻함) */
public uint subSentPosition; /* 인용부호나 괄호로 둘러싸인 하위 문장의 번호. 1부터 시작. 0인 경우 하위 문장이 아님을 뜻함 */
}
public enum Option
{
IntegrateAllomorph = 1 << 0,
LoadDefaultDict = 1 << 1,
LoadTypoDict = 1 << 2,
MaxUnkFormSize = 0x8002,
SpaceTolerance = 0x8003,
CutOffThreshold = 0x9001,
UnkFormScoreScale = 0x9002,
UnkFormScoreBias = 0x9003,
SpacePenalty = 0x9004,
TypoCostWeight = 0x9005,
}
public enum ModelType
{
KNLM = 0x0000,
SBG = 0x0100,
}
public enum MatchWord
{
Url = 1 << 0,
Email = 1 << 1,
Hashtag = 1 << 2,
Mention = 1 << 3,
Serial = 1 << 4,
All = Url | Email | Hashtag | Mention | Serial,
NormalizeCoda = 1 << 16,
JoinNounPrefix = 1 << 17,
JoinNounSuffix = 1 << 18,
JoinVerbSuffix = 1 << 19,
JoinAdjSuffix = 1 << 20,
JoinAdvSuffix = 1 << 21,
SplitComplex = 1 << 22,
ZCoda = 1 << 23,
}
public class KiwiLoader
{
private static IntPtr dllHandle = IntPtr.Zero;
public static string GetDefaultPath()
{
var myPath = new Uri(typeof(KiwiCAPI).Assembly.CodeBase).LocalPath;
string path = Path.GetDirectoryName(myPath);
return path;
}
public static bool LoadDll(string path = null)
{
if (dllHandle != IntPtr.Zero) return true;
if (path == null)
{
path = GetDefaultPath();
}
return (dllHandle = KiwiCAPI.LoadDll(path)) != IntPtr.Zero;
}
}
public class TypoTransformer
{
public KiwiTypoHandle inst;
public TypoTransformer(bool useBasicSet = false)
{
inst = useBasicSet ? KiwiCAPI.kiwi_typo_get_basic() : KiwiCAPI.kiwi_typo_init();
}
public int Add(string[] orig, string[] error, float cost, int condition)
{
if (inst == KiwiCAPI.kiwi_typo_get_basic())
{
throw new InvalidOperationException("basic typo object cannot be modified!");
}
return KiwiCAPI.kiwi_typo_add(inst, new Utf8StringArray(orig).IntPtr, orig.Length, new Utf8StringArray(error).IntPtr, error.Length, cost, condition);
}
~TypoTransformer()
{
if (inst != null && inst != KiwiCAPI.kiwi_typo_get_basic())
{
KiwiCAPI.kiwi_typo_close(inst);
}
}
}
public class KiwiBuilder
{
public delegate string Reader(int id);
private KiwiBuilderHandle inst;
private Reader reader;
private Tuple<int, string> readItem;
static KiwiBuilder()
{
if (KiwiLoader.LoadDll()) return;
if (KiwiLoader.LoadDll(KiwiLoader.GetDefaultPath() + "\\..")) return;
if (KiwiLoader.LoadDll(KiwiLoader.GetDefaultPath() + "\\..\\..")) return;
}
private static KiwiCAPI.CReader readerInst = (int id, IntPtr buf, IntPtr userData) =>
{
GCHandle handle = (GCHandle)userData;
KiwiBuilder ki = handle.Target as KiwiBuilder;
if (ki.readItem?.Item1 != id)
{
ki.readItem = new Tuple<int, string>(id, ki.reader(id));
}
if (buf == IntPtr.Zero)
{
return ki.readItem.Item2?.Length ?? 0;
}
KiwiCAPI.CopyMemory(buf, new Utf16String(ki.readItem.Item2).IntPtr, (uint)ki.readItem.Item2.Length * 2);
return 0;
};
public KiwiBuilder(string modelPath, int numThreads = 0, Option options = Option.LoadDefaultDict | Option.LoadTypoDict | Option.IntegrateAllomorph, ModelType modelType = ModelType.KNLM)
{
inst = KiwiCAPI.kiwi_builder_init(new Utf8String(modelPath).IntPtr, numThreads, (int)options | (int)modelType);
if (inst == IntPtr.Zero) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
}
public int AddWord(string word, string pos, float score)
{
int ret = KiwiCAPI.kiwi_builder_add_word(inst, new Utf8String(word).IntPtr, new Utf8String(pos).IntPtr, score);
if (ret < 0) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
return ret;
}
public int LoadDictionary(string dictPath)
{
int ret = KiwiCAPI.kiwi_builder_load_dict(inst, new Utf8String(dictPath).IntPtr);
if (ret < 0) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
return ret;
}
public ExtractedWord[] ExtractWords(Reader reader, int minCnt = 5, int maxWordLen = 10, float minScore = 0.1f, float posThreshold = -3)
{
GCHandle handle = GCHandle.Alloc(this);
this.reader = reader;
readItem = null;
KiwiWsHandle ret = KiwiCAPI.kiwi_builder_extract_words_w(inst, readerInst, (IntPtr)handle, minCnt, maxWordLen, minScore, posThreshold);
handle.Free();
if (inst == IntPtr.Zero) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
ExtractedWord[] words = KiwiCAPI.ToExtractedWord(ret);
KiwiCAPI.kiwi_ws_close(ret);
return words;
}
public ExtractedWord[] ExtractAddWords(Reader reader, int minCnt = 5, int maxWordLen = 10, float minScore = 0.1f, float posThreshold = -3)
{
GCHandle handle = GCHandle.Alloc(this);
this.reader = reader;
readItem = null;
KiwiWsHandle ret = KiwiCAPI.kiwi_builder_extract_add_words_w(inst, readerInst, (IntPtr)handle, minCnt, maxWordLen, minScore, posThreshold);
handle.Free();
if (inst == IntPtr.Zero) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
ExtractedWord[] words = KiwiCAPI.ToExtractedWord(ret);
KiwiCAPI.kiwi_ws_close(ret);
return words;
}
public Kiwi Build()
{
KiwiHandle ret = KiwiCAPI.kiwi_builder_build(inst, (IntPtr)null, 0);
if (ret == IntPtr.Zero) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
return new Kiwi(ret);
}
public Kiwi Build(TypoTransformer typo, float typoCostThreshold = 2.5f)
{
KiwiHandle ret = KiwiCAPI.kiwi_builder_build(inst, typo.inst, typoCostThreshold);
if (ret == IntPtr.Zero) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
return new Kiwi(ret);
}
~KiwiBuilder()
{
if (inst != IntPtr.Zero)
{
if (KiwiCAPI.kiwi_builder_close(inst) < 0) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
}
}
}
public class KiwiJoiner
{
private KiwiJoinerHandle inst;
public KiwiJoiner(KiwiJoinerHandle _inst)
{
inst = _inst;
}
public string Get()
{
return Marshal.PtrToStringUni(KiwiCAPI.kiwi_joiner_get_w(inst));
}
public void Add(string form, string tag, int option = 1)
{
if (KiwiCAPI.kiwi_joiner_add(inst, new Utf8String(form).IntPtr, new Utf8String(tag).IntPtr, option) < 0) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
}
~KiwiJoiner()
{
if (inst != IntPtr.Zero)
{
if (KiwiCAPI.kiwi_joiner_close(inst) < 0) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
}
}
}
public class Kiwi
{
public delegate string Reader(int id);
public delegate int Receiver(int id, Result[] res);
private KiwiHandle inst;
private Reader reader;
private Receiver receiver;
private Tuple<int, string> readItem;
static Kiwi()
{
if (KiwiLoader.LoadDll()) return;
if (KiwiLoader.LoadDll(KiwiLoader.GetDefaultPath() + "\\..")) return;
if (KiwiLoader.LoadDll(KiwiLoader.GetDefaultPath() + "\\..\\..")) return;
}
private static KiwiCAPI.CReader readerInst = (int id, IntPtr buf, IntPtr userData) =>
{
GCHandle handle = (GCHandle)userData;
Kiwi ki = handle.Target as Kiwi;
if (ki.readItem?.Item1 != id)
{
ki.readItem = new Tuple<int, string>(id, ki.reader(id));
}
if (buf == IntPtr.Zero)
{
return ki.readItem.Item2?.Length ?? 0;
}
KiwiCAPI.CopyMemory(buf, new Utf16String(ki.readItem.Item2).IntPtr, (uint)ki.readItem.Item2.Length * 2);
return 0;
};
private static KiwiCAPI.CReceiver receiverInst = (int id, KiwiResHandle kiwi_res, IntPtr userData) =>
{
GCHandle handle = (GCHandle)userData;
Kiwi ki = handle.Target as Kiwi;
return ki.receiver(id, KiwiCAPI.ToResult(kiwi_res));
};
public Kiwi(KiwiHandle _inst)
{
inst = _inst;
}
public static string Version()
{
return Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_version());
}
public Result[] Analyze(string text, int topN = 1, MatchWord matchOptions = MatchWord.All)
{
KiwiResHandle res = KiwiCAPI.kiwi_analyze_w(inst, new Utf16String(text).IntPtr, topN, (int)matchOptions);
if (inst == IntPtr.Zero) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
Result[] ret = KiwiCAPI.ToResult(res);
KiwiCAPI.kiwi_res_close(res);
return ret;
}
public void AnalyzeMulti(Reader reader, Receiver receiver, int topN = 1, MatchWord matchOptions = MatchWord.All)
{
GCHandle handle = GCHandle.Alloc(this);
this.reader = reader;
this.receiver = receiver;
readItem = null;
int ret = KiwiCAPI.kiwi_analyze_mw(inst, readerInst, receiverInst, (IntPtr)handle, topN, (int)matchOptions);
handle.Free();
if (ret < 0) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
}
public KiwiJoiner NewJoiner(bool lmSearch = true)
{
var h = KiwiCAPI.kiwi_new_joiner(inst, lmSearch ? 1 : 0);
if (h == IntPtr.Zero) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
return new KiwiJoiner(h);
}
public bool IntegrateAllomorph
{
get { return KiwiCAPI.kiwi_get_option(inst, (int)Option.IntegrateAllomorph) != 0; }
set { KiwiCAPI.kiwi_set_option(inst, (int)Option.IntegrateAllomorph, value ? 1 : 0); }
}
public int MaxUnkFormSize
{
get { return KiwiCAPI.kiwi_get_option(inst, (int)Option.MaxUnkFormSize); }
set { KiwiCAPI.kiwi_set_option(inst, (int)Option.MaxUnkFormSize, value); }
}
public int SpaceTolerance
{
get { return KiwiCAPI.kiwi_get_option(inst, (int)Option.SpaceTolerance); }
set { KiwiCAPI.kiwi_set_option(inst, (int)Option.SpaceTolerance, value); }
}
public float CutOffThreshold
{
get { return KiwiCAPI.kiwi_get_option_f(inst, (int)Option.CutOffThreshold); }
set { KiwiCAPI.kiwi_set_option_f(inst, (int)Option.CutOffThreshold, value); }
}
public float UnkFormScoreScale
{
get { return KiwiCAPI.kiwi_get_option_f(inst, (int)Option.UnkFormScoreScale); }
set { KiwiCAPI.kiwi_set_option_f(inst, (int)Option.UnkFormScoreScale, value); }
}
public float UnkFormScoreBias
{
get { return KiwiCAPI.kiwi_get_option_f(inst, (int)Option.UnkFormScoreBias); }
set { KiwiCAPI.kiwi_set_option_f(inst, (int)Option.UnkFormScoreBias, value); }
}
public float SpacePenalty
{
get { return KiwiCAPI.kiwi_get_option_f(inst, (int)Option.SpacePenalty); }
set { KiwiCAPI.kiwi_set_option_f(inst, (int)Option.SpacePenalty, value); }
}
public float TypoCostWeight
{
get { return KiwiCAPI.kiwi_get_option_f(inst, (int)Option.TypoCostWeight); }
set { KiwiCAPI.kiwi_set_option_f(inst, (int)Option.TypoCostWeight, value); }
}
~Kiwi()
{
if (inst != IntPtr.Zero)
{
if (KiwiCAPI.kiwi_close(inst) < 0) throw new KiwiException(Marshal.PtrToStringAnsi(KiwiCAPI.kiwi_error()));
}
}
}
}

View File

@@ -0,0 +1,82 @@
using System;
using KART_API.Utils;
namespace KART_API.Services
{
public class LogService
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(LogService));
/// <summary>
/// 로그인 로그 기록
/// </summary>
/// <param name="userEmail">User</param>
public static void insertLoginLog(string userEmail)
{
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectReport();
try
{
string sqlString = " INSERT INTO dbo.TB_LOGIN_LOG(M_USER, L_IP) VALUES('" + userEmail + "', '" + Common.GetRemoteIP() + "'); ";
msdal.ExecuteSQL(sqlString, connection);
msdal.Disconnect(connection);
}
catch (Exception ex)
{
logger.Fatal("Log > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
msdal.Disconnect(connection);
}
}
public static void InsertSiteLog(string mkey, string projectCode, string logTitle, string logContent)
{
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectReport();
try
{
string logString = "{\"projectCode\":\"" + projectCode + "\", \"LOGTITLE\":\"" + logTitle + "\", \"LOGCONTENT\":" + logContent + "}";
string userIP = Common.GetRemoteIP();
string insertString = "insert into TB_SITE_LOG(M_USER, S_PAGE_INFO, S_IP) values ('" + mkey + "','" + logString + "','" + userIP + "')";
msdal.ExecuteSQL(insertString, connection);
}
catch (Exception ex)
{
logger.Fatal("Log > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
msdal.Disconnect(connection);
}
}
/// <summary>
/// Visit Log 작성
/// </summary>
/// <param name="mkey">User Key</param>
/// <param name="logContent">로그 내용</param>
public static void InsertVisitLog(string mkey, string projectCode, string logContent)
{
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectReport();
try
{
string userIP = Common.GetRemoteIP();
string insertString = "insert into TB_VISIT_LOG(M_USER, V_PAGE_INFO, V_PKEY, V_IP) values ('" + mkey + "','" + logContent + "','" + projectCode + "','" + userIP + "')";
msdal.ExecuteSQL(insertString, connection);
}
catch (Exception ex)
{
logger.Fatal("Log > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
msdal.Disconnect(connection);
}
}
}
}

View File

@@ -0,0 +1,375 @@
using System;
using System.Linq;
using System.Drawing;
using OfficeOpenXml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.Style;
using KART_API.Utils;
using Svg;
namespace KART_API.Services
{
public class MakeExcelService
{
public byte[] getTableExcel(string dataString, string isTurn)
{
JArray tableArray = Common.GetJArrayFromString(dataString);
string contentString = "목차";
string tableString = "테이블";
ExcelPackage ExcelPkg = new ExcelPackage();
ExcelWorksheet wsSheet1 = ExcelPkg.Workbook.Worksheets.Add(contentString);
ExcelWorksheet wsSheet2 = ExcelPkg.Workbook.Worksheets.Add(tableString);
wsSheet1.Cells.Style.Font.Name = "맑은 고딕";
wsSheet1.Cells.Style.Font.Size = 10;
wsSheet1.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
wsSheet1.Cells.Style.WrapText = false;
wsSheet2.Cells.Style.Font.Name = "맑은 고딕";
wsSheet2.Cells.Style.Font.Size = 9;
wsSheet2.Cells.Style.WrapText = true;
for (int row = 1; row <= (tableArray.Count + 4); row++)
{
wsSheet1.Row(row).Height = 20;
}
////1,1부터 시작
using (ExcelRange Rng = wsSheet1.Cells[1, 1, 4, 2])
{
Rng.Value = "목차";
Rng.Merge = true;
Rng.Style.Font.Size = 25;
Rng.Style.Font.Bold = true;
Rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
Rng.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
Rng.Style.Font.Color.SetColor(Color.FromArgb(0xFFFFFF));
Rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
Rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0x333333));
}
using (ExcelRange Rng = wsSheet1.Cells[5, 1, (5 + tableArray.Count-1), 2])
{
Rng.Style.Border.Top.Style = ExcelBorderStyle.Hair;
Rng.Style.Border.Bottom.Style = ExcelBorderStyle.Hair;
Rng.Style.Border.Right.Style = ExcelBorderStyle.Hair;
Rng.Style.Border.Left.Style = ExcelBorderStyle.Hair;
Rng.Style.Border.BorderAround(ExcelBorderStyle.Thin);
}
int tableRow = 1;
for(int i = 0; i < tableArray.Count; i++)
{
var tableJson = tableArray[i];
if (String.IsNullOrEmpty(tableJson["body"].ToString()) == false)
{
///목차
string titleString = string.Empty;
if (String.IsNullOrEmpty(Common.GetNullString(tableJson["vname"])))
{
titleString = Common.StripHTML(tableJson["head"].ToString());
}
else
{
titleString = "<표 " + tableJson["vname"] + ">" + " " + Common.StripHTML(tableJson["head"].ToString());
}
titleString = titleString.Replace("<br />", "");
var titleCell = wsSheet1.Cells[(5 + i), 1, (5 + i), 1];
var linkCell = wsSheet1.Cells[(5 + i), 2, (5 + i), 2];
titleCell.Value = titleString;
Uri url = new Uri("#'" + tableString + "'!A" + tableRow, UriKind.Relative);
linkCell.Value = "Go";
linkCell.Hyperlink = url;
linkCell.Style.Font.UnderLine = true;
linkCell.Style.Font.Color.SetColor(Color.Blue);
///목차
///테이블
JArray tableBody = Common.GetJArrayFromString(tableJson["body"].ToString());
if (tableJson["qtype"].ToString() == "single" && isTurn == "1")
{
for(int brow = 0; brow < tableBody.Count; brow++)
{
string valueString = string.Empty;
if(brow == 0)
{
valueString = "계||";
}
else
{
valueString = "100.0";
}
JObject tempRow = tableBody[brow] as JObject;
tempRow.Add("add_0", valueString);
tableBody[brow] = tempRow;
}
}
using (ExcelRange Rng = wsSheet2.Cells[tableRow, 1, tableRow, tableBody.First.SelectTokens("*").Count()])
{
Rng.Value = titleString;
Rng.Merge = true;
Rng.Style.Font.Bold = true;
tableRow++;
}
int meanPoint = 0;
int tableStartRow = tableRow;
int startRowSpan = 0;
int startColSpan = 0;
for (int row = 0; row < tableBody.Count; row++)
{
var bodyRow = tableBody[row].Values();
int col = 1;
foreach (var bodyCell in bodyRow)
{
var cellDetail = bodyCell.ToString().Split('|');
if (cellDetail.Length == 3)
{
int rowSpan = Convert.ToInt32(Common.GetNullToZero(cellDetail[1]));
int colSpan = Convert.ToInt32(Common.GetNullToZero(cellDetail[2]));
if (rowSpan > 0)
{
rowSpan = rowSpan - 1;
}
if (colSpan > 0)
{
colSpan = colSpan - 1;
}
if (row == 0 && col == 1)
{
startRowSpan = rowSpan;
startColSpan = colSpan;
}
using (ExcelRange Rng = wsSheet2.Cells[tableRow, col, tableRow + rowSpan, col + colSpan])
{
if(rowSpan > 0 || colSpan > 0)
{
Rng.Merge = true;
}
Rng.Style.Border.BorderAround(ExcelBorderStyle.Thin);
Rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
if(row > startRowSpan - 1 && col < startColSpan + 2)
{
Rng.Style.VerticalAlignment = ExcelVerticalAlignment.Top;
}
else
{
Rng.Style.VerticalAlignment = ExcelVerticalAlignment.Bottom;
}
}
}
using (ExcelRange Rng = wsSheet2.Cells[tableRow, col, tableRow, col])
{
if (cellDetail[0] == "Mean")
{
if (isTurn != "1")
{
meanPoint = tableRow;
}
else
{
meanPoint = col;
}
}
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Value = Common.StripHTML(cellDetail[0]);
}
col++;
}
tableRow++;
}
int tableMidRow = tableStartRow + startRowSpan;
int tableMidCol = 1 + startColSpan;
int tableEndRow = tableStartRow + tableBody.Count - 1;
int tableEndCol = tableBody.First.SelectTokens("*").Count();
if (String.IsNullOrEmpty(tableJson["wcr"].ToString()) == false)
{
var svgDoc = SvgDocument.FromSvg<SvgDocument>(tableJson["wcr"].ToString());
svgDoc.CustomAttributes["fill"] = "white";
SvgRectangle rect = new SvgRectangle();
rect.Fill = new SvgColourServer(Color.White);
rect.Width = svgDoc.Width;
rect.Height = svgDoc.Height;
svgDoc.Children.Insert(0, rect);
var bitmap = svgDoc.Draw();
insertPicture(wsSheet2, bitmap, tableStartRow, 1 + tableEndCol);
}
wsSheet2.Cells[tableStartRow, 1, tableMidRow, tableMidCol].Style.Border.BorderAround(ExcelBorderStyle.Thick);
wsSheet2.Cells[tableStartRow, tableMidCol + 1, tableMidRow, tableEndCol].Style.Border.BorderAround(ExcelBorderStyle.Thick);
wsSheet2.Cells[tableMidRow + 1, 1, tableEndRow, tableMidCol].Style.Border.BorderAround(ExcelBorderStyle.Thick);
wsSheet2.Cells[tableMidRow + 1, tableMidCol + 1, tableEndRow, tableEndCol].Style.Border.BorderAround(ExcelBorderStyle.Thick);
for (int row = tableMidRow + 1; row <= tableEndRow; row++)
{
for (int col = tableMidCol + 1; col <= tableEndCol; col++)
{
using (ExcelRange Rng = wsSheet2.Cells[row, col])
{
if (Common.IsNumeric(Rng.Value.ToString()))
{
if (Rng.Value.ToString().IndexOf(".") < 0)
{
///사례수
Rng.Value = "(" + Rng.Value + ")";
}
else if (isTurn != "1" && row == meanPoint || isTurn == "1" && col == meanPoint)
{
Rng.Style.Numberformat.Format = "0.00";
Rng.Value = Convert.ToDouble(Rng.Value);
}
else
{
Rng.Style.Numberformat.Format = "0.0";
Rng.Value = Convert.ToDouble(Rng.Value);
}
}
else
{
Rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
}
}
}
///테이블
tableRow++;
}
}
wsSheet1.Column(1).AutoFit();
wsSheet1.View.FreezePanes(5, 1);
return ExcelPkg.GetAsByteArray();
}
public byte[] getQuotaExcel(string dataString)
{
ExcelPackage ExcelPkg = new ExcelPackage();
JArray tableArray = Common.GetJArrayFromString(dataString);
for (int i = 0; i < tableArray.Count; i++)
{
var tableJson = tableArray[i];
string titleString = Common.StripHTML(tableJson["head"].ToString());
JArray tableBody = Common.GetJArrayFromString(tableJson["body"].ToString());
ExcelWorksheet wsSheet = ExcelPkg.Workbook.Worksheets.Add(titleString);
wsSheet.Cells.Style.Font.Name = "맑은 고딕";
wsSheet.Cells.Style.Font.Size = 9;
//wsSheet.Cells.Style.WrapText = true;
int tableRow = 1;
using (ExcelRange Rng = wsSheet.Cells[tableRow, 1, tableRow, tableBody.First.SelectTokens("*").Count()])
{
Rng.Value = titleString;
Rng.Merge = true;
Rng.Style.Font.Bold = true;
Rng.Style.Font.Size = 14;
Rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
Rng.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
tableRow++;
}
wsSheet.Row(1).Height = 30;
int tableStartRow = tableRow;
int startRowSpan = 0;
int startColSpan = 0;
for (int row = 0; row < tableBody.Count; row++)
{
var bodyRow = tableBody[row].Values();
int col = 1;
foreach (var bodyCell in bodyRow)
{
var cellDetail = bodyCell.ToString().Split('|');
if (cellDetail.Length == 3)
{
int rowSpan = Convert.ToInt32(Common.GetNullToZero(cellDetail[1]));
int colSpan = Convert.ToInt32(Common.GetNullToZero(cellDetail[2]));
if (rowSpan > 0)
{
rowSpan = rowSpan - 1;
}
if (colSpan > 0)
{
colSpan = colSpan - 1;
}
if (row == 0 && col == 1)
{
startRowSpan = rowSpan;
startColSpan = colSpan;
}
using (ExcelRange Rng = wsSheet.Cells[tableRow, col, tableRow + rowSpan, col + colSpan])
{
if (rowSpan > 0 || colSpan > 0)
{
Rng.Merge = true;
}
Rng.Style.Border.BorderAround(ExcelBorderStyle.Thin);
Rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
Rng.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
}
}
using (ExcelRange Rng = wsSheet.Cells[tableRow, col, tableRow, col])
{
string cellValue = Common.StripHTML(cellDetail[0]);
if (tableRow > tableStartRow + startRowSpan && col > 1 + startColSpan)
{
cellValue = cellValue.Substring(0, cellValue.IndexOf("/", cellValue.IndexOf("/") + 1));
}
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Value = Common.StripHTML(cellValue);
Rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
Rng.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
}
col++;
}
tableRow++;
}
int tableMidRow = tableStartRow + startRowSpan;
int tableMidCol = 1 + startColSpan;
int tableEndRow = tableStartRow + tableBody.Count - 1;
int tableEndCol = tableBody.First.SelectTokens("*").Count();
wsSheet.Cells[tableStartRow, 1, tableMidRow, tableMidCol].Style.Border.BorderAround(ExcelBorderStyle.Thick);
wsSheet.Cells[tableStartRow, tableMidCol + 1, tableMidRow, tableEndCol].Style.Border.BorderAround(ExcelBorderStyle.Thick);
wsSheet.Cells[tableMidRow + 1, 1, tableEndRow, tableMidCol].Style.Border.BorderAround(ExcelBorderStyle.Thick);
wsSheet.Cells[tableMidRow + 1, tableMidCol + 1, tableEndRow, tableEndCol].Style.Border.BorderAround(ExcelBorderStyle.Thick);
wsSheet.Cells[wsSheet.Dimension.Address].AutoFitColumns();
}
return ExcelPkg.GetAsByteArray();
}
public void insertPicture(ExcelWorksheet worksheet, Bitmap imageData, int cellY, int cellX)
{
string imgName = cellY + "_" + cellX;
var picture = worksheet.Drawings.AddPicture(imgName, imageData);
picture.SetSize(1000, 512);
picture.SetPosition(cellY - 1, 30, cellX - 1, 0);
}
}
}

View File

@@ -0,0 +1,367 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Collections.ObjectModel;
using KART_API.Utils;
using Microsoft.IdentityModel.Tokens;
namespace KART_API.Services
{
public class NlpService
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(NlpService));
public class AnalyzeResult
{
public int Id { get; set; }
public string Input { get; set; }
public List<List<Token>> Result { get; set; }
public AnalyzeResult(int Id, string Input, List<List<Token>> Result)
{
this.Id = Id;
this.Input = Input;
this.Result = Result;
}
public AnalyzeResult(int Id, string Input, List<Token> Result)
{
this.Id = Id;
this.Input = Input;
this.Result = new List<List<Token>>();
this.Result.Add(Result);
}
}
public class WordTag
{
public string Text { get; set; } = string.Empty;
public string Tag { get; set; } = string.Empty;
public WordTag(string inText, string inTag)
{
Text = inText;
Tag = inTag;
}
}
public class WordCloudTag
{
public string Text { get; set; } = string.Empty;
//public string Tag { get; set; } = string.Empty;
public string Count { get; set; } = string.Empty;
public WordCloudTag(string inText, string inTag, string inCount)
{
Text = inText;
//Tag = inTag;
Count = inCount;
}
}
public string getWordTag(string projectCode, string qid, JArray dataJson)
{
string jsonData = String.Empty;
try
{
List<string> textDataList = new List<string>();
var vArrayList = dataJson.Where(x => x.Value<JArray>(qid).IsNullOrEmpty() == false).Select(x => x.Value<JArray>(qid).Children<JObject>().Values<string>("o"));
foreach (var vArray in vArrayList)
{
textDataList.AddRange(vArray);
}
List<AnalyzeResult> resultData = WordNLP(textDataList, projectCode, qid);
string[] tags = getTags(projectCode, qid);
//var positive = resultData.Select(x => x.Result.Where(y => y.Where(z => z.tag == "VCP").Count() > 0).ToList()).Where(x => x.Count > 0).ToList();
//var negative = resultData.Select(x => x.Result.Where(y => y.Where(z => z.tag == "VCN").Count() > 0).ToList()).Where(x => x.Count > 0).ToList();
//////여기 손봐서 업그레이드 해야함
List<WordTag> wordList =new List<WordTag>();
foreach (AnalyzeResult result in resultData)
{
foreach(List<Token> tokenList in result.Result)
{
foreach (Token token in tokenList)
{
if(Array.IndexOf(tags, token.tag) > -1 && (token.tag.StartsWith("N") || token.form.Length > 1) || token.tag == "SL")
{
wordList.Add(new WordTag(token.form, token.tag));
}
}
}
}
//////여기 손봐서 업그레이드 해야함
List<WordCloudTag> cloudTagList = makeTagTable(wordList, 100);
cloudTagList.Insert(0, new WordCloudTag("Text", "Tag", "Count"));
jsonData = Common.GetJsonFromObject(cloudTagList);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return jsonData;
}
public List<AnalyzeResult> WordNLP(List<string> textDataList, string projectCode = "", string qid = "")
{
ObservableCollection<AnalyzeResult> resultData = new ObservableCollection<AnalyzeResult>();//결과???
try
{
Kiwi instKiwi;//키위 라이브러리
ModelType modelType = ModelType.SBG;//분석 모델(근거리 관계까지 추론 - 느림)
//KiwiCS.ModelType modelType = KiwiCS.ModelType.KNLM;//분석 모델(근거리 관계만 추론 - 빠름)
bool useTypoCorrection = false;//오타 수정(오래 걸림 잘 안되는듯?)
var builder = new KiwiBuilder(Common.MapPath("NlpModel/"), 0, Option.LoadDefaultDict | Option.LoadTypoDict, modelType);
builder = AddWords(builder, projectCode, qid); ////단어 추가
if (useTypoCorrection)
{
instKiwi = builder.Build(new TypoTransformer(true));////오타 수정 세팅
}
else
{
instKiwi = builder.Build();////오타 수정 세팅
}
int mode = 1;//어절:0/문장:1/줄:2/전체:3
int topN = 1;
instKiwi.IntegrateAllomorph = false;////이형태 통합
////아/어, 았/었 등의 이형태를 통합할 지 선택합니다.
MatchWord match = 0;
if (false) match |= MatchWord.NormalizeCoda;////종성우선 현상 정규화
////'먹었엌ㅋㅋ'처럼 연속하는 종성이 따라붙어 오분석이 나는 경우를 정규화합니다.
if (false) match |= MatchWord.Url;////url을 포함
if (false) match |= MatchWord.Email;////이메일을 포함
if (false) match |= MatchWord.Hashtag;////해시태그를 포함(#)
if (false) match |= MatchWord.Mention;////맨션을 포함(@+영어)
if (false) match |= MatchWord.Serial;////시리얼(일련번호)
if (false) match |= MatchWord.JoinNounPrefix;////명사+접두사
if (false) match |= MatchWord.JoinNounSuffix;////명사+접두사
if (false) match |= MatchWord.JoinVerbSuffix;////동사 파생접사
if (false) match |= MatchWord.JoinAdjSuffix;////형용사 파생 접사
foreach (string textData in textDataList)
{
foreach (var r in AnalyzeText(instKiwi, textData, mode, match, topN))
{
resultData.Add(r);
}
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return resultData.ToList();
}
private KiwiBuilder AddWords(KiwiBuilder builder, string projectCode, string qid)
{
//builder.AddWord("사랑", "NNP", 90);//// 이런식으로 추가
DataTable addWordTable = getAddWords(projectCode, qid);
foreach(DataRow addWordRow in addWordTable.Rows)
{
try
{
builder.AddWord(addWordRow["WORD_TEXT"].ToString(), addWordRow["WORD_TAG"].ToString(), Convert.ToInt32(addWordRow["WORD_SCORE"]));
}
catch(Exception ex)
{
}
}
// <단일 형태소를 추가하는 경우>
// (형태) \t (품사태그) \t (점수)
// * (점수)는 생략시 0으로 처리됩니다.
// 예) 키위 NNP -5.0
//
// <이미 존재하는 형태소의 이형태를 추가하는 경우>
// (이형태) \t (원형태소/품사태그) \t (점수)
// * (점수)는 생략시 0으로 처리됩니다.
// 예) 기위 키위/NNG -3.0
//
// <기분석 형태를 추가하는 경우>
// (형태) \t (원형태소/품사태그 + 원형태소/품사태그 + ...) \t (점수)
// * (점수)는 생략시 0으로 처리됩니다.
// 예) 사겼다 사귀/VV + 었/EP + 다/EF -1.0
//
// 현재는 공백을 포함하는 다어절 형태를 등록할 수 없습니다.
//
// <규칙 기반의 변형된 이형태를 추가하는 경우>
// (형태 규칙)$ \t (변형된 형태/품사태그) \t (점수)
// 예) 요$ 용/EF -5
return builder;
}
/// <summary>
/// 텍스트 분석기
/// </summary>
/// <param name="text">input</param>
/// <param name="mode">어절/문장/줄/전체</param>
/// <param name="match">옵션</param>
/// <param name="topN">결과 개수 몇개 까지?</param>
/// <returns>?</returns>
private IEnumerable<AnalyzeResult> AnalyzeText(Kiwi instKiwi, string text, int mode, MatchWord match, int topN = 1)
{
if (mode == 2)
{
int rid = 0;
foreach (var line in text.Trim().Split('\n'))
{
var trimmed = line.Trim();
var res = instKiwi.Analyze(trimmed, topN, match);
List<List<Token>> s = new List<List<Token>>();
foreach (var r in res)
{
if (r.morphs.Length == 0) continue;
s.Add(new List<Token>(r.morphs));
}
if (trimmed.Length == 0) continue;
yield return new AnalyzeResult(++rid, trimmed, s);
}
}
else if (mode == 3)
{
var res = instKiwi.Analyze(text, topN, match);
List<List<Token>> s = new List<List<Token>>();
foreach (var r in res)
{
if (r.morphs.Length == 0) continue;
s.Add(new List<Token>(r.morphs));
}
yield return new AnalyzeResult(1, text.Trim(), s);
}
else
{
var r = instKiwi.Analyze(text, 1, match)[0];
int wp = 0, sp = 0, cp = 0, rid = 0, c = 0;
List<Token> s = new List<Token>();
foreach (var m in r.morphs)
{
if (mode == 0 ? (wp != m.wordPosition || sp != m.sentPosition) : (sp != m.sentPosition))
{
yield return new AnalyzeResult(++rid, text.Substring(cp, (int)m.chrPosition - cp).Trim(), s);
cp = (int)m.chrPosition;
c = 0;
s = new List<Token>();
}
s.Add(m);
wp = (int)m.wordPosition;
sp = (int)m.sentPosition;
}
if (s.Count > 0)
{
yield return new AnalyzeResult(++rid, text.Substring(cp), s);
}
}
}
public string[] getTags(string projectCode, string qid)
{
List<string> tags = new List<string>();
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectReport();
try
{
string sql = string.Empty;
sql += " SELECT DISTINCT [WORD_TAG] " + Environment.NewLine;
sql += " FROM( " + Environment.NewLine;
sql += " SELECT [WORD_TAG] FROM[REPORT_KON].[dbo].[REPORT_NLP_TAG] WHERE projectCode = 'ALL' " + Environment.NewLine;
sql += " UNION " + Environment.NewLine;
sql += " SELECT [WORD_TAG] FROM[REPORT_KON].[dbo].[REPORT_NLP_TAG] WHERE projectCode = '" + projectCode + "' AND QID = 'ALL' " + Environment.NewLine;
sql += " UNION " + Environment.NewLine;
sql += " SELECT [WORD_TAG] FROM[REPORT_KON].[dbo].[REPORT_NLP_TAG] WHERE projectCode = '" + projectCode + "' AND QID = '" + qid + "' " + Environment.NewLine;
sql += " ) TAGS " + Environment.NewLine;
DataTable tagTable = msdal.GetDataTable(sql, connection);
foreach (DataRow row in tagTable.Rows)
{
tags.Add(row["WORD_TAG"].ToString());
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
msdal.Disconnect(connection);
}
return tags.ToArray();
}
public DataTable getAddWords(string projectCode, string qid)
{
DataTable addWordsTable = new DataTable();
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectReport();
try
{
string sql = string.Empty;
sql += " SELECT DISTINCT [WORD_TAG], [WORD_TEXT], [WORD_SCORE] " + Environment.NewLine;
sql += " FROM( " + Environment.NewLine;
sql += " SELECT [WORD_TAG], [WORD_TEXT], 10 as [WORD_SCORE] FROM [REPORT_KON].[dbo].[REPORT_NLP_WORD] WHERE projectCode = 'ALL' " + Environment.NewLine;
sql += " UNION " + Environment.NewLine;
sql += " SELECT [WORD_TAG], [WORD_TEXT], 50 as [WORD_SCORE] FROM [REPORT_KON].[dbo].[REPORT_NLP_WORD] WHERE projectCode = '" + projectCode + "' AND QID = 'ALL' " + Environment.NewLine;
sql += " UNION " + Environment.NewLine;
sql += " SELECT [WORD_TAG], [WORD_TEXT], 100 as [WORD_SCORE] FROM [REPORT_KON].[dbo].[REPORT_NLP_WORD] WHERE projectCode = '" + projectCode + "' AND QID = '" + qid + "' " + Environment.NewLine;
sql += " ) WORDS " + Environment.NewLine;
addWordsTable = msdal.GetDataTable(sql, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
msdal.Disconnect(connection);
}
return addWordsTable;
}
/// <summary>
/// 단어 사전을 태그화 시키는 모듈
/// </summary>
/// <param name="wordDic">단어 사전</param>
/// <returns>단어, 카운트 테이블</returns>
public List<WordCloudTag> makeTagTable(List<WordTag> wordDic, int maxCount)
{
List<WordCloudTag> cloudTagList = new List<WordCloudTag>();
var distinctDic = wordDic.Select(x => new { x.Text, x.Tag}).Distinct().ToList();
foreach (var word in distinctDic)
{
int tagCount = wordDic.Where(x => x.Text == word.Text && x.Tag == word.Tag).Count();
cloudTagList.Add(new WordCloudTag(word.Text, word.Tag, tagCount.ToString()));
}
cloudTagList = cloudTagList.OrderByDescending(x => Convert.ToInt32(x.Count)).Take(maxCount).ToList();
return cloudTagList;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,192 @@
using Accord;
using KART_API.Utils;
using Microsoft.Extensions.FileSystemGlobbing;
using Microsoft.Extensions.FileSystemGlobbing.Internal;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
namespace KART_API.Services
{
public class RegexFilterService
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(RegexFilterService));
Regex fullSyntaxRegex = new Regex(@"\[(UK|uk)\:\d+\]+(?![^\[]*\])(\[.*?\])*\s*(\[.*?\])*\s*[=<>!]+\s*(?:[\d\/\,]*("")*)");
Regex questionUniqueKeyRegex = new Regex(@"\[(UK|uk)\:\d+\]");
Regex questionIdRegex = new Regex(@"\b([A-Za-z]\w+)+(?![^\[]*\])");
Regex inValueRegex = new Regex(@"\(\s*(\d+\s*(,\s*\d+\s*)*)\)");
Regex positiveOrRegex = new Regex(@"(?<!=|!|<|>)=\s*((?:\d+\/?)+)(?![^, ]*\\,)"); //-> S_V in (1,2,3) or in (1)
Regex positiveNullRegex = new Regex(@"((?<!!=|!|<|>)=\s*""+)"); //-> S_V is null
Regex negativeOrRegex = new Regex(@"(\!\=\s*\d+(?:\,\d+)+)"); //-> (S_V != 1 or S_V != 2 or S_V != 3)
Regex negativeNullRegex = new Regex(@"(\!\=\s*""+)"); //-> S_V is not null
Regex greaterLessRegex = new Regex(@"([<>])=?");
Regex operatorValueRegex = new Regex(@"[=<>!]+\s*(?:[\d\/\,]*("")*)");
Regex valueRegex = new Regex(@"\d+");
public string makeFilterString(string projectCode, string filter) {
bool isQ_UK = true;
filter = filter.ToUpper();
//QUK[L1][T2][M1][R1]
/////filterString이 Q|로 시작하면 QUK가 아닌 QID로 작성된 필터문
if (filter.IndexOf("Q|") == 0)
{
isQ_UK = false;
filter = filter.Replace("Q|", "");
}
while (filter.IndexOf(" ") > -1)
{
filter = filter.Replace(" ", " ");
}
filter = filter.Replace("< >", "<>");
filter = filter.Replace("! =", "!=");
filter = filter.Replace("IN", "=");
filter = filter.Replace("NOT IN", "!=");
filter = filter.Replace("IS NULL", "=\"\"");
filter = filter.Replace("IS NOT NULL", "!=\"\"");
filter = inValueToValueString(filter);
string[] reservedTargetArray = new string[] { "t", "m", "r", "l" };
foreach (Match fullsyntax in fullSyntaxRegex.Matches(filter))
{
List<string> fullSyntaxJoiner = new List<string>();
string questionUK = "";
string fullsyntaxString = fullsyntax.Value;
if (isQ_UK)
{
foreach (Match qukMatch in questionUniqueKeyRegex.Matches(fullsyntaxString))
{
questionUK = Regex.Replace(qukMatch.Value.ToString().Trim(), @"\D", "");
break;
}
}
else
{
foreach (Match qukMatch in questionIdRegex.Matches(fullsyntaxString))
{
questionUK = getQuestionUK(projectCode, qukMatch.Value.ToString().Trim());
break;
}
}
foreach(string reservedTarget in reservedTargetArray)
{
Regex reservedPattern = new Regex(@"\s*\[\s*("+reservedTarget+"|"+reservedTarget.ToUpper()+@")[\d\/\s]+\s*\]\s*");
foreach(Match reservedMatch in reservedPattern.Matches(fullsyntaxString))
{
fullSyntaxJoiner.Add("JSON_CONTAINS(DT.ANS_DATA -> '\\$.\"" + questionUK + "\"[*].\"" + reservedTarget + "\"',json_array(" + inValueString(reservedMatch.Value) + "))");
}
}
foreach (Match operatorValueMatch in operatorValueRegex.Matches(fullsyntaxString))
{
string matchString = operatorValueMatch.Value.ToString().Trim();
fullSyntaxJoiner.Add(replaceLogicValueString(matchString, questionUK));
}
filter = filter.Replace(fullsyntaxString, Environment.NewLine + "(" + String.Join(" AND" + Environment.NewLine, fullSyntaxJoiner) + ")");
}
string filterString = " AND ";
filterString += filter;
return filterString;
}
private string getQuestionUK(string projectCode, string questionID)
{
string questionUK = questionID;
MYDAL mydal = new MYDAL();
var connection = mydal.ConnectNewssak();
try
{
string sqlString = "SELECT Q_UK FROM question where PRJ_CD = '" + projectCode + "' and Q_ID = '" + questionID + "'";
var returnTable = mydal.GetDataTable(sqlString, connection);
if (returnTable != null)
{
questionUK = returnTable.Rows[0][0].ToString();
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
mydal.Disconnect(connection);
}
return questionUK;
}
private String replaceLogicValueString(String operatorValueString, String questionUK)
{
///////Range에 대한 것은 추후에 추가 하도록 하자.
String returnString = "";
if (positiveOrRegex.IsMatch(operatorValueString))
{
returnString = "JSON_OVERLAPS(DT.ANS_DATA -> '$.\"" + questionUK + "\"[*].\"s\"',json_array(" + inValueString(operatorValueString) + "))";
}
else if (positiveNullRegex.IsMatch(operatorValueString))
{
returnString = "DT.ANS_DATA -> '$.\"" + questionUK + "\"[*].\"s\"' is null";
}
else if (negativeOrRegex.IsMatch(operatorValueString))
{
returnString = " ( JSON_CONTAINS(DT.ANS_DATA -> '$.\"" + questionUK + "\"[*].\"s\"',json_array(" + inValueString(operatorValueString) + ")) = false OR DT.ANS_DATA -> '$.\"" + questionUK + "\"[*].\"s\"' is null ) ";
}
else if (negativeNullRegex.IsMatch(operatorValueString))
{
returnString = "DT.ANS_DATA -> '$.\"" + questionUK + "\"[*].\"s\"' is not null";
}
else
{
Match greaterLessMatcher = greaterLessRegex.Match(operatorValueString);
if (greaterLessMatcher.Success)
{
String greatLessString = greaterLessMatcher.Value;
returnString = "EXISTS(SELECT 1 FROM JSON_TABLE( DT.ANS_DATA -> '$.\"" + questionUK + "\"', '$[*]' COLUMNS(s INT PATH '$.s')) AS jt WHERE jt.s " + greatLessString + " " + inValueString(operatorValueString) + ") = 1";
}
}
return returnString;
}
private string inValueToValueString(string filter)
{
foreach(Match inValue in inValueRegex.Matches(filter))
{
filter = filter.Replace(inValue.Value, inValue.Value.Replace("(", "").Replace(")", "").Replace(",", "/"));
}
return filter;
}
private string inValueString(string originString)
{
List<string> valueString = new List<string>();
foreach(Match valueMatch in valueRegex.Matches(originString))
{
valueString.Add(valueMatch.Value);
}
return String.Join(",", valueString);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,252 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace KART_API.Services
{
public class StatisticsService
{
/// <summary>
/// Sum값 반환
/// </summary>
/// <param name="doubleList">실수 List</param>
/// <returns>Sum값</returns>
public static double getSum(List<double> doubleList)
{
return doubleList.Sum();
}
/// <summary>
/// Max값 반환
/// </summary>
/// <param name="doubleList">실수 List</param>
/// <returns>Max값</returns>
public static double getMax(List<double> doubleList)
{
return doubleList.Max();
}
/// <summary>
/// Min값 반환
/// </summary>
/// <param name="doubleList">실수 List</param>
/// <returns>Min값</returns>
public static double getMin(List<double> doubleList)
{
return doubleList.Min();
}
/// <summary>
/// 표준편차값 반환
/// </summary>
/// <param name="doubleList">실수 List</param>
/// <returns>표준편차값</returns>
public static double getStandardDeviation(List<double> doubleList)
{
double returnValue = 0.0;
double average = doubleList.Average();
double varianceSum = 0;
foreach (double value in doubleList)
{
varianceSum += (value) * (value);
}
double varianceAverage = varianceSum / doubleList.Count;
returnValue = Math.Sqrt(varianceAverage - (average * average));
return returnValue;
}
/// <summary>
/// 최빈값 반환
/// </summary>
/// <param name="doubleList">실수 List</param>
/// <returns>최빈값</returns>
public static double getMode(List<double> doubleList)
{
double returnValue = 0.0;
returnValue = doubleList.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.First()
.Key;
return returnValue;
}
/// <summary>
/// 중위수 반환
/// </summary>
/// <param name="doubleList">실수 List</param>
/// <returns>중위수</returns>
public static double getMedian(List<double> doubleList)
{
double returnValue = 0.0;
int size = doubleList.Count;
int mid = size / 2;
doubleList.Sort();
returnValue = (size % 2 != 0) ? doubleList[mid] : (doubleList[mid] + doubleList[mid - 1]) / 2;
return returnValue;
}
/// <summary>
/// WilcoxonSignedRanks 구조
/// </summary>
public class WilcoxonSignedRanks
{
public double minusRankMean { get; set; } = 0.0;
public double plusRankMean { get; set; } = 0.0;
public double minusRankSum { get; set; } = 0.0;
public double plusRankSum { get; set; } = 0.0;
public double minRankSum { get; set; } = 0.0;
public double sampleSize { get; set; } = 0.0;
public double zValue { get; set; } = 0.0;
public double pValue { get; set; } = 0.0;
}
/// <summary>
/// WilcoxonSignedRank에 사용할 구조
/// </summary>
public class WSRList
{
public double xValue1 { get; set; } = 0.0;
public double xValue2 { get; set; } = 0.0;
public double diff { get; set; } = 0.0;
public double absDiff { get; set; } = 0.0;
}
/// <summary>
/// WilcoxonSignedRank에서 사용할 순위 구조
/// </summary>
public class RankList
{
public double value { get; set; } = 0.0;
public double rank { get; set; } = 0.0;
public double frequency { get; set; } = 0.0;
}
/// <summary>
/// WSRList 제작
/// </summary>
/// <param name="inTable">DataTable</param>
/// <param name="columName1">value1 Column Name</param>
/// <param name="columName2">value2 Column Name</param>
/// <returns>WSRList의 List</returns>
static public List<WSRList> makeWSRList(DataTable inTable, string columName1, string columName2)
{
List<WSRList> wsrList = new List<WSRList>();
foreach (DataRow inRow in inTable.Rows)
{
StatisticsService.WSRList wsrListItem = new StatisticsService.WSRList();
wsrListItem.xValue1 = Convert.ToDouble(inRow[columName1]);
wsrListItem.xValue2 = Convert.ToDouble(inRow[columName2]);
wsrList.Add(wsrListItem);
}
return wsrList;
}
/// <summary>
/// WilcoxonSignedRanksTest
/// </summary>
/// <param name="inTable">DataTable</param>
/// <param name="columName1">value1 Column Name</param>
/// <param name="columName2">value2 Column Name</param>
/// <returns>wilcoxonSignedRanks</returns>
static public WilcoxonSignedRanks getWilcoxonSignedRanksTest(DataTable inTable, string columName1 = "X1", string columName2 = "X2")
{
WilcoxonSignedRanks wilcoxonSignedRanks = new WilcoxonSignedRanks();
List<WSRList> wsrList = makeWSRList(inTable, columName1, columName2);
#region 차이, 차이 절댓값 계산
for (int i = 0; i < wsrList.Count; i++)
{
wsrList[i].diff = wsrList[i].xValue2 - wsrList[i].xValue1;
wsrList[i].absDiff = Math.Abs(wsrList[i].diff);
}
#endregion
#region 차이가 0인 샘플 삭제
wsrList = wsrList.Where(x => x.diff != 0.0).ToList();
#endregion
#region rank 기입
List<double> absDiffList = wsrList.Select(x => x.absDiff).Distinct().OrderBy(x => x).ToList();
List<RankList> rankList = new List<RankList>();
double accumulateCount = 0.0;
double frequencySum = 0.0;
for (int i = 0; i < absDiffList.Count(); i++)
{
double xValue = absDiffList[i];
double xCount = wsrList.Where(x => x.absDiff == xValue).ToList().Count();
double frequency = (Math.Pow(xCount, 3) - xCount) / 48;
RankList rankListItem = new RankList();
rankListItem.value = xValue;
rankListItem.rank = (accumulateCount + 1) + ((xCount - 1) / 2);
rankListItem.frequency = frequency;
rankList.Add(rankListItem);
frequencySum += frequency;
accumulateCount += xCount;
}
#endregion
#region 계산
double sampleSize = wsrList.Count;
double plusCount = 0.0;
double plusRankSum = 0.0;
double minusCount = 0.0;
double minusRankSum = 0.0;
double minRankSum = 0.0;
double denominator = 0.0; // 분모
double numerator = 0.0; //분자
for (int i = 0; i < wsrList.Count; i++)
{
double xRank = rankList.Where(x => x.value == wsrList[i].absDiff).Select(x => x.rank).ToList()[0];
if (wsrList[i].diff > 0)
{
plusCount++;
plusRankSum += xRank;
}
else if (wsrList[i].diff < 0)
{
minusCount++;
minusRankSum += xRank;
}
}
if (plusRankSum > minusRankSum)
{
minRankSum = minusRankSum;
}
else
{
minRankSum = plusRankSum;
}
denominator = Math.Sqrt(((sampleSize * (sampleSize + 1) * (2 * sampleSize + 1)) / 24) - frequencySum);
numerator = minRankSum - (sampleSize * (sampleSize + 1)) / 4;
#endregion
wilcoxonSignedRanks.plusRankSum = plusRankSum;
wilcoxonSignedRanks.plusRankMean = plusRankSum / plusCount;
wilcoxonSignedRanks.minusRankSum = minusRankSum;
wilcoxonSignedRanks.minusRankMean = minusRankSum / minusCount;
wilcoxonSignedRanks.minRankSum = minRankSum;
wilcoxonSignedRanks.sampleSize = sampleSize;
wilcoxonSignedRanks.zValue = numerator / denominator;
wilcoxonSignedRanks.pValue = Accord.Math.Special.Erfc(Math.Abs(wilcoxonSignedRanks.zValue) / Math.Sqrt(2));
return wilcoxonSignedRanks;
}
}
}

View File

@@ -0,0 +1,128 @@
using System;
using System.Data;
using System.Linq;
using KART_API.Dto;
using KART_API.Utils;
namespace KART_API.Services
{
public class URIService
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(URIService));
/// <summary>
/// 단축 URL 반환
/// </summary>
/// <param name="realURI">실제 URL</param>
/// <returns>단축 URL</returns>
public static string GetURIKey(string realURI, int mode, string skey, string projectTitle, string okey)
{
string returnString = string.Empty;
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectReport();
try
{
DataTable urlKeyTable = msdal.GetDataTable("select * from REPORT_URL with(nolock) where REAL_URL = '" + realURI + "' and SKEY ='"+ skey + "' and URL_OWNER ='" + okey + "' and IS_PAGE_ONLY="+mode, connection);
if (urlKeyTable.Rows.Count > 0)
{
returnString = urlKeyTable.Rows[0]["URL_KEY"].ToString();
}
else
{
DataTable urlKeysTable = msdal.GetDataTable("select URL_KEY from REPORT_URL with(nolock) ", connection);
string randomString = string.Empty;
do
{
randomString = Common.GetRandomString();
}
while (urlKeysTable.AsEnumerable().Where(dr => dr.Field<string>("URL_KEY") == randomString).ToList().Count > 0);
//while ((from DataRow dr in urlKeysTable.Rows where dr.Field<string>("URL_KEY") == randomString select dr).ToList().Count > 0);
string insertString = "insert into REPORT_URL(URL_KEY, REAL_URL, IS_PAGE_ONLY, SKEY, PROJECT_TITLE, URL_OWNER, LANDING_CNT) values ('" + randomString + "','" + realURI + "'," + mode + ",'" + skey + "','" + projectTitle + "','" + okey + "', 0)";
msdal.ExecuteSQL(insertString, connection);
returnString = randomString;
}
}
catch (Exception ex)
{
logger.Fatal("URI" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
msdal.Disconnect(connection);
}
return returnString;
}
/// <summary>
/// 실제 URL 반환
/// </summary>
/// <param name="urlKey">단축 URL의 Key값</param>
/// <param name="isCount">카운트 Update 여부</param>
/// <returns>실제 URL</returns>
public static DataTable GetRealURL(string urlKey, bool isCount)
{
DataTable urlTable = new DataTable();
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectReport();
try
{
urlTable = GetUriInfo(urlKey);
if (urlTable.Rows.Count > 0)
{
if (isCount)
{
string insertString = "update a set a.LANDING_CNT = a.LANDING_CNT + 1 from REPORT_URL a where URL_KEY = '" + urlKey + "'";
msdal.ExecuteSQL(insertString, connection);
}
}
}
catch (Exception ex)
{
logger.Fatal("URI" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
msdal.Disconnect(connection);
}
return urlTable;
}
public static DataTable GetUriInfo(string urlKey)
{
DataTable uriInfo = new DataTable();
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectReport();
try
{
uriInfo = msdal.GetDataTable("SELECT [URL_KEY],[REAL_URL],[IS_PAGE_ONLY],[SKEY], '' as [VER],[PROJECT_TITLE],[URL_OWNER] FROM REPORT_URL WHERE [URL_KEY] collate Korean_Wansung_CS_AS = '" + urlKey + "'", connection);
if (uriInfo.Rows.Count > 0)
{
projectCodeInfo projectCodeInfo = new projectCodeInfo(uriInfo.Rows[0]["SKEY"].ToString());
Common.SetEnableDataTableForEdit(ref uriInfo,0);
uriInfo.Columns["VER"].MaxLength = 50;
uriInfo.Rows[0]["VER"] = projectCodeInfo.ver;
}
}
catch (Exception ex)
{
logger.Fatal("URI" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
msdal.Disconnect(connection);
}
return uriInfo;
}
}
}

View File

@@ -0,0 +1,92 @@
using System.Data;
using System.Data.SqlTypes;
using KART_API.Utils;
namespace KART_API.Services
{
public class UserService
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(UserService));
/// <summary>
/// Login
/// </summary>
/// <param name="userEmail">ID</param>
/// <param name="userPW">PW</param>
/// <returns>User 정보</returns>
public DataTable userLogin(string userEmail, string userPW)
{
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectIntra();
string sqlString = " select p_no, p_user_mail as mail, p_name as member_name, p_depart_now + p_team_now as team, '' as member_redirect ";
sqlString += " , CASE WHEN p_depart_now + p_team_now='M101' AND p_job_now = '02' THEN 1 ELSE 2 END as is_kri ";
sqlString += " from project2.dbo.V_PERSON ";
sqlString += " where p_resign = '0' and p_pass_new is not null ";
sqlString += " and (p_user_mail = '" + userEmail + "' or p_user_mail = '" + userEmail + "@kric.com') and p_pass_new COLLATE Korean_Wansung_CS_AS = '" + userPW + "'";
DataTable resultTable = msdal.GetDataTable(sqlString, connection);
msdal.Disconnect(connection);
if (resultTable.Rows.Count < 1)
{
connection = msdal.ConnectReport();
sqlString = " SELECT 99999999 as p_no, member_mail as mail, member_name as member_name, 'CLIENT' as team, member_redirect, is_kri ";
sqlString += " FROM REPORT_MEMBER ";
sqlString += " where is_use = 1 and member_mail = '" + userEmail + "' and member_pw = '" + userPW + "' ";
resultTable = msdal.GetDataTable(sqlString, connection);
msdal.Disconnect(connection);
}
return resultTable;
}
public static string userNumber(string userEmail)
{
string userNumber = "";
if (Common.IsNumeric(userEmail))
{
userNumber = userEmail;
}
else
{
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectIntra();
string sqlString = " select p_no ";
sqlString += " from project2.dbo.V_PERSON ";
sqlString += " where p_resign = '0' and p_pass_new is not null ";
sqlString += " and (p_user_mail = '" + userEmail + "' or p_user_mail = '" + userEmail + "@kric.com')";
DataTable resultTable = msdal.GetDataTable(sqlString, connection);
msdal.Disconnect(connection);
if (resultTable.Rows.Count > 0)
{
userNumber = resultTable.Rows[0][0].ToString();
}
}
return userNumber;
}
public static string getDinIDs()
{
string returnString = string.Empty;
MSDAL msdal = new MSDAL();
var connection = msdal.ConnectIntra();
DataTable resultTable = msdal.GetDataTable("SELECT STRING_AGG(''''+p_user_mail+'''',',') as DinIDs FROM [project2].[dbo].[person] WHERE p_depart_now='S' and p_team_now in ('101','201')", connection);
msdal.Disconnect(connection);
if(resultTable.Rows.Count > 0)
{
returnString = resultTable.Rows[0][0].ToString();
}
return returnString;
}
}
}

1002
KART_API/Utils/Common.cs Normal file

File diff suppressed because it is too large Load Diff

616
KART_API/Utils/MSDAL.cs Normal file
View File

@@ -0,0 +1,616 @@
using System.Data.SqlClient;
using System.Data;
namespace KART_API.Utils
{
public class MSDAL
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MSDAL));
/// <summary>
/// Config 파일 로드
/// </summary>
/// <returns></returns>
public IConfiguration GetConfiguration()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
return builder.Build();
}
/// <summary>
/// Report DB 연결
/// </summary>
/// <returns>DB 연결 객체</returns>
public SqlConnection ConnectReport()
{
SqlConnection connection = new SqlConnection();
try
{
var configuration = GetConfiguration();
connection.ConnectionString = configuration.GetSection("ConnectionStrings").GetSection("KartString").Value;
connection.Open();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in ConnectReport : " + ex.ToString() + Environment.NewLine);
}
return connection;
}
/// <summary>
/// KON / KIWI DB 연결
/// </summary>
/// <param name="isKiwi">0:kon 1:kiwi</param>
/// <returns>DB 연결 객체</returns>
public SqlConnection ConnectKonKiwi(int isKiwi)
{
SqlConnection connection = new SqlConnection();
string connectionString = string.Empty;
try
{
var configuration = GetConfiguration();
if (isKiwi == 0)
{
connectionString = configuration.GetSection("ConnectionStrings").GetSection("KonString").Value;
}
else
{
connectionString = configuration.GetSection("ConnectionStrings").GetSection("KiwiString").Value;
}
connection.ConnectionString = connectionString;
connection.Open();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in ConnectKonKiwi : " + connectionString + "///" + ex.ToString() + Environment.NewLine);
}
return connection;
}
/// <summary>
/// 인트라넷 DB 연결
/// </summary>
/// <returns>DB 연결 객체</returns>
public SqlConnection ConnectIntra()
{
SqlConnection connection = new SqlConnection();
try
{
var configuration = GetConfiguration();
connection.ConnectionString = configuration.GetSection("ConnectionStrings").GetSection("IntraString").Value;
connection.Open();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in ConnectIntra : " + ex.ToString() + Environment.NewLine);
}
return connection;
}
/// <summary>
/// DB 연결
/// </summary>
/// <param name="connectionString">Connection String</param>
/// <returns>DB 연결 객체</returns>
public SqlConnection Connect(string connectionString)
{
SqlConnection connection = new SqlConnection();
try
{
connection.ConnectionString = connectionString;
connection.Open();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in Connect : " + ex.ToString() + Environment.NewLine);
}
return connection;
}
/// <summary>
/// DB 연결 해제
/// </summary>
/// <param name="connection">DB 연결 객체</param>
public void Disconnect(SqlConnection connection)
{
try
{
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in Disconnect : " + ex.ToString() + Environment.NewLine);
}
}
/// <summary>
/// DB접속객체에서 Procedure 실행하여 DataReader로 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <param name="sqlParameter">인수배열</param>
/// <returns>결과 행이 저장되어 있는 DataReader 객체</returns>
public SqlDataReader GetDataReader(string procedureName, SqlConnection connection, List<SqlParameter> sqlParameter)
{
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
for (int i = 0; i < sqlParameter.Count; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in GetDataReader : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return reader;
}
/// <summary>
/// 프로시저를 수행하여 DataReader로 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns>결과 행이 저장되어 있는 DataReader 객체</returns>
public SqlDataReader GetDataReaderWithProcedure(string procedureName, SqlConnection connection)
{
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in GetDataReader : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return reader;
}
/// <summary>
/// SQL문을 수행하여 DataReader로 반환
/// </summary>
/// <param name="sql">SQL문</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns>결과 행이 저장되어 있는 DataReader 객체</returns>
public SqlDataReader GetDataReader(string sql, SqlConnection connection)
{
SqlDataReader reader = null;
/*
string sessionID = hcAccessor.HttpContext.Session.Id;
//killProcessQuery(sessionID, connection);
sql = "--" + sessionID + "--" + Environment.NewLine + sql;
*/
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.Text;
reader = cmd.ExecuteReader();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in GetDataReader : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return reader;
}
/// <summary>
/// 프로시저를 수행하여 DataTable 객체 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <param name="sqlParameter">인수배열</param>
/// <returns>프로시저 수행 결과 DataTable</returns>
public DataTable GetDataTable(string procedureName, SqlConnection connection, SqlParameter[] sqlParameter)
{
DataTable dataTable = new DataTable();
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
for (int i = 0; i < sqlParameter.Length; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
dataTable.Load(reader);
reader.Close();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in GetDataTable : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return dataTable;
}
/// <summary>
/// 파라미터 없이 프로시저를 수행하여 DataTable 객체 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns></returns>
public DataTable GetDataTableNonePara(string procedureName, SqlConnection connection)
{
DataTable dataTable = new DataTable();
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
dataTable.Load(reader);
reader.Close();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in GetDataTable : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return dataTable;
}
/// <summary>
/// 프로시저를 수행하여 DataTable 객체 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <param name="sqlParameter">인수 List</param>
/// <returns></returns>
public DataTable GetDataTable(string procedureName, SqlConnection connection, List<SqlParameter> sqlParameter)
{
DataTable dataTable = new DataTable();
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
for (int i = 0; i < sqlParameter.Count; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
dataTable.Load(reader);
reader.Close();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in GetDataTable(" + procedureName + ") : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return dataTable;
}
/// <summary>
/// SQL문을 수행하여 DataTable 객체 반환
/// </summary>
/// <param name="sql">SQL문</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns>SQL문 수행 결과 DataTable</returns>
public DataTable GetDataTable(string sql, SqlConnection connection)
{
DataTable dataTable = new DataTable();
SqlDataReader reader = null;
/*
string sessionID = hcAccessor.HttpContext.Session.Id;
//killProcessQuery(sessionID, connection);
sql = "--" + sessionID + "--" + Environment.NewLine + sql;
*/
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.Text;
reader = cmd.ExecuteReader();
dataTable.Load(reader);
reader.Close();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in GetDataTable : " + Environment.NewLine + sql + Environment.NewLine + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return dataTable;
}
/// <summary>
/// 프로시저를 수행하여 DataSet 객체 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객제</param>
/// <param name="sqlParameter">인수배열</param>
/// <returns>프로시저를 수행결과 DataSet</returns>
public DataSet GetDataSet(string procedureName, SqlConnection connection, SqlParameter[] sqlParameter)
{
SqlDataAdapter adapter = null;
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
for (int i = 0; i < sqlParameter.Length; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
cmd.CommandType = CommandType.StoredProcedure;
adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in GetDataSet : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
adapter.Dispose();
}
return ds;
}
/// <summary>
/// SQL문을 수행하여 DataSet 객체 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객제</param>
/// <param name="sqlParameter">인수배열</param>
/// <returns>프로시저를 수행결과 DataSet</returns>
public DataSet GetDataSet(string sql, SqlConnection connection)
{
SqlDataAdapter adapter = null;
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.Text;
adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in GetDataSet : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
adapter.Dispose();
}
return ds;
}
/// <summary>
/// SQL문 실행
/// </summary>
/// <param name="sql">SQL문</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns>실패 : -1</returns>
public int ExecuteSQL(string sql, SqlConnection connection)
{
int affectedRow = 0;
/*
string sessionID = hcAccessor.HttpContext.Session.Id;
//killProcessQuery(sessionID, connection);
sql = "--" + sessionID + "--" + Environment.NewLine + sql;
*/
try
{
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandTimeout = 300;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception ex)
{
affectedRow = -1;
logger.Info("MSDAL class exception in ExecuteSQL : " + ex.ToString() + Environment.NewLine);
}
return affectedRow;
}
/// <summary>
/// 프로시저 수행
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <param name="sqlParameter">인수 배열</param>
/// <returns>실패 : -1</returns>
public int ExecuteStoredProcedure(string procedureName, SqlConnection connection, SqlParameter[] sqlParameter)
{
int affectedRow = -1;
SqlCommand cmd = new SqlCommand(procedureName, connection);
try
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 300;
for (int i = 0; i < sqlParameter.Length; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
affectedRow = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in ExecuteStoredProcedure : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return affectedRow;
}
/// <summary>
/// 프로시저 수행
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <param name="sqlParameter">인수 List</param>
/// <returns>실패 : -1</returns>
public int ExecuteStoredProcedure(string procedureName, SqlConnection connection, List<SqlParameter> sqlParameter)
{
int affectedRow = -1;
SqlCommand cmd = new SqlCommand(procedureName, connection);
try
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 300;
for (int i = 0; i < sqlParameter.Count; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
affectedRow = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in ExecuteStoredProcedure : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return affectedRow;
}
/// <summary>
/// 프로시저 수행
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns>실패 : -1</returns>
public int ExecuteStoredProcedure(string procedureName, SqlConnection connection)
{
int affectedRow = -1;
SqlCommand cmd = new SqlCommand(procedureName, connection);
try
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 300;
affectedRow = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in ExecuteStoredProcedure : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return affectedRow;
}
/// <summary>
/// 쿼리 강제로 KILL
/// </summary>
/// <param name="sessionID">Session ID</param>
/// <param name="connection">DB 연결 객체</param>
public void killProcessQuery(string sessionID, SqlConnection connection)
{
string killQuery = "declare @spid int" + Environment.NewLine;
killQuery += " select @spid = session_id" + Environment.NewLine;
killQuery += " from sys.dm_exec_requests handle" + Environment.NewLine;
killQuery += " outer apply sys.fn_get_sql(handle.sql_handle) spname" + Environment.NewLine;
killQuery += " where spname.text is not null" + Environment.NewLine;
killQuery += " and spname.text like '%" + sessionID + "%'" + Environment.NewLine;
killQuery += " and spname.text not like '%from sys.dm_exec_requests handle%'" + Environment.NewLine;
killQuery += " if @spid <> ''" + Environment.NewLine;
killQuery += " begin" + Environment.NewLine;
killQuery += " exec('kill '+@spid)" + Environment.NewLine;
killQuery += " end" + Environment.NewLine;
try
{
SqlCommand cmd = new SqlCommand(killQuery, connection);
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandTimeout = 300;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception ex)
{
logger.Info("MSDAL class exception in killProcessQuery : " + ex.ToString() + Environment.NewLine);
}
}
}
}

513
KART_API/Utils/MYDAL.cs Normal file
View File

@@ -0,0 +1,513 @@
using System.Data;
using MySqlConnector;
namespace KART_API.Utils
{
public class MYDAL
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MSDAL));
/// <summary>
/// Config 파일 로드
/// </summary>
/// <returns></returns>
public IConfiguration GetConfiguration()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
return builder.Build();
}
/// <summary>
/// 새싹 DB 연결
/// </summary>
/// <returns>DB 연결 객체</returns>
public MySqlConnection ConnectNewssak()
{
MySqlConnection connection = new MySqlConnection();
string connectionString = string.Empty;
try
{
var configuration = GetConfiguration();
connection.ConnectionString = configuration.GetSection("ConnectionStrings").GetSection("NewssakString").Value;
connection.Open();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in ConnectKonKiwi : " + connectionString + "///" + ex.ToString() + Environment.NewLine);
}
return connection;
}
/// <summary>
/// DB 연결
/// </summary>
/// <param name="connectionString">Connection String</param>
/// <returns>DB 연결 객체</returns>
public MySqlConnection Connect(string connectionString)
{
MySqlConnection connection = new MySqlConnection();
try
{
connection.ConnectionString = connectionString;
connection.Open();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in Connect : " + ex.ToString() + Environment.NewLine);
}
return connection;
}
/// <summary>
/// DB 연결 해제
/// </summary>
/// <param name="connection">DB 연결 객체</param>
public void Disconnect(MySqlConnection connection)
{
try
{
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in Disconnect : " + ex.ToString() + Environment.NewLine);
}
}
/// <summary>
/// DB접속객체에서 Procedure 실행하여 DataReader로 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <param name="sqlParameter">인수배열</param>
/// <returns>결과 행이 저장되어 있는 DataReader 객체</returns>
public MySqlDataReader GetDataReader(string procedureName, MySqlConnection connection, List<MySqlParameter> sqlParameter)
{
MySqlDataReader reader = null;
MySqlCommand cmd = new MySqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
for (int i = 0; i < sqlParameter.Count; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in GetDataReader : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return reader;
}
/// <summary>
/// 프로시저를 수행하여 DataReader로 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns>결과 행이 저장되어 있는 DataReader 객체</returns>
public MySqlDataReader GetDataReaderWithProcedure(string procedureName, MySqlConnection connection)
{
MySqlDataReader reader = null;
MySqlCommand cmd = new MySqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in GetDataReader : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return reader;
}
/// <summary>
/// SQL문을 수행하여 DataReader로 반환
/// </summary>
/// <param name="sql">SQL문</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns>결과 행이 저장되어 있는 DataReader 객체</returns>
public MySqlDataReader GetDataReader(string sql, MySqlConnection connection)
{
MySqlDataReader reader = null;
MySqlCommand cmd = new MySqlCommand(sql, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.Text;
reader = cmd.ExecuteReader();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in GetDataReader : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return reader;
}
/// <summary>
/// 프로시저를 수행하여 DataTable 객체 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <param name="sqlParameter">인수배열</param>
/// <returns>프로시저 수행 결과 DataTable</returns>
public DataTable GetDataTable(string procedureName, MySqlConnection connection, MySqlParameter[] sqlParameter)
{
DataTable dataTable = new DataTable();
MySqlDataReader reader = null;
MySqlCommand cmd = new MySqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
for (int i = 0; i < sqlParameter.Length; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
dataTable.Load(reader);
reader.Close();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in GetDataTable : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return dataTable;
}
/// <summary>
/// 파라미터 없이 프로시저를 수행하여 DataTable 객체 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns></returns>
public DataTable GetDataTableNonePara(string procedureName, MySqlConnection connection)
{
DataTable dataTable = new DataTable();
MySqlDataReader reader = null;
MySqlCommand cmd = new MySqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
dataTable.Load(reader);
reader.Close();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in GetDataTable : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return dataTable;
}
/// <summary>
/// 프로시저를 수행하여 DataTable 객체 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <param name="sqlParameter">인수 List</param>
/// <returns></returns>
public DataTable GetDataTable(string procedureName, MySqlConnection connection, List<MySqlParameter> sqlParameter)
{
DataTable dataTable = new DataTable();
MySqlDataReader reader = null;
MySqlCommand cmd = new MySqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
for (int i = 0; i < sqlParameter.Count; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
dataTable.Load(reader);
reader.Close();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in GetDataTable(" + procedureName + ") : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return dataTable;
}
/// <summary>
/// SQL문을 수행하여 DataTable 객체 반환
/// </summary>
/// <param name="sql">SQL문</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns>SQL문 수행 결과 DataTable</returns>
public DataTable GetDataTable(string sql, MySqlConnection connection)
{
DataTable dataTable = new DataTable();
MySqlDataReader reader = null;
MySqlCommand cmd = new MySqlCommand(sql, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.Text;
reader = cmd.ExecuteReader();
dataTable.Load(reader);
reader.Close();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in GetDataTable : " + Environment.NewLine + sql + Environment.NewLine + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return dataTable;
}
/// <summary>
/// 프로시저를 수행하여 DataSet 객체 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객제</param>
/// <param name="sqlParameter">인수배열</param>
/// <returns>프로시저를 수행결과 DataSet</returns>
public DataSet GetDataSet(string procedureName, MySqlConnection connection, MySqlParameter[] sqlParameter)
{
MySqlDataAdapter adapter = null;
DataSet ds = new DataSet();
MySqlCommand cmd = new MySqlCommand(procedureName, connection);
cmd.CommandTimeout = 300;
try
{
for (int i = 0; i < sqlParameter.Length; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
cmd.CommandType = CommandType.StoredProcedure;
adapter = new MySqlDataAdapter(cmd);
adapter.Fill(ds);
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in GetDataSet : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
adapter.Dispose();
}
return ds;
}
/// <summary>
/// SQL문을 수행하여 DataSet 객체 반환
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객제</param>
/// <param name="sqlParameter">인수배열</param>
/// <returns>프로시저를 수행결과 DataSet</returns>
public DataSet GetDataSet(string sql, MySqlConnection connection)
{
MySqlDataAdapter adapter = null;
DataSet ds = new DataSet();
MySqlCommand cmd = new MySqlCommand(sql, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.Text;
adapter = new MySqlDataAdapter(cmd);
adapter.Fill(ds);
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in GetDataSet : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
adapter.Dispose();
}
return ds;
}
/// <summary>
/// SQL문 실행
/// </summary>
/// <param name="sql">SQL문</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns>실패 : -1</returns>
public int ExecuteSQL(string sql, MySqlConnection connection)
{
int affectedRow = 0;
try
{
MySqlCommand cmd = new MySqlCommand(sql, connection);
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandTimeout = 300;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception ex)
{
affectedRow = -1;
logger.Info("MYDAL class exception in ExecuteSQL : " + ex.ToString() + Environment.NewLine);
}
return affectedRow;
}
/// <summary>
/// 프로시저 수행
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <param name="sqlParameter">인수 배열</param>
/// <returns>실패 : -1</returns>
public int ExecuteStoredProcedure(string procedureName, MySqlConnection connection, MySqlParameter[] sqlParameter)
{
int affectedRow = -1;
MySqlCommand cmd = new MySqlCommand(procedureName, connection);
try
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 300;
for (int i = 0; i < sqlParameter.Length; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
affectedRow = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in ExecuteStoredProcedure : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return affectedRow;
}
/// <summary>
/// 프로시저 수행
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <param name="sqlParameter">인수 List</param>
/// <returns>실패 : -1</returns>
public int ExecuteStoredProcedure(string procedureName, MySqlConnection connection, List<MySqlParameter> sqlParameter)
{
int affectedRow = -1;
MySqlCommand cmd = new MySqlCommand(procedureName, connection);
try
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 300;
for (int i = 0; i < sqlParameter.Count; i++)
{
cmd.Parameters.Add(sqlParameter[i]);
}
affectedRow = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in ExecuteStoredProcedure : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return affectedRow;
}
/// <summary>
/// 프로시저 수행
/// </summary>
/// <param name="procedureName">프로시저명</param>
/// <param name="connection">DB 연결 객체</param>
/// <returns>실패 : -1</returns>
public int ExecuteStoredProcedure(string procedureName, MySqlConnection connection)
{
int affectedRow = -1;
MySqlCommand cmd = new MySqlCommand(procedureName, connection);
try
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 300;
affectedRow = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
logger.Info("MYDAL class exception in ExecuteStoredProcedure : " + ex.ToString() + Environment.NewLine);
}
finally
{
cmd.Dispose();
}
return affectedRow;
}
}
}

216
KART_API/Utils/Security.cs Normal file
View File

@@ -0,0 +1,216 @@
using System.Text;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using KART_API.Dto;
namespace KART_API.Utils
{
public class Security
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Security));
private static readonly string keyString = "kriT#3415%130$^$tuDi0_Ds34155100";//32글자
private static readonly string keyString_iv = keyString.Substring(0, 16);//16byte "asxnWolsZy98kCfWuyrnqg==";
/// <summary>
/// 문자열 암호화(AES256)
/// </summary>
/// <param name="InputText">암호화 할 String</param>
/// <returns></returns>
public string encryptString(string InputText)
{
byte[] encrypted;
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Key = Encoding.UTF8.GetBytes(keyString);;
aes.IV = Encoding.UTF8.GetBytes(keyString_iv);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform enc = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, enc, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(InputText);
}
encrypted = ms.ToArray();
}
}
}
return Convert.ToBase64String(encrypted);
}
/// <summary>
/// 문자열 복호화(AES256)
/// </summary>
/// <param name="InputText">복호화 할 String</param>
/// <returns></returns>
public string decryptString(string InputText)
{
string decrypted = String.Empty;
byte[] cipher = Convert.FromBase64String(InputText);
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
aes.KeySize = 256; //AES256
aes.BlockSize = 128;
aes.Key = Encoding.UTF8.GetBytes(keyString);
aes.IV = Encoding.UTF8.GetBytes(keyString_iv);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform dec = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(cipher))
{
using (CryptoStream cs = new CryptoStream(ms, dec, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
decrypted = sr.ReadToEnd();
}
}
}
}
return decrypted;
}
public string GenerateToken(string userID, string userName, string userTeam, string isAdmin)
{
// 암호문을 바이트 배열로 변환
byte[] secretArray = Encoding.UTF8.GetBytes(keyString);
// 암호를 바탕으로 대칭키 알고리즘에 사용될 보안키 객체 생성.
SymmetricSecurityKey securityKey = new SymmetricSecurityKey(secretArray);
// 토큰 생성에 필요한 클레임과 서명 방식을 기술하는 객체
SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
{
// ClaimsIdentity(Claim[] claims) 생성자 호출
Subject = new ClaimsIdentity(
// 클레임 배열
new[] {
// Claim(string type, string value) 클레임의 유형과 값을 이용하여 클레임 객채를 생성한다.
// ClaimTypes는 클레임의 이름이 의미하는 바를 통일하도록 미리 정한 것이다.
// ClaimTypes.Name은 수혜자의 이름을 나타내기 위한 클레임 유형이다.
new Claim(ClaimTypes.Sid, userID),
new Claim(ClaimTypes.Name, userName),
new Claim(ClaimTypes.GroupSid, userTeam),
new Claim(ClaimTypes.Role, isAdmin)
}),
Expires = DateTime.UtcNow.AddHours(4),
//Expires = DateTime.UtcNow.AddSeconds(10),
// JWT의 검증서명을 만드는데 필요한 객체를 지정한다. 보안키, 알고리즘이 지정되었다
SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature)
};
// JWT 처리자 객체로 토큰 객체를 생성하고 검증하는 역할.
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
// 토큰 객체 생성
JwtSecurityToken token = handler.CreateJwtSecurityToken(descriptor);
// 토큰 객체를 직렬화하여 반환.
return handler.WriteToken(token);
}
private static ClaimsPrincipal GetPrincipal(string token)
{
try
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token);
if (jwtToken == null)
return null;
byte[] secretArray = Encoding.UTF8.GetBytes(keyString);
TokenValidationParameters parameters = new TokenValidationParameters()
{
IssuerSigningKey = new SymmetricSecurityKey(secretArray),
ValidateIssuerSigningKey = true,
ValidateIssuer = false,
ValidateAudience = false,
// set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
ClockSkew = TimeSpan.Zero
};
SecurityToken securityToken;
ClaimsPrincipal principal = tokenHandler.ValidateToken(token, parameters, out securityToken);
return principal;
}
catch (Exception)
{
return null;
}
}
public static UserInfo ValidateToken(string token)
{
ClaimsPrincipal entity = GetPrincipal(token);
UserInfo userInfo;
if (entity == null)//KART 토큰을 해석하지 못하면 새싹 토큰으로 취급
{
JObject requestHeader = new JObject();
requestHeader.Add("Authorization", "Bearer "+token);
string rquestValue = Common.callWebRequest("GET", "https://seed.kric.com:7443/api/v1/member/getInfo", requestHeader, null);
if (Common.IsJson(rquestValue))
{
JObject requestJson = JObject.Parse(rquestValue);
userInfo = new UserInfo(
requestJson["member_id"].ToString(),
requestJson["member_name"].ToString(),
requestJson["teamInfo"]["groupCode"].ToString() + requestJson["teamInfo"]["code"].ToString(),
requestJson["is_admin"].ToString()
);/////ADMIN 등급 수정필요
return userInfo;
}
return null;
}
ClaimsIdentity identity;
try
{
identity = (ClaimsIdentity)entity.Identity;
}
catch (NullReferenceException)
{
return null;
}
// Claim nameClaim = entity.FindFirst(ClaimTypes.Name); 도 동일한 효과
Claim idClaim = identity.FindFirst(ClaimTypes.Sid);
Claim nameClaim = identity.FindFirst(ClaimTypes.Name);
Claim teamClaim = identity.FindFirst(ClaimTypes.GroupSid);
Claim roleClaim = identity.FindFirst(ClaimTypes.Role);
userInfo = new UserInfo(idClaim.Value, nameClaim.Value, teamClaim.Value, roleClaim.Value);
return userInfo;
}
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

17
KART_API/appsettings.json Normal file
View File

@@ -0,0 +1,17 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"IntraString": "Persist Security Info=True;Data Source=1.235.195.34;Initial Catalog=project2;User ID=sa;Password=krco#51304;",
"KartString": "Persist Security Info=True;Data Source=1.235.195.8,20022;Initial Catalog=REPORT_KON;User Id=kon;Password=kon#51304;",
"KonString": "Persist Security Info=True;Data Source=1.235.195.8,20022;Initial Catalog=KON;User Id=kon;Password=kon#51304;",
"KiwiString": "Persist Security Info=True;Data Source=mssql-7sq2n-kr.vpc-pub-cdb.ntruss.com;Initial Catalog=konkiwi;User Id=kadmin;Password=it#51304;",
"NewssakString": "Server=db-md87m-kr.vpc-pub-cdb.ntruss.com;Port=3306;User ID=newssak;Password=ns#51304;Database=newssak;"
},
"AllowedHosts": "*"
}

BIN
KART_API/kiwi.dll Normal file

Binary file not shown.

25
KART_API/log4net.config Normal file
View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs/" />
<datepattern value="yyyy-MM-dd.'txt'"/>
<maxSizeRollBackups value="10" />
<maximumFileSize value="1024KB" />
<staticlogfilename value="false"/>
<appendtofile value="true"/>
<rollingstyle value="Composite"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>