firts commit

This commit is contained in:
2025-10-24 10:25:54 +09:00
commit edf42de8f9
45 changed files with 133446 additions and 0 deletions

View File

@@ -0,0 +1,941 @@
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace REPORT_API_ver6.Services
{
public class Common
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Common));
/// <summary>
/// Request 변수값 반환
/// </summary>
/// <param name="fieldName">필드명</param>
/// <returns>Request 변수값</returns>
public static string GetRequestValue(string fieldName)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
string returnValue = string.Empty;
try
{
returnValue = hcAccessor.HttpContext.Request.Query[fieldName].ToString();
if (String.IsNullOrEmpty(returnValue))
{
returnValue = hcAccessor.HttpContext.Request.Form[fieldName].ToString();
}
}
catch (Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return returnValue;
}
/// <summary>
/// Request 변수값 반환 없으면 0
/// </summary>
/// <param name="fieldName">필드명</param>
/// <returns>Request 변수값</returns>
public static string GetRequestValueZero(string fieldName)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
var returnValue = "";
try
{
returnValue = hcAccessor.HttpContext.Request.Query[fieldName].ToString();
if (String.IsNullOrEmpty(returnValue))
{
returnValue = hcAccessor.HttpContext.Request.Form[fieldName].ToString();
}
}
catch (Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
if (String.IsNullOrEmpty(returnValue) == true)
{
returnValue = "0";
}
return returnValue;
}
/// <summary>
/// URL 파라미터 값 반환
/// </summary>
/// <param name="url">URL</param>
/// <param name="key">필드명</param>
/// <returns>파라미터 값</returns>
public static string getParamInURL(string url, string key)
{
string returnString = string.Empty;
Uri uri = new Uri(url);
var queryDictionary = HttpUtility.ParseQueryString(uri.Query);
returnString = GetNullString(queryDictionary[key]);
return returnString;
}
/// <summary>
/// NULL 값을 0으로 변환
/// </summary>
/// <param name="value">값</param>
/// <returns>입력 값</returns>
public static string GetNullToZero(object value)
{
var returnValue = "0";
if (value != null && value.ToString() != "")
{
returnValue = value.ToString();
}
return returnValue;
}
public static string ReplaceUnicodeEmpty(string inputString)
{
return Regex.Replace(inputString, @"(\\U\d*)", string.Empty);
}
/// <summary>
/// string을 JObject로 변환
/// </summary>
/// <param name="jsonString">JSON 형식 문자열</param>
/// <returns>JObject</returns>
public static JObject GetJObjectFromString(string jsonString)
{
JObject pJson = new JObject();
try
{
if (String.IsNullOrEmpty(jsonString) == false)
{
pJson = JObject.Parse(jsonString);
}
}
catch(Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return pJson;
}
/// <summary>
/// string을 JArray로 변환
/// </summary>
/// <param name="jsonString">JSON 형식 문자열</param>
/// <returns>JArray</returns>
public static JArray GetJArrayFromString(string jsonString)
{
JArray pJson = new JArray();
try
{
if (String.IsNullOrEmpty(jsonString) == false)
{
pJson = JArray.Parse(jsonString);
}
}
catch (Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return pJson;
}
/// <summary>
/// JArray 머지
/// </summary>
/// <param name="oldArray">기존 JArray</param>
/// <param name="newArray">추가할 JArray</param>
/// <returns>JArray</returns>
public static JArray mergeJarray(JArray oldArray, JArray newArray)
{
JArray returnArray = oldArray;
if (oldArray != null)
{
/*
IDKEY를 기준으로
for (int i = 0; i < newArray.Count; i++)
{
if (returnArray.Where(x => x.Value<string>("IDKEY") == newArray[i]["IDKEY"].ToString()).Count() < 1)
{
returnArray.Add(newArray[i]);
}
}
*/
returnArray.Merge(newArray);
}
else
{
returnArray = newArray;
}
return returnArray;
}
/// <summary>
/// JSON여부 판단
/// </summary>
/// <param name="jsonString">JSON 형식 문자열</param>
/// <returns>true / false</returns>
public static bool IsJson(string jsonString)
{
bool isJson = false;
try
{
if (jsonString.StartsWith("{") && jsonString.EndsWith("}"))
{
JObject.Parse(jsonString);
isJson = true;
}
else if (jsonString.StartsWith("[") && jsonString.EndsWith("]"))
{
JArray.Parse(jsonString);
isJson = true;
}
}
catch (Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return isJson;
}
/// <summary>
/// Javascript Block 생성
/// </summary>
/// <param name="script">Javascript 내용</param>
/// <returns>Javascript 문자열</returns>
public static string GetJavascriptBlock(string script)
{
var scriptBlock = new StringBuilder(200);
scriptBlock.Append("<script language=\"javascript\" type=\"text/javascript\">" + Environment.NewLine);
scriptBlock.Append(script);
scriptBlock.Append("</script>" + Environment.NewLine);
return scriptBlock.ToString();
}
/// <summary>
/// DataTable로 부터 JSON 형식 생성
/// </summary>
/// <param name="dataTable">Data</param>
/// <returns>JSON 형식 문자열</returns>
public static string GetJsonFromObject(object Data)
{
return JsonConvert.SerializeObject(Data, Formatting.Indented);
}
public static string GetStringFromJson(JObject jobject)
{
string returnString = jobject.ToString().Replace(Environment.NewLine, "");
while (returnString.IndexOf(" ") > -1)
{
returnString = returnString.Replace(" ", "");
}
return returnString;
}
/// <summary>
/// JArray를 DataTable로 변환
/// </summary>
/// <param name="jArray">DataTable로 변환할 JArray</param>
/// <returns>변환된 DataTable</returns>
public static DataTable GetDataTableFromJArray(JArray jArray)
{
var result = new DataTable();
//Initialize the columns, If you know the row type, replace this
foreach (var row in jArray)
{
foreach (var jToken in row)
{
var jproperty = jToken as JProperty;
if (jproperty == null) continue;
if (result.Columns[jproperty.Name] == null)
result.Columns.Add(jproperty.Name, typeof(string));
}
}
foreach (var row in jArray)
{
var datarow = result.NewRow();
foreach (var jToken in row)
{
var jProperty = jToken as JProperty;
if (jProperty == null) continue;
datarow[jProperty.Name] = jProperty.Value.ToString();
}
result.Rows.Add(datarow);
}
return result;
}
/// <summary>
/// 지정된 경로와 파일명을 전달하며 고유한 파일명 반환
/// </summary>
/// <param name="uploadFolder">업로드 경로</param>
/// <param name="fileName">파일명</param>
/// <returns>고유한 파일명</returns>
public static string GetUniqueFileName(string uploadFolder, string fileName)
{
var uploadFile = new FileInfo(uploadFolder + fileName);
var fileIndex = 0;
while (uploadFile.Exists)
{
string[] filearray = uploadFile.Name.Split(' ');
if (filearray.Length > 1)
{
fileIndex = Int32.Parse(Regex.Replace(filearray[1], @"[\-()" + uploadFile.Extension + "]", string.Empty));
}
fileIndex++;
var file = String.Format("{0}({1}){2}", filearray[0].Replace(uploadFile.Extension, String.Empty), fileIndex.ToString(), uploadFile.Extension);
return GetUniqueFileName(uploadFolder, file);
}
return uploadFolder + fileName;
}
/// <summary>
/// 파일 경로에서 파일명만 추출
/// </summary>
/// <param name="fileFullName">파일 경로</param>
/// <returns>경로가 제거된 파일명</returns>
public static string GetOnlyFileName(string fileFullName)
{
if (fileFullName.Contains("\\") == true)
{
fileFullName = fileFullName.Substring(fileFullName.LastIndexOf("\\") + 1);
}
return fileFullName;
}
/// <summary>
/// upload_data 디렉토리에 파일 업로드
/// </summary>
/// <param name="fileName">파일명</param>
/// <param name="sourceFile">파일</param>
/// <returns>저장된 파일 경로</returns>
public static string uploadFile(string fileName, IFormFile sourceFile)
{
fileName = Common.GetOnlyFileName(fileName);
string outFileName = MapPath("upload_data") + "\\" + fileName;
using (FileStream output = System.IO.File.Create(outFileName))
{
sourceFile.CopyTo(output);
}
return outFileName;
}
/// <summary>
/// Text(탭으로 분리) OR CSV형태의 파일을 DataTable로 변환
/// </summary>
/// <param name="filepath">파일 경로</param>
/// <param name="extension">확장자</param>
/// <param name="header">헤더 목록</param>
/// <returns>변환된 DataTable</returns>
public static DataTable textToDataTable(string filepath, string extension = ".txt", string[] header = null)
{
DataTable returnTable = new DataTable();
StreamReader uploadStream = new StreamReader(filepath, Encoding.GetEncoding("euc-kr"));
try
{
string sep = "\t";
if (extension.ToLower() == ".csv")
{
sep = ",";
}
if (header != null)
{
Common.tableAddColumn(returnTable, header);
}
else
{
string headerString = uploadStream.ReadLine();
Common.tableAddColumn(returnTable, headerString.Split(sep.ToCharArray()));
}
string readString = String.Empty;
while ((readString = uploadStream.ReadLine()) != null)
{
string[] valueArray = readString.Split(sep.ToCharArray());
returnTable.Rows.Add(valueArray);
}
uploadStream.Close();
}
catch (Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnTable = new DataTable();
Common.tableAddColumn(returnTable, new string[] { "error" });
returnTable.Rows.Add(new string[] { ex.Message });
}
finally
{
uploadStream.Close();
}
return returnTable;
}
/// <summary>
/// 엑셀 파일을 DataTable로
/// </summary>
/// <param name="filepath">파일 경로</param>
/// <param name="sheetName">변환할 Sheet Name</param>
/// <param name="header">특별한 header가 있으면 설정</param>
/// <returns>변환된 DataTable</returns>
public static DataTable ExceltoDataTable(string filepath, string sheetName = "", string[] header = null)
{
DataTable returnTable = new DataTable();
try
{
FileInfo importFile = new FileInfo(filepath);
using (var excelPackage = new ExcelPackage(importFile))
{
using (var stream = File.OpenRead(filepath))
{
excelPackage.Load(stream);
}
if (String.IsNullOrEmpty(sheetName))
{
sheetName = excelPackage.Workbook.Worksheets.First().Name;
}
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[sheetName];
if (header != null)
{
Common.tableAddColumn(returnTable, header);
}
else
{
foreach (var firstRowCell in worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column])
{
returnTable.Columns.Add(firstRowCell.Text);
}
}
for (int rowNum = 2; rowNum <= worksheet.Dimension.End.Row; rowNum++)
{
var wsRow = worksheet.Cells[rowNum, 1, rowNum, worksheet.Dimension.End.Column];
DataRow row = returnTable.Rows.Add();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
}
}
}
catch (Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnTable = new DataTable();
Common.tableAddColumn(returnTable, new string[] { "error" });
returnTable.Rows.Add(new string[] { ex.Message });
}
return returnTable;
}
/// <summary>
/// DataTable을 Excel로 변환
/// </summary>
/// <param name="excelTable">변환할 DataTable</param>
/// <param name="sheetName">만들 Sheet Name / 기본값 : Sheet1</param>
/// <returns>Excel파일</returns>
public static byte[] DataTableToExcel(DataTable excelTable, string sheetName = "Sheet1")
{
ExcelPackage excelPackage = new ExcelPackage();
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add(sheetName);
worksheet.Cells["A1"].LoadFromDataTable(excelTable, true);
return excelPackage.GetAsByteArray();
}
/// <summary>
/// DataTable을 CSV로 변환
/// </summary>
/// <param name="csvTable">변환할 DataTable</param>
/// <returns>FileByteArray</returns>
public static byte[] DataTableToCSV(DataTable csvTable)
{
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = csvTable.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in csvTable.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
string tempFileName = GetRandomString() + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".csv";
File.WriteAllText(Common.MapPath("temp_data/"+ tempFileName), sb.ToString());
byte[] fileByteArray = File.ReadAllBytes(Common.MapPath("temp_data/"+ tempFileName));
File.Delete(Common.MapPath("temp_data/" + tempFileName));
return fileByteArray;
}
/// <summary>
/// Null 이 아닌경우 String 으로 변환 Null은 공백
/// </summary>
/// <param name="inputObject">입력값</param>
/// <returns>변환된 String</returns>
public static string GetNullString(object inputObject)
{
var returnString = string.Empty;
if (inputObject != null)
{
returnString = inputObject.ToString();
}
return returnString;
}
/// <summary>
/// 특수 문자열
/// </summary>
/// <param name="strLen">만들 문자 길이 / 기본값 : 8</param>
/// <returns></returns>
public static string GetRandomString(int strLen = 8)
{
Random rand = new Random();
string returnString = string.Empty;
string sourceString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < strLen; i++)
{
int randNumber = rand.Next(sourceString.Length);
returnString += sourceString.Substring(randNumber, 1);
}
return returnString;
}
/// <summary>
/// 이미지 태그 제거
/// </summary>
/// <param name="text">문자열</param>
/// <returns>이미지 태그가 제거된 문자열</returns>
public static string StripImgTag(string text)
{
return Regex.Replace(text, @"<img\s[^>]*>(?:\s*?</img>)?", "", RegexOptions.IgnoreCase);
}
/// <summary>
/// HTML 태그 제거
/// </summary>
/// <param name="input">문자열</param>
/// <returns>HTML 태크가 제거된 문자열</returns>
public static string StripHTML(string input)
{
input = StripHTMLChracters(input);
return Regex.Replace(input, "<[a-zA-Z/].*?>", String.Empty);
}
/// <summary>
/// HTML 엔티티 치환
/// </summary>
/// <param name="input">문자열</param>
/// <returns>HTML 엔티티 치환된 문자열</returns>
public static string StripHTMLChracters(string input)
{
return HttpUtility.HtmlDecode(input);
}
/// <summary>
/// 접속 IP 반환
/// </summary>
/// <returns>접속IP</returns>
public static string GetRemoteIP()
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
var ip = hcAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
ip = ip.Split(',').Last().Trim();
return ip;
}
/// <summary>
/// 숫자 여부 판단
/// </summary>
/// <param name="s">문자열</param>
/// <returns>true / false</returns>
public static bool IsNumeric(string s)
{
float output;
return float.TryParse(s, out output);
}
/// <summary>
/// 반올림 형식 반환
/// </summary>
/// <param name="roundPointer">반올림 위치</param>
/// <returns>반올림 형식 문자열</returns>
public static string makeRoundFormat(int roundPointer)
{
string formatString = "#0";
for (int i = 0; i < roundPointer; i++)
{
if (i == 0)
{
formatString += ".";
}
formatString += "0";
}
return formatString;
}
/// <summary>
/// 반올림
/// </summary>
/// <param name="inString">반올림 할 숫자(문자열)</param>
/// <param name="roundPointer">반올림 위치</param>
/// <returns>반올림 된 문자열</returns>
public static string RoundValue(string inString, int roundPointer)
{
if (IsNumeric(inString) && roundPointer > -1)
{
string formatString = makeRoundFormat(roundPointer);
double pointConstant = 1;
for (int i = 0; i < roundPointer; i++)
{
pointConstant = pointConstant * 10;
}
inString = (Math.Round(Convert.ToDouble(inString) * pointConstant, MidpointRounding.AwayFromZero) / pointConstant).ToString(formatString);
}
return inString;
}
/// <summary>
/// 반올림
/// </summary>
/// <param name="inDouble">반올림 할 숫자(실수)</param>
/// <param name="roundPointer">반올림 위치</param>
/// <returns>반올림 된 문자열</returns>
public static string RoundValue(double inDouble, int roundPointer)
{
string returnValue = inDouble.ToString();
if (roundPointer > -1)
{
string formatString = makeRoundFormat(roundPointer);
double pointConstant = 1;
for (int i = 0; i < roundPointer; i++)
{
pointConstant = pointConstant * 10;
}
returnValue = (Math.Round(inDouble * pointConstant, MidpointRounding.AwayFromZero) / pointConstant).ToString(formatString);
}
return returnValue;
}
/// <summary>
/// 초를 시분초로 변경한 값
/// </summary>
/// <param name="secondString">초</param>
/// <returns>시:분:초</returns>
public static string SecondToTime(string secondString)
{
string timeString = string.Empty;
try
{
if (IsNumeric(secondString))
{
int num = Convert.ToInt32(secondString);
int hours = 0;
int minute = 0;
int second = 0;
//시간공식
hours = num / 3600;//시 공식
minute = num % 3600 / 60;//분을 구하기위해서 입력되고 남은값에서 또 60을 나눈다.
second = num % 3600 % 60;//마지막 남은 시간에서 분을 뺀 나머지 시간을 초로 계산함
timeString = hours.ToString("#00") + ":" + minute.ToString("00") + ":" + second.ToString("00");
}
}
catch (Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return timeString;
}
/// <summary>
/// 문자열 배열을 정수형 배열로 변환
/// </summary>
/// <param name="inputArray">문자열 배열</param>
/// <returns>정수형 배열</returns>
public static int[] ConvertIntArray(string[] inputArray)
{
List<int> intList = new List<int>();
int[] returnArray = new int[0];
try
{
for (int i = 0; i < inputArray.Length; i++)
{
if (Common.IsNumeric(inputArray[i]))
{
intList.Add(Convert.ToInt32(inputArray[i]));
}
}
returnArray = intList.Distinct().ToArray();
}
catch (Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return returnArray;
}
/// <summary>
/// 문자열 배열을 실수형 배열로 변환
/// </summary>
/// <param name="inputArray">문자열 배열</param>
/// <returns>정수형 배열</returns>
public static double[] ConvertDoubleArray(string[] inputArray)
{
List<double> doubleList = new List<double>();
double[] returnArray = new double[0];
try
{
for (int i = 0; i < inputArray.Length; i++)
{
if (Common.IsNumeric(inputArray[i]))
{
doubleList.Add(Convert.ToDouble(inputArray[i]));
}
}
returnArray = doubleList.Distinct().ToArray();
}
catch (Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return returnArray;
}
/// <summary>
/// DataTable Row 위치 옮기기
/// </summary>
/// <param name="listTable">Row 위치를 수정할 DataTable</param>
/// <param name="query">Row를 찾을 Query</param>
/// <param name="rowOrder">옮길 Row 위치</param>
public static void ReorderDataTableRow(ref DataTable listTable, string query, int rowOrder)
{
if (rowOrder < 0)
{
rowOrder = listTable.Rows.Count + rowOrder;
}
DataRow selectRow = listTable.Select(query)[0];
DataRow insertRow = listTable.NewRow();
insertRow.ItemArray = selectRow.ItemArray;
listTable.Rows.Remove(selectRow);
listTable.Rows.InsertAt(insertRow, rowOrder);
}
/// <summary>
/// DataTable을 수정 가능한 형태로 변경
/// </summary>
/// <param name="listTable">변경할 DataTable</param>
/// <returns></returns>
public static DataTable SetEnableDataTableForEdit(DataTable listTable)
{
foreach (DataColumn col in listTable.Columns)
{
col.DataType = typeof(String);
col.ReadOnly = false;
}
return listTable;
}
/// <summary>
/// DataTable을 수정 가능한 형태로 변경
/// </summary>
/// <param name="listTable">변경할 DataTable</param>
/// <param name="changeDataType">1인 경우 모든 칼럼을 String으로 변경</param>
public static void SetEnableDataTableForEdit(ref DataTable listTable, short changeDataType)
{
foreach (DataColumn col in listTable.Columns)
{
if (changeDataType == 1)
{
col.DataType = typeof(String);
}
col.ReadOnly = false;
}
}
/// <summary>
/// DataTable 생성
/// </summary>
/// <param name="columnName">Column Name들</param>
/// <returns>columnName을 Header로 생성된 DataTable</returns>
public static DataTable makeDataTable(string[] columnName)
{
DataTable returnTable = new DataTable();
for (int i = 0; i < columnName.Length; i++)
{
returnTable.Columns.Add(columnName[i], typeof(String));
}
return returnTable;
}
/// <summary>
/// DataTable에 Column추가(string)
/// </summary>
/// <param name="returnTable">Column을 추가할 DataTable</param>
/// <param name="columnName">추가할 Column Name들</param>
public static void tableAddColumn(DataTable returnTable, string[] columnName)
{
for (int i = 0; i < columnName.Length; i++)
{
returnTable.Columns.Add(columnName[i], typeof(String));
}
}
/// <summary>
/// DataTable에서 컬럼 제거
/// </summary>
/// <param name="returnTable">Column을 제거할 DataTable</param>
/// <param name="columnName">제거할 Column Name들</param>
public static void tableRemoveColumn(DataTable returnTable, string[] columnName)
{
for (int i = 0; i < columnName.Length; i++)
{
returnTable.Columns.Remove(columnName[i]);
}
}
/// <summary>
/// DataTable의 Column Name들 반환
/// </summary>
/// <param name="dataTable">Column Name을 반환할 Table</param>
/// <returns>문자열 배열 형태의 Column Name들</returns>
public static string[] getColumnNames(DataTable dataTable)
{
string[] returnArray = new string[dataTable.Columns.Count];
for (int i = 0; i < dataTable.Columns.Count; i++)
{
returnArray[i] = dataTable.Columns[i].ColumnName;
}
return returnArray;
}
/// <summary>
/// 서버 로컬 Path 반환
/// </summary>
/// <param name="path">서버안의 Path</param>
/// <returns>서버 Path</returns>
public static string MapPath(string path)
{
return Path.Combine((string)AppDomain.CurrentDomain.GetData("ContentRootPath"), path);
}
public static string callWebRequest(string requestMethod, string reuqestURL, JObject headerJson, JObject bodyJson)
{
string responseFromServer = string.Empty;
try
{
WebRequest request = WebRequest.Create(reuqestURL);
request.Method = requestMethod.ToUpper();
request.ContentType = "application/json";
foreach(var jsonElement in headerJson)
{
request.Headers[jsonElement.Key] = jsonElement.Value.ToString();
}
byte[] bytes = new byte[0];
if(bodyJson != null)
{
bytes = Encoding.ASCII.GetBytes(GetStringFromJson(bodyJson));
request.ContentLength = bytes.Length; // 바이트수 지정
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bytes, 0, bytes.Length);
}
}
using (WebResponse response = request.GetResponse())
using (Stream dataStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(dataStream))
{
responseFromServer = reader.ReadToEnd();
}
}
catch (Exception ex)
{
logger.Fatal("Common" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return responseFromServer;
}
}
}

View File

@@ -0,0 +1,620 @@
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Data.SqlClient;
using System.Data;
namespace REPORT_API_ver6.Services
{
public class DAL
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(DAL));
/// <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("ReportString").Value;
connection.Open();
}
catch (Exception ex)
{
logger.Info("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL 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("DAL class exception in killProcessQuery : " + ex.ToString() + Environment.NewLine);
}
}
}
}

