public ActionResult GetPic(string fileId, int?width, int?height) { string fileIdPre = fileId; if (!string.IsNullOrEmpty(fileIdPre)) { var arr = fileIdPre.Split('_'); if (arr.Length > 0) { fileIdPre = arr[0]; } } byte[] fileBytes = FileStoreHelper.GetFile(fileIdPre); Image img = ImageHelper.GetImageFromBytes(fileBytes); if (width != null && height != null) { int fWidth = (int)((double)height.Value * (double)img.Width / (double)img.Height); //纵向布满后后横向超出了给定宽度 //则横向布满 if (fWidth > width.Value) { int fHeight = (int)((double)img.Height * (double)width.Value / (double)img.Width); img = img.GetThumbnailImage(width.Value, fHeight, null, IntPtr.Zero); } else { img = img.GetThumbnailImage(fWidth, height.Value, null, IntPtr.Zero); } } return(new ImageActionResult(img)); }
public static void DownloadFile(Packet packet) { Packet sendPacket; try { string[] splited = packet.Argument.Split(char.Parse("|")); Project project = new Project(splited[0]); string path = splited[1]; ConsoleUtils.Print(string.Format("[{0}]'s Request: Download file from project {1} [{2}]", packet.ClientIP, project.ProjectName, packet.Username)); FileStoreHelper.DownloadFile(project.FullPath + path, packet.Stream); sendPacket = PacketParser.CreatePacketWithToken(ResponseEnum.Success, packet.Token); packet.Stream.Write(sendPacket.GetBytes(), 0, sendPacket.Length); ConsoleUtils.Print(string.Format("[{0}]'s Request: Download file success: {1} [{2}]", packet.ClientIP, path.Substring(path.LastIndexOf(char.Parse("/"))), packet.Username)); } catch (Exception e) { ConsoleUtils.Print(string.Format("Download File Error: [{0}] {1}", e.GetType().ToString(), e.Message)); sendPacket = PacketParser.CreatePacketWithToken(ResponseEnum.Failure, packet.Token); packet.Stream.Write(sendPacket.GetBytes(), 0, sendPacket.Length); return; } }
public IActionResult Upload(FileStoreDTO upModel) { if (Request.Form != null && Request.Form.Files.Count > 0) { foreach (var formFile in Request.Form.Files) { if (formFile.Length > 100000000) { return(StatusCode(500));//TODO вывести нормальную ошибку } //Костыль с кастомным FileStore. Когда будет новый core, нужно переписать var coreModel = new Core.Data.DTO.Common.FileStoreDTO(); _objectMapper.Map(upModel, coreModel); var dto = FileStoreHelper.SaveFile(Configuration, formFile, coreModel); if (dto != null) { try { _objectMapper.Map(dto, upModel); Service.SaveAsync(upModel).Wait(); } catch { FileStoreHelper.DeleteFileIfExist(dto.FilePath); throw; } } } return(Ok(new { count = Request.Form.Files.Count })); } else { return(NotFound()); } }
/// <summary> /// 如果是可直接浏览文件格式,直接跳转 /// </summary> /// <param name="fileID"></param> private void ImageDirect(string fileID) { fileID = fileID.ToLower(); //如果附件为图片格式 if (fileID.Contains(".jpg") || fileID.Contains(".png") || fileID.Contains(".gif")) { object fileBytes = null; string fileName = FileStoreHelper.GetFileFullPath(fileID); if (fileName.LastIndexOf('.') > -1) { var suffix = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower(); fileBytes = FileStoreHelper.GetFile(fileID); if (fileBytes != null && fileBytes != DBNull.Value) { this.Response.Clear(); if (suffix == "jpg" || suffix == "png" || suffix == "gif") { this.Response.ContentType = "image/gif"; this.Response.OutputStream.Write(fileBytes as byte[], 0, ((byte[])fileBytes).Length); this.Response.End(); } } } } }
public override async Task <JsonResult> Delete(Guid id) { try { var eDoc = _dataService.GetEntity <EDocument>(x => x.Id == id).SingleOrDefault(); eDoc.RecordState = RecordState.D; var eDocBranches = _dataService.GetEntity <BranchEDocument>(x => x.EDocumentId == eDoc.Id) .ToList(); eDocBranches.ForEach(x => x.RecordState = RecordState.D); var files = _dataService.GetEntity <FileStore>(x => x.EntityId == id && x.EntityName == "EDocument") .ToList(); files.ForEach(x => { x.RecordState = RecordState.D; FileStoreHelper.DeleteFileIfExist(x.FilePath); }); await _dataService.SaveChangesAsync(); return(await Task.FromResult(Json(new { success = true }))); } catch (Exception e) { return(await Task.FromResult(Json(new { success = false, ErrorMessage = "Помилка видалення. " + (e.InnerException ?? e).Message }))); } }
public ActionResult ViewerPDF(string FileID) { ViewBag.IsExist = false; if (!System.IO.File.Exists(GetFileFullName(FixFileID(FileID)))) { var sqlDb = Config.SQLHelper.CreateSqlHelper(Config.ConnEnum.FileStore); sqlDb.ExecuteNonQuery(string.Format("Update FsFile Set ConvertResult=null Where ID='{0}'", FixFileID(FileID))); ViewBag.IsExist = false; ViewBag.IsImg = false; ViewBag.FileID = FileID; string fileName = FileStoreHelper.GetFileFullPath(FileID); if (fileName.LastIndexOf('.') > -1) { var suffix = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower(); if (suffix == "jpeg" || suffix == "bmp" || suffix == "gif" || suffix == "png" || suffix == "jpg") { ViewBag.IsImg = true; } //ImageDirect(FileID); } } else { var filePath = "/MvcConfig/ViewFile/GetFile?FileID=" + FixFileID(FileID); ViewBag.FilePath = filePath; ViewBag.IsExist = true; } return(View()); }
public static async Task SaveFile(IConfiguration config, FilesViewModel model, FileStoreDTO fileStoreDto, ICommonDataService dataService) { var folderForSave = config.GetSection("FileStorePath").Value + DateTime.Now.ToString("ddMMyyyy") + "/"; var filePath = Path.GetFullPath(folderForSave); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } var newName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".zip"; var tempfolder = Path.GetTempPath(); var fullOrigPath = tempfolder + model.name; string fullZipPath = filePath + newName; var directoryInfo = (new FileInfo(fullOrigPath)).Directory; directoryInfo?.Create(); await File.WriteAllBytesAsync(fullOrigPath, Convert.FromBase64String(model.file)); CreateZip(fullZipPath, fullOrigPath); FileStoreHelper.DeleteFileIfExist(fullOrigPath); fileStoreDto.FileName = newName; fileStoreDto.FilePath = fullZipPath; dataService.Add <FileStore>(fileStoreDto); }
private void btnSave_Click(object sender, RoutedEventArgs e) { FileStoreHelper.SaveToFile(FILE_NAME, new NodesWithEdges { Nodes = _nodes, Edges = _edges }); }
public string ExportPDF(string fileName, string formID, string tmpCode) { SQLHelper sqlHeper = SQLHelper.CreateSqlHelper(ConnEnum.Base); var dtWordTmpl = sqlHeper.ExecuteDataTable(string.Format("select * from S_UI_Word where Code='{0}'", tmpCode)); if (dtWordTmpl.Rows.Count == 0) { return(""); } UIFO uiFO = FormulaHelper.CreateFO <UIFO>(); DataSet ds = uiFO.GetWordDataSource(tmpCode, formID); #region 获取word导出的版本 DataRow wordTmplRow = dtWordTmpl.Rows[0]; DateTime date; if (ds.Tables[0].Columns.Contains("CreateTime")) { date = DateTime.Parse(ds.Tables[0].Rows[0]["CreateTime"].ToString()); } else { date = DateTime.Parse(ds.Tables[0].Rows[0]["CreateDate"].ToString()); } foreach (DataRow row in dtWordTmpl.Rows) { var _startDate = DateTime.Parse(row["VersionStartDate"].ToString()); var _endDate = DateTime.MaxValue; if (row["VersionEndDate"].ToString() != "") { _endDate = DateTime.Parse(row["VersionEndDate"].ToString()); } if (date > _startDate && date < _endDate) { wordTmplRow = row; break; } } int?versionNum = 1; if (wordTmplRow["VersionNum"].ToString() != "") { versionNum = int.Parse(wordTmplRow["VersionNum"].ToString()); } string tmplName = dtWordTmpl.Rows[0]["Code"].ToString() + "_" + versionNum + ".docx"; string tempPath = Server.MapPath("/") + "WordTemplate/" + tmplName; if (System.IO.File.Exists(tempPath) == false) { tmplName = dtWordTmpl.Rows[0]["Code"].ToString() + ".docx"; tempPath = Server.MapPath("/") + "WordTemplate/" + tmplName; } #endregion var export = new Formula.ImportExport.AsposeWordExporter(); byte[] result = export.ExportPDF(ds, tempPath); var name = fileName.IndexOf(".pdf") >= 0 ? fileName : fileName + ".pdf"; return(FileStoreHelper.UploadFile(name, result)); }
public ActionResult GetPic(string fileID, int?width, int?height) { byte[] file = FileStoreHelper.GetFile(fileID); if (file != null) { return(new ImageActionResult(file, width, height)); } return(Content(string.Empty)); }
public async Task Delete(Guid id) { var branch = _dataService.GetEntity <Branch>(x => x.Id == id).SingleOrDefault(); branch.RecordState = RecordState.D; var branchContractors = _dataService.GetEntity <PrlBranchContractor>(x => x.BranchId == id).ToList(); var contractors = _dataService .GetEntity <PrlContractor>(x => branchContractors.Select(y => y.ContractorId).Contains(x.Id)).ToList(); contractors.ForEach(contr => { var contrBranches = _dataService.GetEntity <PrlBranchContractor>(x => x.ContractorId == contr.Id).ToList(); if (contrBranches.All(z => z.BranchId == id)) { contr.RecordState = RecordState.D; contrBranches.ForEach(x => x.RecordState = RecordState.D); } } ); var branchAssignees = _dataService.GetEntity <AppAssigneeBranch>(x => x.BranchId == id).ToList(); var assignees = _dataService .GetEntity <AppAssignee>(x => branchAssignees.Select(y => y.AssigneeId).Contains(x.Id)).ToList(); assignees.ForEach(assignee => { var assigneeBranches = _dataService.GetEntity <AppAssigneeBranch>(x => x.AssigneeId == assignee.Id).ToList(); if (assigneeBranches.All(z => z.BranchId == id)) { assignee.RecordState = RecordState.D; assigneeBranches.ForEach(x => x.RecordState = RecordState.D); } } ); var branchEDocuments = _dataService.GetEntity <BranchEDocument>(x => x.BranchId == id).ToList(); var eDocuments = _dataService .GetEntity <EDocument>(x => branchEDocuments.Select(y => y.EDocumentId).Contains(x.Id)).ToList(); eDocuments.ForEach(eDoc => { var eDocBranches = _dataService.GetEntity <BranchEDocument>(x => x.EDocumentId == eDoc.Id).ToList(); if (eDocBranches.All(z => z.BranchId == id)) { eDoc.RecordState = RecordState.D; var files = _dataService.GetEntity <FileStore>(x => x.EntityId == eDoc.Id && x.EntityName == "EDocument").ToList(); files.ForEach(file => { file.RecordState = RecordState.D; FileStoreHelper.DeleteFileIfExist(file.FilePath); }); eDocBranches.ForEach(x => x.RecordState = RecordState.D); } } ); await _dataService.SaveChangesAsync(); }
public async Task TestSaveFile() { var fileStoreHelper = new FileStoreHelper(); var rssReader = new RssReader(); var result = await rssReader.DownloadRssString(); var isSuccess = await fileStoreHelper.SaveRssFileAsync(result); Assert.IsTrue(isSuccess); }
public IActionResult Download(Guid fileId) { var fileStoreDTO = Service.GetDetailDTO().FirstOrDefault(x => x.Id == fileId); var coreModel = new Core.Data.DTO.Common.FileStoreDTO(); _objectMapper.Map(fileStoreDTO, coreModel); if (FileStoreHelper.LoadFile(coreModel, out var stream, out var contentType)) { return(File(stream, contentType, fileStoreDTO.OrigFileName)); }
private async Task <MemoryStream> GetFile(Guid fileId) { var dto = (await DataService.GetDtoAsync <FileStoreDTO>(x => x.Id == fileId)).FirstOrDefault(); // С новым кором переделать FileStoreDTO var dtoCore = new Core.Data.DTO.Common.FileStoreDTO(); _objectMapper.Map(dto, dtoCore); if (FileStoreHelper.LoadFile(dtoCore, out var stream, out var contentType)) { return(stream); }
public async Task TestReadFile() { var fileStoreHelper = new FileStoreHelper(); var rssReader = new RssReader(); var result = await rssReader.DownloadRssString(); await fileStoreHelper.SaveRssFileAsync(result); var content = await fileStoreHelper.ReadRssFileAsync(); Assert.AreEqual <string>(result, content); }
private void btnLoad_Click(object sender, RoutedEventArgs e) { var nodesWithEdges = FileStoreHelper.LoadFromFile(FILE_NAME); drawingCanvas.Children.Clear(); _nodes = nodesWithEdges.Nodes; _edges = nodesWithEdges.Edges; ResetVisitedFlag(); PaintAll(); }
public FileResult GetFile(string fileID) { byte[] file = FileStoreHelper.GetFile(fileID); if (file != null) { return(File(file, "application/pdf")); } else { throw new Formula.Exceptions.WebException("服务器上找不到浏览文件!"); } }
private void RunPlotQueue() { FileRepository repo = new FileRepository(); FileTask task = null; while ((task = repo.GetTask("")) != null) { if (task.ExtName.Equals("dwg", StringComparison.OrdinalIgnoreCase)) { try { label2.Text = string.Format("正在获取文件...[{0}]", task.Name); //1.从filestore获取文件 byte[] bytes = FileStoreHelper.GetFile(task.ID); FileStoreHelper.SaveFileBuffer(bytes, Path.Combine(OfficeHelper.GetFolderPath(task.ID, "Files"), task.Name)); //2.设置文件数据库状态为进行中 repo.StartTask(task.ID); //3.开始进行转换 label2.Text = string.Format("正在进行格式打印...[{0}]", task.Name); var imgDTO = OfficeHelper.InitDTO(task.Name, bytes.Length, task.ID); var result = FileConverter.Exec(imgDTO); bool isSucc = false; if (result != null && result.status) { //4.设置转图层次,并生成json文件 imgDTO.Versions[0].ImageZoomLevel = result.ZoomLevel; OfficeHelper.WriteJsonFile(imgDTO); isSucc = true; } Application.DoEvents(); //5.回置状态 label2.Text = "最近:[" + imgDTO.Name + "]打印" + (isSucc ? "成功":"失败") + ",打印时间(" + DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分") + ")"; repo.EndTask(task.ID, isSucc ? ResultStatus.Success:ResultStatus.Error); //6.删除原文件 if (File.Exists(imgDTO.Versions[0].FullPath)) { File.Delete(imgDTO.Versions[0].FullPath); } } catch (Exception ex) { // 记录日志 LogWriter.Info(string.Format(ex.Message, DateTime.Now.ToString(), task.ID, task.Name, ex.StackTrace)); repo.EndTask(task.ID, ResultStatus.Error); } } } }
public void UpdatePictureFromFileStore(string fileId) { byte[] bytes = FileStoreHelper.GetFile(fileId); var obj = this.S_A_UserImg.SingleOrDefault(c => c.UserID == this.ID); if (obj == null) { obj = new S_A_UserImg(); obj.ID = FormulaHelper.CreateGuid(); obj.UserID = this.ID; this.S_A_UserImg.Add(obj); } obj.Picture = bytes; }
protected static void SetupFolder(string path, string projectname) { Directory.CreateDirectory(path); Directory.CreateDirectory(string.Format("{0}/{1}", path, projectname)); Directory.CreateDirectory(string.Format("{0}/{1}/Other Users", path, projectname)); Directory.CreateDirectory(string.Format("{0}/Avid MediaFiles/MXF/1", path)); FileStoreHelper.CopyFile("/project/.Template_Avid/tmpl_Proj.avp", string.Format("{0}/{1}/{2}.avp", path, projectname, projectname)); FileStoreHelper.CopyFile("/project/.Template_Avid/tmpl_Proj Settings.avs", string.Format("{0}/{1}/{2} Settings.avs", path, projectname, projectname)); FileStoreHelper.CopyFile("/project/.Template_Avid/tmpl_Proj Settings.xml", string.Format("{0}/{1}/{2} Settings.xml", path, projectname, projectname)); Directory.CreateDirectory(string.Format("{0}/{1}/SearchData", path, projectname)); Directory.CreateDirectory(string.Format("{0}/{1}/Statistics", path, projectname)); Directory.CreateDirectory(string.Format("{0}/{1}/WaveformCache", path, projectname)); Directory.CreateDirectory(string.Format("{0}/{1}/Trash", path, projectname)); ACLModifier.ChangePermission(path, 3777, true); }
public FileResult GetImgFile(string fileID) { //string fileFullName = GetFileFullName(fileID); //byte[] swfFile = GetViewFile(fileFullName); fileID = fileID.ToLower(); //如果附件为图片格式 if (fileID.Contains(".jpeg") || fileID.Contains(".bmp") || fileID.Contains(".jpg") || fileID.Contains(".png") || fileID.Contains(".gif")) { string fileName = FileStoreHelper.GetFileFullPath(fileID); if (fileName.LastIndexOf('.') > -1) { var suffix = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower(); byte[] fileBytes = FileStoreHelper.GetFile(fileID); if (fileBytes == null) { throw new Formula.Exceptions.WebException("服务器上找不到浏览文件!"); } if (fileBytes != null) { switch (suffix) { case "jpg": return(File(fileBytes, "application/x-jpg/" + Path.GetExtension(fileName))); case "png": return(File(fileBytes, "application/x-png/" + Path.GetExtension(fileName))); case "gif": return(File(fileBytes, "image/gif/" + Path.GetExtension(fileName))); case "jpeg": return(File(fileBytes, "image/jpeg/" + Path.GetExtension(fileName))); case "bmp": return(File(fileBytes, "application/x-bmp/" + Path.GetExtension(fileName))); default: throw new Formula.Exceptions.WebException("文件格式不支持!"); } } } } throw new Formula.Exceptions.WebException("文件格式不正确!"); }
public async Task <FilesViewModel> GetEDocumentJsonFile(Guid id) { var applicationBranchesIds = _commonDataService .GetEntity <ApplicationBranch>(x => x.LimsDocumentId == id && x.RecordState != RecordState.D) .Select(x => x.BranchId) .Distinct() .ToList(); var applicationEdocumentBranches = _commonDataService.GetEntity <BranchEDocument>(x => applicationBranchesIds.Contains(x.BranchId) && x.RecordState != RecordState.D); var applicationEdocumentIds = applicationEdocumentBranches.Select(x => x.EDocumentId).Distinct().ToList(); var applicationEdocuments = _commonDataService .GetEntity <EDocument>(x => applicationEdocumentIds.Contains(x.Id) && x.RecordState != RecordState.D).ToList(); var listEDocJson = new List <EDocumentMD5Model>(); foreach (var applicationEdocument in applicationEdocuments) { var fileStore = _commonDataService .GetEntity <FileStore>(x => x.EntityName == "EDocument" && x.EntityId == applicationEdocument.Id && x.RecordState != RecordState.D) .ToList(); try { foreach (var file in fileStore) { var dto = (await _commonDataService.GetDtoAsync <FileStoreDTO>(x => x.Id == file.Id)).FirstOrDefault(); // С новым кором переделать FileStoreDTO var dtoCore = new Core.Data.DTO.Common.FileStoreDTO(); _objectMapper.Map(dto, dtoCore); if (FileStoreHelper.LoadFile(dtoCore, out var stream, out var contentType)) { var plainTextBytes = Encoding.UTF8.GetBytes(dto?.OrigFileName); var base64Name = Convert.ToBase64String(plainTextBytes); listEDocJson.Add(new EDocumentMD5Model() { Id = file.Id, Name = base64Name, File = FileSignHelper.CalculateMd5(stream) }); } else { throw new Exception(); } } }
public JsonResult SaveAuditFile(string ProductID, string AuditStep, string FileID, bool IsOverride) { var product = this.GetEntityByID <S_E_Product>(ProductID); if (product == null) { throw new Formula.Exceptions.BusinessException("未能找到指定的成果。"); } var PDFAuditFiles = JsonHelper.ToList(product.PDFAuditFiles); if (IsOverride) { PDFAuditFiles.RemoveWhere(a => a.GetValue("AuditStep") == AuditStep && a.GetValue("SubmitUser") == CurrentUserInfo.UserID); } var dic = new Dictionary <string, object>(); dic.SetValue("AuditStep", AuditStep); dic.SetValue("SubmitUser", CurrentUserInfo.UserID); dic.SetValue("SubmitUserName", CurrentUserInfo.UserName); dic.SetValue("SubmitDate", System.DateTime.Now.ToString("s")); dic.SetValue("Attachment", FileID); PDFAuditFiles.Add(dic); product.PDFAuditFiles = JsonHelper.ToJson(PDFAuditFiles); product.UpdateVersison(); this.entities.SaveChanges(); #region 获取PDF中的校审信息 byte[] bytes = FileStoreHelper.GetFile(FileID); var list = GetAnnots(bytes); #endregion var reslut = new Dictionary <string, object>(); reslut.Add("list", list); reslut.Add("code", product.Code); return(Json(reslut)); }
public IActionResult Upload(FileStoreDTO upModel) { if (Request.Form != null && Request.Form.Files.Count > 0) { foreach (var formFile in Request.Form.Files) { if (formFile.Length > 1e+8) { return(Json(new { success = false, fileSize = formFile.Length, fileName = formFile.FileName })); } //Костыль с кастомным FileStore. Когда будет новый core, нужно переписать var coreModel = new Core.Data.DTO.Common.FileStoreDTO(); _objectMapper.Map(upModel, coreModel); var dto = FileStoreHelper.SaveFile(Configuration, formFile, coreModel); if (dto == null) { continue; } try { _objectMapper.Map(dto, upModel); Service.SaveAsync(upModel).Wait(); } catch { FileStoreHelper.DeleteFileIfExist(dto.FilePath); throw; } } return(Ok(new { count = Request.Form.Files.Count })); } else { return(NotFound()); } }
public ActionResult GetPic(string fieldId, int?width, int?height) { byte[] fileBytes = FileStoreHelper.GetFile(fieldId); Image img = ImageHelper.GetImageFromBytes(fileBytes); if (width != null && height != null) { int fWidth = (int)((double)height.Value * (double)img.Width / (double)img.Height); //纵向布满后后横向超出了给定宽度 //则横向布满 if (fWidth > width.Value) { int fHeight = (int)((double)img.Height * (double)width.Value / (double)img.Width); img = img.GetThumbnailImage(width.Value, fHeight, null, IntPtr.Zero); } else { img = img.GetThumbnailImage(fWidth, height.Value, null, IntPtr.Zero); } } return(new ImageActionResult(img)); }
public JsonResult UploadPicture() { if (Request.Files["FileData"] != null) { var t = Request.Files["FileData"].InputStream; string fileName = Request.Files["FileData"].FileName; string extName = Path.GetExtension(fileName); Image img = Image.FromStream(t); ImageFormat imgFormat = ImageHelper.GetImageFormat(extName); byte[] bt = ImageHelper.ImageToBytes(img, imgFormat); int height = img.Height; int width = img.Width; int limitedHeight = !string.IsNullOrEmpty(Request["ThumbHeight"]) ? Convert.ToInt32(Request["ThumbHeight"]) : 60; int thumbHeight, thumbWidth; byte[] btThumb = null; if (height > limitedHeight) { thumbHeight = limitedHeight; thumbWidth = thumbHeight * width / height; Image imgThumb = img.GetThumbnailImage(thumbWidth, thumbHeight, null, IntPtr.Zero); btThumb = ImageHelper.ImageToBytes(imgThumb, imgFormat); } else { btThumb = bt; } var fileID = FileStoreHelper.UploadFile(fileName, bt, "", "", "", "DocAtlas"); var thumbFileID = FileStoreHelper.UploadFile(fileName, btThumb, "", "", "", "DocAtlas"); return(Json(new { PictureName = fileID, ThumbName = thumbFileID })); } else { return(Json("")); } }
public void ExecuteQueue() { var queueData = this.SQLHelperInterface.ExecuteObject <I_FileSynQueue>("select top 1 * from I_FileSynQueue where SynState='" + SynState.New.ToString() + "' order by CreateTime"); while (queueData != null) { try { StringBuilder interfaceSb = new StringBuilder(); if (queueData.SynType == SynType.Download.ToString()) { queueData.RequestUrl = this.BaseStorageUrl + "Download?md5=" + queueData.MD5Code + "&filename=" + queueData.FileName; #region 调用api下载文件 var response = HttpHelper.GetResponse(queueData.RequestUrl); if (response.ResponseStatus != RestSharp.ResponseStatus.Completed) { throw new Exception(response.ErrorMessage); } var bs = response.RawBytes; if (bs.Length == 0) { var content = response.Content; if (!string.IsNullOrEmpty(content) && content.StartsWith("{")) { throw new Exception(content); } throw new Exception("没有获得正确得文件流数据"); } #endregion #region filestore queueData.FsFileID = FileStoreHelper.UploadFile(queueData.FileName, bs); if (string.IsNullOrEmpty(queueData.FsFileID)) { throw new Exception("上传FileStore失败:" + queueData.FsFileID); } #endregion ExecuteDownload(queueData, interfaceSb); } else { queueData.RequestUrl = this.BaseStorageUrl + "UploadFileMobile"; #region 载filestore文件 var bs = FileStoreHelper.GetFile(queueData.FsFileID); if (bs.Length == 0) { throw new Exception("从FileStore下载失败:" + queueData.FsFileID); } #endregion #region 调用api上传文件 if (string.IsNullOrEmpty(queueData.FileName)) { queueData.FileName = GetFileName(queueData.FsFileID); } queueData.Response = HttpHelper.PostFile(queueData.RequestUrl, bs, queueData.FileName); #endregion ExecuteUpload(queueData, interfaceSb, bs.Length); } ComplateSync(queueData, interfaceSb); } catch (Exception e) { ErrorSync(queueData, e.Message); } queueData = this.SQLHelperInterface.ExecuteObject <I_FileSynQueue>("select top 1 * from I_FileSynQueue where SynState='" + SynState.New.ToString() + "' order by CreateTime"); } }
public void Convert() { #region 创建esHelper、configHelper var esUrl = ConfigurationManager.AppSettings["EsUrl"]; if (string.IsNullOrEmpty(esUrl)) { LogWriter.Error(string.Format("文字提取程序异常:{0},错误:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "配置文件缺少EsUrl")); return; } var esHelper = EsBaseHelper.CreateEsHelper(esUrl); try { if (!esHelper.ExistsIndex(EsConst.defaultEsFileIndex)) { esHelper.CreateIndex <EsFile>(EsConst.defaultEsFileIndex);//创建es索引 } } catch (Exception ex) { LogWriter.Error(ex, string.Format("文字提取程序异常:{0},错误:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.Message)); return; } esHelper.DefaultIndex = EsConst.defaultEsFileIndex;//设置es默认索引 SQLHelper configHelper = SQLHelper.CreateSqlHelper("DocConfigCntString"); #endregion string spaceSql = "select * from dbo.S_DOC_Space "; var spaceDt = configHelper.ExecuteDataTable(spaceSql); string nodeConfigSQL = @"select NodeID ConfigID,SpaceID,AttrField Field,DataType,InputType,EnumKey,FulltextProp,AttrSort from S_DOC_NodeAttr where FulltextProp='True' union select FileID ConfigID,SpaceID,FileAttrField Field,DataType,InputType,EnumKey,FulltextProp,AttrSort from S_DOC_FileAttr where FulltextProp='True' order by AttrSort "; var propFieldDt = configHelper.ExecuteDataTable(nodeConfigSQL); var enumFieldDt = propFieldDt.Select("EnumKey is not null"); var enumDic = new Dictionary <string, DataTable>(); var enumService = Formula.FormulaHelper.GetService <Formula.IEnumService>(); foreach (var item in enumFieldDt) { var enumKey = item["EnumKey"].ToString(); if (enumDic.ContainsKey(enumKey)) { continue; } var enumDt = enumService.GetEnumTable(enumKey); enumDic.Add(enumKey, enumDt); } foreach (DataRow space in spaceDt.Rows) { try { string constr = String.Format(conStrTemplate, space["Server"].ToString() , space["UserName"].ToString(), space["Pwd"].ToString(), space["DbName"].ToString()); SQLHelper sqlHepler = new SQLHelper(constr); string sql = @"select S_Attachment.*,S_FileInfo.ConfigID from S_Attachment left join S_FileInfo on S_FileInfo.ID = S_Attachment.FileID where S_Attachment.State='Normal' and CurrentVersion='True' and S_FileInfo.State='Published' and ((MainFile is not null and MainFile!='' ) or (PDFFile is not null and PDFFile!='' )) order by ID"; DataTable dt = sqlHepler.ExecuteDataTable(sql); var SpaceID = space["ID"].ToString(); int i = 1; foreach (DataRow attItem in dt.Rows) { string logSql = string.Empty; var Id = SQLHelper.CreateGuid(); string mainFile = string.Empty; if (attItem["PDFFile"] != DBNull.Value && attItem["PDFFile"] != null && !string.IsNullOrEmpty(attItem["PDFFile"].ToString())) { mainFile = attItem["PDFFile"].ToString(); } if (string.IsNullOrEmpty(mainFile)) { if (attItem["MainFile"] != DBNull.Value && attItem["MainFile"] != null && !string.IsNullOrEmpty(attItem["MainFile"].ToString())) { mainFile = attItem["MainFile"].ToString(); } } var FileID = attItem["FileID"].ToString(); var NodeID = attItem["NodeID"].ToString(); var ConfigID = attItem["ConfigID"].ToString(); var AttrID = attItem["ID"].ToString(); string FormatLogSql = @"INSERT INTO S_DOC_FulltextSearchConvertLog ([ID],[FsFileID],[AttrID] ,[FileID] ,[NodeID] ,[SpaceID] ,[CreateDate] ,[ConvertState],[ErrorMeesage]) VALUES ('" + Id + "' ,'" + mainFile.Replace("'", "''") + "','" + AttrID + "','" + FileID + "' ,'" + NodeID + "' ,'" + SpaceID + "' ,'" + DateTime.Now + "','{0}','{1}')"; string updateSql = "update S_Attachment Set State='Finish' where ID='" + attItem["ID"].ToString() + "'"; Console.WriteLine("文件信息:" + mainFile + " " + DateTime.Now.ToString()); var ext = GetFileExt(mainFile).ToLower(); try { string content = string.Empty; //string fullPath = service.GetFileFullPath(mainFile); var file = FileStoreHelper.GetFile(mainFile); //Console.WriteLine("文件路径:" + fullPath); #region 提取文字 switch (ext) { case "docx": case "doc": content = ExtractHelper.GetWordText(file); break; case "xls": case "xlsx": content = ExtractHelper.GetExcelText(file); break; case "pdf": content = ExtractHelper.GetPdfText_Itextsharp(file); break; case "txt": content = ExtractHelper.GetTxtText(file); break; default: { Console.WriteLine(ext + "文件跳过"); sqlHepler.ExecuteNonQuery(updateSql); Console.Write(ext + " 格式不对跳过" + i.ToString() + "/" + dt.Rows.Count); i++; continue; } } Console.WriteLine("获取信息内容完成"); #endregion #region 属性json、全路径json var fileDt = sqlHepler.ExecuteDataTable(@"select * from S_FileInfo where id='" + FileID + "'"); if (fileDt.Rows.Count == 0) { throw new Exception(string.Format("没有找到ID为【{0}】的S_FileInfo的记录", FileID)); } var nodeFullID = fileDt.Rows[0]["FullNodeID"].ToString(); var nodeDt = sqlHepler.ExecuteDataTable(@"select * from S_NodeInfo where id in ('" + nodeFullID.Replace(".", "','") + "')"); nodeDt.PrimaryKey = new DataColumn[] { nodeDt.Columns["ID"] }; string propertyJson = string.Empty; //属性,空格分隔的string,暂时不存Json string nodePathJson = string.Empty; //全路径Json var nodePathList = new List <Dictionary <string, string> >(); nodePathList.Add(new Dictionary <string, string>() { { "id", SpaceID }, { "name", space["Name"].ToString() }, { "type", "space" } }); foreach (var nid in nodeFullID.Split('.')) { var nodeRow = nodeDt.Rows.Find(nid); if (nodeRow == null) { continue; } //目录属性 var propString = GetPropStrings(propFieldDt, nodeRow, enumDic); propertyJson += propString; //全路径 string nname = nodeRow["Name"].ToString(); nodePathList.Add(new Dictionary <string, string>() { { "id", nid }, { "name", nname }, { "type", "node" } }); } //文件节点目录 nodePathList.Add(new Dictionary <string, string>() { { "id", SpaceID }, { "name", fileDt.Rows[0]["Name"].ToString() }, { "type", "file" } }); nodePathJson = JsonHelper.ToJson(nodePathList); //文件属性 var filePropString = GetPropStrings(propFieldDt, fileDt.Rows[0], enumDic); propertyJson += filePropString; propertyJson = propertyJson.TrimEnd(); #endregion #region 插入Es var esFile = new EsFile(); esFile.Id = FileID; esFile.SpaceID = SpaceID; esFile.NodeID = NodeID; esFile.FileID = FileID; esFile.AttrID = AttrID; esFile.ConfigID = ConfigID; if (!string.IsNullOrEmpty(mainFile)) { esFile.FsFileID = System.Convert.ToInt32(mainFile.Split('_')[0]); } esFile.Title = GetFileName(mainFile); esFile.Content = content; esFile.PropertyJson = propertyJson; esFile.FullPathJson = nodePathJson; if (attItem["CreateDate"] != null && attItem["CreateDate"] != DBNull.Value) { esFile.FileCreateDate = System.Convert.ToDateTime(attItem["CreateDate"]); } else { esFile.FileCreateDate = DateTime.Now; //归档日期 } if (attItem["CreateUserName"] != null && attItem["CreateUserName"] != DBNull.Value) { esFile.FileCreateUser = attItem["CreateUserName"].ToString(); //归档人 } esFile.SecretLevel = string.Empty; //密级 esHelper.AddDocument(esFile); Console.WriteLine("更新Es数据完成"); #endregion sqlHepler.ExecuteNonQuery(updateSql); logSql = String.Format(FormatLogSql, "Success", ""); configHelper.ExecuteNonQuery(logSql); Console.Write(" 成功" + i.ToString() + "/" + dt.Rows.Count); i++; } catch (Exception ex) { logSql = String.Format(FormatLogSql, "Error", ex.Message); configHelper.ExecuteNonQuery(logSql); LogWriter.Error(ex, string.Format("文字提取程序异常:{0},错误:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.Message)); Console.WriteLine("失败跳过" + i.ToString() + "/" + dt.Rows.Count); i++; continue; } } } catch (Exception exp) { LogWriter.Error(exp, string.Format("文字提取程序异常:{0},错误:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), exp.Message)); Console.WriteLine(exp.InnerException); continue; } } }
public JsonResult MultiSaveAuditFile(string AuditID, string ChangeAuditID, string AuditStep, string FileIDs, bool IsOverride) { var productList = new List <S_E_Product>(); if (!string.IsNullOrEmpty(AuditID)) { productList = this.entities.Set <S_E_Product>().Where(a => a.AuditID == AuditID).ToList(); } else if (!string.IsNullOrEmpty(ChangeAuditID)) { productList = this.entities.Set <S_E_Product>().Where(a => a.ChangeAuditID == ChangeAuditID).ToList(); } List <Dictionary <string, object> > errorFiles = new List <Dictionary <string, object> >();//上传的文件解析错误,找到多个成果,未找到对应的成果 List <Dictionary <string, object> > successFiles = new List <Dictionary <string, object> >(); foreach (var FileID in FileIDs.Split(',')) { if (FileID.IndexOf("_") < 0 || FileID.ToLower().IndexOf(".pdf") < 0) { errorFiles.Add(new Dictionary <string, object> { { "name", FileID }, { "message", "文件名解析错误" } }); continue; } var validateProducts = productList.Where(a => !string.IsNullOrEmpty(a.MainFile) && a.MainFile.Split('_')[1] == FileID.Split('_')[1]).ToList(); if (validateProducts.Count > 1) { errorFiles.Add(new Dictionary <string, object> { { "name", FileID.Split('_')[1] }, { "message", "根据成果附件匹配到多个成果" } }); continue; } if (validateProducts.Count == 0) { errorFiles.Add(new Dictionary <string, object> { { "name", FileID.Split('_')[1] }, { "message", "根据成果附件未找到对应的成果" } }); continue; } var product = validateProducts.FirstOrDefault(); var PDFAuditFiles = JsonHelper.ToList(product.PDFAuditFiles); if (IsOverride) { PDFAuditFiles.RemoveWhere(a => a.GetValue("AuditStep") == AuditStep && a.GetValue("SubmitUser") == CurrentUserInfo.UserID); } var dic = new Dictionary <string, object>(); dic.SetValue("AuditStep", AuditStep); dic.SetValue("SubmitUser", CurrentUserInfo.UserID); dic.SetValue("SubmitUserName", CurrentUserInfo.UserName); dic.SetValue("SubmitDate", System.DateTime.Now.ToString("s")); dic.SetValue("Attachment", FileID); PDFAuditFiles.Add(dic); product.PDFAuditFiles = JsonHelper.ToJson(PDFAuditFiles); product.UpdateVersison(); //提取pdf批注信息 byte[] bytes = FileStoreHelper.GetFile(FileID); var list = GetAnnots(bytes); successFiles.Add(new Dictionary <string, object> { { "list", list }, { "code", product.Code } }); } this.entities.SaveChanges(); return(Json(new { successFiles, errorFiles })); }
public async Task Delete(Guid id, bool softDeleting) { try { var application = _commonDataService.GetEntity <ImlApplication>(x => x.Id == id).SingleOrDefault(); application.RecordState = RecordState.D; var applicationBranches = _commonDataService.GetEntity <ApplicationBranch>(x => x.LimsDocumentId == id).ToList(); applicationBranches.ForEach(x => x.RecordState = RecordState.D); var branches = _commonDataService.GetEntity <Branch>(x => applicationBranches.Select(y => y.BranchId).Contains(x.Id)).ToList(); branches.ForEach(x => x.RecordState = RecordState.D); var branchAssignees = _commonDataService.GetEntity <AppAssigneeBranch>(x => branches.Select(y => y.Id).Contains(x.BranchId)).ToList(); branchAssignees.ForEach(x => x.RecordState = RecordState.D); var assignees = _commonDataService .GetEntity <AppAssignee>(x => branchAssignees.Select(y => y.AssigneeId).Contains(x.Id)).ToList(); assignees.ForEach(x => x.RecordState = RecordState.D); var eDocumentBranches = _commonDataService .GetEntity <BranchEDocument>(x => branches.Select(y => y.Id).Contains(x.BranchId)).ToList(); eDocumentBranches.ForEach(x => x.RecordState = RecordState.D); var eDocument = _commonDataService.GetEntity <EDocument>(x => eDocumentBranches.Select(y => y.EDocumentId).Contains(x.Id)).ToList(); var licFileName = new List <string>(); eDocument.ForEach(x => { if (x.IsFromLicense == true) { var files = _commonDataService .GetEntity <FileStore>(y => y.EntityId == x.Id && y.EntityName == "EDocument").ToList(); licFileName.AddRange(files.Select(p => p.FileName)); } }); eDocument.ForEach(x => { if (x.IsFromLicense == true) { return; } x.RecordState = RecordState.D; var files = _commonDataService .GetEntity <FileStore>(y => y.EntityId == x.Id && y.EntityName == "EDocument").ToList(); files.ForEach(y => { y.RecordState = RecordState.D; // Удалить файлы которые не принадлежат лицензии if (!licFileName.Contains(y.FileName)) { FileStoreHelper.DeleteFileIfExist(y.FilePath); } }); }); await _commonDataService.SaveChangesAsync(); } catch (Exception) { throw new Exception(); } }