public async Task <ResponseModel> Post(RequestModel model) { var filePath = await fileManager.ReturnFileFullPath(model); if (String.IsNullOrEmpty(filePath)) { throw new ServiceException($"Could not find file path.!! ({ filePath })"); } gmail.auth(gmailOptions.Username, gmailOptions.Password); gmail.fromAlias = emailOptions.SenderName; gmail.To = "*****@*****.**"; gmail.Message = String.Empty; gmail.Priority = 0; gmail.Html = false; gmail.Subject = GetMessage(model); gmail.attach(filePath); var success = gmail.send(); if (!success) { throw new ServiceException($"UpdateTwitPic Fail!!({filePath})"); } return(ResponseModel.Message("1", $"UpdateTwitPic Success!!({ filePath })")); }
/// <summary> /// 파일 존재여부 확인 /// </summary> #endregion public ResponseModel GetFileInfo() { /* * gubun = file_info * attachment_key = string */ //_httpContext.Response.ClearHeaders(); //_httpContext.Response.ClearContent(); _httpContext.Response.Clear(); string xmldata = XMLCommonUtil.XMLHeader; ResponseModel responseModel = null; try { string fileFullPath = this.ReturnFileFullPath(ATTACHMENT_KEY); //가져온 파일정보에 맞는 파일을 리턴한다. if (File.Exists(fileFullPath)) { //xmldata += xmlCommonUtil.returnMSGXML("1", "서버상에 해당 파일이 존재합니다."); responseModel = ResponseModel.Message("1", "서버상에 해당 파일이 존재합니다."); } else { //xmldata += xmlCommonUtil.returnErrorMSGXML("서버상에 해당 파일이 존재하지 않습니다."); throw new ServiceException("서버상에 해당 파일이 존재하지 않습니다."); } } catch (ServiceException ex) { throw ex; } catch (Exception ex) { //xmldata += xmlCommonUtil.returnErrorMSGXML("httpservice(GetFileInfo).Error check", ex); throw new ServiceException("httpservice(GetFileInfo).Error check", ex); } finally { //_httpContext.Response.Write(xmldata); //_httpContext.Response.End(); } return(responseModel); }
/// <summary> /// 파일 존재여부 확인 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task <ResponseModel> GetFileInfo(RequestModel model) { ResponseModel result = null; try { string fileFullPath = await this.ReturnFileFullPath(model); if (!System.IO.File.Exists(fileFullPath)) { throw new ServiceException("서버상에 해당 파일이 존재하지 않습니다."); } result = ResponseModel.Message("1", "서버상에 해당 파일이 존재합니다."); } catch (Exception ex) { result = responsePreprocessManager.ProcessException(ex); } return(result); }
private static void UploadHandler(IApplicationBuilder app) { app.Run(async(context) => { var loggerFactory = app.ApplicationServices.GetService <ILoggerFactory>(); var logger = loggerFactory.CreateLogger("UploadHandler"); var httpContextManager = app.ApplicationServices.GetService <IHttpContextManager>(); var fileManager = app.ApplicationServices.GetService <IFileManager>(); RequestModel requestModel = null; ResponseModel responseModel = null; try { requestModel = await httpContextManager.ParseRequestData(); responseModel = await fileManager.UploadFile(requestModel); } catch (ServiceException ex) { responseModel = ResponseModel.ErrorMessage(ex); } catch (Exception ex) { logger.LogError(ex, $"{nameof(UploadHandler)}: {ex.Message}"); responseModel = ResponseModel.Message("100", "파일업로드 에러가 발생했습니다."); } if (responseModel == null) { responseModel = ResponseModel.DefaultMessage; } await context.ExecuteResponseModelResult(responseModel); }); }
public async Task <ResponseModel> Send(RequestModel model) { ResponseModel responseModel = null; try { //gmail.auth("*****@*****.**", "lee1004"); //1)web.config포함 -> 2)cms관리 mail 포함 //gmail.fromAlias = "kesso.kr";//1)web.config포함 -> 2)cms관리 mail 포함 gmail.auth(gmailOptions.Username, gmailOptions.Password); gmail.fromAlias = emailOptions.SenderName; gmail.Priority = 0; var pType = model.GetValue(Constants.P_TYPE_key); if (pType != Constants.P_TYPE_DIRECT_value) { throw new ServiceException("[p_type = direct] 이외 아직까지 구현되지 않았습니다."); } gmail.Html = false; var subject = model.GetValue(Constants.SUBJECT_key); var body = model.GetValue(Constants.MESSAGE_key); var toRaw = model.GetValue(Constants.TO_key); var toList = SplitEmailAddress(toRaw); //var attachment = model.GetValue(Constants.ATTACHMENT_KEY_key); if (String.IsNullOrEmpty(subject)) { //return xmlCommonUtil.ResponseWriteErrorMSG("제목이 없습니다.[subject = ?]"); throw new ServiceException("제목이 없습니다.[subject = ?]"); } gmail.Subject = subject; //"test 한글2"; gmail.Message = body; // "test 한글3"; if (toList.Count() == 0) { //return xmlCommonUtil.ResponseWriteErrorMSG("받을 사람이 없습니다.[to = ?]"); throw new ServiceException("받을 사람이 없습니다.[to = ?]"); } foreach (string to in toList) { gmail.To = to; } //FileCommonUtil fcu = new FileCommonUtil(); //string fileFullPath = fcu.CheckAttachmentKeyAndReturnFullFilePath();//첨부파일 1개기준 //string fileFullPath = fileCommonUtil.CheckAttachmentKeyAndReturnFullFilePath(); string fileFullPath = await fileManager.ReturnFileFullPath(model); if (!String.IsNullOrEmpty(fileFullPath)) { gmail.attach(fileFullPath); } bool success = gmail.send(); if (!success) { // TODO 추후 error로그 저장 후 메시지 전송할 것. throw new ServiceException("UpdateTwitPic Fail!!"); } // TODO 추후 로그 저장 후 메시지 전송할 것. responseModel = ResponseModel.Message("1", "UpdateTwitPic Success!!"); } catch (Exception ex) { responseModel = responsePreprocessManager.ProcessException(ex); } return(responseModel); }
private static void DefaultHandler(IApplicationBuilder app) { app.Run(async(context) => { if (context.Request.Path.HasValue) { var path = context.Request.Path.Value; } string[] noCheckSessionIDGubun = { "menu_ctrl_bind", }; // 의존 객체의 인스턴스를 생성합니다. var databaseManager = app.ApplicationServices.GetService <IDatabaseManager>(); var fileManager = app.ApplicationServices.GetService <IFileManager>(); var mobileMessageManager = app.ApplicationServices.GetService <IMobileMessageManager>(); var emailManager = app.ApplicationServices.GetService <IEmailManager>(); var httpContextManager = app.ApplicationServices.GetService <IHttpContextManager>(); var responsePreprocessManager = app.ApplicationServices.GetService <IResponsePreprocessManager>(); var twitPicManager = app.ApplicationServices.GetService <ITwitPicManager>(); RequestModel model = new RequestModel(); // HTTP 요청 본문 또는 FormData 를 객체로 변환합니다. model = await httpContextManager.ParseRequestData(); string gubun = model.GetValue(Constants.GUBUN_KEY_STRING); Func <bool> passCheckSessionIDFunc = () => { bool isPass = false; for (int i = 0; i < noCheckSessionIDGubun.Length; i++) { if (noCheckSessionIDGubun[i] == gubun) { isPass = true; break; } } return(isPass); }; var PassCheckSessionID = passCheckSessionIDFunc(); ResponseModel responseModel = null; DataSet dataSet = null; try { if (!PassCheckSessionID && !httpContextManager.Check(model)) { var clientSessionId = model.GetValue(Constants.SESSIONID_KEY_STRING); if (String.IsNullOrEmpty(clientSessionId)) { throw new ServiceException($"{Constants.SESSIONID_KEY_STRING}값을 넘기지 않았습니다."); } throw new ServiceException("999", "서버와 세션유지시간이 초과하였습니다."); } switch (gubun) { //sessionID_check case Constants.SESSIONID_CHECK_GUBUN: case Constants.GET_SESSIONID_GUBUN: var currentSessionId = httpContextManager.GetSessionId(); responseModel = ResponseModel.Message("1", currentSessionId); break; //userlogin case Constants.USER_LOGIN_GUBUN: dataSet = await databaseManager.ExecuteQueryAsync(model, true); responseModel = responsePreprocessManager.ProcessDataSet(dataSet); break; //break; case "menu_ctrl_bind": // 메뉴 데이터 처리 dataSet = await databaseManager.ExecuteQueryAsync(model, true); responseModel = responsePreprocessManager.ProcessDataSet(dataSet); break; /*/sendSMS - 사용안함. * case "send_public_sms": * string dataMmsPublicKey = xmlCommonUtil.QueryString["mms_public_key"]; * if (string.IsNullOrEmpty(dataMmsPublicKey)) * { * break; * } * string mmsPublicKey = ConfigurationManager.AppSettings["mms_public_key"].ToString(); * if (!string.Equals(dataMmsPublicKey, mmsPublicKey)) * { * break; * } * * SendMobileMSGCommon smmc2 = new SendMobileMSGCommon(); * smmc2.SendMobileMSG(); * break; * //*/ case "send_sms": responseModel = await mobileMessageManager.Send(model); break; case "csv": responseModel = await fileManager.DownloadCsv(model); break; case "send_email": responseModel = await emailManager.Send(model); break; case "upload_twitpic": responseModel = await twitPicManager.Post(model); break; /*기본 xml return *********************************/ default: if (!string.IsNullOrEmpty(model.GetValue(XMLCommonUtil.PROC_KEY_STRING))) { dataSet = await databaseManager.ExecuteQueryAsync(model, false); // 예제 데이터 확인 //dataResult = ResponseModel.Sampe; //dataResult = ResponseModel.Empty; responseModel = responsePreprocessManager.ProcessDataSet(dataSet); } else { throw new ServiceException("필수 매개변수를 넘기지 않았습니다."); } break; } } catch (Exception ex) { responseModel = responsePreprocessManager.ProcessException(ex); } if (responseModel == null) { responseModel = ResponseModel.DefaultMessage; } await context.ExecuteResponseModelResult(responseModel); return; }); }
/// <summary> /// 파일 이름 변경 /// </summary> #endregion public ResponseModel FileRename() { // TODO 사용되지 않습니다. /* * gubun = file_rename * attachment_gubun = string * target_file_name = string * file_name = string * ******************************************* * (옵션-DB 업데이트, 구현안됨)db_work = yes * (옵션-디비수정,구현안됨)attachment_key = string */ //_httpContext.Response.ClearHeaders(); //_httpContext.Response.ClearContent(); _httpContext.Response.Clear(); string xmldata = XMLCommonUtil.XMLHeader; ResponseModel responseModel = null; try { //string newFileName = xmlCommonUtil.QueryString[FileCommonUtil.ATTACHMENT_FILENAME_key]; string newFileName = xmlCommonUtil.RequestData.GetValue(FileCommonUtil.ATTACHMENT_FILENAME_key); string fileDir = ATTACHMENT_UPLOAD_PATH; //string targetFileName = xmlCommonUtil.QueryString[FileCommonUtil.ATTACHMENT_FILETARGET_key]; string targetFileName = xmlCommonUtil.RequestData.GetValue(FileCommonUtil.ATTACHMENT_FILETARGET_key); string fileFullPath = fileDir + targetFileName; string msg = string.Empty; if (File.Exists(fileFullPath)) { string fileName = newFileName; string dirName = fileDir; string fileFullPath2 = string.Format(@"{0}\{1}", dirName, fileName); fileFullPath2 = this.MakeUniqueFileName(fileFullPath2); File.Move(fileFullPath, fileFullPath2); FileInfo fi = new FileInfo(fileFullPath2); string renamedFileName = fi.Name; msg += string.Format("파일이름이 수정되었습니다.\n{0}->{1}", targetFileName, renamedFileName); } else { msg += "이름을 변경할 파일정보가 존재하지 않습니다."; } //xmldata += xmlCommonUtil.returnMSGXML("1", "파일 이름 변경.\n" + msg); responseModel = ResponseModel.Message("1", "파일 이름 변경.\n" + msg); } catch (ServiceException ex) { throw ex; } catch (Exception ex) { xmldata += xmlCommonUtil.returnErrorMSGXML("httpservice(FileRename).Error check", ex); throw new ServiceException("httpservice(FileRename).Error check", ex); } finally { //_httpContext.Response.Write(xmldata); //_httpContext.Response.End(); } return(responseModel); }
/// <summary> /// 파일 삭제 /// </summary> #endregion public ResponseModel DeleteFile() { /* * gubun = file_delete * (옵션1)************************************ * attachment_key = string * (옵션2)************************************ * attachment_gubun = string * file_name = string * db_work = pass */ string fileFullPath = string.Empty; ResponseModel responseModel = null; if (!string.IsNullOrEmpty(ATTACHMENT_KEY)) { fileFullPath = this.ReturnFileFullPath(ATTACHMENT_KEY); } else { //string namedFileName = xmlCommonUtil.QueryString[FileCommonUtil.ATTACHMENT_FILENAME_key]; string namedFileName = xmlCommonUtil.RequestData.GetValue(FileCommonUtil.ATTACHMENT_FILENAME_key); if (!string.IsNullOrEmpty(namedFileName)) { fileFullPath = this.ATTACHMENT_UPLOAD_PATH + namedFileName; } else { fileFullPath = string.Empty; } } string xmldata = XMLCommonUtil.XMLHeader; if (string.IsNullOrEmpty(fileFullPath)) { //xmldata += xmlCommonUtil.returnErrorMSGXML("삭제할 파일 정보가 올바르지 않습니다.(파일 삭제 방식을 체크하세요.)"); //_httpContext.Response.Clear(); //_httpContext.Response.Write(xmldata); //_httpContext.Response.End(); //return; throw new ServiceException("삭제할 파일 정보가 올바르지 않습니다.(파일 삭제 방식을 체크하세요.)"); } try { string msg = string.Empty; //가져온 파일정보의 실제 파일을 삭제한다. if (File.Exists(fileFullPath)) { FileInfo fi = new FileInfo(fileFullPath); string fileName = fi.Name; string dirName = fi.DirectoryName; if (!fileName.StartsWith("_del_")) { string fileFullPath2 = string.Format(@"{0}\{1}", dirName, "_del_" + fileName); fileFullPath2 = this.MakeUniqueFileName(fileFullPath2); fi.MoveTo(fileFullPath2); } //File.Delete(fileFullPath);//실제 삭제하지 않음. } if (string.IsNullOrEmpty(fileFullPath)) { msg += "파일정보가 존재하지 않습니다."; } //디비에서 해당 파일항목을 삭제한다. //string isDBWork = xmlCommonUtil.QueryString[FileCommonUtil.DB_WORK_GUBUN_value]; string isDBWork = xmlCommonUtil.RequestData.GetValue(FileCommonUtil.DB_WORK_GUBUN_value); if (!string.IsNullOrEmpty(isDBWork) && !isDBWork.Equals("pass")) { //db_work=pass 명시적으로 표시할 경우 디비 작업 없음. } else { this.Attachment_D(ATTACHMENT_KEY); } //xmldata += xmlCommonUtil.returnMSGXML("1", "파일 삭제완료.\r\n" + msg); responseModel = ResponseModel.Message("1", "파일 삭제완료.\r\n" + msg); } catch (ServiceException ex) { throw ex; } catch (Exception ex) { //xmldata += xmlCommonUtil.returnErrorMSGXML("httpservice(DeleteFile).Error check", ex); throw new ServiceException("httpservice(DeleteFile).Error check", ex); } //_httpContext.Response.Clear(); //_httpContext.Response.Write(xmldata); //_httpContext.Response.End(); return(responseModel); }
public async Task <ResponseModel> UploadFile(RequestModel model) { ResponseModel responseModel = null; try { /*웹서버 세션 정보 체크*/ string sessionID = httpContextManager.GetSessionId(); string client_SessionID = model.GetValue(Constants.SESSIONID_KEY_STRING); if (Constants.SESSION_CHECK && String.IsNullOrWhiteSpace(client_SessionID)) { throw new ServiceException("세션정보가 빈값이거나, 세션 정보를 넘기지 않습니다. 로그인 후 사용바랍니다."); } else if (Constants.SESSION_CHECK && httpContextManager.CheckSessionId(client_SessionID)) { throw new ServiceException("세션 정보가 올바르지 않습니다. 다시 로그인한 후 사용바랍니다."); } var formFiles = httpContextManager.GetFormFiles(); /*파일 업로드 갯수 제한*/ if (formFiles.Count == 0) { throw new ServiceException("업로드 파일이 없습니다."); } else if (formFiles.Count > 1) { throw new ServiceException("파일은 하나씩만 업로드 가능합니다."); } //저장위치를 지정 //string uploadDir = ConfigurationManager.AppSettings["etc"]; var uploadDir = appOptions.Etc; uploadDir = GetATTACHMENT_UPLOAD_PATH(model); //디렉토리 체크 if (!Directory.Exists(uploadDir)) { try { Directory.CreateDirectory(uploadDir); } catch (Exception ex) { throw new ServiceException("파일경로를 만들 수 없습니다.", ex); } } // 파일을 저장하고,(+이미지 파일일 경우 섬네일이미지를 생성하고 - 구현안됨) foreach (var file in formFiles) { //HttpPostedFile file = _context.Request.Files[fileKey]; //파일이름을 지정하여 저장할 것인가? file_name string namedFileName = model.GetValue(Constants.ATTACHMENT_FILENAME_key); string fileFullPath = String.Empty; if (!String.IsNullOrEmpty(namedFileName)) { fileFullPath = Path.Join(uploadDir, namedFileName); } else { fileFullPath = Path.Join(uploadDir, file.FileName); } fileFullPath = MakeUniqueFileName(fileFullPath); using (var stream = file.OpenReadStream()) { using (var destinationStream = new FileStream(fileFullPath, FileMode.Create, FileAccess.Write)) { await stream.CopyToAsync(destinationStream); await destinationStream.FlushAsync(); destinationStream.Close(); } stream.Close(); } FileInfo fileInfo = new FileInfo(fileFullPath); var attachment_filename = fileInfo.Name; var attachment_fileformat = fileInfo.Extension; var attachment_filesize = fileInfo.Length; // 디비를 저장하고 // 디비에 저장할 것인가? db_work string isDBWork = model.GetValue(Constants.DB_WORK_GUBUN_value); string return_msg = string.Empty; string resultXML = String.Empty; if (!String.IsNullOrEmpty(isDBWork) && !isDBWork.Equals("pass")) { //db_work=pass 명시적으로 표시할 경우 디비 작업 없음. // TODO 메시지가 없어서 추가 responseModel = ResponseModel.Message("1", "요청하신 파일이 업로드되었습니다."); } else { var dataSet = await Attachment_CRDAsync(CRUD.C, model, new FileModel { Name = attachment_filename, Format = attachment_fileformat, Size = attachment_filesize, }); responseModel = responsePreprocessManager.ProcessDataSet(dataSet); } } } catch (ServiceException ex) { responseModel = ResponseModel.ErrorMessage(ex); } catch (Exception ex) { responseModel = ResponseModel.Message("100", "파일업로드 에러가 발생했습니다."); //responseModel = ResponseModel.ErrorMessage(ex); } return(responseModel); }
public Task <ResponseModel> FileRename(RequestModel model) { // TODO 사용되지 않습니다. /* * gubun = file_rename * attachment_gubun = string * target_file_name = string * file_name = string * ******************************************* * (옵션-DB 업데이트, 구현안됨)db_work = yes * (옵션-디비수정,구현안됨)attachment_key = string */ ResponseModel responseModel = null; string message = String.Empty; try { string newFileName = model.GetValue(Constants.ATTACHMENT_FILENAME_key); string fileDir = GetATTACHMENT_UPLOAD_PATH(model); string targetFileName = model.GetValue(Constants.ATTACHMENT_FILETARGET_key); string fileFullPath = Path.Join(fileDir, targetFileName); if (File.Exists(fileFullPath)) { string fileName = newFileName; string dirName = fileDir; //string fileFullPath2 = string.Format(@"{0}\{1}", dirName, fileName); string fileFullPath2 = Path.Join(dirName, fileName); fileFullPath2 = this.MakeUniqueFileName(fileFullPath2); File.Move(fileFullPath, fileFullPath2); FileInfo fi = new FileInfo(fileFullPath2); string renamedFileName = fi.Name; message += $"파일이름이 수정되었습니다.{Environment.NewLine}{targetFileName}->{renamedFileName}"; } else { message += "이름을 변경할 파일정보가 존재하지 않습니다."; } responseModel = ResponseModel.Message("1", $"파일 이름 변경.{Environment.NewLine}{message}"); } catch (ServiceException ex) { responseModel = responsePreprocessManager.ProcessException(ex); } catch (Exception ex) { responseModel = responsePreprocessManager.ProcessException(new ServiceException("httpservice(FileRename).Error check", ex)); } finally { } return(Task.FromResult(responseModel)); }
public async Task <ResponseModel> DeleteFile(RequestModel model) { /* * gubun = file_delete * (옵션1)************************************ * attachment_key = string * (옵션2)************************************ * attachment_gubun = string * file_name = string * db_work = pass */ string fileFullPath = string.Empty; ResponseModel responseModel = null; if (model.HasKey(Constants.ATTACHMENT_KEY_key)) { fileFullPath = await this.ReturnFileFullPath(model); } else { string namedFileName = model.GetValue(Constants.ATTACHMENT_FILENAME_key); if (!string.IsNullOrEmpty(namedFileName)) { var uploadPath = GetATTACHMENT_UPLOAD_PATH(model); fileFullPath = System.IO.Path.Join(uploadPath, namedFileName); } else { fileFullPath = string.Empty; } } try { if (String.IsNullOrEmpty(fileFullPath)) { throw new ServiceException("삭제할 파일 정보가 올바르지 않습니다.(파일 삭제 방식을 체크하세요.)"); } //가져온 파일정보의 실제 파일을 삭제한다. if (File.Exists(fileFullPath)) { FileInfo fi = new FileInfo(fileFullPath); string fileName = fi.Name; string dirName = fi.DirectoryName; if (!fileName.StartsWith("_del_")) { //string fileFullPath2 = string.Format(@"{0}\{1}", dirName, "_del_" + fileName); string fileFullPath2 = Path.Join(dirName, "_del_", fileName); fileFullPath2 = this.MakeUniqueFileName(fileFullPath2); fi.MoveTo(fileFullPath2); } //File.Delete(fileFullPath);//실제 삭제하지 않음. } //디비에서 해당 파일항목을 삭제한다. string isDBWork = model.GetValue(Constants.DB_WORK_GUBUN_value); if (!string.IsNullOrEmpty(isDBWork) && !isDBWork.Equals("pass")) { //db_work=pass 명시적으로 표시할 경우 디비 작업 없음. } else { await Attachment_CRDAsync(CRUD.D, model, FileModel.Empty); } //responseModel = ResponseModel.Message("1", "파일 삭제완료.\r\n" + msg); responseModel = ResponseModel.Message("1", "파일 삭제완료."); } catch (ServiceException ex) { responseModel = responsePreprocessManager.ProcessException(ex); } catch (Exception ex) { //throw new ServiceException("httpservice(DeleteFile).Error check", ex); responseModel = ResponseModel.ErrorMessage(ex, "httpservice(DeleteFile).Error check"); } return(responseModel); }