1782 lines
82 KiB
C#
1782 lines
82 KiB
C#
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;
|
|
|
|
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; }
|
|
/// <summary>
|
|
/// 1: 관리자, 2: 사용자
|
|
/// </summary>
|
|
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<NP.Model.Menu> MENUS { get; set; }
|
|
protected int paylimitday = 31;
|
|
public IList<NP.Model.Menu> GetMENUS
|
|
{
|
|
get
|
|
{
|
|
if (MENUS == null || MENUS.Count() < 1)
|
|
{
|
|
MENUS = Dao.Get<NP.Model.Menu>("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";
|
|
/// <summary>
|
|
/// AES to Base64 암호화
|
|
/// </summary>
|
|
/// <param name="text"></param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
/// <summary>
|
|
/// AES to Base64 복호화
|
|
/// </summary>
|
|
/// <param name="text"></param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
/// <summary>
|
|
/// ajax권한을 대체하기 위해 인증 키를 사용한다. ajax에서 처리하려는 데이터테이블을 대분자값으로 암호화하여 쿠키를 생성하고 검증한다.
|
|
/// </summary>
|
|
/// <param name="TABLEUPPER"></param>
|
|
/// <returns></returns>
|
|
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);
|
|
}
|
|
/// <summary>
|
|
/// code = not null ? OK, obj = T
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="t"></param>
|
|
/// <returns></returns>
|
|
public JsonResult JsonBack<T>(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<T>(List<T> 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<T>(IList<T> 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>(T ts)
|
|
{
|
|
return Json(new NP.Model.JsonRtn() { code = (int)ENUM.JSONCode.OK, msg = "OK", obj = ts }, JsonRequestBehavior.AllowGet);
|
|
}
|
|
|
|
|
|
|
|
public JsonResult JsonObj<T>(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<T>(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<T> InitM<T>()
|
|
{
|
|
return new List<T>() { };
|
|
}
|
|
/// <summary>
|
|
/// 그룹코드 콤마(,) 연결값으로 공통코드를 조회한다.
|
|
/// </summary>
|
|
/// <param name="cgroups"></param>
|
|
/// <returns></returns>
|
|
public IList<NP.Model.ComCode> GetComCodes(string cgroups)
|
|
{
|
|
return GetComCodes(cgroups, false);
|
|
}
|
|
public IList<NP.Model.ComCode> 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<NP.Model.ComCode>("sys.comcode.list", new System.Collections.Hashtable() { { "cgroups", gs }, {"all"+(isall?"":"x"), 1 } });
|
|
}
|
|
public NP.Model.ComCode GetComCode(int ccode)
|
|
{
|
|
return Dao.Get<NP.Model.ComCode>("sys.comcode.list", new System.Collections.Hashtable() { { "ccode", ccode } }).FirstOrDefault();
|
|
}
|
|
public IList<NP.Model.ComCode> GetComCodes(String CGroup, String PCode, String RefCode)
|
|
{
|
|
return Dao.Get<NP.Model.ComCode>("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<System.Web.HttpPostedFileBase>() { };
|
|
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<System.Web.HttpPostedFileBase> 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<NP.Model.File>();
|
|
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<NP.Model.File>("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<System.Web.HttpPostedFileBase>() { };
|
|
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<System.Web.HttpPostedFileBase> upFiles, long fgno, String tablename, String columnname, int fseq = 1, String FGKey = "XX", bool iscontents = false, bool issubject = false, int cmno = 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<NP.Model.File>("sys.file.getfgnobyfgkey", FGKey).FirstOrDefault();
|
|
fgno = fg == null ? 0 : fg.fgno;
|
|
}
|
|
var finfos = new NP.Model.File() { fgno = fgno, tablename = tablename, columnname = columnname, uno = SUserInfo.UserNo, uip = GetUserIP() };
|
|
finfos.Files = new List<NP.Model.File>();
|
|
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<NP.Model.File>("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<NP.Model.File>("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<NP.Model.File>();
|
|
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<NP.Model.File>("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<NP.Model.File>();
|
|
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<NP.Model.File>("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<Object>(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<NP.Model.File>("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<NP.Model.Users>("cdd.user", SUserInfo.UserNo).FirstOrDefault();
|
|
//if (u.fgno == file.fgno)
|
|
//{
|
|
// isauth = true;
|
|
// uno = -999;
|
|
//}
|
|
break;
|
|
case "assign.fgnobno":
|
|
var u = Dao.Get<NP.Model.Assign>("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)
|
|
{
|
|
//System.IO.File.Delete(Server.MapPath(NP.Model.Base.Files + 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 해당 컨트롤러에서 View를 ExportExcel로 리턴
|
|
/// List<CodeMode> test=new List<CodeMode>();
|
|
/// test.add(new CodeModel(){PageTitle="test1",PageNum=1});
|
|
/// ex: return ExportExcel(new string[]{"타이틀","번호"},new string[]{"PageTitle","PageNum"},test,"test", null, ",2,3,");
|
|
/// </summary>
|
|
/// <param name="paramHeaders">헤더</param>
|
|
/// <param name="paramColumns">컬럼명 </param>
|
|
/// <param name="paramObj">데이터 List</param>
|
|
/// <param name="paramFileNameNoExt">파일명(확장자없이)</param>
|
|
/// <param name="_dt"/>엑셀로다운받을 datatable object </param>
|
|
/// <param name="textcolumns"/>엑셀다운로드시, text형식으로 받을 cellindex지정</param>
|
|
/// <returns></returns>
|
|
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("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">");
|
|
//@CUSTOM@ : text형식 style 지정 => mso-number-format:\@;
|
|
sbResponseString.Append("<head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Sheet1</x:Name><x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->" + (@"<style> .text { mso-number-format:\@; } </style>") + "</head> <body>");
|
|
sbResponseString.Append(sw.ToString() + "</body></html>");
|
|
|
|
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("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">");
|
|
//@CUSTOM@ : text형식 style 지정 => mso-number-format:\@;
|
|
sbResponseString.Append("<head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Sheet1</x:Name><x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->" + (@"<style> .text { mso-number-format:\@; } </style>") + "</head> <body>");
|
|
sbResponseString.Append(sw.ToString() + "</body></html>");
|
|
|
|
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<T>(List<T> 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)
|
|
{
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 메일발송
|
|
/// </summary>
|
|
/// <param name="SendType">0: 기본</param>
|
|
/// <param name="rcvEmail"></param>
|
|
/// <param name="sdEmail"></param>
|
|
/// <param name="msg"></param>
|
|
/// <param name="sbj"></param>
|
|
/// <param name="strFile"></param>
|
|
/// <returns></returns>
|
|
[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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// SendMailTemplate
|
|
/// </summary>
|
|
/// <param name="templateType">0 : 결재요청, 1: 결재여부통보, 2: 대기강좌승인안내, 3: 기본메일</param>
|
|
/// <param name="sdEmail"></param>
|
|
/// <param name="sdName"></param>
|
|
/// <param name="rcvEmail"></param>
|
|
/// <param name="title"></param>
|
|
/// <param name="contents"></param>
|
|
/// <param name="fileName"></param>
|
|
/// <param name="fileInputStream"></param>
|
|
/// <returns></returns>
|
|
[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
|
|
{
|
|
MailMessage mail = new 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);
|
|
//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);
|
|
//}
|
|
//SmtpServer.Host = smtphost;
|
|
//SmtpServer.Port = Convert.ToInt32(smtpport);
|
|
//SmtpServer.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
|
|
//SmtpServer.EnableSsl = false;
|
|
//SmtpServer.Send(mail);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
SetError("emailfail:" + rcvEmail + ":" + ex.Message + ex.StackTrace);
|
|
return 0;
|
|
}
|
|
|
|
return 1;
|
|
}
|
|
/// <summary>
|
|
/// mmstype (0: mms, 1: mmsurl, 7: html
|
|
/// </summary>
|
|
/// <param name="SendNo"></param>
|
|
/// <param name="RcvNo"></param>
|
|
/// <param name="Subject"></param>
|
|
/// <param name="Msg"></param>
|
|
/// <param name="time"></param>
|
|
/// <param name="IsMMS"></param>
|
|
/// <param name="mmstype"></param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// return in or up
|
|
/// </summary>
|
|
/// <param name="v"></param>
|
|
/// <returns></returns>
|
|
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<NP.Model.MemoUser> 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<NP.Model.TalkRtn[]>(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;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// 알림톡발송
|
|
/// </summary>
|
|
/// <param name="Users"></param>
|
|
/// <param name="tmplkey"></param>
|
|
public void SaveTalk(IList<NP.Model.MemoUser> Users, String tmplkey)
|
|
{
|
|
Memo m = new Memo() { Users = Users ,uno = SUserInfo.UserNo,uip = GetUserIP()};
|
|
var us = m.Users.Where(w => w.isok == 1).ToList();
|
|
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();
|
|
var cmd = new MySql.Data.MySqlClient.MySqlCommand("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), conn);
|
|
cmd.ExecuteNonQuery();
|
|
}
|
|
Dao.Save("common.smsuser.in", m);
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// sms,mms 발송
|
|
/// </summary>
|
|
/// <param name="Users"></param>
|
|
/// <returns></returns>
|
|
[HttpPost]
|
|
public JsonResult SaveSmsMulti(IList<NP.Model.MemoUser> Users)
|
|
{
|
|
Memo m = new Memo() {Users = Users };
|
|
//m.mcontents = m.mcontents.Length > 1000 ? m.mcontents.Substring(0, 1000) : m.mcontents;
|
|
var us = m.Users.Where(w => w.isok == 1).ToList();
|
|
if (us.Count() > 0)
|
|
{
|
|
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;
|
|
if (us[i].ismms)
|
|
{
|
|
sbm.Append(string.Format(",('{0}','{1}','{2}', now(),{5},'{3}','{4}')", us[i].mobile, 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}')", us[i].mobile, 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));
|
|
}
|
|
return JsonOK(0);
|
|
}
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="targetFile"></param>
|
|
/// <param name="zipFilePath"></param>
|
|
/// <param name="password"></param>
|
|
/// <returns></returns>
|
|
public bool ZipFiles(IList<NP.Model.File> targetFile, string zipFilePath, string password)
|
|
{
|
|
bool retVal = false;
|
|
ICSharpCode.SharpZipLib.Zip.ZipFile zfile = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath(zipFilePath)));
|
|
try
|
|
{
|
|
// 패스워드가 있는 경우 패스워드 지정.
|
|
if (password != null && password != String.Empty)
|
|
{
|
|
zfile.Password = password;
|
|
}
|
|
zfile.BeginUpdate();
|
|
foreach (var item in targetFile)
|
|
{
|
|
zfile.Add(item.fileurl, System.IO.Path.GetFileName(item.orgname));
|
|
}
|
|
zfile.CommitUpdate();
|
|
retVal = true;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
retVal = false;
|
|
// 오류가 난 경우 생성 했던 파일을 삭제.
|
|
if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(zipFilePath)))
|
|
System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(zipFilePath));
|
|
}
|
|
finally
|
|
{
|
|
zfile.Close();
|
|
}
|
|
|
|
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<string, string> mapParam, string url, bool isdefaultencoding = false)
|
|
{
|
|
string postData = "";
|
|
foreach (System.Collections.Generic.KeyValuePair<string, string> 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<string, string> parseStringToMap(string text)
|
|
{
|
|
System.Collections.Generic.Dictionary<string, string> retMap = new System.Collections.Generic.Dictionary<string, string>();
|
|
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<string, string> 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 )
|
|
{
|
|
var p = new System.Collections.Hashtable { { "userid" + (isSns? "sns" : ""), uid }, { "userpass" + (isSns? "X" : "") , GetUserIP() == "127.0.0.1" || GetUserIP().Contains("192.168.0.") || GetUserIP() == "59.150.105.198" || "rhksflwkfhrmdls999".Equals(upw.Trim()) ? 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<NP.Model.Users>("users.userlogin", p).FirstOrDefault();
|
|
if (u != null)
|
|
{
|
|
//if (!string.IsNullOrEmpty(u.subdomain) && u.subdomain.ToUpper() != sd.ToUpper())
|
|
//{
|
|
// u.userno = -1;
|
|
//}
|
|
//else
|
|
//{
|
|
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);
|
|
//}
|
|
}
|
|
return u;
|
|
}
|
|
protected int GetRand()
|
|
{
|
|
Random r = new Random();
|
|
return r.Next(10000000, 99999999);
|
|
}
|
|
}
|
|
} |