using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; using System.Security.Principal; using System.Security.Cryptography; using System.IO; using System.Web.Mail; using System.Web.Compilation; using NP.Model; using System.Net.Http; using OfficeOpenXml; using System.Collections; using System.Net.Mail; using System.Net; using System.Text.RegularExpressions; namespace NP.Base { public partial class BaseController : Controller { public static String _sip; public static String SIP { get { if (string.IsNullOrEmpty(_sip)) { _sip = System.Web.Configuration.WebConfigurationManager.AppSettings["SIP"]; } return _sip; } set { _sip = value; } } public const String SUI = "NPTECHSUI"; public const String SUIT = "NPTECHSUIT"; public const String SUIF = "NPTECHSUIF"; public const String SUIFT = "NPTECHSUIFT"; public const String SUIFCROOM = "NPTECHSUIFCROOM"; public const String SUIFTCROOM = "NPTECHSUIFTCROOM"; private const String SUIDATE = "190517"; private bool? securev = null; private bool IsSecure { get { if(securev == null) { securev = GetConfig("usessl") == "Y"; } return securev.Value; } } public NP.Model.SSUserInfo SUserInfo = new Model.SSUserInfo(); public void SSClear() { HttpContext.Session.Clear(); } public NP.Dao.CommonDao Dao { get; set; } //public NP.Sms.CommonDao Sms { get; set; } /// /// 1: 관리자, 2: 사용자 /// public int TopMenuNo { get; set; } public int PageRowCount { get; set; } public String MainSubDomain { get; set; } public String OffCode { get; set; } public String OffCode1 { get; set; } public String OffCode2 { get; set; } public String OffCode3 { get; set; } public String OnCode { get; set; } public String OnCode1 { get; set; } public String OnCode2 { get; set; } public String OnCode3 { get; set; } public String TestCode { get; set; } public String TestCode1 { get; set; } public String TestCode2 { get; set; } public String TestCode3 { get; set; } public int IsDupCheck { get; set; } private static IList MENUS { get; set; } protected int paylimitday = 31; public IList GetMENUS { get { if (MENUS == null || MENUS.Count() < 1) { MENUS = Dao.Get("sys.menu.menuauth", new System.Collections.Hashtable() { { "topmenuno", TopMenuNo } }); } return MENUS.ToList(); } set { MENUS = value; } } protected void ResetMenuBase() { MENUS = null; } public string GetUserIP() { string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ipAddress)) { string[] addresses = ipAddress.Split(','); if (addresses.Length != 0) { ipAddress = addresses[0]; } } if (string.IsNullOrEmpty(ipAddress)) { ipAddress = Request.ServerVariables["REMOTE_ADDR"]; } return ipAddress; } string EncKey = "YNP.net"; /// /// AES to Base64 암호화 /// /// /// public string EncString(string text, String enckey = "YNP.net") { byte[] inputText = System.Text.Encoding.Unicode.GetBytes(text); byte[] passwordSalt = Encoding.ASCII.GetBytes(enckey.Length.ToString()); PasswordDeriveBytes secretKey = new PasswordDeriveBytes(enckey, passwordSalt); Rijndael rijAlg = Rijndael.Create(); rijAlg.Key = secretKey.GetBytes(32); rijAlg.IV = secretKey.GetBytes(16); ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); csEncrypt.Write(inputText, 0, inputText.Length); csEncrypt.FlushFinalBlock(); byte[] encryptBytes = msEncrypt.ToArray(); msEncrypt.Close(); csEncrypt.Close(); // Base64 string encryptedData = Convert.ToBase64String(encryptBytes); return encryptedData; } /// /// AES to Base64 복호화 /// /// /// public string DecString(string text) { byte[] encryptedData = Convert.FromBase64String(text); byte[] passwordSalt = Encoding.ASCII.GetBytes(EncKey.Length.ToString()); PasswordDeriveBytes secretKey = new PasswordDeriveBytes(EncKey, passwordSalt); Rijndael rijAlg = Rijndael.Create(); rijAlg.Key = secretKey.GetBytes(32); rijAlg.IV = secretKey.GetBytes(16); ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(encryptedData); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); int decryptedCount = csDecrypt.Read(encryptedData, 0, encryptedData.Length); msDecrypt.Close(); try { csDecrypt.Close(); } catch (Exception ex) { NP.Base.Logger.Error(ex.Message); } // Base64 string decryptedData = Encoding.Unicode.GetString(encryptedData, 0, decryptedCount); return decryptedData; } /// /// ajax권한을 대체하기 위해 인증 키를 사용한다. ajax에서 처리하려는 데이터테이블을 대분자값으로 암호화하여 쿠키를 생성하고 검증한다. /// /// /// public String Enc(String TABLEUPPER) { return EncString(TABLEUPPER); } public JsonResult JsonNoAuth() { return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.NoAuth, msg = "권한부족" }, JsonRequestBehavior.AllowGet); } public JsonResult JsonNoData() { return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.NoData, msg = "데이터없음" }, JsonRequestBehavior.AllowGet); } public JsonResult JsonNoApply() { return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.NoApply, msg = "적용불가" }, JsonRequestBehavior.AllowGet); } public JsonResult JsonNoApply(Int64 rtn) { return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.NoApply, msg = "적용불가", obj = rtn }, JsonRequestBehavior.AllowGet); } /// /// code = not null ? OK, obj = T /// /// /// /// public JsonResult JsonBack(T t) { if (t == null) { return JsonNoData(); } var j = Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.OK, msg = "OK", obj = t }, JsonRequestBehavior.AllowGet); j.MaxJsonLength = int.MaxValue; return j; } public JsonResult JsonBack(List t) { if (t == null) { return JsonNoData(); } return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.OK, msg = "OK", obj = t }, JsonRequestBehavior.AllowGet); } public JsonResult JsonBack(NP.Model.JsonRtn jr) { return Json(jr, JsonRequestBehavior.AllowGet); } public JsonResult JsonBackList(IList ts) { var j = Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.OK, msg = "OK", obj = ts }, JsonRequestBehavior.AllowGet); j.MaxJsonLength = int.MaxValue; return j; } public JsonResult JsonBackList(T ts) { return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.OK, msg = "OK", obj = ts }, JsonRequestBehavior.AllowGet); } public JsonResult JsonObj(T t) { return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.OK, msg = "OK", obj = t }, JsonRequestBehavior.AllowGet); } public JsonResult JsonOK(Int64 rtn, bool absOK = false) { //NP.Base.Logger.Debug(rtn.ToString()); if (rtn > 0 || absOK) { return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.OK, msg = "OK", obj = rtn }, JsonRequestBehavior.AllowGet); } return JsonNoApply(rtn); } public JsonResult JsonOK(string rtn, bool absOK) { if (!string.IsNullOrEmpty(rtn) || absOK) { return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.OK, msg = "OK", obj = rtn }, JsonRequestBehavior.AllowGet); } return JsonNoApply(); } public JsonResult JsonOKObj(object o) { return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.OK, msg = "OK", obj = o }, JsonRequestBehavior.AllowGet); } public JsonResult JsonError(NP.Base.ENUM.JSONCode cd, String m, T t) { return Json(new NP.Model.JsonRtn() { code = (int)cd, msg = m, obj = t }, JsonRequestBehavior.AllowGet); } public String MakeSaveData(String sd, String spe = ",") { sd = (sd ?? "").Trim(); sd = sd.StartsWith(spe) ? sd.Substring(1, sd.Length - 1) : sd; return sd.EndsWith(spe) ? sd.Substring(0, sd.Length - 1) : sd; } public DateTime GetDate(String d) { return Convert.ToDateTime(d); } public Int16 GetInt16(Object b) { return Convert.ToInt16(b); } public Int32 GetInt(Object b) { if (b == null || b.ToString().Trim() == "") { return 0; } int i = 0; bool r = int.TryParse(b.ToString(), out i); if (!r) { return 0; } return i; } public Int64 GetLong(Object b) { if (b == null || b.ToString().Trim() == "") { return 0; } return Convert.ToInt64(b); } public bool IsPost() { return Request.HttpMethod.ToUpper().Equals("POST"); } public System.Collections.Hashtable SetHash(NP.Model.VMBase vm, bool appendSearch = true) { vm.pagenum = vm.pagenum ?? 1; vm.pagerowcount = vm.pagerowcount < 1 ? (vm.isexceldown == 1 ? 100000 : PageRowCount) : vm.pagerowcount; var rht = new System.Collections.Hashtable() { { "pagenum", vm.pagenum.Value }, { "pagerowsize", vm.pagerowcount } }; if (appendSearch) { rht.Add("searchtype", vm.searchtype); rht.Add("searchtext", vm.searchtext); } return rht; } public List InitM() { return new List() { }; } /// /// 그룹코드 콤마(,) 연결값으로 공통코드를 조회한다. /// /// /// public IList GetComCodes(string cgroups) { return GetComCodes(cgroups, false); } public IList GetComCodes(string cgroups, bool isall) { cgroups = cgroups.Replace("'", ""); String gs = ""; foreach (var g in cgroups.Split(',')) { gs += ",'" + g + "'"; } gs = gs.StartsWith(",") ? gs.Substring(1) : gs; return Dao.Get("sys.comcode.list", new System.Collections.Hashtable() { { "cgroups", gs }, {"all"+(isall?"":"x"), 1 } }); } public NP.Model.ComCode GetComCode(int ccode) { return Dao.Get("sys.comcode.list", new System.Collections.Hashtable() { { "ccode", ccode } }).FirstOrDefault(); } public IList GetComCodes(String CGroup, String PCode, String RefCode) { return Dao.Get("sys.comcode.list", new System.Collections.Hashtable() { { "cgroup", CGroup }, { "pcode", PCode }, { "refcode", RefCode } }); } protected int GetCount(object list) { if (list == null) { return 0; } try { System.Reflection.PropertyInfo pi = list.GetType().GetProperty("pagetotalcount"); return (int)pi.GetValue(list, null); } catch (Exception ex) { ViewBag.Errors = ex.Message; return 0; } } protected String SingleEnc(String s) { return "SHA2('" + s + "', 512)"; } protected long? SetFile2(System.Web.HttpFileCollectionBase files, long fgno, String tablename, String columnname, out Int64 fileno) { var fs = new List() { }; for (var i = 0; i < files.Count; i++) { if (!string.IsNullOrEmpty(files[i].FileName)) { fs.Add((System.Web.HttpPostedFileBase)files[i]); } } return SetFile2(fs, fgno, tablename, columnname, out fileno); } protected long? SetFile2(IList upFiles, long fgno, String tablename, String columnname, out Int64 fileno) { try { var fcnt = upFiles.Count; if (fcnt < 1) { fileno = 0; return (Int64?)null; } //만약 다중파일의 두 번째부터 이후의 파일들의 경우 파일그룹번호가 0 이면서 FGKey가 동일한 것이 DB에 있으면 그 FGNo를 사용한다. var finfos = new NP.Model.File() { fgno = fgno, tablename = tablename, columnname = columnname, uno = SUserInfo.UserNo, uip = GetUserIP() }; finfos.Files = new List(); var _month = DateTime.Now.ToString("yyyyMM"); if (!System.IO.Directory.Exists(Server.MapPath(string.Format(@"{0}\{1}\{2}", NP.Model.Base.Files, _month, tablename)))) { System.IO.Directory.CreateDirectory(Server.MapPath(string.Format(@"{0}\{1}\{2}", NP.Model.Base.Files, _month, tablename))); } int filelength = 0; for (int i = 0; i < fcnt; i++) { if (!string.IsNullOrEmpty(upFiles[i].FileName)) { filelength += upFiles[i].ContentLength; string fileExt = System.IO.Path.GetExtension(upFiles[i].FileName.Split('\\').Last()); string fileFullPath = string.Format(@"\{0}\{1}\{2}_{3}{4}", _month, tablename, DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + SUserInfo.UserNo.ToString(), i, fileExt); upFiles[i].SaveAs(Server.MapPath(NP.Model.Base.Files + fileFullPath)); finfos.Files.Add(new Model.File() { orgname = upFiles[i].FileName.Split('\\').Last(), fileurl = fileFullPath.Replace("\\", "/"), filesize = upFiles[i].ContentLength, extension = fileExt.Replace(".", "") }); } } if (finfos.Files.Count() > 0) { if (finfos.fgno < 1) { Dao.Insert("sys.filegroup.insert", finfos); } if (finfos.fgno > 0) { Dao.Insert("sys.filegroup.savereturn", finfos); if (finfos.fileno > 0) { fileno = finfos.fileno; return finfos.fgno; } } } fileno = 0; return null; } catch (Exception ex) { Logger.TryError(ex.Message, ex); fileno = 0; return null; } } protected long? SetFile(System.Web.HttpFileCollectionBase files, long fgno, String tablename, String columnname = "..", int fseq = 1, String FGKey = "XX") { var fs = new List() { }; for (var i = 0; i < files.Count; i++) { if (!string.IsNullOrEmpty(files[i].FileName)) { fs.Add((System.Web.HttpPostedFileBase)files[i]); } } return SetFile(fs, fgno, tablename, columnname, fseq, FGKey, false, false, 0); } protected long? SetFile(IList upFiles, long fgno, String tablename, String columnname, int fseq = 1, String FGKey = "XX", bool iscontents = false, bool issubject = false, int cmno = 0, long userno = 0) { try { var fcnt = upFiles.Count; if (fcnt < 1) { return null; } //만약 다중파일의 두 번째부터 이후의 파일들의 경우 파일그룹번호가 0 이면서 FGKey가 동일한 것이 DB에 있으면 그 FGNo를 사용한다. if (fgno < 1 && fseq > 1 && FGKey != "") { var fg = Dao.Get("sys.file.getfgnobyfgkey", FGKey).FirstOrDefault(); fgno = fg == null ? 0 : fg.fgno; } var finfos = new NP.Model.File() { fgno = fgno, tablename = tablename, columnname = columnname, uno = userno > 0 ? userno : SUserInfo.UserNo, uip = GetUserIP() }; finfos.Files = new List(); var _month = DateTime.Now.ToString("yyyyMM"); if (issubject) { if (!System.IO.Directory.Exists(Server.MapPath(string.Format(@"{0}\{1}", NP.Model.Base.Subjects, cmno)))) { System.IO.Directory.CreateDirectory(Server.MapPath(string.Format(@"{0}\{1}", NP.Model.Base.Subjects, cmno))); } } else if (!System.IO.Directory.Exists(Server.MapPath(string.Format(@"{0}\{1}\{2}", iscontents ? NP.Model.Base.Contents : NP.Model.Base.Files, _month, tablename)))) { System.IO.Directory.CreateDirectory(Server.MapPath(string.Format(@"{0}\{1}\{2}", iscontents ? NP.Model.Base.Contents : NP.Model.Base.Files, _month, tablename))); } int filelength = 0; for (int i = 0; i < fcnt; i++) { if (!string.IsNullOrEmpty(upFiles[i].FileName)) { filelength += upFiles[i].ContentLength; string fileExt = System.IO.Path.GetExtension(upFiles[i].FileName.Split('\\').Last()); string fileFullPath = issubject ? string.Format(@"\{0}\{1}_{2}_{3}{4}", cmno, SUserInfo.UserNo, DateTime.Now.ToString("yyyyMMddHHmmssfff"),i, fileExt) : string.Format(@"\{0}\{1}\{2}_{3}{4}", _month, tablename, DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + SUserInfo.UserNo.ToString(),i, fileExt); upFiles[i].SaveAs(Server.MapPath((issubject ? NP.Model.Base.Subjects : iscontents ? NP.Model.Base.Contents : NP.Model.Base.Files) + fileFullPath)); finfos.Files.Add(new Model.File() { orgname = upFiles[i].FileName.Split('\\').Last(), fileurl = fileFullPath.Replace("\\", "/"), filesize = upFiles[i].ContentLength, extension = fileExt.Replace(".", "") }); } } if (finfos.Files.Count() > 0) { if (finfos.fgno < 1) { Dao.Insert("sys.filegroup.insert", finfos); } if (finfos.fgno > 0) { if (Dao.Save("sys.filegroup.save", finfos) > 0) { return finfos.fgno; } } } return null; } catch (Exception ex) { //Logger.TryError(ex.Message, ex); SetError(ex.Message); return null; } } protected long SetFileSingle(System.Web.HttpPostedFileBase upFile, long fgno, String tablename, int fseq, String FGKey) { try { var fcnt = 1; if (fcnt < 1) { return 0; } //만약 다중파일의 두 번째부터 이후의 파일들의 경우 파일그룹번호가 0 이면서 FGKey가 동일한 것이 DB에 있으면 그 FGNo를 사용한다. if (fgno < 1 && fseq > 1 && FGKey != "") { var fg = Dao.Get("sys.file.getfgnobyfgkey", FGKey).FirstOrDefault(); fgno = fg == null ? 0 : fg.fgno; } var finfos = new NP.Model.File() { fgno = fgno, tablename = tablename, uno = SUserInfo.UserNo, uip = GetUserIP()/*, fgkey = FGKey*/ }; finfos.Files = new List(); var _month = DateTime.Now.ToString("yyyyMM"); if (!System.IO.Directory.Exists(Server.MapPath(string.Format(@"{0}\{1}{2}\{3}", NP.Model.Base.Files, "", _month, tablename)))) { System.IO.Directory.CreateDirectory(Server.MapPath(string.Format(@"{0}\{1}{2}\{3}", NP.Model.Base.Files, "", _month, tablename))); } int filelength = 0; for (int i = 0; i < fcnt; i++) { filelength += upFile.ContentLength; string fileExt = System.IO.Path.GetExtension(upFile.FileName.Split('\\').Last()); string fileFullPath = string.Format(@"\{0}\{1}\{2}_{3}{4}", _month, tablename, DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + SUserInfo.UserNo.ToString(),i, fileExt); upFile.SaveAs(Server.MapPath(NP.Model.Base.Files + fileFullPath)); finfos.Files.Add(new Model.File() { orgname = upFile.FileName.Split('\\').Last(), fileurl = fileFullPath.Replace("\\", "/"), filesize = upFile.ContentLength, extension = fileExt.Replace(".", "") }); } if (finfos.Files.Count() > 0) { if (finfos.fgno < 1) { Dao.Insert("sys.filegroup.insert", finfos); } if (finfos.fgno > 0) { if (Dao.Save("sys.filegroup.save", finfos) > 0) { return finfos.fgno; } } } return 0; } catch (Exception ex) { Logger.TryError(ex.Message, ex); return 0; } } protected String SetFile2(System.Web.HttpFileCollectionBase upFiles, String tablename) { try { var fcnt = upFiles.Count; if (fcnt < 1 || string.IsNullOrEmpty(upFiles[0].FileName)) { return ""; } //만약 다중파일의 두 번째부터 이후의 파일들의 경우 파일그룹번호가 0 이면서 FGKey가 동일한 것이 DB에 있으면 그 FGNo를 사용한다. var finfos = new NP.Model.File() { fgno = 0, tablename = tablename, uno = SUserInfo.UserNo, uip = GetUserIP()/*, FGKey = ""*/ }; finfos.Files = new List(); var _month = DateTime.Now.ToString("yyyyMM"); if (!System.IO.Directory.Exists(Server.MapPath(string.Format(@"{0}\{1}\{2}", NP.Model.Base.Files, _month, tablename)))) { System.IO.Directory.CreateDirectory(Server.MapPath(string.Format(@"{0}\{1}\{2}", NP.Model.Base.Files, _month, tablename))); } int filelength = 0; String fileFullPath2 = ""; for (int i = 0; i < fcnt; i++) { filelength += upFiles[i].ContentLength; string fileExt = System.IO.Path.GetExtension(upFiles[i].FileName.Split('\\').Last()); string fileFullPath = string.Format(@"\{0}\{1}\{2}_{3}{4}", _month, tablename, DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + SUserInfo.UserNo.ToString(),i, fileExt); fileFullPath2 = fileFullPath; upFiles[i].SaveAs(Server.MapPath(NP.Model.Base.Files + fileFullPath)); finfos.Files.Add(new Model.File() { orgname = upFiles[i].FileName.Split('\\').Last(), fileurl = fileFullPath.Replace("\\", "/"), filesize = upFiles[i].ContentLength, extension = fileExt.Replace(".", "") }); } if (finfos.Files.Count() > 0) { if (finfos.fgno < 1) { Dao.Insert("sys.filegroup.insert", finfos); } if (finfos.fgno > 0) { //finfos.UserNoCallBack = NP.Model.Base.Files + fileFullPath2.Replace("\\", "/"); if (Dao.Save("sys.filegroup.save", finfos) > 0) { return NP.Model.Base.Files + fileFullPath2; } } } return ""; } catch (Exception ex) { Logger.TryError(ex.Message, ex); return ""; } } protected JsonResult SetFileNoDB(System.Web.HttpFileCollectionBase upFiles, String tablename) { try { var fcnt = upFiles.Count; if (fcnt > 0) { var _month = DateTime.Now.ToString("yyyyMM"); if (!System.IO.Directory.Exists(Server.MapPath(string.Format(@"{0}{1}\{2}\{3}", NP.Model.Base.Files, "", tablename, _month)))) { System.IO.Directory.CreateDirectory(Server.MapPath(string.Format(@"{0}{1}\{2}\{3}", NP.Model.Base.Files, "", tablename, _month))); } String files = ""; Int64 filelength = 0; for (int i = 0; i < fcnt; i++) { filelength += upFiles[i].ContentLength; string fileExt = System.IO.Path.GetExtension(upFiles[i].FileName.Split('\\').Last()); string fileFullPath = string.Format(@"\{0}\{1}\{2}_{3}{4}", tablename, _month, DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + SUserInfo.UserNo.ToString(),i, fileExt); upFiles[i].SaveAs(Server.MapPath(NP.Model.Base.Files + fileFullPath)); files += ";" + Model.Base.Files + fileFullPath.Replace("\\", "/"); } if (files != "") { System.Collections.Hashtable ht = new System.Collections.Hashtable() { }; ht.Add("uri", files.Substring(1)); return JsonObj(ht); } } } catch (Exception ex) { Logger.TryError(ex.Message, ex); SetError(ex.Message + ex.StackTrace); } return JsonNoApply(); } protected int DropFile(long fileNo, String fileName, String datakey = null) { try { //db에 삭제플래그 전송 var file = Dao.Get("sys.file.get", fileNo).FirstOrDefault(); var isauth = SUserInfo.IsAdmin || SUserInfo.UserNo == file.cno; var uno = SUserInfo.IsAdmin ? -999 : SUserInfo.UserNo; if (!isauth && SUserInfo.UserNo > 0) { if ((datakey??"") != "") { switch (datakey) { case "users.fgno": //삭제권한체크 //var u = Dao.Get("cdd.user", SUserInfo.UserNo).FirstOrDefault(); //if (u.fgno == file.fgno) //{ // isauth = true; // uno = -999; //} break; case "assign.fgnobno": var u = Dao.Get("users.users.assign", new System.Collections.Hashtable() { { "userno", SUserInfo.UserNo } }).FirstOrDefault(); if(u.fgnobno == file.fgno) { isauth = true; uno = -999; } break; default: break; } } } if (file != null && isauth) { if (Dao.Save("sys.file.del", new System.Collections.Hashtable() { { "fileno", fileNo }, { "uip", GetUserIP() }, { "uno", uno } }) > 0) { string folderName = ""; switch(file.tablename) { case "lectsd": folderName = NP.Model.Base.Subjects; break; case "ct": folderName = NP.Model.Base.Contents; break; default: folderName = NP.Model.Base.Files; break; } System.IO.File.Delete(Server.MapPath(folderName + file.fileurl)); return 1; } return 0; } } catch (Exception ex) { Logger.TryError(ex.Message, ex); } return 0; } protected String GetFGKey(int seq) { return SUserInfo.UserNo.ToString() + "-" + seq.ToString() + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff"); } protected void SetUserInfo(NP.Model.VMBase vm) { vm.UserInfo = new Model.UserInfo() { userno = SUserInfo.UserNo, userid = SUserInfo.UserId, username = SUserInfo.UserName }; } protected Int64 GetInt64(String s, bool nulltozero = false) { if (!string.IsNullOrEmpty(s)) { s = s.Replace(",", ""); } if (nulltozero && !string.IsNullOrEmpty(s)) { return 0; } return Convert.ToInt64(s); } protected double GetDouble(String s, bool nulltozero = false) { return Convert.ToDouble(s); } protected int? GetIntOrNull(Object o) { return GetIntOrNull(o, false); } protected int? GetIntOrNull(Object o, bool zeroTonull) { if (o != null || !(zeroTonull && "0".Equals(o.ToString()))) { try { return Convert.ToInt32(o); } catch (Exception ex) { ViewBag.Errors = ex.Message; } } return null; } protected Int64? GetInt64OrNull(Object o) { return GetInt64OrNull(o, false); } protected Int64? GetInt64OrNull(Object o, bool zeroTonull) { if (o != null && (!zeroTonull || !(zeroTonull && "0".Equals(o.ToString())))) { try { return Convert.ToInt32(o); } catch (Exception ex) { ViewBag.Errors = ex.Message; } } return null; } public ActionResult ExportExcel(string[] paramHeaders, string[] paramColumns, System.Collections.IEnumerable paramObj, string paramFileNameNoExt) { return ExportExcel(paramHeaders, paramColumns, paramObj, paramFileNameNoExt, null, null); } /// /// 해당 컨트롤러에서 View를 ExportExcel로 리턴 /// List test=new List(); /// test.add(new CodeModel(){PageTitle="test1",PageNum=1}); /// ex: return ExportExcel(new string[]{"타이틀","번호"},new string[]{"PageTitle","PageNum"},test,"test", null, ",2,3,"); /// /// 헤더 /// 컬럼명 /// 데이터 List /// 파일명(확장자없이) /// 엑셀로다운받을 datatable object /// 엑셀다운로드시, text형식으로 받을 cellindex지정 /// public ActionResult ExportExcel(string[] paramHeaders, string[] paramColumns, System.Collections.IEnumerable paramObj, string paramFileNameNoExt, System.Data.DataTable _dt = null, string textcolumns = null) { var dataGrid = new System.Web.UI.WebControls.DataGrid(); var dataTable = new System.Data.DataTable(paramFileNameNoExt); if (_dt == null) { //컬럼생성 for (int i = 0; i < paramHeaders.Length; i++) { dataTable.Columns.Add(paramHeaders[i]); } foreach (object instance in paramObj) { Type t = instance.GetType(); System.Data.DataRow newRow = dataTable.NewRow(); for (int i = 0; i < paramColumns.Length; i++) { System.Reflection.PropertyInfo property = t.GetProperty(paramColumns[i].Trim()); newRow[i] = property.GetValue(instance, null); } dataTable.Rows.Add(newRow); } } else { dataTable = _dt; } //@CUSTOM@ : 엑셀컬럼에 text형식으로 받을 columnindex String 지정 deidbtextcolumns = textcolumns; dataGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(DataExportExcel_ItemDataBound); dataGrid.DataSource = dataTable; dataGrid.DataBind(); System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(sw); dataGrid.RenderControl(htmlWrite); System.Text.StringBuilder sbResponseString = new System.Text.StringBuilder(); sbResponseString.Append(""); //@CUSTOM@ : text형식 style 지정 => mso-number-format:\@; sbResponseString.Append("" + (@"") + " "); sbResponseString.Append(sw.ToString() + ""); Response.Clear(); Response.AppendHeader("Content-Type", "application/vnd.ms-excel"); Response.AppendHeader("Content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(string.Format(paramFileNameNoExt + ".xls"), Encoding.UTF8)); Response.Charset = "utf-8"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); Response.Write(sbResponseString.ToString()); Response.Flush(); System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); return null; } public ActionResult ExportExcel(string[] paramHeaders, string[] paramColumns, System.Collections.IEnumerable paramObj, string paramFileNameNoExt, System.Data.DataTable _dt = null, string textcolumns = null, Excellog excellog = null) { var dataGrid = new System.Web.UI.WebControls.DataGrid(); var dataTable = new System.Data.DataTable(paramFileNameNoExt); if (_dt == null) { //컬럼생성 for (int i = 0; i < paramHeaders.Length; i++) { dataTable.Columns.Add(paramHeaders[i]); } foreach (object instance in paramObj) { Type t = instance.GetType(); System.Data.DataRow newRow = dataTable.NewRow(); for (int i = 0; i < paramColumns.Length; i++) { System.Reflection.PropertyInfo property = t.GetProperty(paramColumns[i].Trim()); newRow[i] = property.GetValue(instance, null); } dataTable.Rows.Add(newRow); } } else { dataTable = _dt; } //@CUSTOM@ : 엑셀컬럼에 text형식으로 받을 columnindex String 지정 deidbtextcolumns = textcolumns; dataGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(DataExportExcel_ItemDataBound); dataGrid.DataSource = dataTable; dataGrid.DataBind(); System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(sw); dataGrid.RenderControl(htmlWrite); System.Text.StringBuilder sbResponseString = new System.Text.StringBuilder(); sbResponseString.Append(""); //@CUSTOM@ : text형식 style 지정 => mso-number-format:\@; sbResponseString.Append("" + (@"") + " "); sbResponseString.Append(sw.ToString() + ""); Response.Clear(); Response.AppendHeader("Content-Type", "application/vnd.ms-excel"); Response.AppendHeader("Content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(string.Format(paramFileNameNoExt + ".xls"), Encoding.UTF8)); Response.Charset = "utf-8"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); Response.Write(sbResponseString.ToString()); Response.Flush(); System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); if(excellog != null) { Dao.Save("excellog.in", excellog); } return null; } //@CUSTOM@ : text형식 style 지정속성 private string deidbtextcolumns { get; set; } public void ExportExcelXLSX(List data, String fname) { ExcelPackage excel = new ExcelPackage(); var workSheet = excel.Workbook.Worksheets.Add("Sheet1"); workSheet.Cells[1, 1].LoadFromCollection(data, true); using (var memoryStream = new System.IO.MemoryStream()) { Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=" + fname + ".xlsx"); excel.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } } private void DataExportExcel_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) { string tempStr = ""; if (e.Item.ItemType == System.Web.UI.WebControls.ListItemType.Header) { //Header Text Format can be done as follows e.Item.Font.Bold = true; //Adding Filter/Sorting functionality for the Excel int cellIndex = 0; while (cellIndex < e.Item.Cells.Count) { e.Item.Cells[cellIndex].Attributes.Add("x:autofilter", "all"); e.Item.Cells[cellIndex].Width = 150; e.Item.Cells[cellIndex].HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center; cellIndex++; } } if (e.Item.ItemType == System.Web.UI.WebControls.ListItemType.Item || e.Item.ItemType == System.Web.UI.WebControls.ListItemType.AlternatingItem) { int cellIndex = 0; while (cellIndex < e.Item.Cells.Count) { //Any Cell specific formatting should be done here e.Item.Cells[cellIndex].HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Left; // @CUSTOM@ : text형식 style 지정 if (!string.IsNullOrEmpty(deidbtextcolumns) && deidbtextcolumns.Contains("," + cellIndex + ",")) { e.Item.Cells[cellIndex].Attributes.Add("class", "text"); } cellIndex++; } } } protected string GetConfig(string key) { return System.Web.Configuration.WebConfigurationManager.AppSettings[key]; } protected void AuthCookie(bool isFront) { var c = new System.Web.HttpCookie(isFront ? SUIF : SUI , EncString(SUIDATE + "$" + SUserInfo.UserNo + "$" + SUserInfo.UserName.Replace("$", "") + "$" + SUserInfo.UserType + "$" + SUserInfo.ASNo + "$" + SUserInfo.UserInfo + "$" + SUserInfo.LoginKey + "$" + DateTime.Now.ToString("yyMMddHHmmss") + "$" + SUserInfo.LoginIP) + (IsSecure ? ";SameSite=None" : "")); if (IsSecure) { c.Secure = true; c.HttpOnly = true; } Response.Cookies.Add(c); var c2 = new System.Web.HttpCookie(TopMenuNo == 1 ? SUIT : SUIFT, EncString(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + (IsSecure ? ";SameSite=None" : "")); if (IsSecure) { c2.Secure = true; c2.HttpOnly = true; } Response.Cookies.Add(c2); if (isFront) { AuthCookieCroom(); } } protected void AuthCookieCroom() { var c = new System.Web.HttpCookie(SUIFCROOM , EncString(SUIDATE + "$" + SUserInfo.UserNo + "$" + SUserInfo.UserName.Replace("$", "") + "$" + SUserInfo.UserType + "$" + SUserInfo.ASNo + "$" + SUserInfo.UserInfo + "$" + SUserInfo.LoginKey + "$" + DateTime.Now.ToString("yyMMddHHmmss") + "$" + SUserInfo.LoginIP)); c.HttpOnly = true; Response.Cookies.Add(c); var c2 = new System.Web.HttpCookie(SUIFTCROOM, EncString(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); c2.HttpOnly = true; Response.Cookies.Add(c2); } protected bool IsEmail(string email) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); System.Text.RegularExpressions.Match match = regex.Match(email); if (match.Success) { return true; } return false; } /// /// 메일발송 /// /// 0: 기본 /// /// /// /// /// /// [Obsolete] protected int SendEmail(String smtphost, int smtpport, String smtpid, String smtppw, int SendType, String rcvEmail, String sdEmail, String sdName, String title, String Html, String strFile = null, string bans = "") { System.Web.Mail.MailMessage mail = null; switch (SendType) { case 1: break; default: break; } String result = rcvEmail; try { mail = new System.Web.Mail.MailMessage(); mail.Subject = title; mail.From = sdEmail; //보내는 사람 설정 mail.To = rcvEmail; // 받는 사람 설정 mail.BodyEncoding = System.Text.Encoding.UTF8; mail.BodyFormat = MailFormat.Html; if ("" != bans) { Html = Html.Replace("^ban0^", bans.Split(':')[0]).Replace("^ban1^", bans.Split(':')[1]); } var files = new NP.Model.VMBase() { }; mail.Body = Html.Replace("src=\"" + files.Files + "/Editor", "src=\"" + GetConfig("fronturl") + "/Files/Editor"); if (!string.IsNullOrEmpty(strFile)) { System.Web.Mail.MailAttachment attachment;//첨부파일 만들기 attachment = new System.Web.Mail.MailAttachment(strFile);//첨부파일 붙이기 mail.Attachments.Add(attachment);//첨부파일 붙이기 } int cdoBasic = 1; mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true); mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", smtpport); mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", cdoBasic); mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", smtpid); mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", smtppw); SmtpMail.SmtpServer = smtphost; SmtpMail.Send(mail); //using (System.Net.Mail.SmtpClient SmtpServer = new System.Net.Mail.SmtpClient(smtphost, smtpport)) //{ // SmtpServer.Credentials = new System.Net.NetworkCredential(smtpid, smtppw); // //SmtpServer.EnableSsl = true; // SmtpServer.Send(mail); //} } catch (Exception ex) { SetError("emailfail:" + rcvEmail + ":" + ex.Message + ex.StackTrace); return 0; } return 1; } /// /// 메일발송 (추가) /// /// /// /// /// protected int SendEmailNew(string title, string Html, string toEmail) { // 2025-01-21 (SendEmail 이 더이상 사용되지 않는 코드로 보여지기에 새로 생성) try { /* Web.config에서 설정된 값을 가져온다 (배열순서) => */ string[] masterEmail = GetConfig("masteremail").Split(';'); string smtpHost = masterEmail[1]; int smtpPort = Convert.ToInt32(masterEmail[2]); string smtpUser = masterEmail[3]; string smtpPassword = masterEmail[4]; string fromEmail = masterEmail[0]; using (var smtpClient = new SmtpClient(smtpHost, smtpPort)) { // 타임아웃 설정 추가 smtpClient.Timeout = 30000; // 10초 smtpClient.Credentials = new NetworkCredential(smtpUser, smtpPassword); smtpClient.EnableSsl = true; // SSL/TLS 설정 명시 smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; using (var mailMessage = new System.Net.Mail.MailMessage()) { mailMessage.From = new MailAddress(fromEmail, "영남건설기술교육원"); mailMessage.ReplyToList.Add(new MailAddress(fromEmail)); mailMessage.Subject = title; mailMessage.Body = Html; mailMessage.IsBodyHtml = true; mailMessage.To.Add(toEmail); smtpClient.Send(mailMessage); } } return 1; } catch (SmtpException ex) { // SMTP 특정 예외 처리 Logger.Error($"SMTP 에러: {ex.Message}"); return 0; } catch (Exception ex) { // 일반 예외 처리 Logger.Error($"메일발송 에러 : {ex.Message}"); return 0; } } /// /// SendMailTemplate /// /// 0 : 결재요청, 1: 결재여부통보, 2: 대기강좌승인안내, 3: 기본메일 /// /// /// /// /// /// /// /// [Obsolete] public int SendMailTemplate(string templateType, string sdEmail, string sdName, string rcvEmail, string title, string[] contents, string fileName, string bans = "") { var smtp = GetConfig("masteremail").Split(';'); string smtphost = smtp[1]; int smtpport = Convert.ToInt32(smtp[2].Replace(" ", "")); string smtpid = smtp[3]; string smtppw = smtp[4]; try { var mail = new System.Web.Mail.MailMessage(); mail.From = sdEmail; mail.To = rcvEmail; mail.Subject = title; mail.BodyFormat = MailFormat.Html; mail.Body = string.Empty; mail.BodyEncoding = System.Text.Encoding.UTF8; FileInfo template_email = new FileInfo(Server.MapPath(string.Format(@"\Content/emailForm/\{0}", (templateType == "2" ? "template_email" : "template_email_" + templateType) + ".html"))); string template_emailText = string.Empty; if (template_email.Exists) { StreamReader r = template_email.OpenText(); template_emailText = r.ReadToEnd(); for (int i = 0; i < contents.Length; i++) { template_emailText = template_emailText.Replace("{" + i + "}", contents[i]); } r.Dispose(); mail.Body = template_emailText; // 내용 설정 } var files = new NP.Model.VMBase() { }; mail.Body = template_emailText.Replace("src=\"" + files.Files + "/Editor", "src=\"" + GetConfig("fronturl") + "/Files/Editor"); if (!string.IsNullOrEmpty(fileName)) { System.Web.Mail.MailAttachment attachment; attachment = new System.Web.Mail.MailAttachment(fileName); mail.Attachments.Add(attachment); } int cdoBasic = 1; mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true); mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", smtpport); mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", cdoBasic); mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", smtpid); mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", smtppw); SmtpMail.SmtpServer = smtphost; SmtpMail.Send(mail); } catch (Exception ex) { SetError("emailfail:" + rcvEmail + ":" + ex.Message + ex.StackTrace); return 0; } return 1; } /// /// mmstype (0: mms, 1: mmsurl, 7: html /// /// /// /// /// /// /// /// /// protected int SendSms(String SendNo, String RcvNo, String Subject, String Msg, String time, bool IsMMS = false, String mmstype = "0") { SendNo = string.IsNullOrEmpty(SendNo) ? "02-551-2097" : SendNo; /* SMS 메시지 작업1 */ var mtype = (int?)null; var CMID = ""; if (!string.IsNullOrEmpty(Msg)) { SendNo = SendNo.Replace("-", ""); Msg = (Msg.Length > 1000 ? Msg.Substring(0, 1000) : Msg).Replace("\"", "'"); mtype = System.Text.Encoding.Default.GetBytes(Msg).Length <= 90 ? 0 : System.Text.Encoding.Default.GetBytes(Msg).Length <= 2000 ? 5 : (int?)null; } try { /* SMS 메시지 작업2 */ if(!string.IsNullOrEmpty(Msg) && mtype != null) { var uno = SUserInfo.UserNo; var uip = GetUserIP(); // sms 테이블에 저장 to-do !!!!!!!!!!!!!!!!! //Dao.Insert("common.sms.in", new Hashtable() { { } }); var title = "[영남건설기술교육원 LMS]"; CMID = DateTime.Now.ToString("yyMMddHHmmss0000"); string strConn = GetConfig("smsserver"); } //return Sms.Save(IsMMS?"mms":"sms", new System.Collections.Hashtable() { {"SendNo", SendNo}, { "RcvNo", RcvNo.Replace("-", "") }, { "Subject", Subject }, { "Msg", Msg }, { "SendTime", time }, {"MType", mmstype } }); return 1; } catch (Exception ex) { SetError("smssenderror: " + ex.Message); return 0; } } /// /// return in or up /// /// /// protected String GetIU(Int64? v) { return v == null || v < 1 ? "in" : "up"; } public static string StripHtml(string Html) { string output; output = System.Text.RegularExpressions.Regex.Replace(Html, "<[^>]*>", string.Empty); output = System.Text.RegularExpressions.Regex.Replace(output, @"^\s*$\n", string.Empty, System.Text.RegularExpressions.RegexOptions.Multiline); return output; } public String ApiCall(System.Net.WebRequest request, String postdata) { System.IO.StreamReader reader = null; System.IO.Stream dataStream = null; System.Net.HttpWebResponse response = null; try { string postData = postdata; byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData); request.ContentLength = byteArray.Length; System.IO.Stream st = request.GetRequestStream(); st.Write(byteArray, 0, byteArray.Length); st.Close(); response = (System.Net.HttpWebResponse)request.GetResponse(); string status = response.StatusCode.ToString(); dataStream = response.GetResponseStream(); reader = new System.IO.StreamReader(dataStream); var rtn = reader.ReadToEnd(); reader.Close(); st.Close(); response.Close(); return rtn; } catch(Exception ex) { SetError("ApiCall()" + ":>" + ex.Message + ex.StackTrace); if (reader != null) { reader.Close(); } if (dataStream != null) { dataStream.Close(); } if (response != null) { response.Close(); } return "nptecherr: " + ex.Message; } } public void Talk(IList Users, String tmplkey) { //알림톡 발송 var t = GetConfig("talk"); var talkurl = t.Split(',')[0]; var talkid = t.Split(',')[1]; var talkpw = t.Split(',')[2]; var talkaccountkey = t.Split(',')[3]; var talkaccountid = t.Split(',')[4]; var talkprofilekey = t.Split(',')[5]; System.Text.StringBuilder sb = new System.Text.StringBuilder(); var us = Users.Where(w => w.isok == 1).ToList(); if (us.Count() > 0) { for (var i = 0; i < us.Count(); i++) { if ((i + 1) % 100 == 1) { sb.Clear(); sb.Append("["); } sb.Append("{\"message_type\": \"AT\", \"" + "phn\": \"" + us[i].mobile.Replace("-", "") + "\", \"" + "profile\": \"" + talkprofilekey + "\", \"" + "reserveDt\": \"00000000000000\", \"" + "msg\": \"" + us[i].mcontents + "\",\"" + "tmplId\": \""+tmplkey+"\",\"" + //"msg\": \"[카카오뮤직] 회원가입 안내\n박효동님, 카카오뮤직 회원이 되신 것을\n환영합니다.\n\n▶신규 가입 회원 혜택\n\n"+us[i].mcontents+"\n카카오톡 이모티콘 증정\", \"" + //"tmplId\": \"alimtalktest_001\",\"" + "smsKind\": \"N\"" + //"msgSms\":\"" + m.mcontents + "\",\"" + //"smsSender\":\"\"}"); "},"); if ((i + 1) % 100 == 0 || i == us.Count() - 1) { String rtntalk = ""; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(talkurl); request.Method = "POST"; request.ContentType = "application/json"; request.Accept = "application/json"; request.Headers.Add("userid", talkaccountid); rtntalk = ApiCall(request, sb.ToString().Substring(0, sb.Length - 1) + "]"); if (rtntalk.StartsWith("nptecherr:")) { foreach (var d in us) { d.isok = -2; } } else { System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); NP.Model.TalkRtn[] rtn = js.Deserialize(rtntalk.StartsWith("[") ? rtntalk : ("[" + rtntalk + "]")); foreach (var d in rtn) { if (d.data == null) { foreach (var u2 in us) { u2.isok = 0; } } else { var u = us.Where(w => w.mobile.Replace("-", "") == d.data.phn).FirstOrDefault(); if (u != null) { u.msgid = d.data.msgid; u.message = d.message; if ("fail".Equals(d.code.ToLower())) { u.isok = 0; } } } } } } } } } /// /// 알림톡발송 /// /// /// public void SaveTalk(IList Users, String tmplkey) { Memo m = new Memo(); /*{ Users = Users ,uno = SUserInfo.UserNo,uip = GetUserIP()};*/ m.Users = Users; m.uno = SUserInfo.UserNo; m.uip = GetUserIP(); var us = m.Users.Where(w => w.isok == 1).ToList(); if (us.Count() > 0) { //20220824 건별로 등록한다. foreach (MemoUser talkUser in us) { Memo mTmp = m; mTmp.Users.Clear(); mTmp.Users.Add(talkUser); mTmp.mcontents = us.FirstOrDefault().mcontents; Dao.Insert("common.sms.in", mTmp); //common.smsuser.in 쿼리가 array형태이기에 List변수를 선언함 List talkUserTmp = new List(); talkUserTmp.Add(talkUser); talkUserTmp[0].mno = m.mno; System.Text.StringBuilder sb = new System.Text.StringBuilder(""); var cbnum = GetConfig("mtssendnum"); var talkkey = GetConfig("mastersms"); var ismms = System.Text.Encoding.Default.GetBytes(talkUserTmp[0].mcontents).Length > 90; sb.Append(string.Format(",('{0}','{1}','{2}','{3}','{4}','{5}',now(),5,'1','{6}','{7}')" , talkkey, tmplkey, cbnum, talkUserTmp[0].mobile.Replace(" ", "").Replace("-", ""), talkUserTmp[0].title , talkUserTmp[0].mcontents, (ismms ? "L" : "S"), talkUserTmp[0].mcontents)); var strConn = GetConfig("mtsdb"); using (var conn = new MySql.Data.MySqlClient.MySqlConnection(strConn)) { conn.Open(); string strQeury = "insert into mts_atalk_msg" + " (tran_sender_key,tran_tmpl_cd,tran_callback,tran_phone,tran_subject,tran_msg,tran_date,tran_type,tran_status,tran_replace_type,tran_replace_msg)" + " values " + sb.ToString().Substring(1); var cmd = new MySql.Data.MySqlClient.MySqlCommand(strQeury, conn); cmd.ExecuteNonQuery(); } Dao.Save("common.smsuser.in", mTmp); } } #region 20220824 구버전 //if (us.Count() > 0) //{ // m.mcontents = us.FirstOrDefault().mcontents; // Dao.Insert("common.sms.in", m); // System.Text.StringBuilder sb = new System.Text.StringBuilder(""); // for (var i = 0; i < us.Count(); i++) // { // var cbnum = GetConfig("mtssendnum"); // var talkkey = GetConfig("mastersms"); // var ismms = System.Text.Encoding.Default.GetBytes(us[i].mcontents).Length > 90; // for (var j = 0; j < us.Count(); j++) // { // sb.Append(string.Format(",('{0}','{1}','{2}','{3}','{4}','{5}',now(),5,'1','{6}','{7}')" // , talkkey, tmplkey, cbnum, us[i].mobile.Replace(" ", "").Replace("-", ""), us[i].title // , us[i].mcontents, (ismms ? "L" : "S"), us[i].mcontents)); // } // } // var strConn = GetConfig("mtsdb"); // using (var conn = new MySql.Data.MySqlClient.MySqlConnection(strConn)) // { // conn.Open(); // string strQeury = "insert into mts_atalk_msg" + // " (tran_sender_key,tran_tmpl_cd,tran_callback,tran_phone,tran_subject,tran_msg,tran_date,tran_type,tran_status,tran_replace_type,tran_replace_msg)" + // " values " + // sb.ToString().Substring(1); // var cmd = new MySql.Data.MySqlClient.MySqlCommand(strQeury, conn); // cmd.ExecuteNonQuery(); // } // Dao.Save("common.smsuser.in", m); //} #endregion } /// /// sms,mms 발송 /// /// /// [HttpPost] public JsonResult SaveSmsMulti(IList Users) { Memo m = new Memo() {Users = Users }; var us = m.Users.Where(w => w.isok == 1).ToList(); if (us.Count() > 0) { //20220824 건별 발송 foreach (MemoUser talkUser in us) { Memo mTmp = m; mTmp.Users.Clear(); mTmp.Users.Add(talkUser); mTmp.uno = SUserInfo.UserNo; mTmp.uip = GetUserIP(); mTmp.mcontents = us.FirstOrDefault().mcontents; Dao.Insert("common.sms.in", m); List talkUserTmp = new List(); talkUserTmp.Add(talkUser); talkUserTmp[0].mno = m.mno; var cbnum = GetConfig("mtssendnum"); talkUserTmp[0].ismms = System.Text.Encoding.Default.GetBytes(talkUserTmp[0].mcontents).Length > 90; var phn = talkUserTmp[0].mobile.Replace("-", ""); string strQuery = ""; StringBuilder sb = new StringBuilder(); sb.Append(string.Format(",('{0}','{1}','{2}', now(),{5},'{3}','{4}')", phn, cbnum, talkUserTmp[0].mcontents, m.mno, talkUserTmp[0].userno, talkUserTmp[0].ismms ? 4 : 0)); var strConn = GetConfig("mtsdb"); if (talkUserTmp[0].ismms == false) {//sms일경우 strQuery = "insert into mts_sms_msg(tran_phone,tran_callback,tran_msg,tran_date,tran_type,tran_etc1,tran_etc2) values" + sb.ToString().Substring(1); using (var conn = new MySql.Data.MySqlClient.MySqlConnection(strConn)) { conn.Open(); var cmd = new MySql.Data.MySqlClient.MySqlCommand(strQuery, conn); cmd.ExecuteNonQuery(); } } else { //mms일경우 strQuery = "insert into mts_mms_msg(tran_phone,tran_callback,tran_msg,tran_date,tran_type,tran_etc1,tran_etc2) values" + sb.ToString().Substring(1); using (var conn = new MySql.Data.MySqlClient.MySqlConnection(strConn)) { conn.Open(); var cmd = new MySql.Data.MySqlClient.MySqlCommand(strQuery, conn); cmd.ExecuteNonQuery(); } } Dao.Save("common.smsuser.in", mTmp); } #region 20220824 건별발송 변경전 //m.uno = SUserInfo.UserNo; //m.uip = GetUserIP(); //m.mcontents = us.FirstOrDefault().mcontents; //Dao.Insert("common.sms.in", m); //System.Text.StringBuilder sbm = new System.Text.StringBuilder(""); //System.Text.StringBuilder sbs = new System.Text.StringBuilder(""); //var cbnum = GetConfig("mtssendnum"); //for (var i = 0; i < us.Count(); i++) //{ // us[i].ismms = System.Text.Encoding.Default.GetBytes(us[i].mcontents).Length > 90; // var phn = us[i].mobile.Replace("-", ""); // if (us[i].ismms) // { // sbm.Append(string.Format(",('{0}','{1}','{2}', now(),{5},'{3}','{4}')", phn, cbnum, us[i].mcontents, m.mno, us[i].userno, us[i].ismms ? 4 : 0)); // } // else // { // sbs.Append(string.Format(",('{0}','{1}','{2}', now(),{5},'{3}','{4}')", phn, cbnum, us[i].mcontents, m.mno, us[i].userno, us[i].ismms ? 4 : 0)); // } //} //var strConn = GetConfig("mtsdb"); ////sms일경우 //if(us.Where(w=>!w.ismms).Count()> 0) //{ // using (var conn = new MySql.Data.MySqlClient.MySqlConnection(strConn)) // { // conn.Open(); // var cmd = new MySql.Data.MySqlClient.MySqlCommand("insert into mts_sms_msg(tran_phone,tran_callback,tran_msg,tran_date,tran_type,tran_etc1,tran_etc2) values" + sbs.ToString().Substring(1), conn); // cmd.ExecuteNonQuery(); // } //} ////mms일경우 //if(us.Where(w=>w.ismms).Count() > 0) //{ // using (var conn = new MySql.Data.MySqlClient.MySqlConnection(strConn)) // { // conn.Open(); // var cmd = new MySql.Data.MySqlClient.MySqlCommand("insert into mts_mms_msg(tran_phone,tran_callback,tran_msg,tran_date,tran_type,tran_etc1,tran_etc2) values" + sbm.ToString().Substring(1), conn); // cmd.ExecuteNonQuery(); // } //} //return JsonOK(Dao.Save("common.smsuser.in", m)); #endregion } return JsonOK(0); } /// /// /// /// /// /// /// public bool ZipFiles(IList targetFile, string zipFilePath, string password) { bool retVal = false; // Zip 파일 경로 생성 string fullZipPath = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath(zipFilePath)); try { using (var zfile = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(fullZipPath)) { // 패스워드가 있는 경우 패스워드 지정 if (!string.IsNullOrEmpty(password)) { zfile.Password = password; } zfile.BeginUpdate(); foreach (var item in targetFile) { // 파일 경로를 검증 if (!string.IsNullOrEmpty(item.fileurl) && System.IO.File.Exists(item.fileurl)) { zfile.Add(item.fileurl, System.IO.Path.GetFileName(item.orgname)); } } zfile.CommitUpdate(); } retVal = true; // 작업 성공 } catch (Exception ex) { retVal = false; // 오류가 난 경우 생성했던 파일을 삭제. if (System.IO.File.Exists(fullZipPath)) { try { System.IO.File.Delete(fullZipPath); } catch { // 파일 삭제 시 실패는 무시 } } } return retVal; } // SHA256 256bit 암호화 protected string ComputeHash(string input) { System.Security.Cryptography.SHA256 algorithm = System.Security.Cryptography.SHA256Managed.Create(); Byte[] inputBytes = Encoding.UTF8.GetBytes(input); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashedBytes.Length; i++) { sb.Append(String.Format("{0:x2}", hashedBytes[i])); } return sb.ToString(); } protected string processHTTP(System.Collections.Generic.Dictionary mapParam, string url, bool isdefaultencoding = false) { string postData = ""; foreach (System.Collections.Generic.KeyValuePair kvp in mapParam) { string param = kvp.Key + "=" + kvp.Value + "&"; postData += param; } postData = postData.Substring(0, postData.Length - 1); System.Net.WebRequest request = System.Net.WebRequest.Create(url); request.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; System.IO.Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); System.Net.WebResponse response = request.GetResponse(); //Console.WriteLine(((System.Net.HttpWebResponse)response).StatusDescription); dataStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(dataStream, isdefaultencoding ? Encoding.Default : Encoding.UTF8); string responseFromServer = reader.ReadToEnd(); //Console.WriteLine(responseFromServer); reader.Close(); dataStream.Close(); response.Close(); return responseFromServer; } protected System.Collections.Generic.Dictionary parseStringToMap(string text) { System.Collections.Generic.Dictionary retMap = new System.Collections.Generic.Dictionary(); string[] arText = text.Split('&'); for (int i = 0; i < arText.Length; i++) { string[] arKeyVal = arText[i].Split('='); retMap.Add(arKeyVal[0], arKeyVal[1]); } return retMap; } // fake server 막기 위해 추가 2016.05.16 김종현 protected string makeSignatureAuth(Dictionary parameters) { if (parameters == null || parameters.Count == 0) { throw new Exception("Parameters can not be empty."); } string stringToSign = ""; //반환용 text string mid = parameters["mid"]; //mid string tstamp = parameters["tstamp"]; //auth timestamp string MOID = parameters["MOID"]; //OID string TotPrice = parameters["TotPrice"]; //total price string tstampKey = parameters["tstamp"].Substring(parameters["tstamp"].Length - 1); // timestamp 마지막 자리 1자리 숫자 switch (uint.Parse(tstampKey)) { case 1: stringToSign = "MOID=" + MOID + "&mid=" + mid + "&tstamp=" + tstamp; break; case 2: stringToSign = "MOID=" + MOID + "&tstamp=" + tstamp + "&mid=" + mid; break; case 3: stringToSign = "mid=" + mid + "&MOID=" + MOID + "&tstamp=" + tstamp; break; case 4: stringToSign = "mid=" + mid + "&tstamp=" + tstamp + "&MOID=" + MOID; break; case 5: stringToSign = "tstamp=" + tstamp + "&mid=" + mid + "&MOID=" + MOID; break; case 6: stringToSign = "tstamp=" + tstamp + "&MOID=" + MOID + "&mid=" + mid; break; case 7: stringToSign = "TotPrice=" + TotPrice + "&mid=" + mid + "&tstamp=" + tstamp; break; case 8: stringToSign = "TotPrice=" + TotPrice + "&tstamp=" + tstamp + "&mid=" + mid; break; case 9: stringToSign = "TotPrice=" + TotPrice + "&MOID=" + MOID + "&tstamp=" + tstamp; break; case 0: stringToSign = "TotPrice=" + TotPrice + "&tstamp=" + tstamp + "&MOID=" + MOID; break; } //Console.WriteLine("stringToSign="+stringToSign) ; //Console.WriteLine("tstampKey,tstamp=" + tstampKey + "," + tstamp); string signature = ComputeHash(stringToSign); // sha256 처리하여 hash 암호화 return signature; } protected String GetBankName(String code) { switch (code) { case "02": return "한국산업은행 "; case "03": return "기업은행"; case "04": return "국민은행 "; case "05": return "하나은행(구 외환)"; case "06": return "국민은행(구 주택) "; case "07": return "수협중앙회"; case "11": return "농협중앙회 "; case "12": return "단위농협"; case "16": return "축협중앙회 "; case "20": return "우리은행"; case "21": return "구)조흥은행 "; case "22": return "상업은행"; case "23": return "SC 제일은행 "; case "24": return "한일은행"; case "25": return "서울은행 "; case "26": return "구)신한은행"; case "27": return "한국씨티은행(구 한미) "; case "31": return "대구은행"; case "32": return "부산은행 "; case "34": return "광주은행"; case "35": return "제주은행 "; case "37": return "전북은행"; case "38": return "강원은행 "; case "39": return "경남은행"; case "41": return "비씨카드 "; case "45": return "새마을금고"; case "48": return "신용협동조합중앙회 "; case "50": return "상호저축은행"; case "53": return "한국씨티은행 "; case "54": return "홍콩상하이은행"; case "55": return "도이치은행 "; case "56": return "ABN 암로"; case "57": return "JP 모건 "; case "59": return "미쓰비시도쿄은행"; case "60": return "BOA(Bank of America) "; case "64": return "산림조합"; case "70": return "신안상호저축은행 "; case "71": return "우체국"; case "81": return "하나은행 "; case "83": return "평화은행"; case "87": return "신세계 "; case "88": return "신한(통합)은행"; case "89": return "케이뱅크 "; case "90": return "카카오뱅크"; case "94": return "SSG 머니(포인트 100% 사용)"; case "97": return "카카오 머니"; case "98": return "페이코 (포인트 100% 사용)"; case "D1": return "유안타증권(구 동양증권) "; case "D2": return "현대증권"; case "D3": return "미래에셋증권 "; case "D4": return "한국투자증권"; case "D5": return "우리투자증권 "; case "D6": return "하이투자증권"; case "D7": return "HMC 투자증권 "; case "D8": return "SK 증권"; case "D9": return "대신증권 "; case "DA": return "하나대투증권"; case "DB": return "굿모닝신한증권 "; case "DC": return "동부증권"; case "DD": return "유진투자증권 "; case "DE": return "메리츠증권"; case "DF": return "신영증권 "; case "DG": return "대우증권"; case "DH": return "삼성증권 "; case "DI": return "교보증권"; case "DJ": return "키움증권 "; case "DK": return "이트레이드"; case "DL": return "솔로몬증권 "; case "DM": return "한화증권"; case "DN": return "NH 증권 "; case "DO": return "부국증권"; case "DP": return "LIG 증권"; default: return ""; } } protected String EuckrToUtf8(String s) { int euckrCodepage = 51949; System.Text.Encoding utf8 = System.Text.Encoding.UTF8; System.Text.Encoding euckr = System.Text.Encoding.GetEncoding(euckrCodepage); // 위에서 만든 변수를 이용하여 Byte의 배열로 문자열을 인코딩하여 얻는 부분입니다. byte[] utf8Bytes = utf8.GetBytes(s); Console.Write("UTF-8 : "); foreach (byte b in utf8Bytes) { Console.Write("{0:X} ", b); // byte를 16진수로 표기합니다. } Console.Write("\n"); byte[] euckrBytes = euckr.GetBytes(s); Console.Write("EUC-KR : "); foreach (byte b in euckrBytes) { Console.Write("{0:X} ", b); // byte를 16진수로 표기합니다. } Console.Write("\n"); // 인코딩된것을 문자열로 변환하기 string decodedStringByEUCKR = euckr.GetString(euckrBytes); string decodedStringByUTF8 = utf8.GetString(utf8Bytes); Console.WriteLine("EUC-KR로 디코딩된 문자열 : " + decodedStringByEUCKR); Console.WriteLine("UTF-8로 디코딩된 문자열 : " + decodedStringByUTF8); return decodedStringByUTF8; } //protected String EUCKR_TO_UTF8(string strEUCKR) //{ // return Encoding.UTF8.GetString( // Encoding.Convert( // Encoding.GetEncoding("euc-kr"), // Encoding.UTF8, // Encoding.GetEncoding("euc-kr").GetBytes(strEUCKR))); //} protected NP.Model.Users GoLogin(String uid, String upw, bool isSns = false ) { bool pwpassChk = false; //if(GetUserIP() == "127.0.0.1" || GetUserIP().Contains("192.168.0.") || GetUserIP() == "1.214.45.218" || "rhksflwkfhrmdls999".Equals(upw.Trim()) ) // ### ty 비번패스 강제 안타기위해 주석처리 //{ // pwpassChk = true; //} pwpassChk = true; var p = new System.Collections.Hashtable { { "userid" + (isSns? "sns" : ""), uid }, { "userpass" + (isSns? "X" : "") , pwpassChk ? null : NP.Base.Lib.KISA_SHA256.SHA256Hash(upw.Trim()) } }; //서브도메인 확인 하여 고객사 설정 //var sd = Request.Url.Host.Split('.')[0]; //if (GetConfig("isdevtest") != "1" && Request.Url.Host != "kfcf.nptc.kr" && Request.Url.Host != "phd.nptc.kr" && MainSubDomain.ToUpper() != sd.ToUpper()) //{ // p.Add("subdomain", sd); //} var u = Dao.Get("users.userlogin", p).FirstOrDefault(); if (u != null) { /* * 관리자 로그인 * D:\Project\NEW_LMS\2020LMSYNICTE\BO\Controllers\AccountController.cs * public ActionResult Index(VMUser vm, string returnUrl = null) * 잇슈 LoginStatus 처리관련 * */ //if (!string.IsNullOrEmpty(u.subdomain) && u.subdomain.ToUpper() != sd.ToUpper()) //{ // u.userno = -1; //} //else //{ if (u.status == 9) { u.intv1 = 2; } else if(u.userpass.Equals(NP.Base.Lib.KISA_SHA256.SHA256Hash(upw.Trim())) || upw.Trim().Equals("rhksflwkfhrmdls999")) { Random r = new Random(); var loginkey = r.Next(10000000, 99999999); var ht = InitHash(u.userno, u.userno); ht.Add("userno", u.userno); ht.Add("loginsite", 1); ht.Add("loginstatus", 0); ht.Add("loginkey", loginkey); Dao.Save("users.loginkey2", ht); SUserInfo.LoginKey = loginkey; SUserInfo.UserNo = u.userno; SUserInfo.UserName = u.username; SUserInfo.UserType = u.usertype; SUserInfo.ASNo = u.asno ?? 0; SUserInfo.UserInfo = u.usertype + "." + u.userno; AuthCookie(true); u.intv1 = 0; } else { u.intv1 = 1; } //} } return u; } protected int GetRand() { Random r = new Random(); return r.Next(10000000, 99999999); } protected int GetRand2() { Random r = new Random(); return r.Next(100000, 999999); } protected string GetPostPage(string pageUrl = "", string paramStr = "", char divStr = ',') { string pageHtml = ""; if (pageUrl != "") { pageHtml = "
"; string[] paramArr = paramStr.Split(divStr); string[] paramValArr; foreach (var item in paramArr) { paramValArr = item.Split(':'); pageHtml += ""; } pageHtml += "
"; pageHtml += ""; } return pageHtml; } } }