Util.cs 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  1. using System;
  2. using System.Configuration;
  3. using System.Web;
  4. using System.Text;
  5. using System.IO;
  6. using System.Reflection;
  7. using System.Globalization;
  8. using System.Text.RegularExpressions;
  9. using System.Data;
  10. using System.Collections;
  11. using System.Linq;
  12. using System.Xml;
  13. using NVC = System.Collections.Specialized.NameValueCollection;
  14. using HT = System.Collections.Hashtable;
  15. using System.Linq.Expressions;
  16. using SixLabors.ImageSharp;
  17. using SixLabors.ImageSharp.Processing;
  18. using SixLabors.ImageSharp.PixelFormats;
  19. using System.Diagnostics;
  20. using System.Collections.Generic;
  21. using System.Security.Cryptography;
  22. using System.Net;
  23. using System.Net.NetworkInformation;
  24. using System.Net.Sockets;
  25. using System.IO.Compression;
  26. using Microsoft.Extensions.Logging;
  27. using System.Dynamic;
  28. namespace FMSAdmin.Helpers {
  29. // 각종 Util성 Helper Function모음
  30. public class Util {
  31. public static ILogger _logger;
  32. public static void Log(string message) {
  33. _logger.LogInformation(message);
  34. }
  35. /* ht, nvc (Hashtable, NameValueCollection)
  36. * ----------------------------------------------------------------------------- */
  37. public static HT NewHT(params object[] items) {
  38. // NewHT(Key1, Value1, Key2, Value2, ...)
  39. HT ht = new HT();
  40. for (int i = 0; i < items.Length; i += 2) {
  41. if (i + 1 < items.Length) {
  42. ht.Add(items[i], items[i + 1]);
  43. }
  44. }
  45. return ht;
  46. }
  47. public static HT AddHT(HT ht1, params object[] items) {
  48. // AddHT(Key1, Value1, Key2, Value2, ...)
  49. HT ht = (ht1 == null) ?
  50. ht = new HT()
  51. :
  52. ht = new HT(ht1);
  53. for (int i = 0; i < items.Length; i += 2) {
  54. if (i + 1 < items.Length) {
  55. ht.Add(items[i], items[i + 1]);
  56. }
  57. }
  58. return ht;
  59. }
  60. public static object HT(HT ht, Array keys) {
  61. HT last = ht;
  62. int index = 0;
  63. foreach (object key in keys) {
  64. if (last[key] is HT) {
  65. last = last[key] as HT;
  66. } else {
  67. if (index == keys.Length - 1) {
  68. return last[key];
  69. }
  70. }
  71. index++;
  72. }
  73. return null;
  74. }
  75. public static void HT(HT ht, Array keys, object val) {
  76. HT last = ht;
  77. int index = 0;
  78. foreach (object key in keys) {
  79. if (!last.Contains(key)) {
  80. last.Add(key, null);
  81. }
  82. if (index == keys.Length - 1) {
  83. last[key] = val;
  84. } else {
  85. if (last[key] == null) {
  86. last[key] = new HT();
  87. }
  88. last = last[key] as HT;
  89. }
  90. index++;
  91. }
  92. }
  93. public static HT ParseHT(string data) { return ParseHT(data, null); }
  94. public static HT ParseHT(string data, HT ht1) {
  95. // key1:val1,key2:val2,key3:val3, ...
  96. HT ht = (ht1 != null) ? new HT(ht1) : new HT();
  97. _logger.LogDebug("Util.ParseHT : " + data);
  98. string[] items = data.Split(',');
  99. for (int i = 0; i < items.Length; i++) {
  100. if (string.IsNullOrEmpty(items[i])) continue;
  101. var pos = items[i].IndexOf(':');
  102. if (pos == -1) {
  103. ht.Add(i, items[i]);
  104. } else {
  105. string key = items[i].Substring(0, pos);
  106. string value = items[i].Substring(pos + 1);
  107. ht.Add(key, value);
  108. }
  109. }
  110. return ht;
  111. }
  112. public static HT ExtendHT(HT child, HT parent) { return ExtendHT(child, parent, true); }
  113. public static HT ExtendHT(HT child, HT parent, bool bNewAdd) {
  114. if (parent == null) return child;
  115. foreach (object key in parent.Keys) {
  116. if (child.Contains(key)) {
  117. child[key] = parent[key];
  118. } else if (bNewAdd) {
  119. child.Add(key, parent[key]);
  120. }
  121. }
  122. return child;
  123. }
  124. public static NVC NewNVC(params string[] items) {
  125. // NewNVC(Key1, Value1, Key2, Value2, ...)
  126. NVC nvc = new NVC();
  127. for (int i = 0; i < items.Length; i += 2) {
  128. if (i + 1 < items.Length) {
  129. nvc.Add(items[i], items[i + 1]);
  130. }
  131. }
  132. return nvc;
  133. }
  134. public static NVC AddNVC(NVC nvc1, params string[] items) {
  135. // AddNVC(Key1, Value1, Key2, Value2, ...)
  136. NVC nvc = new NVC(nvc1);
  137. for (int i = 0; i < items.Length; i += 2) {
  138. if (i + 1 < items.Length) {
  139. nvc.Add(items[i], items[i + 1]);
  140. }
  141. }
  142. return nvc;
  143. }
  144. public static NVC ParseNVC(string data) { return ParseNVC(data, null); }
  145. public static NVC ParseNVC(string data, NVC nvc1) {
  146. // key1:val1,key2:val2,key3:val3, ...
  147. NVC nvc = (nvc1 != null) ? new NVC(nvc1) : new NVC();
  148. string[] items = data.Split(',', ':');
  149. for (int i = 0; i < items.Length; i += 2) {
  150. if (i + 1 < items.Length) {
  151. nvc.Add(items[i], items[i + 1]);
  152. }
  153. }
  154. return nvc;
  155. }
  156. public static NVC ExtendNVC(NVC child, NVC parent) { return ExtendNVC(child, parent, true); }
  157. public static NVC ExtendNVC(NVC child, NVC parent, bool bNewAdd) {
  158. if (parent == null) return child;
  159. foreach (string key in parent.Keys) {
  160. if (!string.IsNullOrEmpty(child[key])) {
  161. child[key] = parent[key];
  162. } else if (bNewAdd) {
  163. child.Add(key, parent[key]);
  164. }
  165. }
  166. return child;
  167. }
  168. public static ArrayList SortedHT(HT ht) {
  169. ArrayList sorter = new ArrayList();
  170. sorter.AddRange(ht);
  171. sorter.Sort(new htSortedClass());
  172. return sorter;
  173. }
  174. private class htSortedClass : IComparer {
  175. int IComparer.Compare(object x, object y) {
  176. if (x == null) return -1;
  177. if (y == null) return 1;
  178. HT ht1 = ((DictionaryEntry)x).Value as HT;
  179. HT ht2 = ((DictionaryEntry)y).Value as HT;
  180. if (ht1 == null && ht2 == null) return 0;
  181. if (ht1 == null) return -1;
  182. if (ht2 == null) return 1;
  183. int n1 = ToInt(ht1["_order"]);
  184. int n2 = ToInt(ht2["_order"]);
  185. return (int)(n1 - n2);
  186. }
  187. }
  188. public static HT QueryToHT(string query) {
  189. HT ht = new HT();
  190. var groups = query.Split('&');
  191. foreach (var group in groups) {
  192. if (string.IsNullOrEmpty(group)) continue;
  193. var items = group.Split('=');
  194. if (items.Length < 2) continue;
  195. ht[items[0]] = items[1];
  196. }
  197. return ht;
  198. }
  199. public static string HTToQuery(HT query) {
  200. StringBuilder sb = new StringBuilder();
  201. foreach (DictionaryEntry entry in query) {
  202. if (sb.Length > 0) {
  203. Util.SB(sb, "&");
  204. }
  205. Util.SB(sb, entry.Key, "=");
  206. Util.SB(sb, entry.Value);
  207. }
  208. return sb.ToString();
  209. }
  210. public static dynamic Combine(dynamic item1, dynamic item2) {
  211. var dictionary1 = (IDictionary<string, object>)item1;
  212. var dictionary2 = (IDictionary<string, object>)item2;
  213. var result = new ExpandoObject();
  214. var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
  215. foreach (var pair in dictionary1.Concat(dictionary2)) {
  216. d[pair.Key] = pair.Value;
  217. }
  218. return result;
  219. }
  220. /* alias
  221. * ----------------------------------------------------------------------------- */
  222. public static object[] A(params object[] items) {
  223. return items;
  224. }
  225. public static string S(object str) {
  226. if (str == null) str = "";
  227. return str.ToString();
  228. }
  229. public static string F(string format, params object[] args) {
  230. return string.Format(format, args);
  231. }
  232. public static string SB(params object[] args) {
  233. StringBuilder sb = new StringBuilder();
  234. foreach (object s in args) {
  235. sb.Append(s);
  236. }
  237. return sb.ToString();
  238. }
  239. public static void SB(StringBuilder sb, params object[] args) {
  240. foreach (object s in args) {
  241. sb.Append(s);
  242. }
  243. }
  244. public static string Substring(object str, int start) {
  245. if (str == null) str = "";
  246. string text = str.ToString();
  247. if (start > text.Length) start = text.Length;
  248. if (start < 0) start = text.Length + start;
  249. return text.Substring(start);
  250. }
  251. public static string Substring(object str, int start, int length) {
  252. if (str == null) str = "";
  253. string text = str.ToString();
  254. if (start > text.Length) start = text.Length;
  255. if (start < 0) start = text.Length + start;
  256. if (start + length > text.Length) {
  257. length = text.Length - start;
  258. }
  259. return text.Substring(start, length);
  260. }
  261. public static string Substring(object str, string startSymbol, string endSymbol) {
  262. if (str == null) str = "";
  263. string text = str.ToString();
  264. int start = 0;
  265. int end = 0;
  266. int resultLen = text.Length;
  267. if (text.IndexOf(startSymbol) >= 0) {
  268. start = text.IndexOf(startSymbol) + 1;
  269. }
  270. if (text.IndexOf(endSymbol) > 0 && endSymbol != "") {
  271. end = text.IndexOf(endSymbol, start);
  272. } else {
  273. end = text.Length;
  274. }
  275. resultLen = end - start;
  276. return text.Substring(start, resultLen);
  277. }
  278. public static string SubstringByByte(object str, int count) {
  279. try {
  280. if (str == null) str = "";
  281. string text = str.ToString();
  282. byte[] strByte = Encoding.Default.GetBytes(text);
  283. if (strByte.Count() > count) {
  284. char[] cc = Encoding.Default.GetChars(strByte, 0, count);
  285. return string.Join("", cc);
  286. } else {
  287. return text;
  288. }
  289. } catch {
  290. return "";
  291. }
  292. }
  293. public static string Pick(string val, string def) {
  294. if (string.IsNullOrEmpty(val)) return def;
  295. return val;
  296. }
  297. public static string Pick(object val, string def) {
  298. if (val == null) return def;
  299. return val.ToString();
  300. }
  301. public static object Pick(object val, object def) {
  302. if (val == null) return def;
  303. return val.ToString();
  304. }
  305. /* string
  306. * ----------------------------------------------------------------------------- */
  307. public static bool IsNullOrEmpty(object val) {
  308. return string.IsNullOrEmpty(S(val));
  309. }
  310. public static string ReplaceOnce(string str, string oldVal, string newVal) { return ReplaceOnce(str, oldVal, newVal, StringComparison.CurrentCulture); }
  311. public static string ReplaceOnce(string str, string oldVal, string newVal, StringComparison comp) {
  312. string newstr = str.TrimStart();
  313. int spos = newstr.IndexOf(newstr, comp);
  314. if (spos != -1) {
  315. newstr = newstr.Remove(spos, oldVal.Length).Insert(spos, newVal);
  316. }
  317. return newstr;
  318. }
  319. /*
  320. * String.Format 확장
  321. * index가 아닌 정확한 명칭 매칭
  322. * ex)
  323. * string text = "이름은 {@이름}이고 연락처는 {@연락처}입니다.";
  324. * Util.Format(text, new HT {{"이름", "홍길동"},{"연락처", "02-1234-1234"}})
  325. */
  326. public static string Format(string str, HT map) {
  327. string str1 = str;
  328. int ctlpos = 0;
  329. Regex regex = new Regex(@"\{@([^\}]*)\}");
  330. MatchCollection mc = regex.Matches(str1);
  331. foreach (Match match in mc) {
  332. if (match.Groups.Count >= 2) {
  333. string name = match.Groups[1].Value;
  334. int pos = match.Groups[0].Index + ctlpos;
  335. int len = match.Groups[0].Length;
  336. if (map.Contains(name)) {
  337. str1 = str1.Remove(pos, len)
  338. .Insert(pos, S(map[name]));
  339. ctlpos += S(map[name]).Length - len;
  340. } else {
  341. str1 = str1.Remove(pos, len);
  342. ctlpos -= len;
  343. }
  344. }
  345. }
  346. return str1;
  347. }
  348. public static string Format(string str, DataRow map) {
  349. string str1 = str;
  350. int ctlpos = 0;
  351. Regex regex = new Regex(@"\{@([^\}]*)\}");
  352. MatchCollection mc = regex.Matches(str1);
  353. foreach (Match match in mc) {
  354. if (match.Groups.Count >= 2) {
  355. string name = match.Groups[1].Value;
  356. int pos = match.Groups[0].Index + ctlpos;
  357. int len = match.Groups[0].Length;
  358. if (map.Table.Columns.Contains(name) && map[name] != null) {
  359. str1 = str1.Remove(pos, len)
  360. .Insert(pos, S(map[name]));
  361. ctlpos += S(map[name]).Length - len;
  362. } else {
  363. str1 = str1.Remove(pos, len);
  364. ctlpos -= len;
  365. }
  366. }
  367. }
  368. return str1;
  369. }
  370. /*
  371. * Util.Format의 확장
  372. * 대체값에 대한 if 비교
  373. * ex)
  374. * string text = "이름은 {@이름} {?연락처}이고 연락처는 {@연락처}입니다.{/연락처}{?!연락처}입니다.{/연락처}";
  375. * Util.Format(text, new HT {{"이름", "홍길동"}})
  376. * 연락처가 없으므로 뒷부분은 "입니다"로 치환
  377. * text => 이름은 홍길동입니다.
  378. */
  379. public static string FormatEx(string str, HT map) {
  380. string str1 = str;
  381. int ctlpos = 0;
  382. Regex regex = new Regex(@"\{\?([\!]?)([^\}]*)\}(.+?)\{\/\2\}", RegexOptions.Singleline);
  383. MatchCollection mc = regex.Matches(str1);
  384. foreach (Match match in mc) {
  385. if (match.Groups.Count >= 3) {
  386. string not = match.Groups[1].Value;
  387. string name = match.Groups[2].Value;
  388. string content = match.Groups[3].Value;
  389. int pos = match.Groups[0].Index + ctlpos;
  390. int len = match.Groups[0].Length;
  391. if (map.Contains(name) && map[name] != null) {
  392. if (string.IsNullOrEmpty(not)) {
  393. content = FormatEx(content, map);
  394. str1 = str1.Remove(pos, len);
  395. str1 = str1.Insert(pos, content);
  396. ctlpos += content.Length - len;
  397. } else {
  398. str1 = str1.Remove(pos, len);
  399. ctlpos -= len;
  400. }
  401. } else {
  402. if (!string.IsNullOrEmpty(not)) {
  403. content = FormatEx(content, map);
  404. str1 = str1.Remove(pos, len);
  405. str1 = str1.Insert(pos, content);
  406. ctlpos += content.Length - len;
  407. } else {
  408. str1 = str1.Remove(pos, len);
  409. ctlpos -= len;
  410. }
  411. }
  412. }
  413. }
  414. return Format(str1, map);
  415. }
  416. public static string FormatEx(string str, DataRow map) {
  417. string str1 = str;
  418. int ctlpos = 0;
  419. Regex regex = new Regex(@"\{\?([\!]?)([^\}]*)\}(.+?)\{\/\2\}", RegexOptions.Singleline);
  420. MatchCollection mc = regex.Matches(str1);
  421. foreach (Match match in mc) {
  422. if (match.Groups.Count >= 3) {
  423. string not = match.Groups[1].Value;
  424. string name = match.Groups[2].Value;
  425. string content = match.Groups[3].Value;
  426. int pos = match.Groups[0].Index + ctlpos;
  427. int len = match.Groups[0].Length;
  428. if (map.Table.Columns.Contains(name) && map[name] != null) {
  429. if (string.IsNullOrEmpty(not)) {
  430. content = FormatEx(content, map);
  431. str1 = str1.Remove(pos, len);
  432. str1 = str1.Insert(pos, content);
  433. ctlpos += content.Length - len;
  434. } else {
  435. str1 = str1.Remove(pos, len);
  436. ctlpos -= len;
  437. }
  438. } else {
  439. if (!string.IsNullOrEmpty(not)) {
  440. content = FormatEx(content, map);
  441. str1 = str1.Remove(pos, len);
  442. str1 = str1.Insert(pos, content);
  443. ctlpos += content.Length - len;
  444. } else {
  445. str1 = str1.Remove(pos, len);
  446. ctlpos -= len;
  447. }
  448. }
  449. }
  450. }
  451. return Format(str1, map);
  452. }
  453. /*
  454. * 연속 포맷 정의
  455. * text = "1111112222222"
  456. * SubFormat(text, 6, "-", 7);
  457. * => 111111-2222222
  458. * text = "0212345678"
  459. * SubFormat(text, 2, "-", 4, "-", 4);
  460. * => 02-1234-5678
  461. **/
  462. public static string SubFormat(string str, params object[] paramlist) {
  463. StringBuilder sb = new StringBuilder();
  464. int totalpos = 0;
  465. int? startlen = null;
  466. int? length = null;
  467. foreach (object param in paramlist) {
  468. if (param is int) {
  469. if (startlen == null) {
  470. startlen = (int)param;
  471. } else if (length == null) {
  472. length = (int)param;
  473. } else {
  474. sb.Append(str.Substring((int)startlen, (int)length));
  475. startlen = null;
  476. length = null;
  477. }
  478. } else {
  479. if (startlen != null && length != null) {
  480. sb.Append(str.Substring((int)startlen, (int)length));
  481. sb.Append(S(param));
  482. totalpos = (int)startlen + (int)length;
  483. } else if (startlen != null) {
  484. sb.Append(str.Substring(totalpos, (int)startlen));
  485. sb.Append(S(param));
  486. totalpos += (int)startlen;
  487. }
  488. startlen = null;
  489. length = null;
  490. }
  491. }
  492. if (startlen != null && length != null) {
  493. sb.Append(str.Substring((int)startlen, (int)length));
  494. } else if (startlen != null) {
  495. sb.Append(str.Substring(totalpos, (int)startlen));
  496. }
  497. return sb.ToString();
  498. }
  499. public static string Trim(object str) {
  500. return str.ToString().Trim();
  501. }
  502. public static string DBString(string str) {
  503. return str.Replace("--", "").Replace("'", "''");
  504. }
  505. /**
  506. * 텍스트를 일정 길이 만큼 자르는 함수
  507. *
  508. * @param string str 텍스트
  509. * @param string len 자를 길이
  510. * @param string suffix 끝에 붙일 텍스트
  511. * @return string 잘린 텍스트
  512. */
  513. public static string CutStr(string str, int len, string suffix = "..") {
  514. System.Text.Encoding myEncoding = System.Text.Encoding.GetEncoding("ks_c_5601-1987");
  515. byte[] buf = myEncoding.GetBytes(str);
  516. if (buf.Length < len) return str;
  517. string result = myEncoding.GetString(buf, 0, len);
  518. if (result.Substring(result.Length - 1) == "?") {
  519. result = result.Substring(0, result.Length - 1);
  520. }
  521. return result + suffix;
  522. }
  523. /* request (post in server.execute)
  524. * ----------------------------------------------------------------------------- */
  525. public static void ServerRequest(StringWriter output, string url, NVC post) {
  526. }
  527. /* convert helper
  528. * ----------------------------------------------------------------------------- */
  529. public static string ToPrice(object prc) {
  530. if (prc == null) return "";
  531. if (prc is Int32) {
  532. return ((Int32)prc).ToString("N0");
  533. } else if (prc is Int64) {
  534. return ((Int64)prc).ToString("N0");
  535. } else {
  536. Int64 n = 0;
  537. try {
  538. string s = prc.ToString();
  539. int pos = s.LastIndexOf('.');
  540. if (pos == -1) {
  541. s = Regex.Replace(s, "[^-0-9]", "");
  542. n = Int64.Parse(s);
  543. return n.ToString("N0");
  544. } else {
  545. var num = Int64.Parse(Regex.Replace(s.Substring(0, pos), "[^-0-9]", ""));
  546. var frac = s.Substring(pos + 1);
  547. if (string.IsNullOrEmpty(frac)) {
  548. return num.ToString("N0");
  549. } else {
  550. return num.ToString("N0") + "." + frac;
  551. }
  552. }
  553. } catch { }
  554. return prc.ToString();
  555. }
  556. }
  557. public static int ParsePriceVal(object str) {
  558. string price = S(str).Replace("\\", "").Replace(",", "");
  559. return ToInt(price);
  560. }
  561. public static string ParsePrice(object str) {
  562. string price = S(str).Replace("\\", "").Replace(",", "");
  563. return price;
  564. }
  565. public static int ToInt(object str) { return ToInt(str, 0); }
  566. public static int ToInt(object str, int def) {
  567. if (str is int) return (int)str;
  568. int n = 0;
  569. try {
  570. str = ParsePrice(str);
  571. n = int.Parse(S(str));
  572. } catch { n = def; }
  573. return n;
  574. }
  575. public static long ToLong(object str) { return ToInt(str, 0); }
  576. public static long ToLong(object str, long def) {
  577. if (str is long) return (long)str;
  578. long n = 0;
  579. try {
  580. str = ParsePrice(str);
  581. n = long.Parse(S(str));
  582. } catch { n = def; }
  583. return n;
  584. }
  585. public static double ToDouble(object str) { return ToDouble(str, 0.0); }
  586. public static double ToDouble(object str, double def) {
  587. if (str is double) return (double)str;
  588. if (str is float) return double.Parse(str.ToString());
  589. double n = 0;
  590. try {
  591. str = ParsePrice(str);
  592. n = double.Parse(S(str));
  593. } catch { n = def; }
  594. return n;
  595. }
  596. public static float ToFloat(object str) { return ToFloat(str, 0.0f); }
  597. public static float ToFloat(object str, float def) {
  598. if (str is double) return (float)str;
  599. if (str is float) return float.Parse(str.ToString());
  600. float n = 0;
  601. try {
  602. str = ParsePrice(str);
  603. n = float.Parse(S(str));
  604. } catch { n = def; }
  605. return n;
  606. }
  607. public static bool ToBool(object str) {
  608. if (str is bool) {
  609. return (bool)str;
  610. } else if (str is int) {
  611. return (int)str != 0;
  612. }
  613. bool ret = false;
  614. try {
  615. ret = bool.Parse(S(str));
  616. } catch {
  617. ret = (ToInt(str) != 0);
  618. }
  619. return ret;
  620. }
  621. public static string ToJson(object obj) {
  622. if (obj == null) return "{}";
  623. return System.Text.Json.JsonSerializer.Serialize(obj);
  624. }
  625. public static string ToTitleCase(string str) {
  626. TextInfo txtinfo = CultureInfo.CurrentCulture.TextInfo;
  627. return txtinfo.ToTitleCase(str);
  628. }
  629. public static string ToClassCase(string str) {
  630. Regex regex = new Regex(@"([A-Z])");
  631. Regex regexDiv = new Regex(@"[^a-zA-Z0-9]");
  632. string clsstr = regex.Replace(str, " $1");
  633. TextInfo txtinfo = CultureInfo.CurrentCulture.TextInfo;
  634. string[] words = regexDiv.Split(clsstr);
  635. StringBuilder builder = new StringBuilder();
  636. foreach (string word in words) {
  637. if (word.Length == 0) continue;
  638. builder.Append(txtinfo.ToTitleCase(word));
  639. }
  640. return builder.ToString();
  641. }
  642. public static string ToCamelCase(string str) {
  643. Regex regex = new Regex(@"([A-Z])");
  644. Regex regexDiv = new Regex(@"[^a-zA-Z0-9]");
  645. string camelstr = regex.Replace(str, " $1");
  646. TextInfo txtinfo = CultureInfo.CurrentCulture.TextInfo;
  647. string[] words = regexDiv.Split(camelstr);
  648. StringBuilder builder = new StringBuilder();
  649. foreach (string word in words) {
  650. if (word.Length == 0) continue;
  651. if (builder.Length > 0) {
  652. builder.Append(txtinfo.ToTitleCase(word));
  653. } else {
  654. builder.Append(word.ToLower());
  655. }
  656. }
  657. return builder.ToString();
  658. }
  659. public static string ToUnderbarCase(string str) {
  660. Regex regex = new Regex(@"([A-Z])");
  661. Regex regexDiv = new Regex(@"[^a-zA-Z0-9]");
  662. string understr = regex.Replace(str, " $1");
  663. string[] words = regexDiv.Split(understr);
  664. StringBuilder builder = new StringBuilder();
  665. foreach (string word in words) {
  666. if (word.Length == 0) continue;
  667. if (builder.Length > 0) builder.Append("_");
  668. builder.Append(word.ToLower());
  669. }
  670. return builder.ToString();
  671. }
  672. public static string ToShortDate(object obj) {
  673. return ToDate(obj, "yyyy-MM-dd");
  674. }
  675. public static string ToDate(object obj) {
  676. return ToDate(obj, "yyyy-MM-dd hh:mm:ss");
  677. }
  678. public static string ToDate(object obj, string format) {
  679. string date = "";
  680. try {
  681. if (obj is DateTime) {
  682. date = ((DateTime)obj).ToString(format);
  683. } else {
  684. date = S(obj);
  685. if (string.IsNullOrEmpty(date)) return "";
  686. if (date.Length > 10) {
  687. date = Substring(date, 0, 10);
  688. }
  689. date = DateTime.Parse(date).ToString(format);
  690. }
  691. } catch (Exception ex) {
  692. _logger.LogError("Util:ToDate " + obj, ex);
  693. }
  694. return date;
  695. }
  696. public static NVC ToNVC(DataRowCollection rows, string key, string val) {
  697. NVC nvc = new NVC();
  698. if (rows != null) {
  699. foreach (DataRow row in rows) {
  700. nvc.Add(row[key].ToString(), row[val].ToString());
  701. }
  702. }
  703. return nvc;
  704. }
  705. public static NVC ToNVC(DataRow row) {
  706. NVC nvc = new NVC();
  707. foreach (DataColumn col in row.Table.Columns) {
  708. nvc.Add(col.ToString(), row[col].ToString());
  709. }
  710. return nvc;
  711. }
  712. public static NVC ToNVC(HT ht) {
  713. NVC nvc = new NVC();
  714. foreach (object col in ht.Keys) {
  715. if (col == null) continue;
  716. nvc.Add(col.ToString(), (ht[col] ?? "").ToString());
  717. }
  718. return nvc;
  719. }
  720. public static HT ToHT(DataRowCollection rows, string key, string val) {
  721. HT ht = new HT();
  722. if (rows != null) {
  723. foreach (DataRow row in rows) {
  724. ht.Add(row[key].ToString(), row[val].ToString());
  725. }
  726. }
  727. return ht;
  728. }
  729. public static HT ToHT(DataRow row) {
  730. HT ht = new HT();
  731. foreach (DataColumn col in row.Table.Columns) {
  732. ht.Add(col.ToString(), row[col]);
  733. }
  734. return ht;
  735. }
  736. public static HT ToHT(NVC nvc) {
  737. HT ht = new HT();
  738. foreach (string key in nvc.Keys) {
  739. if (key == null) continue;
  740. ht.Add(key, nvc[key]);
  741. }
  742. return ht;
  743. }
  744. public static HT ToHT(XmlNode node) {
  745. _logger.LogDebug("ToHT(XmlNode node) -> " + node.Name);
  746. HT ht = new HT();
  747. if (node.Attributes != null) {
  748. foreach (XmlAttribute attr in node.Attributes) {
  749. ht.Add(attr.Name, attr.Value);
  750. }
  751. }
  752. if (node.NodeType == XmlNodeType.Text || node.NodeType == XmlNodeType.CDATA) {
  753. _logger.LogDebug("=> text");
  754. ht.Add("value", node.Value);
  755. } else if (node.ChildNodes.Count == 1 && (node.ChildNodes[0].NodeType == XmlNodeType.Text || node.ChildNodes[0].NodeType == XmlNodeType.CDATA)) {
  756. _logger.LogDebug("=> one-child text");
  757. ht.Add("value", node.ChildNodes[0].Value);
  758. } else {
  759. _logger.LogDebug("=> xml");
  760. foreach (XmlNode child in node.ChildNodes) {
  761. if (child.ChildNodes.Count == 1 && child.Attributes.Count == 0 && (child.ChildNodes[0].NodeType == XmlNodeType.Text || child.ChildNodes[0].NodeType == XmlNodeType.CDATA)) {
  762. _logger.LogDebug("_AddChildHT @1 " + child.Name);
  763. _AddChildHT(ht, child.Name, NewHT(
  764. "value",
  765. child.ChildNodes[0].Value
  766. ));
  767. } else {
  768. _logger.LogDebug("_AddChildHT @2 " + child.Name);
  769. _AddChildHT(ht, child.Name, ToHT(child));
  770. }
  771. }
  772. }
  773. return ht;
  774. }
  775. private static void _AddChildHT(HT ht, object key, object val) {
  776. if (ht.Contains(key)) {
  777. if (ht[key] is ArrayList) {
  778. ((ArrayList)ht[key]).Add(val);
  779. } else {
  780. ArrayList newval = new ArrayList();
  781. newval.Add(ht[key]);
  782. newval.Add(val);
  783. ht[key] = newval;
  784. }
  785. } else {
  786. ht.Add(key, val);
  787. }
  788. }
  789. public static string ToGET(NVC nvc) {
  790. StringBuilder sb = new StringBuilder();
  791. foreach (string name in nvc.AllKeys) {
  792. if (nvc[name] == null) continue;
  793. if (sb.Length > 0) sb.Append("&");
  794. sb.Append(name);
  795. sb.Append("=");
  796. sb.Append(HttpUtility.UrlEncode(nvc[name]));
  797. }
  798. return sb.ToString();
  799. }
  800. public static string ToGET(HT ht) {
  801. StringBuilder sb = new StringBuilder();
  802. foreach (object key in ht.Keys) {
  803. if (ht[key] == null) continue;
  804. if (sb.Length > 0) sb.Append("&");
  805. sb.Append(key.ToString());
  806. sb.Append("=");
  807. sb.Append(HttpUtility.UrlEncode(ht[key].ToString()));
  808. }
  809. return sb.ToString();
  810. }
  811. public static string ToAttr(NVC nvc) {
  812. StringBuilder sb = new StringBuilder();
  813. foreach (string name in nvc.AllKeys) {
  814. if (sb.Length > 0) sb.Append(" ");
  815. sb.Append(name.ToString());
  816. sb.Append("=\"");
  817. sb.Append(nvc[name]);
  818. sb.Append("\"");
  819. }
  820. return sb.ToString();
  821. }
  822. public static string ToAttr(HT ht) {
  823. StringBuilder sb = new StringBuilder();
  824. foreach (object key in ht.Keys) {
  825. if (sb.Length > 0) sb.Append(" ");
  826. sb.Append(key.ToString());
  827. sb.Append("=\"");
  828. sb.Append(ht[key].ToString());
  829. sb.Append("\"");
  830. }
  831. return sb.ToString();
  832. }
  833. public static string StripTags(string html) {
  834. Regex regHtml = new Regex("<[^>]*>");
  835. return regHtml.Replace(html, "");
  836. }
  837. public static string PriceFormat(object val) {
  838. return String.Format("{0:#,0}", val);
  839. }
  840. public static string PriceFormat(string val) {
  841. return String.Format("{0:#,0}", val);
  842. }
  843. public static string PriceFormat(int val) {
  844. return String.Format("{0:#,0}", val);
  845. }
  846. public static long ToTicks(DateTime dtInput) {
  847. long ticks = 0;
  848. ticks = dtInput.Ticks;
  849. return ticks;
  850. }
  851. public static long SubTicks(DateTime date1, DateTime date2) {
  852. return date1.Subtract(date2).Ticks;
  853. }
  854. public static DateTime ToDateTime(long lticks) {
  855. DateTime dtresult = new DateTime(lticks);
  856. return dtresult;
  857. }
  858. /* etc
  859. * ----------------------------------------------------------------------------- */
  860. public static string RandCode(int length, bool number = true, bool smallAlpha = true, bool bigAlpha = false, bool speicialChar = false) {
  861. StringBuilder sbWord = new StringBuilder();
  862. StringBuilder sbTicket = new StringBuilder();
  863. if (number) {
  864. sbTicket.Append("0123456789");
  865. }
  866. if (smallAlpha) {
  867. sbTicket.Append("abcdefghijklmnopqrstuvwxyz");
  868. }
  869. if (bigAlpha) {
  870. sbTicket.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  871. }
  872. if (speicialChar) {
  873. sbTicket.Append("~!@#$%^&*()_+-=");
  874. }
  875. string tickets = sbTicket.ToString();
  876. Random rand = new Random((int)DateTime.Now.Ticks);
  877. for (int i = 0; i < length; i++) {
  878. int pos = rand.Next(tickets.Length - 1);
  879. sbWord.Append(tickets.Substring(pos, 1));
  880. }
  881. return sbWord.ToString();
  882. }
  883. public static string DesEncrypt(string strData, string strKey = "ubitems1") {
  884. byte[] Skey = ASCIIEncoding.ASCII.GetBytes(strKey);
  885. if (Skey.Length != 8) {
  886. throw (new Exception("키는 8자이어야 합니다."));
  887. }
  888. DESCryptoServiceProvider rc2 = new DESCryptoServiceProvider();
  889. rc2.Key = Skey;
  890. rc2.IV = Skey;
  891. MemoryStream ms = new MemoryStream();
  892. CryptoStream cryStream = new CryptoStream(ms, rc2.CreateEncryptor(), CryptoStreamMode.Write);
  893. byte[] data = Encoding.UTF8.GetBytes(strData.ToCharArray());
  894. cryStream.Write(data, 0, data.Length);
  895. cryStream.FlushFinalBlock();
  896. return Convert.ToBase64String(ms.ToArray());
  897. }
  898. public static string DesDecrypt(string strData, string strKey = "ubitems1") {
  899. byte[] Skey = ASCIIEncoding.ASCII.GetBytes(strKey);
  900. if (Skey.Length != 8) {
  901. throw (new Exception("키는 8자이어야 합니다."));
  902. }
  903. DESCryptoServiceProvider rc2 = new DESCryptoServiceProvider();
  904. rc2.Key = Skey;
  905. rc2.IV = Skey;
  906. MemoryStream ms = new MemoryStream();
  907. CryptoStream cryStream = new CryptoStream(ms, rc2.CreateDecryptor(), CryptoStreamMode.Write);
  908. byte[] data = Convert.FromBase64String(strData);
  909. cryStream.Write(data, 0, data.Length);
  910. cryStream.FlushFinalBlock();
  911. return Encoding.UTF8.GetString(ms.GetBuffer());
  912. }
  913. /*
  914. * MD5알고리즘
  915. * @param type hex or base64
  916. **/
  917. public static string MD5(string input, string type = "hex") {
  918. if (input == null) {
  919. return string.Empty;
  920. }
  921. MD5 md5 = System.Security.Cryptography.MD5.Create();
  922. byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
  923. byte[] hashBytes = md5.ComputeHash(inputBytes);
  924. string retData = "";
  925. if (type == "base64") {
  926. retData = Convert.ToBase64String(hashBytes);
  927. } else if (type == "hex") {
  928. StringBuilder sb = new StringBuilder();
  929. for (int i = 0; i < hashBytes.Length; i++) {
  930. sb.Append(hashBytes[i].ToString("X2"));
  931. }
  932. retData = sb.ToString();
  933. }
  934. return retData;
  935. }
  936. /*
  937. * SHA256알고리즘기반 HMAC(해시기반 메세지인증코드)
  938. * key값로 훼손여부 검증
  939. * @param type hex or base64
  940. * @param key 비밀키
  941. **/
  942. public static string HMAC_SHA256(string value, string type = "hex", string key = "ubi%&%$&%*") {
  943. if (value == null) {
  944. return string.Empty;
  945. }
  946. byte[] valueByte = System.Text.Encoding.Unicode.GetBytes(value);
  947. byte[] keyByte = System.Text.Encoding.Unicode.GetBytes(key);
  948. HMACSHA256 hash = new HMACSHA256(keyByte);
  949. byte[] hashBytes = hash.ComputeHash(valueByte);
  950. string retData = "";
  951. if (type == "base64") {
  952. retData = Convert.ToBase64String(hashBytes);
  953. } else if (type == "hex") {
  954. StringBuilder sb = new StringBuilder();
  955. for (int i = 0; i < hashBytes.Length; i++) {
  956. sb.Append(hashBytes[i].ToString("X2"));
  957. }
  958. retData = sb.ToString();
  959. }
  960. return retData;
  961. }
  962. /*
  963. * 가볍게 쓸수 있는 암호화 - 암호화
  964. * 표식을 붙여 암호화 여부를 판단한다. 표식이 없을경우 일반 문자열
  965. * 표식을 이용하여 일반 문자열과 혼용해서 사용할 수 있다.
  966. * deflate/gzip -> base64
  967. * ※ 문자열을 첫글자는 표식문자 '*'가 올수 없다.
  968. **/
  969. public static string LiteEncode(string value) {
  970. string encode = null;
  971. try {
  972. // to byte
  973. byte[] byteArray = new byte[value.Length];
  974. int index = 0;
  975. foreach (char item in value.ToCharArray()) {
  976. byteArray[index++] = (byte)item;
  977. }
  978. // ready
  979. MemoryStream ms = new MemoryStream();
  980. DeflateStream zs = new DeflateStream(ms, CompressionMode.Compress);
  981. // compress
  982. zs.Write(byteArray, 0, byteArray.Length);
  983. zs.Close();
  984. // to base64
  985. encode = Convert.ToBase64String(ms.ToArray());
  986. // 특수문자 교체
  987. encode = encode.Replace("==", "$");
  988. //encode = encode.Replace("=", "#");
  989. //encode = encode.Replace("/", "%");
  990. ms.Close();
  991. zs.Dispose();
  992. ms.Dispose();
  993. // 표식을 붙여 return
  994. return "*" + encode;
  995. } catch (Exception ex) {
  996. _logger.LogDebug("", ex);
  997. }
  998. return value;
  999. }
  1000. /*
  1001. * 가볍게 쓸수 있는 암호화 - 복호화
  1002. * 표식을 붙여 암호화 여부를 판단한다. 표식이 없을경우 일반 문자열
  1003. * 표식을 이용하여 일반 문자열과 혼용해서 사용할 수 있다.
  1004. * base64 -> deflate/gzip
  1005. * ※ 문자열을 첫글자는 표식문자 '*'가 올수 없다.
  1006. **/
  1007. public static string LiteDecode(string value) {
  1008. // 표식 식별
  1009. if (value != null && value.Length > 1 && value.Substring(0, 1) == "*") {
  1010. try {
  1011. string base64 = value.Substring(1);
  1012. // 특수문자 교체
  1013. base64 = base64.Replace("$", "==");
  1014. //base64 = base64.Replace("#", "=");
  1015. //base64 = base64.Replace("%", "/");
  1016. // decode base64
  1017. byte[] byteArray = Convert.FromBase64String(base64);
  1018. int readBytes = 0;
  1019. MemoryStream ms = new MemoryStream(byteArray);
  1020. DeflateStream zs = new DeflateStream(ms, CompressionMode.Decompress);
  1021. // buffer
  1022. byte[] decodeBytes = new byte[512];
  1023. StringBuilder sb = new StringBuilder();
  1024. while ((readBytes = zs.Read(decodeBytes, 0, decodeBytes.Length)) != 0) {
  1025. for (int i = 0; i < readBytes; i++) sb.Append((char)decodeBytes[i]);
  1026. }
  1027. ms.Close();
  1028. zs.Dispose();
  1029. ms.Dispose();
  1030. return sb.ToString();
  1031. } catch (Exception ex) {
  1032. _logger.LogDebug("", ex);
  1033. }
  1034. }
  1035. return value;
  1036. }
  1037. public static string StackTrace() {
  1038. StringBuilder sb = new StringBuilder();
  1039. var stackTrace = new StackTrace(true);
  1040. foreach (var r in stackTrace.GetFrames()) {
  1041. Util.SB(sb, string.Format("Filename: {0} Method: {1} Line: {2} Column: {3} ",
  1042. r.GetFileName(), r.GetMethod(), r.GetFileLineNumber(),
  1043. r.GetFileColumnNumber()));
  1044. }
  1045. return sb.ToString();
  1046. }
  1047. public static void StreamCopy(Stream input, Stream output) {
  1048. const int bufferSize = 2048;
  1049. byte[] buffer = new byte[bufferSize];
  1050. int read = 0;
  1051. do {
  1052. read = input.Read(buffer, 0, buffer.Length);
  1053. output.Write(buffer, 0, read);
  1054. } while (read >= bufferSize);
  1055. }
  1056. /*
  1057. * 객체내의 value값 반환
  1058. * 훨씬 유연하게 객체에 속한 하위객체의 값을 구할 수 있다.
  1059. * ex)
  1060. * string memName = "";
  1061. * // 기존
  1062. * if (order != null) {
  1063. * if (order.Member != null) {
  1064. * memName = order.Member.Name;
  1065. * }
  1066. * }
  1067. * // 함수사용
  1068. * memName = Util.V(order, x=>x.Member.Name);
  1069. * 더 복잡한 Util.V(order, x=>x.Product.VendorComp.Name) 등등..
  1070. *
  1071. * @param model 대상 객체
  1072. * @param express 람다표현식
  1073. **/
  1074. public static TResult V<TModel, TResult>(TModel model, Expression<Func<TModel, TResult>> expression) { return DeepValue<TModel, TResult>(model, expression); }
  1075. public static TResult DeepValue<TModel, TResult>(TModel model, Expression<Func<TModel, TResult>> expression) {
  1076. try {
  1077. var func = expression.Compile();
  1078. var value = func(model);
  1079. return value;
  1080. } catch (Exception) {
  1081. return default(TResult);
  1082. }
  1083. }
  1084. public static bool ImageResize(string filePath, string targetPath, int width, int height, bool cut = false, uint argb = 0xFFFFFFFF) {
  1085. try {
  1086. int dstHeight = 0;
  1087. int dstWidth = 0;
  1088. using (Image image = Image.Load(filePath)) {
  1089. if (!cut) {
  1090. dstWidth = width;
  1091. dstHeight = (int)Math.Round((float)(width * image.Height) / (float)image.Width);
  1092. if (dstHeight > height) {
  1093. dstHeight = height;
  1094. dstWidth = (int)Math.Round((float)(height * image.Width) / (float)image.Height);
  1095. }
  1096. } else {
  1097. dstWidth = width;
  1098. dstHeight = (int)Math.Round((float)(width * image.Height) / (float)image.Width);
  1099. if (dstHeight < height) {
  1100. dstHeight = height;
  1101. dstWidth = (int)Math.Round((float)(height * image.Width) / (float)image.Height);
  1102. }
  1103. }
  1104. image.Mutate(x => x.Resize(width, height));
  1105. image.Save(targetPath);
  1106. }
  1107. } catch (Exception ex) {
  1108. _logger.LogError("Util:ImageResize", ex);
  1109. }
  1110. return true;
  1111. }
  1112. public static string GetServerIP(int index = 0) {
  1113. IList<string> list = new List<string>();
  1114. foreach (var ni in NetworkInterface.GetAllNetworkInterfaces()) {
  1115. foreach (var uipi in ni.GetIPProperties().UnicastAddresses) {
  1116. if (uipi.Address.AddressFamily != AddressFamily.InterNetwork) continue;
  1117. if (uipi.IPv4Mask == null) continue; //ignore 127.0.0.1
  1118. list.Add(uipi.Address.ToString());
  1119. }
  1120. }
  1121. return list[index];
  1122. }
  1123. /// <summary>
  1124. /// 우편번호나 전화번호에 '-' 삽입
  1125. /// positions 는 뒷에서부터 자리수 표현
  1126. /// </summary>
  1127. /// <param name="value">삽입할 문자열</param>
  1128. /// <param name="positions">자리수(뒤의 자리부터)</param>
  1129. /// <returns></returns>
  1130. public static string HyphenFormat(string value, int[] positions) {
  1131. ArrayList al = new ArrayList();
  1132. int offset = positions.Length - 1;
  1133. int digit = 0;
  1134. string retValue = "";
  1135. foreach (char ch in value.Replace("-", "").ToCharArray().Reverse()) {
  1136. retValue = ch.ToString() + retValue;
  1137. digit++;
  1138. if (offset >= 0 && digit == positions[offset]) {
  1139. retValue = "-" + retValue;
  1140. offset--;
  1141. digit = 0;
  1142. }
  1143. }
  1144. return retValue;
  1145. }
  1146. public static string ConvertUtf8(string str) {
  1147. return ConvertEncoding(Encoding.GetEncoding("949"), Encoding.UTF8, str);
  1148. }
  1149. public static string ConvertEuckr(string str) {
  1150. return ConvertEncoding(Encoding.UTF8, Encoding.GetEncoding("EUC-KR"), str);
  1151. }
  1152. /*
  1153. public static string decodeEuckrUrl(string url)
  1154. {
  1155. System.Text.Encoding euckr = System.Text.Encoding.GetEncoding(51949);
  1156. byte[] euckrBytes = System.Web.HttpUtility.UrlDecodeToBytes(url);
  1157. return euckr.GetString(euckrBytes);
  1158. }
  1159. * */
  1160. public static string Base64Encode(string strData, System.Text.Encoding encType = null) {
  1161. if (encType == null) encType = System.Text.Encoding.ASCII;
  1162. if (string.IsNullOrEmpty(strData)) return "";
  1163. return Convert.ToBase64String(encType.GetBytes(strData));
  1164. }
  1165. public static string Base64Decode(string strData, System.Text.Encoding encType = null) {
  1166. if (encType == null) encType = System.Text.Encoding.ASCII;
  1167. if (string.IsNullOrEmpty(strData)) return "";
  1168. byte[] buf = Convert.FromBase64String(strData);
  1169. return encType.GetString(buf);
  1170. }
  1171. public static string ConvertEncoding(Encoding src, Encoding dst, string str) {
  1172. byte[] b = src.GetBytes(str);
  1173. byte[] bConvert = System.Text.Encoding.Convert(src, dst, b);
  1174. string retValue = "";
  1175. foreach (byte bb in bConvert) {
  1176. retValue += ((char)bb).ToString();
  1177. }
  1178. return retValue;
  1179. }
  1180. public static string DecodeHtmlChars(string aText) {
  1181. string[] parts = aText.Split(new string[] { "&#" }, StringSplitOptions.None);
  1182. for (int i = 1; i < parts.Length; i++) {
  1183. int n = parts[i].IndexOf(';');
  1184. string number = parts[i].Substring(0, n);
  1185. try {
  1186. string data = string.Format("{0:X}", int.Parse(number));
  1187. int unicode = Convert.ToInt32(data, 16);
  1188. parts[i] = ((char)unicode) + parts[i].Substring(n + 1);
  1189. } catch { }
  1190. }
  1191. return String.Join("", parts);
  1192. }
  1193. public static string MakeData(NVC Form) {
  1194. string retValue = "";
  1195. foreach (string key in Form.AllKeys) {
  1196. if (key != "__VIEWSTATE") {
  1197. string[] array_data = Form[key].Split(',');
  1198. if (array_data.Length == 1) {
  1199. if (retValue == "") {
  1200. retValue = key + "=" + Form[key];
  1201. } else {
  1202. retValue += "&" + key + "=" + Form[key];
  1203. }
  1204. } else {
  1205. foreach (string value in array_data) {
  1206. if (retValue == "") {
  1207. retValue = key + "=" + value;
  1208. } else {
  1209. retValue += "&" + key + "=" + value;
  1210. }
  1211. }
  1212. }
  1213. }
  1214. }
  1215. return retValue;
  1216. }
  1217. public static int GetNotInVat(object Price) {
  1218. if (ToInt(Price) == 0) {
  1219. return 0;
  1220. }
  1221. return (int)Math.Round(ToInt(Price) / 1.1, 0);
  1222. }
  1223. public static int GetVat(object Price) {
  1224. if (ToInt(Price) == 0) {
  1225. return 0;
  1226. }
  1227. return ToInt(Price) - (int)Math.Round(ToInt(Price) / 1.1, 0);
  1228. }
  1229. public static string LinkString(string targetStr, string str, string separator) {
  1230. if (targetStr == "") {
  1231. targetStr = str;
  1232. } else {
  1233. targetStr += separator + str;
  1234. }
  1235. return targetStr;
  1236. }
  1237. public static Dictionary<string, Dictionary<string, object>> DataTableToDictionaty(DataTable dt, string key_column) {
  1238. var cols = dt.Columns.Cast<DataColumn>().Where(c => c.ColumnName != key_column);
  1239. return dt.Rows.Cast<DataRow>().ToDictionary(r => r[key_column].ToString(), r => cols.ToDictionary(c => c.ColumnName, c => r[c.ColumnName]));
  1240. }
  1241. public static int[] ToInt32Array(string[] array) {
  1242. return array.Select(x => Util.ToInt(x)).ToArray();
  1243. }
  1244. public static string GetIndexString(string[] array, int index, string whitespaceString = "") {
  1245. string result = "";
  1246. if (array.Length > index) {
  1247. result = array[index];
  1248. }
  1249. if (string.IsNullOrWhiteSpace(result)) {
  1250. result = whitespaceString;
  1251. }
  1252. return result;
  1253. }
  1254. public static string GetMaskedValue(string value) {
  1255. return new String('*', Util.S(value).Trim().Length);
  1256. }
  1257. public static string GetMaskedTel(string tel) {
  1258. var value = Util.S(tel).Trim();
  1259. if (value.Length <= 4) return value;
  1260. var pre = value.Substring(0, value.Length - 4);
  1261. var post = value.Substring(value.Length - 4, 4);
  1262. var pre1 = "";
  1263. var pre2 = "";
  1264. if (pre.Length <= 4) {
  1265. pre2 = pre;
  1266. } else {
  1267. pre1 = pre.Substring(0, 3);
  1268. pre2 = pre.Substring(3);
  1269. }
  1270. var regex = new Regex("[0-9]", RegexOptions.Compiled);
  1271. pre2 = regex.Replace(pre2, "*");
  1272. return pre1 + pre2 + post;
  1273. }
  1274. public static string GetMaskedEmail(string email) {
  1275. var value = Util.S(email).Trim();
  1276. var atIndex = value.IndexOf('@');
  1277. if (atIndex == -1) return email;
  1278. var pre = value.Substring(0, atIndex);
  1279. var post = value.Substring(atIndex);
  1280. var pre1 = "";
  1281. var pre2 = "";
  1282. if (pre.Length <= 1) {
  1283. pre1 = pre;
  1284. } else {
  1285. int sIdx = pre.Length / 2;
  1286. pre1 = pre.Substring(0, sIdx);
  1287. pre2 = new String('*', pre.Length - sIdx);
  1288. }
  1289. return pre1 + pre2 + post;
  1290. }
  1291. public static string FormCollectionToQueryString(NVC Form) {
  1292. string retValue = "";
  1293. foreach (string key in Form.AllKeys) {
  1294. if (key != "__VIEWSTATE") {
  1295. string[] array_data = Form.GetValues(key);
  1296. if (array_data.Length == 1) {
  1297. if (retValue == "") {
  1298. retValue = key + "=" + Form[key];
  1299. } else {
  1300. retValue += "&" + key + "=" + Form[key];
  1301. }
  1302. } else {
  1303. foreach (string value in array_data) {
  1304. if (retValue == "") {
  1305. retValue = key + "=" + value;
  1306. } else {
  1307. retValue += "&" + key + "=" + value;
  1308. }
  1309. }
  1310. }
  1311. }
  1312. }
  1313. return retValue;
  1314. }
  1315. public static T GetEnumValueAttribute<T>(object agent) where T : class {
  1316. var enumType = agent.GetType();
  1317. var memberInfos = enumType.GetMember(agent.ToString());
  1318. if (memberInfos != null && memberInfos.Length > 0) {
  1319. var memberInfo = memberInfos[0];
  1320. var enumAttrs = memberInfo.GetCustomAttributes(typeof(T), false);
  1321. if (enumAttrs.Length > 0) {
  1322. var enumAttr = enumAttrs[0] as T;
  1323. if (enumAttr != null) {
  1324. return enumAttr;
  1325. }
  1326. }
  1327. }
  1328. return null;
  1329. }
  1330. /// <summary>
  1331. /// 태그제거
  1332. /// </summary>
  1333. /// <param name="html">HTML</param>
  1334. /// <returns></returns>
  1335. public static string RemoveTag(string html) {
  1336. Regex tag = new Regex("(<([^>]+)>)");
  1337. string removeTag = tag.Replace(html, "");
  1338. return removeTag;
  1339. }
  1340. /// <summary>
  1341. /// 문자열내의 존재하는 단어 찾기
  1342. /// </summary>
  1343. /// <param name="contents">대상 문자열</param>
  1344. /// <param name="words">찾을 문자배열</param>
  1345. /// <returns></returns>
  1346. public static MatchCollection WordsMatch(string contents, string[] words) {
  1347. Regex regWords = new Regex("(" + String.Join("|", words) + ")");
  1348. MatchCollection matches = regWords.Matches(contents);
  1349. return matches;
  1350. }
  1351. public static bool IsDate(string date) {
  1352. return DateTime.TryParse(date, out DateTime outDt);
  1353. }
  1354. }
  1355. }