private static AttachmentInfo SaveAsAttachment(object doc, AttachmentInfo attachment, SaveDocument saveDocument) { string fileId = AttachmentManager.GetNewFileID(); string savePath = AttachmentInfo.FileIDToPath(fileId, AttachmentManager.AttachmentRootPath); Directory.CreateDirectory(savePath.Substring(0, savePath.LastIndexOf(@"\"))); saveDocument.Invoke(doc, savePath); attachment.FileID = fileId; if (String.IsNullOrEmpty(attachment.Name)) { attachment.Name = fileId + attachment.Ext; } //attachment.Name = fileName; //attachment.Ext = fileExt; //attachment.Size = fileSize; attachment.LastUpdate = DateTime.Now; attachment.OwnerAccount = YZAuthHelper.LoginUserAccount; FileInfo fileInfo = new FileInfo(savePath); attachment.Size = fileInfo.Length; using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider) { using (IDbConnection cn = provider.OpenConnection()) { provider.Insert(cn, attachment); } } return(attachment); }
public void RefreshName(IYZDbProvider provider, IDbConnection cn) { AttachmentInfo attachment = AttachmentManager.TryGetAttachmentInfo(provider, cn, this.FileID); if (attachment != null) { this.FileName = attachment.Name; } else { this.FileName = ""; } switch (this.LinkType) { case ReferenceType.SpriteToSprite: case ReferenceType.ProcessToSprite: SpriteIdentity identity = BPAManager.TryGetSpriteIdentity(provider, cn, this.FileID, this.SpriteID); this.SpriteName = identity != null ? identity.Name : ""; break; default: this.SpriteName = ""; break; } }
public virtual object AddAttachmentToFolder(HttpContext context) { YZRequest request = new YZRequest(context); int folderid = request.GetInt32("folderid"); string fileid = request.GetString("fileid"); string flag = request.GetString("flag", null); AttachmentInfo attachmentInfo; File file = new File(); using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider) { using (IDbConnection cn = provider.OpenConnection()) { attachmentInfo = AttachmentManager.GetAttachmentInfo(provider, cn, fileid); file.FolderID = folderid; file.FileID = fileid; file.AddBy = YZAuthHelper.LoginUserAccount; file.AddAt = DateTime.Now; file.Flag = flag; file.OrderIndex = DirectoryManager.GetFileNextOrderIndex(provider, cn, folderid); DirectoryManager.Insert(provider, cn, file); } } using (BPMConnection bpmcn = new BPMConnection()) { bpmcn.WebOpen(); return(this.Serialize(bpmcn, file, attachmentInfo)); } }
public virtual object GetFolderDocuments(HttpContext context) { YZRequest request = new YZRequest(context); int folderid = request.GetInt32("folderid"); int top = request.GetInt32("top", -1); string order = request.GetString("order", null); using (BPMConnection bpmcn = new BPMConnection()) { bpmcn.WebOpen(); using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider) { using (IDbConnection cn = provider.OpenConnection()) { List <object> rv = new List <object>(); FileCollection files = DirectoryManager.GetFiles(provider, cn, folderid, null, order, top); foreach (File file in files) { AttachmentInfo attachmentInfo = AttachmentManager.TryGetAttachmentInfo(provider, cn, file.FileID); if (attachmentInfo == null) { continue; } rv.Add(this.Serialize(bpmcn, file, attachmentInfo)); } return(rv); } } } }
public virtual object UpdateAttachment(HttpContext context) { YZRequest request = new YZRequest(context); int id = request.GetInt32("id"); string fileid = request.GetString("fileid"); string replacewithfileid = request.GetString("replacewithfileid"); File file; AttachmentInfo attachmentInfo; using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider) { using (IDbConnection cn = provider.OpenConnection()) { file = DirectoryManager.GetFileByID(provider, cn, id); attachmentInfo = AttachmentManager.UpdateAttachment(provider, cn, fileid, replacewithfileid); } } using (BPMConnection bpmcn = new BPMConnection()) { bpmcn.WebOpen(); return(this.Serialize(bpmcn, file, attachmentInfo)); } }
private void txtAttachmentURL_KeyDown_1(object sender, KeyEventArgs e) { if (e.Key != Key.Return) { return; } if (txtAttachmentURL.Text.Trim() == "") { return; } var d = DataContext as Discussion; if (d == null) { return; } //ap.RecentlyEnteredMediaUrl = txtAttachmentURL.Text; Attachment a = new Attachment(); if (AttachmentManager.ProcessAttachCmd(null, txtAttachmentURL.Text, ref a) != null) { a.Person = getFreshPerson(); a.Discussion = d; } }
private static Attachment UploadThumbnailPhoto(byte[] photoBytes, string userid) { AttachmentManager attachmentManager = new AttachmentManager(); Attachment thumbnail = attachmentManager.Upload(string.Format("Thumbnail_{0}.jpg", userid), "image/jpeg", photoBytes, userid); return(thumbnail); }
/// <summary> /// Deletes the file binary from the file system. /// </summary> /// <param name="attachmentId">Attachment ID</param> /// <param name="name">Returning the attachment name</param> protected bool DeleteFromFileSystem(int attachmentId, ref string name) { // Delete the file in file system AttachmentInfo ai = Manager.GetAttachmentInfo(attachmentId, false); if (ai != null) { name = ai.AttachmentName; // Ensure the binary column first (check if exists) DataSet ds = Manager.GetAttachments("AttachmentID = " + attachmentId, null, true, 0, "CASE WHEN AttachmentBinary IS NULL THEN 0 ELSE 1 END AS HasBinary"); if (!DataHelper.DataSourceIsEmpty(ds)) { bool hasBinary = ValidationHelper.GetBoolean(ds.Tables[0].Rows[0][0], false); if (!hasBinary) { // Copy the binary data to database ai.AttachmentBinary = Manager.GetFile(ai, GetSiteName(ai.AttachmentSiteID)); ai.Generalized.UpdateData(); } // Delete the file from the disk AttachmentManager.DeleteFile(ai.AttachmentGUID, GetSiteName(ai.AttachmentSiteID), true, false); return(true); } } return(false); }
private static File TryLoad(IYZDbProvider provider, IDbConnection cn, string fileid, out Exception exp) { string filePath = AttachmentInfo.FileIDToPath(fileid, AttachmentManager.AttachmentRootPath); exp = null; if (!System.IO.File.Exists(filePath)) { exp = new Exception(String.Format(Resources.YZStrings.Aspx_Upload_FileIDNotFount, fileid)); return(null); } JObject jProcess; using (System.IO.StreamReader rd = new System.IO.StreamReader(filePath)) jProcess = JObject.Parse(rd.ReadToEnd()); AttachmentInfo attachment = AttachmentManager.GetAttachmentInfo(provider, cn, fileid); File file = jProcess.ToObject <File>(); file.FileID = fileid; file.FileName = attachment != null ? attachment.Name : ""; file.AttachmentInfo = attachment; return(file); }
public static AttachmentInfo DownloadTempMediaFile(string accessToken, string mediaId) { WebClient webClient = new WebClient(); webClient.Encoding = Encoding.UTF8; webClient.Headers.Add(HttpRequestHeader.KeepAlive, "false"); YZUrlBuilder uri = new YZUrlBuilder("https://qyapi.weixin.qq.com/cgi-bin/media/get"); uri.QueryString["access_token"] = accessToken; uri.QueryString["media_id"] = mediaId; using (Stream stream = webClient.OpenRead(uri.ToString())) { StreamReader reader = new StreamReader(stream); ContentDisposition contentDisposition = new ContentDisposition(webClient.ResponseHeaders["Content-Disposition"]); AttachmentInfo attachment = new AttachmentInfo(); attachment.Name = ""; attachment.Ext = Path.GetExtension(contentDisposition.FileName); attachment = AttachmentManager.SaveAsAttachment(stream, attachment); return(attachment); } }
public AttachmentInfoCollection GetAttachmentsInfo(HttpContext context) { YZRequest request = new YZRequest(context); string[] ids = request.GetString("fileids").Split(',', ';'); AttachmentInfoCollection attachments = new AttachmentInfoCollection(); using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider) { using (IDbConnection cn = provider.OpenConnection()) { attachments = AttachmentManager.GetAttachmentsInfo(provider, cn, ids); } } AttachmentInfoCollection rv = new AttachmentInfoCollection(); foreach (string id in ids) { AttachmentInfo attachmentInfo = attachments.TryGetItem(id); if (attachmentInfo != null) { rv.Add(attachmentInfo); } } return(rv); }
private void btnAttachScreenshot_Click_1(object sender, RoutedEventArgs e) { var ap = DataContext as ArgPoint; if (ap == null) { return; } var screenshotWnd = new ScreenshotCaptureWnd((System.Drawing.Bitmap b) => { var attach = AttachmentManager.AttachScreenshot(ap, b); if (attach != null) { var seldId = SessionInfo.Get().person.Id; attach.Person = PrivateCenterCtx.Get().Person.FirstOrDefault(p0 => p0.Id == seldId); ap.ChangesPending = true; UISharedRTClient.Instance.clienRt.SendStatsEvent( StEvent.ScreenshotAdded, ap.Person.Id, ap.Topic.Discussion.Id, ap.Topic.Id, DeviceType.Wpf); UpdateOrderedMedia(); BeginAttachmentNumberInjection(); } }); screenshotWnd.ShowDialog(); }
private void Attach(object sender, ExecutedRoutedEventArgs args) { ArgPoint ap = DataContext as ArgPoint; if (ap == null) { return; } //if ((string)args.Parameter == "Remove selected") //{ // Attachment a = lstBxAttachments.SelectedItem as Attachment; // if (a != null) // ap.Attachment.Remove(a); //} //else { Attachment a = new Attachment(); ImageSource src = AttachmentManager.ProcessAttachCmd(ap, AttachCmd.ATTACH_IMG_OR_PDF, ref a); if (src != null) { a.Person = getFreshCurrentPerson(); } } }
public PartialViewResult RefreshData(RefreshDataParameters parameters) { // Checks for null and if yes - replaces with the defaults parameters.SortingColumn = parameters.SortingColumn ?? Settings.DefaultSortingColumn; parameters.SortingDirection = parameters.SortingDirection ?? Settings.DefaultSortingDirection; // Pull the records from database var recordManager = new RecordManager(); var rec = recordManager.GetData(parameters); // Get list of available attachments and mofy a corresponding Record with it Dictionary <int, string> attchments = AttachmentManager.GetAttachments(); foreach (var record in rec) { record.Attachment = attchments.ContainsKey(record.RecordId) ? attchments[record.RecordId] : String.Empty; } // Set total amount message and erturn a aprtial view ViewBag.Amount = string.Format("Total {0} records.", rec.Count() - 1); // Add sorting column and direction to viewbag in orger to indicate the column by displaying appropriate arrow right hand side from its name ViewBag.SortingColumn = parameters.SortingColumn.ToLower().Trim(); ViewBag.SortingDirection = parameters.SortingDirection; return(PartialView("_Data", rec)); }
public static AttachmentInfo SaveAsAttachment(string path, AttachmentInfo attachment) { using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { return(AttachmentManager.SaveAsAttachment(stream, attachment, new SaveDocument(SaveStream))); } }
public static void RenameFile(string folderPath, string name, string newname) { string oldFile = Path.Combine(folderPath, name); string newFile = Path.Combine(folderPath, newname); string oldExtensionFile = OSFileInfo.GetExtensionFilePath(oldFile); string newExtensionFile = OSFileInfo.GetExtensionFilePath(newFile); string oldThumbnailPath = AttachmentManager.GetThumbnailPath(oldFile, "thumbnail", "png"); string newThumbnailPath = AttachmentManager.GetThumbnailPath(newFile, "thumbnail", "png"); if (System.IO.File.Exists(newFile)) { throw new Exception(String.Format(Resources.YZStrings.Aspx_FileSystem_Ext_FileWithSameNameAleardyExist, newname)); } System.IO.File.Move(oldFile, newFile); if (System.IO.File.Exists(oldExtensionFile)) { System.IO.File.Delete(newExtensionFile); System.IO.File.Move(oldExtensionFile, newExtensionFile); } if (System.IO.File.Exists(oldThumbnailPath)) { System.IO.File.Delete(newThumbnailPath); System.IO.File.Move(oldThumbnailPath, newThumbnailPath); } }
protected virtual void ApplyLinkText(IYZDbProvider provider, IDbConnection cn, JArray jSprites) { if (jSprites == null) { return; } List <JObject> result = new List <JObject>(); foreach (JObject jSprite in jSprites) { string relatiedFile = (string)jSprite["relatiedFile"]; if (!String.IsNullOrEmpty(relatiedFile)) { AttachmentInfo attachmentInfo = AttachmentManager.TryGetAttachmentInfo(provider, cn, relatiedFile); jSprite["relatiedFileName"] = attachmentInfo == null ? relatiedFile : attachmentInfo.Name; } YZJsonHelper.FindBy(jSprite["property"], result, new JsonFindCompare(this.isBPAReferenceCompare)); } foreach (JObject jLink in result) { Reference reference = jLink.ToObject <Reference>(); reference.RefreshName(provider, cn); jLink["FileName"] = reference.FileName; jLink["SpriteName"] = reference.SpriteName; } }
protected virtual void AddReference(IYZDbProvider provider, IDbConnection cn, File file, Sprite sprite, ReferenceCollection refs, BPMObjectNameCollection tagfiletype, JArray rv) { foreach (Reference @ref in refs) { AttachmentInfo tagAttachment = AttachmentManager.TryGetAttachmentInfo(provider, cn, @ref.FileID); if (tagAttachment == null) { continue; } if (tagfiletype.Count != 0 && !tagfiletype.Contains(tagAttachment.Ext)) { continue; } File tagFile = File.TryLoad(provider, cn, @ref.FileID); if (tagFile == null) { continue; } Sprite tagSprite = tagFile.Sprites.TryGetItem(@ref.SpriteID); JObject item = new JObject(); rv.Add(item); item["FileID"] = file.FileID; item["FileName"] = file.FileName; item["SpriteName"] = SpriteIdentity.ConvertSpriteName(sprite == null ? "" : sprite.Name); item["RelatiedFileID"] = tagFile.FileID; item["RelatiedFileName"] = tagFile.FileName; item["RelatiedSpriteName"] = SpriteIdentity.ConvertSpriteName(tagSprite == null ? "" : tagSprite.Name); } }
public virtual object GetNewFileInfo(HttpContext context) { string uid = YZAuthHelper.LoginUserAccount; FileSystem.Folder folder = new FileSystem.Folder(); using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider) { using (IDbConnection cn = provider.OpenConnection()) { folder.FolderType = "BPAFileAttachments"; folder.ParentID = -1; folder.Name = ""; folder.Desc = ""; folder.Owner = uid; folder.CreateAt = DateTime.Now; folder.OrderIndex = 1; FileSystem.DirectoryManager.Insert(provider, cn, folder); folder.RootID = folder.FolderID; FileSystem.DirectoryManager.Update(provider, cn, folder); } } return(new { fileid = AttachmentManager.GetNewFileID(), folderid = folder.FolderID }); }
public virtual SpriteLinkCollection GetSpriteUsedByLinks(HttpContext context) { YZRequest request = new YZRequest(context); string fileid = request.GetString("fileid"); string spriteid = request.GetString("spriteid"); using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider) { using (IDbConnection cn = provider.OpenConnection()) { SpriteLinkCollection links = BPAManager.GetSpriteUsedByLinks(provider, cn, fileid, spriteid, null); foreach (SpriteLink link in links) { AttachmentInfo attachmentInfo = AttachmentManager.TryGetAttachmentInfo(provider, cn, link.FileID); if (attachmentInfo != null) { link["FileName"] = attachmentInfo.Name; link["FileExt"] = attachmentInfo.Ext; link["Attachment"] = JObject.FromObject(attachmentInfo); } SpriteIdentity spriteIdentity = BPAManager.TryGetSpriteIdentity(provider, cn, link.FileID, link.SpriteID); if (spriteIdentity != null) { link["SpriteName"] = spriteIdentity.Name; } } return(links); } } }
public void SaveEmailInData(MailBox mailbox, MailMessage message, string httpContextScheme = null, ILogger log = null) { if (string.IsNullOrEmpty(mailbox.EMailInFolder)) { return; } if (log == null) { log = new NullLogger(); } try { foreach (var attachment in message.Attachments) { using (var file = AttachmentManager.GetAttachmentStream(attachment)) { log.Debug("SaveEmailInData->ApiHelper.UploadToDocuments(fileName: '{0}', folderId: {1})", file.FileName, mailbox.EMailInFolder); UploadToDocuments(file, attachment.contentType, mailbox, httpContextScheme, log); } } } catch (Exception e) { _log.Error("SaveEmailInData(tenant={0}, userId='{1}', messageId={2}) Exception:\r\n{3}\r\n", mailbox.TenantId, mailbox.UserId, message.Id, e.ToString()); } }
public void Delete_Id_Doesnt_Exist() { var attachmentManager = new AttachmentManager(100); bool delete = attachmentManager.Delete(); Assert.IsTrue(delete); }
private void ImportMoneyFile(MyMoney newMoney, AttachmentManager newAttachments) { this.dispatcher.Invoke(new Action(() => { // gather accounts to be merged (skipping closed accounts). foreach (var acct in newMoney.Accounts) { if (!acct.IsClosed && !acct.IsCategoryFund) { list.Add(new AccountImportState() { Dispatcher = this.dispatcher, Account = acct, Name = acct.Name, }); } } })); foreach (AccountImportState a in list) { ImportAccount(newMoney, a, newAttachments); } ShowStatus("Done"); }
private void btnAttachFromUrl_Click_1(object sender, RoutedEventArgs e) { if (_d == null) { return; } InpDialog dlg = new InpDialog(); dlg.ShowDialog(); string URL = dlg.Answer; if (URL == null) { return; } Attachment a = new Attachment(); if (AttachmentManager.ProcessAttachCmd(null, URL, ref a) != null) { a.Discussion = _d; a.Person = getFreshPerson(); insertMedia(a); } }
public ValveViewModel GetList(SearchModel query) { var where = new StringBuilder(); if (query != null) { where = GenerateQuerySQL.GenerateQuery(query, typeof(Valve).Name); } else { query = new SearchModel(); } var v = _dal.GetList(where.ToString()); v.List = v.List.Skip(query.PageIndex * query.PageSize).Take(query.PageSize).ToList(); var ids = new StringBuilder(); where.Clear(); v.List.ForEach(item => { ids.AppendFormat("{0},", item.ValveId); }); if (ids.Length > 0) { where.AppendFormat(" where MeterId in ({0})", ids.ToString().TrimEnd(',')); var att = new AttachmentManager().GetList(where.ToString()); v.List.ForEach(item => { item.AttachmentList = att.FindAll(p => p.MeterId == item.ValveId); }); } return(v); }
public virtual object SaveAttachment(HttpContext context, HttpPostedFile file, string fileName, long fileSize, string fileExt) { //华为手机,fileExt格式 .png?112714368714 if (!String.IsNullOrEmpty(fileExt)) { int index = fileExt.IndexOf('?'); if (index != -1) { fileExt = fileExt.Substring(0, index); } } AttachmentInfo attachment = new AttachmentInfo(); attachment.Name = fileName; attachment.Ext = fileExt; attachment = AttachmentManager.SaveAsAttachment(file, attachment); return(new { success = true, fileid = attachment.FileID, attachment = attachment }); }
public virtual object SaveNotesSpeak(HttpContext context, HttpPostedFile file, string fileName, long fileSize, string fileExt) { YZRequest request = new YZRequest(context); int duration = request.GetInt32("duration"); AttachmentInfo attachment = new AttachmentInfo(); attachment.Name = fileName; attachment.Ext = fileExt; attachment = AttachmentManager.SaveAsAttachment(file, attachment); YZSoft.Apps.Speak speak = new Apps.Speak(); speak.Account = YZAuthHelper.LoginUserAccount; speak.FileID = attachment.FileID; speak.Duration = duration; speak.Comments = Resources.YZStrings.Aspx_NewRecordPerfix + attachment.FileID; speak.CreateAt = DateTime.Now; using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider) { using (IDbConnection cn = provider.OpenConnection()) { YZSoft.Apps.SpeakManager.Insert(provider, cn, speak); } } return(new { success = true, fileid = attachment.FileID, speak = speak }); }
/// <summary> /// Checks whether the name is unique. /// </summary> /// <param name="name">New attachment name</param> /// <param name="extension">New attachment extension. If null current is used.</param> private bool IsNameUnique(string name, string extension) { if ((ai != null) && (AttachmentManager != null)) { // Ensure extension is set extension = extension ?? ai.AttachmentExtension; // Check that the name is unique in the document or version context Guid attachmentFormGuid = QueryHelper.GetGuid("formguid", Guid.Empty); bool nameIsUnique = false; if (attachmentFormGuid == Guid.Empty) { // Get the node TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree); nameIsUnique = DocumentHelper.IsUniqueAttachmentName(node, name, extension, ai.AttachmentID, baseImageEditor.Tree); } else { nameIsUnique = AttachmentManager.IsUniqueTemporaryAttachmentName(attachmentFormGuid, name, extension, ai.AttachmentID); } return(nameIsUnique); } return(false); }
public IActionResult Edit(string id) { try { var invoice = InvoiceManager.GetInvoiceViewModelById(id); invoice.InvoiceLines = InvoiceManager.GetInvoiceLineViewModels(id); invoice.InvoiceLine = new InvoiceLineViewModel(); invoice.BudgetItemList = InvoiceManager.GetOpenBudgetsItemList(invoice.Budget); invoice.CustomerItemList = InvoiceManager.GetOpenCustomersItemList(invoice.Customer); invoice.Attachments = AttachmentManager.GetAttachmentViewModelsForDocument(DocumentType.Invoice, id); return(View(invoice)); } catch (Exception e) { //Console.WriteLine(e.Message); //throw; var innerMessage = e.InnerException == null ? "" : $": {e.InnerException.Message}"; TempData["Error"] = $"Wystąpił problem podczas edytowania faktury: {e.Message}{innerMessage}"; } return(RedirectToAction("Index")); }
public void AddRelationshipEvents(MailMessage message) { var factory = new DaoFactory(CoreContext.TenantManager.GetCurrentTenant().TenantId, CRMConstants.DatabaseId); foreach (var contactEntity in message.LinkedCrmEntityIds) { switch (contactEntity.Type) { case CrmContactEntity.EntityTypes.Contact: var crmContact = factory.GetContactDao().GetByID(contactEntity.Id); CRMSecurity.DemandAccessTo(crmContact); break; case CrmContactEntity.EntityTypes.Case: var crmCase = factory.GetCasesDao().GetByID(contactEntity.Id); CRMSecurity.DemandAccessTo(crmCase); break; case CrmContactEntity.EntityTypes.Opportunity: var crmOpportunity = factory.GetDealDao().GetByID(contactEntity.Id); CRMSecurity.DemandAccessTo(crmOpportunity); break; } var fileIds = new List <int>(); var apiHelper = new ApiHelper(HttpContextScheme); foreach (var attachment in message.Attachments.FindAll(attach => !attach.isEmbedded)) { if (attachment.dataStream != null) { attachment.dataStream.Seek(0, SeekOrigin.Begin); var uploadedFileId = apiHelper.UploadToCrm(attachment.dataStream, attachment.fileName, attachment.contentType, contactEntity); if (uploadedFileId > 0) { fileIds.Add(uploadedFileId); } } else { using (var file = AttachmentManager.GetAttachmentStream(attachment)) { var uploadedFileId = apiHelper.UploadToCrm(file.FileStream, file.FileName, attachment.contentType, contactEntity); if (uploadedFileId > 0) { fileIds.Add(uploadedFileId); } } } } apiHelper.AddToCrmHistory(message, contactEntity, fileIds); } }
public void TestInitialize() { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.None, Converters = new JsonConverter[] { new JsonKnownTypeConverter() } }; var container = new UnityContainer().LoadConfiguration(); container.RegisterInstance<ISymmetricCrypto>(new RijndaelSymmetricCrypto("password", "rgb init vector.", 8, 8, 256, "verysalty", 3)); this.AttachmentManager = container.Resolve<AttachmentManager>(); }
/// <summary> /// Uploads an application attachment. /// The result is returned to the client, in JSON format, via the HttpContext Response property. /// </summary> /// <param name="context">The request context.</param> /// <param name="sessionData">The <see cref="SessionData"/> containing the application id.</param> /// <param name="applicationId">The application id.</param> /// <param name="fileManager">A <see cref="AttachmentManager"/> instance.</param> /// <param name="controlName">The file upload control name.</param> private void Upload(HttpContext context, SessionData sessionData, string applicationId, AttachmentManager fileManager, string controlName) { HttpPostedFile postedFile = context.Request.Files[0]; DataAccessResult dataAccessResult = fileManager.SaveAttachment(sessionData, applicationId, controlName, Path.GetFileName(postedFile.FileName), postedFile.InputStream); var output = new { Success = true, dataAccessResult.Id, dataAccessResult.ApplicationId }; context.Response.ContentEncoding = Encoding.UTF8; context.Response.ContentType = InternetMediaType.TextPlain; context.Response.Write(JsonConvert.SerializeObject(output)); context.ApplicationInstance.CompleteRequest(); }
/// <summary> /// Removes an application attachment. /// </summary> /// <param name="context">The request context.</param> /// <param name="sessionData">The <see cref="SessionData"/> containing the application id.</param> /// <param name="applicationId">The application id.</param> /// <param name="fileManager">A <see cref="AttachmentManager"/> instance.</param> /// <param name="controlName">The file upload control name.</param> /// <param name="fileIdentifier">The file identifier.</param> private void Delete(HttpContext context, SessionData sessionData, string applicationId, AttachmentManager fileManager, string controlName, string fileIdentifier) { fileManager.RemoveAttachment(sessionData, applicationId, controlName, fileIdentifier); var output = new { Success = true }; context.Response.ContentEncoding = Encoding.UTF8; context.Response.ContentType = InternetMediaType.ApplicationJson; context.Response.Write(JsonConvert.SerializeObject(output)); context.ApplicationInstance.CompleteRequest(); }
/// <summary> /// Downloads an application attachment. /// The result is returned to the client, in JSON format, via the HttpContext Response property. /// </summary> /// <param name="context">The request context.</param> /// <param name="sessionData">The <see cref="SessionData"/> containing the application id.</param> /// <param name="applicationId">The application id.</param> /// <param name="fileManager">A <see cref="AttachmentManager"/> instance.</param> /// <param name="controlName">The file upload control name.</param> /// <param name="fileIdentifier">The file identifier.</param> private void Download(HttpContext context, SessionData sessionData, string applicationId, AttachmentManager fileManager, string controlName, string fileIdentifier) { QueryResult<byte[]> data = fileManager.GetAttachment(sessionData, applicationId, controlName, fileIdentifier); HttpResponse response = HttpContext.Current.Response; response.BuildBinaryFileResponse(HttpUtility.UrlPathEncode(fileIdentifier), data.Data, Encoding.UTF8, InternetMediaType.ApplicationOctetStream); response.Flush(); context.ApplicationInstance.CompleteRequest(); }
/// <summary> /// Gets an attachment and modifies its metadata(name, title and description). Called when the "Edit attachment metadata" button is pressed. /// Expects the "Create example document" and "Insert unsorted attachment" methods to be run first. /// </summary> private bool EditMetadata() { // Create a new instance of the Tree provider TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Get the example document TreeNode node = tree.SelectSingleNode(CMSContext.CurrentSiteName, "/API-Example", "en-us"); if (node != null) { string where = "AttachmentIsUnsorted = 1"; string orderBy = "AttachmentLastModified DESC"; // Get the document's unsorted attachments with the latest on top DataSet attachments = DocumentHelper.GetAttachments(node, where, orderBy, false, tree); if (!DataHelper.DataSourceIsEmpty(attachments)) { // Create attachment info object from the first DataRow AttachmentInfo attachment = new AttachmentInfo(attachments.Tables[0].Rows[0]); // Edit its metadata attachment.AttachmentName += " - modified"; attachment.AttachmentTitle += "Example title"; attachment.AttachmentDescription += "This is an example of an unsorted attachment."; // Ensure that the attachment can be updated without supplying its binary data. attachment.AllowPartialUpdate = true; // Save the object into database AttachmentManager manager = new AttachmentManager(); manager.SetAttachmentInfo(attachment); return true; } else { apiEditMetadata.ErrorMessage = "No attachments were found."; } } return false; }