public async Task <IActionResult> UploadAttachFile(IFormFile file, int taskId) { if (file.Length > 0) { var stream = file.OpenReadStream(); AttachmentModel model = new AttachmentModel { FileName = file.FileName, FileData = await stream.ConvertStreamToBytes(), FileType = file.ContentType, Task = new TaskItemModel { TaskId = taskId }, User = new AccountModel { AccountId = Context.CurrentAccount.AccountId } }; var iResult = await EzTask.Task.SaveAttachment(model); if (iResult.Status == ActionStatus.Ok) { string title = string.Format(Context.CurrentAccount.DisplayName + " {0} \"" + iResult.Data.FileName + "\"", Context.GetStringResource("UploadedFile", StringResourceType.TaskPage)); await EzTask.Task.SaveHistory(taskId, title, string.Empty, Context.CurrentAccount.AccountId); } return(Json(model)); } return(BadRequest()); }
public async Task <IHttpActionResult> GetAttachment([FromUri] int id) { #region FullSearch Attachment var attachments = UnitOfWork.RepositoryAttachment.Search(); var attachment = await attachments.Where(x => x.Id == id && x.Status == MasterItemStatus.Active).FirstOrDefaultAsync(); if (attachment == null) { return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound, HttpMessages.AttachmentNotFound))); } var oAttachment = new AttachmentModel(); oAttachment.Id = attachment.Id; if (attachment.Content != null) { oAttachment.Content = Convert.ToBase64String(attachment.Content); } oAttachment.StudentId = attachment.StudentId; oAttachment.Name = attachment.Name; oAttachment.Type = attachment.Type; #endregion return(Ok(oAttachment)); }
/// <summary> /// 上传附件 /// </summary> /// <param name="entityId">附件信息</param> /// <param name="entityType">附件信息</param> /// <returns>上传成功或失败</returns> public static ApiResponse <bool> Upload(int entityId, string entityType) { if (HttpContext.Current.Request.Files.Count > 0) { HttpPostedFile file = HttpContext.Current.Request.Files[0]; Stream fileStream = file.InputStream; var buffer = new byte[file.ContentLength]; var fileName = string.Format("{0}", Guid.NewGuid().ToString("N")); fileStream.Read(buffer, 0, file.ContentLength); var attachment = new AttachmentModel() { Content = buffer, EntityId = entityId, EntityType = entityType, Desc = file.FileName, Name = fileName, CreatedTime = DateTime.Now }; var response = new ApiResponse <bool>() { Result = (new AttachmentService()).Upload(attachment) }; return(response); } return(new ApiResponse <bool>() { Result = false }); }
private static void Frm_TypeReadyEvent(object sender, AttachmentModel e) { List <AttachmentModel> aList = GlobalConfig.Connection.GetAttachments(e.PID); //dgvAttachments.DataSource = null; //dgvAttachments.DataSource = aList; //formatAttGrid(); }
public int SaveFile(IEnumerable <HttpPostedFileBase> attachment, string dataType, long recordId) { var fileUpload = UploadFileHelper.SaveFile(attachment); if (fileUpload != null && fileUpload.Count > 0) { foreach (var file in fileUpload) { var attachmentModel = new AttachmentModel() { FileName = file.Realname, FileSize = file.Size, DisplayFileName = file.Name, RecordId = recordId, DataType = dataType, FileExtension = file.Extension }; var attachmentEntity = MapperHelper.Map <AttachmentModel, AttachmentEntity>(attachmentModel); var attachmentService = EngineContext.Current.Resolve <IAttachmentService>(); attachmentService.SaveAttachment(attachmentEntity); } } var result = fileUpload.Count; return(result); }
public ActionResult SubmitResponse(string[] arr) { IServiceDataModel dataModel = ServiceSystem.GetServiceModel(EnscoConstants.EntityModel.Attachment); IrmaCapaModel m = this.GetModel(this.CapaId); m.DateCompleted = DateTime.Parse(arr[0]); m.WO = arr[1]; m.CompletionDescription = arr[2]; ServiceSystem.Save(EnscoConstants.EntityModel.IrmaCapa, m, true); // if(arr != null) for (int i = 3; i < arr.Length; i++) { AttachmentModel attachment = dataModel.GetItem(string.Format("FilePath =\"{0}\"", HttpUtility.UrlDecode(arr[i])), "Id"); if (attachment != null) { dataModel.Delete(attachment); } } // this.UpdateAttachment(this.CapaId); //this.UpdateAttachment(0); return(RedirectToAction("Index/" + this.CapaId.ToString())); return(null); }
public void UpdateAttachment(int?id) { IServiceDataModel dataModel = ServiceSystem.GetServiceModel(EnscoConstants.EntityModel.Attachment); if (id != 0) { string source = this.Session["Source"] == null ? "" : this.Session["Source"].ToString(); IEnumerable <AttachmentModel> attachments = ServiceSystem.GetAttachments(source, "0"); if (attachments != null) { foreach (AttachmentModel attachment in attachments) { attachment.SourceFormId = id?.ToString(); attachment.SourceForm = "CapaPlan"; dataModel.Update(attachment); } } } else { string[] arr = this.Request.Form.GetValues("Removed"); if (arr != null) { foreach (string path in arr) { AttachmentModel attachment = dataModel.GetItem(string.Format("FilePath =\"{0}\"", HttpUtility.UrlDecode(path)), "Id"); if (attachment != null) { dataModel.Delete(attachment); } } } } }
public async Task <ActionResult <AttachmentModel> > Post(int supplierId, AttachmentModel model) { try { //Make sure AttachmentId is not already taken var existing = await _repository.GetAttachmentAsync(supplierId, model.Id); if (existing != null) { return(BadRequest("Attachment Id in Use")); } //map var Attachment = _mapper.Map <Attachment>(model); //save and return if (!await _repository.StoreNewAttachmentAsync(supplierId, Attachment)) { return(BadRequest("Bad request, could not create record!")); } else { var location = _linkGenerator.GetPathByAction("Get", "Attachment", new { supplierId = Attachment.SupplierId, Attachment.Id }); return(Created(location, _mapper.Map <AttachmentModel>(Attachment))); } } catch (Exception e) { _logger.LogError(e, e.Message); return(this.StatusCode(StatusCodes.Status500InternalServerError, "Database Failure")); } }
/// <summary> /// Creates attachment model collection for <paramref name="emailDto"/>. Replaces inline attachments links in body. /// </summary> /// <param name="emailDto"><paramref name="emailDto"/> instnace.</param> /// <param name="fixedBody">Email body with replaced inline attachments links.</param> /// <returns>Attachment models collection.</returns> private List <AttachmentModel> CreateAttachments(Email emailDto, out string fixedBody) { var result = new List <AttachmentModel>(); fixedBody = emailDto.Body; foreach (var attach in emailDto.Attachments) { var attachModel = new AttachmentModel() { IsInline = attach.IsInline, Name = attach.Name, Id = Guid.NewGuid(), Data = attach.GetData() }; if (attach.IsInline) { var url = _attachmentRepository.GetAttachmentLink(attachModel.Id); var cidUrl = string.Concat("cid:", attach.Id); if (fixedBody.Contains(cidUrl)) { fixedBody = fixedBody.Replace(cidUrl, url); } else { attachModel.IsInline = false; } } result.Add(attachModel); } return(result); }
/// <summary> /// convert attachment view model to domain /// </summary> /// <param name="attachmentModel"></param> /// <returns></returns> public DebitMemoAttachment ConvertToDomain(AttachmentModel attachmentModel) { DebitMemoAttachment attachment = new DebitMemoAttachment(); byte[] tempFile = new byte[attachmentModel.Attachment.ContentLength]; var trimmedFileName = string.Empty; if (attachmentModel.Attachment.FileName.EndsWith("png")) { trimmedFileName = attachmentModel.Attachment.FileName.Replace(".png", ""); } else if (attachmentModel.Attachment.FileName.EndsWith("jpg")) { trimmedFileName = attachmentModel.Attachment.FileName.Replace(".jpg", ""); } else if (attachmentModel.Attachment.FileName.EndsWith("pdf")) { trimmedFileName = attachmentModel.Attachment.FileName.Replace(".pdf", ""); } attachment.DebitMemoId = attachmentModel.DebitMemoId; attachment.Name = trimmedFileName; attachment.Type = attachmentModel.Attachment.ContentType; attachment.Length = attachmentModel.Attachment.ContentLength; attachment.Content = tempFile; return(attachment); }
public void ActionAttachments() { string userData = _userScot; AuthenticationModel authentication = AuthenticationModel.AuthenticationModelTest(userData, _connectionString); using (ConnectionContext connection = new ConnectionContext(authentication)) { // user ticket TicketProxy ticketProxy = IDTreeTest.EmptyTicket(); // from front end TicketModel ticketModel = (TicketModel)Data_API.Create(connection.User, ticketProxy); // dbo.Tickets // ticket action ActionProxy actionProxy = IDTreeTest.EmptyAction(); // from front end ActionModel actionModel = (ActionModel)Data_API.Create(ticketModel, actionProxy); // dbo.Actions // action attachment ActionAttachmentProxy attachmentProxy = (ActionAttachmentProxy)IDTreeTest.CreateAttachment(connection.OrganizationID, AttachmentProxy.References.Actions, actionModel.ActionID, actionModel.AttachmentPath); AttachmentModel attachmentModel = (AttachmentModel)Data_API.Create(actionModel, attachmentProxy); // read back attachment AttachmentProxy read = Data_API.ReadRefTypeProxy <AttachmentProxy>(connection, attachmentProxy.AttachmentID); switch (read) { case ActionAttachmentProxy output: // Action attachment Assert.AreEqual(attachmentProxy, output); break; default: Assert.Fail(); break; } } }
public virtual ActionResult UploadAttachment(AttachmentModel attachmentModel, HttpPostedFileBase fileAttach) { try { if (fileAttach == null) { return(Json(new { isError = true, Message = @"ورودی نامعتبر!" })); } attachmentModel.Extention = Path.GetExtension(fileAttach.FileName); attachmentModel.Size = fileAttach.ContentLength; if (!ModelState.IsValid) { return(Json(new { isError = true, Message = @"ورودی نامعتبر!" })); } using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var addressUrlFile = new AddressUrlFile(Server.MapPath("~//")); var path = addressUrlFile.UploadFiles; Useful.CreateFolderIfNeeded(addressUrlFile.UploadFiles); path += Guid.NewGuid() + Path.GetExtension(fileAttach.FileName); fileAttach.SaveAs(path); attachmentModel.File = Path.GetFileName(path); var data = _attachmentService.Add(attachmentModel); scope.Complete(); return(Json(new { isError = !data.Item1, Message = data.Item2 })); } } catch (Exception) { return(Json(new { isError = true, Message = @"خطا در ویرایش اطلاعات پرسنلی" })); } }
/// <summary> /// 删除记录及对应的文件 /// </summary> public void DeleteById(int FileId) { //先删除文件再删除记录 AttachmentModel old = DBProvider.AttachmentDAO.GetById(FileId); if (old != null) { switch (old.FileServerType) { case (int)GRGTCommonUtils.UtilConstants.ServerType.WebFileService: GRGTCommonUtils.UtilsHelper.DeleteServerFile(old.FileAccessPrefix, old.FileVirtualPath, GRGTCommonUtils.UtilConstants.ServerType.WebFileService); break; case (int)GRGTCommonUtils.UtilConstants.ServerType.FTPService: break; case (int)GRGTCommonUtils.UtilConstants.ServerType.WebService: break; default: break; } } DBProvider.AttachmentDAO.DeleteById(FileId); }
public JsonResult GetAttachment(int AD_Table_ID, int Record_ID) { Ctx ctx = Session["ctx"] as Ctx; AttachmentModel am = new AttachmentModel(); return(Json(new { result = am.GetAttachment(AD_Table_ID, Record_ID, ctx) }, JsonRequestBehavior.AllowGet)); }
public static void OnEntityStreamInEvent(Entity entity) { if (entity.Type == RAGE.Elements.Type.Player) { // Get the identifier of the player int playerId = entity.RemoteId; Player attachedPlayer = Entities.Players.GetAtRemote((ushort)playerId); // Get the attachment on the right hand object attachmentJson = attachedPlayer.GetSharedData(Constants.ITEM_ENTITY_RIGHT_HAND); if (attachmentJson != null) { AttachmentModel attachment = JsonConvert.DeserializeObject <AttachmentModel>(attachmentJson.ToString()); // If the attached item is a weapon, we don't stream it if (RAGE.Game.Weapon.IsWeaponValid(Convert.ToUInt32(attachment.hash))) { return; } attachment.attach = new MapObject(Convert.ToUInt32(attachment.hash), attachedPlayer.Position, new Vector3(), 255, attachedPlayer.Dimension); RAGE.Game.Entity.AttachEntityToEntity(attachment.attach.Handle, attachedPlayer.Handle, 28422, attachment.offset.X, attachment.offset.Y, attachment.offset.Z, attachment.rotation.X, attachment.rotation.Y, attachment.rotation.Z, false, false, false, true, 0, true); // Add the attachment to the dictionary playerAttachments.Add(playerId, attachment); } } }
/// <summary> /// Прикрепляет файл к задаче, используя id обоих /// </summary> /// <param name="attachModel"></param> /// <returns></returns> public async Task <List <Guid> > AttachFileToTaskAsync(AttachmentModel attachModel) { var resultTask = await _context.Tasks.SingleOrDefaultAsync(x => x.TaskId == attachModel.TaskId); if (resultTask == null) { throw new InvalidOperationException($"Задачи с таким id({attachModel.TaskId}) не существует"); } var resultGuids = new List <Guid>(); foreach (var fileId in attachModel.FileIds) { var resultFile = await _context.Files.SingleOrDefaultAsync(x => x.FileId == fileId); if (resultFile != null) { var resultAttach = new Attachment(resultTask.TaskId, resultFile.FileId); _context.Attachments.Add(resultAttach); resultGuids.Add(resultAttach.AttachmentId); } } await _context.SaveChangesAsync(); return(resultGuids); }
public static AttachmentModel SaveAttachment(AttachmentModel attachment) { try { using (var context = new BusinessContext()) { if (attachment.AttachmentId > 0) { context.Attachment.Update(attachment); } else { context.Attachment.Add(attachment); } context.SaveChanges(); return(attachment); } } catch (Exception e) { Logger.Info("Attachment - SaveAttachment"); Logger.Error(e); return(null); } }
protected override void AddAttachment(IMessageAttachment messageAttachment) { UIElement attachmentElement; AttachmentModel attachmentModel = new AttachmentModel(_fileSystem, messageAttachment); switch (messageAttachment.Type) { case AttachmentType.Image: attachmentElement = new AttachmentImage(attachmentModel); break; case AttachmentType.Video: attachmentElement = new AttachmentVideo(attachmentModel); break; case AttachmentType.Audio: attachmentElement = new AttachmentAudio(attachmentModel); break; default: throw new ArgumentException("Unrecognized attachment type: " + messageAttachment.Type.ToString()); } _currentParagraph.Inlines.Add(attachmentElement); }
/// <summary> /// 下载附件 /// </summary> /// <param name="fileId"></param> public void DownLoad(string fileId) { fileId = UtilsHelper.Decrypt(fileId); AttachmentModel fileMode = Global.Business.ServiceProvider.AttachmentService.GetById(int.Parse(fileId)); UtilsHelper.FileDownload(fileMode.FileAccessPrefix, fileMode.FileVirtualPath, fileMode.FileName, (UtilConstants.ServerType)fileMode.FileServerType); }
/// <summary> /// 附件的删除与修改 /// </summary> /// <param name="attachmentXmls"></param> /// <param name="swbh"></param> /// <param name="swlx"></param> /// <param name="tran"></param> public void InserOrUpdateAttachment2(XmlNodeList attachmentXmls, string swbh, string swlx, IDbTransaction tran) { foreach (XmlNode node in attachmentXmls) { string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(node); AttachmentModel JBXXModel = JsonConvert.DeserializeObject <AttachmentModel>(json); B_OA_IAttachment attachment = JBXXModel.FJXX; attachment.Condition.Add("WDBH = " + attachment.WDBH); attachment.Condition.Add("APPBH = " + attachment.APPBH); if (Utility.Database.QueryObject(attachment, tran) == null) { Utility.Database.Insert(attachment, tran); _logger.InfoFormat("成功插入附件表数据!"); } else { attachment.Condition.Add("WDBH = " + attachment.WDBH); attachment.Condition.Add("APPBH = " + attachment.APPBH); Utility.Database.Update(attachment, tran); _logger.InfoFormat("成功修改附件表数据!"); } //文件复制到相应文件夹 service.taskAttachmentsDownload("qjc_lims_test", "TZGG", attachment.WDBH, 0, 100); } }
/// <summary> /// Inicializuje hlavní menu. /// </summary> /// <param name="publicationTypes">typy publikací</param> /// <param name="publicationModel">správce publikací</param> /// <param name="authorModel">správce autorů</param> /// <param name="attachmentModel">správce příloh</param> public MainMenu(List <PublicationType> publicationTypes, PublicationModel publicationModel, AuthorModel authorModel, AttachmentModel attachmentModel) { this.publicationTypes = publicationTypes; this.publicationModel = publicationModel; this.authorModel = authorModel; this.attachmentModel = attachmentModel; MenuLabel = "Hlavní menu"; InitializeMenuItems(new Dictionary <ConsoleKey, MenuItem>() { { ConsoleKey.L, new MenuItem() { Name = "List", Description = "Zobrazí menu výpisu publikací se zadanými filtry.", UIMethod = GetPublicationList } }, { ConsoleKey.R, new MenuItem() { Name = "Read", Description = "Načte detail zadané publikace, kterou lze upravit nebo odstranit.", UIMethod = GetPublicationDetail } }, { ConsoleKey.C, new MenuItem() { Name = "Create", Description = "Vytvoří novou publikaci.", UIMethod = CreateNewPublication } }, { ConsoleKey.A, new MenuItem() { Name = "Authors", Description = "Zobrazí menu výpisu uložených autorů.", UIMethod = GetAuthorList } }, { ConsoleKey.I, new MenuItem() { Name = "Info", Description = "Vypíše stručný popis programu.", UIMethod = PrintInfo } }, }); MenuItems[ConsoleKey.H].Description = "Ukončí program."; }
public void OnPlayerWeaponSwitch(Client player, WeaponHash oldWeapon, WeaponHash newWeapon) { if (player.GetData(EntityData.PLAYER_PLAYING) != null) { int playerId = player.GetData(EntityData.PLAYER_SQL_ID); if (player.GetSharedData(EntityData.PLAYER_RIGHT_HAND) != null) { string rightHand = player.GetSharedData(EntityData.PLAYER_RIGHT_HAND).ToString(); var itemId = NAPI.Util.FromJson <AttachmentModel>(rightHand).itemId; var item = Globals.GetItemModelFromId(itemId); if (NAPI.Util.WeaponNameToModel(item.hash) == 0) { var weaponItem = GetEquippedWeaponItemModelByHash(playerId, newWeapon); player.GiveWeapon(WeaponHash.Unarmed, 1); return; } } // Get previous and new weapon models var oldWeaponModel = GetEquippedWeaponItemModelByHash(playerId, oldWeapon); var currentWeaponModel = GetEquippedWeaponItemModelByHash(playerId, newWeapon); if (oldWeaponModel != null) { // Unequip previous weapon oldWeaponModel.ownerEntity = Constants.ITEM_ENTITY_WHEEL; Task.Factory.StartNew(() => { // Update the weapon into the database Database.UpdateItem(oldWeaponModel); }); } if (currentWeaponModel != null) { // Equip new weapon currentWeaponModel.ownerEntity = Constants.ITEM_ENTITY_RIGHT_HAND; Task.Factory.StartNew(() => { // Update the weapon into the database Database.UpdateItem(currentWeaponModel); }); } // Check if it's armed if (newWeapon == WeaponHash.Unarmed) { player.ResetSharedData(EntityData.PLAYER_RIGHT_HAND); } else { // Add the attachment to the player var attachment = new AttachmentModel(currentWeaponModel.id, currentWeaponModel.hash, "IK_R_Hand", new Vector3(), new Vector3()); player.SetSharedData(EntityData.PLAYER_RIGHT_HAND, NAPI.Util.ToJson(attachment)); } } }
public JsonResult DownloadAttachment(string fileName, int AD_Attachment_ID, int AD_AttachmentLine_ID, string actionOrigin, string originName, int AD_Table_ID, int recordID) { //List<AttFileInfo> _files = JsonConvert.DeserializeObject<List<AttFileInfo>>(files); Ctx ctx = Session["ctx"] as Ctx; AttachmentModel am = new AttachmentModel(); return(Json(new { result = am.DownloadAttachment(ctx, fileName, AD_Attachment_ID, AD_AttachmentLine_ID, actionOrigin, originName, AD_Table_ID, recordID) }, JsonRequestBehavior.AllowGet)); }
public JsonResult SaveAttachmentEntries(string files, int AD_Attachment_ID, string folderKey, int AD_Table_ID, int Record_ID, string fileLocation, int NewRecord_ID, bool IsDMSAttachment) { List <AttFileInfo> _files = JsonConvert.DeserializeObject <List <AttFileInfo> >(files); Ctx ctx = Session["ctx"] as Ctx; AttachmentModel am = new AttachmentModel(); return(Json(new { result = am.CreateAttachmentEntries(_files, AD_Attachment_ID, folderKey, ctx, AD_Table_ID, Record_ID, fileLocation, NewRecord_ID, IsDMSAttachment) }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Saves <paramref name="attach"/> as <paramref name="emailId"/> activity file. /// </summary> /// <param name="attach">Attachment model instance.</param> /// <param name="emailId">Email identifier.</param> private void SaveActivityFile(AttachmentModel attach, Guid emailId) { var uploader = ClassFactory.Get <IFileUploader>("EmailAttachmentUploader", new ConstructorArgument("uc", _userConnection)); var activityFile = CreateActivityFileEntity(attach, emailId); activityFile.Save(); uploader.UploadAttach(activityFile.PrimaryColumnValue, activityFile.GetTypedColumnValue <string>("Name"), attach.Data); }
/// <summary> /// 更新周检附件信息 /// </summary> /// <param name="list"></param> public void UpdateCertFile(IList <InstrumentCertificationModel> list, AttachmentModel attachment) { foreach (InstrumentCertificationModel m in list) { m.FileId = attachment.FileId; DBProvider.InstrumentCertificationDAO.UpdateCertFile(m); } }
public Clue Create(AttachmentModel value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return(this.Create(EntityType.Files.File, value.Attachment.Id)); }
public static void GenerateExcel(List <ZinaraReportModel> grossWrittenPremiumReports) { StreamWriter sw = null; try { int indexList = grossWrittenPremiumReports.Count(); int totalsIndex = indexList + 6; var zinaraAmount = grossWrittenPremiumReports.Sum(x => x.ZinaraAmount); var zinarCount = grossWrittenPremiumReports.Sum(x => x.count); MemoryStream outputStream = new MemoryStream(); using (ExcelPackage package = new ExcelPackage(outputStream)) { // export each facility's rollup and detail to tabs in Excel (two tabs per facility) ExcelWorksheet facilityWorksheet = package.Workbook.Worksheets.Add("Zinara Report"); facilityWorksheet.Cells["A1"].LoadFromText("Zinara Report").Style.Font.Bold = true; facilityWorksheet.Cells["A3"].Value = "Report Generated Date: " + DateTime.Now.ToString(); facilityWorksheet.Cells["A5"].LoadFromCollection(grossWrittenPremiumReports, true, OfficeOpenXml.Table.TableStyles.Light1); facilityWorksheet.Cells["A" + totalsIndex.ToString()].LoadFromText("TOTALS").Style.Font.Bold = true; facilityWorksheet.Cells["B" + totalsIndex.ToString()].LoadFromText(zinaraAmount.ToString()).Style.Font.Bold = true; facilityWorksheet.Cells["C" + totalsIndex.ToString()].LoadFromText(zinarCount.ToString()).Style.Font.Bold = true; package.Save(); outputStream.Position = 0; List <Stream> _attachements = new List <Stream>(); List <AttachmentModel> attachmentModels = new List <AttachmentModel>(); AttachmentModel attachment = new AttachmentModel(); attachment.Attachment = outputStream; attachment.Name = "Zinara Report.xlsx"; attachmentModels.Add(attachment); _attachements.Add(outputStream); Debug.WriteLine("************Attached*************"); StringBuilder mailBody = new StringBuilder(); mailBody.AppendFormat("<div>Please Find Attached.</div>"); Debug.WriteLine("***********SendEmail**************"); string email = System.Configuration.ConfigurationManager.AppSettings["gwpemail"]; Insurance.Service.EmailService objEmailService = new Insurance.Service.EmailService(); objEmailService.SendAttachedEmail(email, "", "", "Zinara Report - " + DateTime.Now.ToShortDateString(), mailBody.ToString(), attachmentModels); Library.WriteErrorLog("Zinara Report - " + DateTime.Now.ToShortDateString()); } } catch (Exception ex) { } finally { } }
/// <summary> ///保存知识库 /// </summary> /// <param name="model"></param> /// <param name="Files"></param> public void Save(KnowledgesModel model, HttpFileCollectionBase Files) { if (Files.Count > 0 && Files[0].ContentLength > 0) { int fileServerType = Convert.ToInt32(WebUtils.GetSettingsValue("WebFileType") == null ? "1" : WebUtils.GetSettingsValue("WebFileType")); HttpPostedFileBase file = Files[0]; string targetPath = WebUtils.GetSettingsValue("KnowledgesPDFFilePath"); string SwfFilePath = WebUtils.GetSettingsValue("KnowledgesSwfFilePath"); string targetFileName = StrUtils.GetUniqueFileName(null); string targetFile = string.Format(@"{0}/{1}{2}", targetPath, targetFileName, Path.GetExtension(Files[0].FileName)); string targetSwfPath, pdfFilestr, srcSwfFile, tempFileName; AttachmentModel attModel = null; Stream fileStream = null; try { attModel = UtilsHelper.FileUpload(WebUtils.GetSettingsValue("WebFileServer"), Files[0], targetFile, (UtilConstants.ServerType)fileServerType); fileStream = UtilsHelper.FileDownload(WebUtils.GetSettingsValue("WebFileServer"), attModel.FileVirtualPath, (UtilConstants.ServerType)fileServerType); tempFileName = Guid.NewGuid().ToString(); pdfFilestr = CommonUtils.GetPhysicsPath(string.Format("{0}/{1}.pdf", "/tempFile", tempFileName)); ToolsLib.FileService.NormalFile.SaveInfoToFile(fileStream, pdfFilestr); srcSwfFile = UtilsHelper.PdfToSwf(pdfFilestr, tempFileName + ".swf"); targetSwfPath = string.Format("{0}/{1}.swf", Path.GetDirectoryName(attModel.FileVirtualPath).Replace("Pdf", "Swf"), Path.GetFileNameWithoutExtension(attModel.FileVirtualPath)); if (fileServerType == 1) { fileStream = new FileStream(srcSwfFile, FileMode.Open); ToolsLib.FileService.NormalFile.SaveInfoToFile(fileStream, targetSwfPath); } else { UtilsHelper.FileUpload(WebUtils.GetSettingsValue("WebFileServer"), srcSwfFile, targetSwfPath, (UtilConstants.ServerType)fileServerType); } File.Delete(pdfFilestr); File.Delete(srcSwfFile); } catch (Exception e) { } attModel.FileType = (int)Instrument.Common.Constants.AttachmentBusinessType.本地知识库.GetHashCode(); attModel.UserId = LoginHelper.LoginUser.UserId; attModel.UserName = LoginHelper.LoginUser.UserName; if (model.FileId != 0)//重新上传删除原来文件 { Global.Business.ServiceProvider.AttachmentService.DeleteById(model.FileId); } Global.Business.ServiceProvider.AttachmentService.Save(attModel); model.FileId = attModel.FileId;//新文件位置 } if (model.KnowledgeId == 0) { model.Creator = LoginHelper.LoginUser.UserName; DBProvider.KnowledgesDao.Add(model); } else { DBProvider.KnowledgesDao.Update(model); } }
/// <summary> /// 文件上传 /// </summary> /// <param name="webFileServer">当文件服务器发生变更,必须指定旧的文件服务器地址</param> /// <param name="sourceFileName">源文件物理地址</param> /// <param name="targetFileName">文件虚拟路径地址</param> /// <param name="targetServer"></param> /// <returns></returns> public static AttachmentModel FileUpload(string webFileServer, string sourceFileName, string targetFileName, UtilConstants.ServerType targetServer) { FileStream fs = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read); AttachmentModel atta = FileUpload(webFileServer, fs, sourceFileName, targetFileName, targetServer); fs.Close(); fs.Dispose(); return(atta); }