View File

@@ -0,0 +1,743 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
using System.Collections.Generic;
namespace REPORT_API_ver6.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,81 @@
using System;
namespace REPORT_API_ver6.Services
{
public class Log
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Log));
/// <summary>
/// 로그인 로그 기록
/// </summary>
/// <param name="userEmail">User</param>
public static void insertLoginLog(string userEmail)
{
DAL dal = new DAL();
var connection = dal.ConnectReport();
try
{
string sqlString = " INSERT INTO dbo.TB_LOGIN_LOG(M_USER, L_IP) VALUES('" + userEmail + "', '" + Common.GetRemoteIP() + "'); ";
dal.ExecuteSQL(sqlString, connection);
dal.Disconnect(connection);
}
catch (Exception ex)
{
logger.Fatal("Log > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
}
public static void InsertSiteLog(string mkey, string pkey, string logTitle, string logContent)
{
DAL dal = new DAL();
var connection = dal.ConnectReport();
try
{
string logString = "{\"PKEY\":\"" + pkey + "\", \"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 + "')";
dal.ExecuteSQL(insertString, connection);
}
catch (Exception ex)
{
logger.Fatal("Log > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
}
/// <summary>
/// Visit Log 작성
/// </summary>
/// <param name="mkey">User Key</param>
/// <param name="logContent">로그 내용</param>
public static void InsertVisitLog(string mkey, string pkey, string logContent)
{
DAL dal = new DAL();
var connection = dal.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 + "','" + pkey + "','" + userIP + "')";
dal.ExecuteSQL(insertString, connection);
}
catch (Exception ex)
{
logger.Fatal("Log > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
}
}
}

View File

@@ -0,0 +1,374 @@
using System;
using System.Linq;
using System.Drawing;
using OfficeOpenXml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.Style;
using Svg;
namespace REPORT_API_ver6.Services
{
public class MakeExcel
{
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,365 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Collections.ObjectModel;
namespace REPORT_API_ver6.Services
{
public class NLP
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(NLP));
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 pkey, string qid, JArray dataJson)
{
string jsonData = String.Empty;
try
{
List<string> keyList = dataJson.Children<JObject>().Properties().Select(x => x.Name).Distinct().Where(x => x.StartsWith(qid + "_") || x == qid).ToList<string>();
List<string> textDataList = new List<string>();
foreach (var key in keyList)
{
textDataList.AddRange(dataJson.Where(x => x.Value<string>(key) != null).Select(x => Common.StripHTMLChracters(x.Value<string>(key).Replace("¸", ","))).ToList<string>());
}
List<AnalyzeResult> resultData = WordNLP(textDataList, pkey, qid);
string[] tags = getTags(pkey, 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 pkey = "", 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("nlp_model/"), 0, Option.LoadDefaultDict | Option.LoadTypoDict, modelType);
builder = AddWords(builder, pkey, 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 pkey, string qid)
{
//builder.AddWord("사랑", "NNP", 90);//// 이런식으로 추가
DataTable addWordTable = getAddWords(pkey, 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 pkey, string qid)
{
List<string> tags = new List<string>();
DAL dal = new DAL();
var connection = dal.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 PKEY = 'ALL' " + Environment.NewLine;
sql += " UNION " + Environment.NewLine;
sql += " SELECT[WORD_TAG] FROM[REPORT_KON].[dbo].[REPORT_NLP_TAG] WHERE PKEY = '" + pkey + "' AND QID = 'ALL' " + Environment.NewLine;
sql += " UNION " + Environment.NewLine;
sql += " SELECT[WORD_TAG] FROM[REPORT_KON].[dbo].[REPORT_NLP_TAG] WHERE PKEY = '" + pkey + "' AND QID = '" + qid + "' " + Environment.NewLine;
sql += " ) TAGS " + Environment.NewLine;
DataTable tagTable = dal.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
{
dal.Disconnect(connection);
}
return tags.ToArray();
}
public DataTable getAddWords(string pkey, string qid)
{
DataTable addWordsTable = new DataTable();
DAL dal = new DAL();
var connection = dal.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 PKEY = '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 PKEY = '" + pkey + "' 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 PKEY = '" + pkey + "' AND QID = '" + qid + "' " + Environment.NewLine;
sql += " ) WORDS " + Environment.NewLine;
addWordsTable = dal.GetDataTable(sql, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,219 @@
using System;
using System.IO;
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 REPORT_API_ver6.Models;
namespace REPORT_API_ver6.Services
{
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"]["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,252 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace REPORT_API_ver6.Services
{
public class Statistics
{
/// <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)
{
Statistics.WSRList wsrListItem = new Statistics.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,118 @@
using System;
using System.Data;
using System.Linq;
namespace REPORT_API_ver6.Services
{
public class URI
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(URI));
/// <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;
DAL dal = new DAL();
var connection = dal.ConnectReport();
try
{
DataTable urlKeyTable = dal.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 = dal.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)";
dal.ExecuteSQL(insertString, connection);
returnString = randomString;
}
}
catch (Exception ex)
{
logger.Fatal("URI" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.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();
DAL dal = new DAL();
var connection = dal.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 + "'";
dal.ExecuteSQL(insertString, connection);
}
}
}
catch (Exception ex)
{
logger.Fatal("URI" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return urlTable;
}
public static DataTable GetUriInfo(string urlKey)
{
DataTable uriInfo = new DataTable();
DAL dal = new DAL();
var connection = dal.ConnectReport();
try
{
uriInfo = dal.GetDataTable("SELECT [URL_KEY],[REAL_URL],[IS_PAGE_ONLY],[SKEY],[PROJECT_TITLE],[URL_OWNER] FROM REPORT_URL WHERE [URL_KEY] collate Korean_Wansung_CS_AS = '" + urlKey + "'", connection);
}
catch (Exception ex)
{
logger.Fatal("URI" + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return uriInfo;
}
}
}

View File

@@ -0,0 +1,61 @@
using System.Data;
namespace REPORT_API_ver6.Services
{
public class User
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(User));
/// <summary>
/// Login
/// </summary>
/// <param name="userEmail">ID</param>
/// <param name="userPW">PW</param>
/// <returns>User 정보</returns>
public DataTable userLogin(string userEmail, string userPW)
{
DAL dal = new DAL();
var connection = dal.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 = dal.GetDataTable(sqlString, connection);
dal.Disconnect(connection);
if (resultTable.Rows.Count < 1)
{
connection = dal.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 = dal.GetDataTable(sqlString, connection);
dal.Disconnect(connection);
}
return resultTable;
}
public static string getDinIDs()
{
string returnString = string.Empty;
DAL dal = new DAL();
var connection = dal.ConnectIntra();
DataTable resultTable = dal.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);
dal.Disconnect(connection);
if(resultTable.Rows.Count > 0)
{
returnString = resultTable.Rows[0][0].ToString();
}
return returnString;
}
}
}