private static string GetDownloadFormat(DownloadFormat downloadFormat, string defaultExtension) { switch (downloadFormat) { case DownloadFormat.Original: return(defaultExtension); case DownloadFormat.JPEG: return("jpg"); case DownloadFormat.PNG: return("png"); case DownloadFormat.TIFF: return("tif"); default: throw new SystemException("Unknown download format: " + downloadFormat); } }
public void DownloadGridData(string gridData, DownloadFormat format, string fileName = null) { switch (format) { case DownloadFormat.XML: Utility.ToXml(gridData, fileName); break; case DownloadFormat.XLS: Utility.ToExcel(gridData, fileName); break; case DownloadFormat.CSV: Utility.ToCsv(gridData, fileName); break; default: break; } }
protected void SelectAssetCheckBox_CheckChanged(object sender, EventArgs e) { AllAssetsSelected = false; CheckBox cb = (CheckBox)sender; foreach (RepeaterItem ri in OrderItemsRepeater.Items) { switch (ri.ItemType) { case (ListItemType.Item): case (ListItemType.AlternatingItem): Control control = ri.FindControl(cb.ID); if (control != null && control.UniqueID == cb.UniqueID) { HiddenField OrderItemIdHiddenField = (HiddenField)ri.FindControl("OrderItemIdHiddenField"); DownloadFormatDropDownList DownloadFormatDropDownList1 = (DownloadFormatDropDownList)ri.FindControl("DownloadFormatDropDownList1"); AssetImageSizeDropDownList AssetImageSizeDropDownList1 = (AssetImageSizeDropDownList)ri.FindControl("AssetImageSizeDropDownList1"); int orderItemId = Convert.ToInt32(OrderItemIdHiddenField.Value); int assetImageSizeId = AssetImageSizeDropDownList1.SelectedId; DownloadFormat downloadFormat = DownloadFormatDropDownList1.SelectedDownloadFormat; if (cb.Checked) { SelectedOrderItems.AddUpdate(orderItemId, downloadFormat, assetImageSizeId); } else { SelectedOrderItems.Remove(orderItemId); } } break; } } }
protected void AssetImageSizeDropDownList1_SelectedIndexChanged(object sender, EventArgs e) { AssetImageSizeDropDownList dropdown = (AssetImageSizeDropDownList)sender; foreach (RepeaterItem ri in OrderItemsRepeater.Items) { switch (ri.ItemType) { case (ListItemType.Item): case (ListItemType.AlternatingItem): AssetImageSizeDropDownList AssetImageSizeDropDownList1 = (AssetImageSizeDropDownList)ri.FindControl("AssetImageSizeDropDownList1"); if (AssetImageSizeDropDownList1.UniqueID == dropdown.UniqueID) { DownloadFormatDropDownList DownloadFormatDropDownList1 = (DownloadFormatDropDownList)ri.FindControl("DownloadFormatDropDownList1"); PlaceHolder ImageOptionsPlaceHolder = (PlaceHolder)ri.FindControl("ImageOptionsPlaceHolder"); HiddenField OrderItemIdHiddenField = (HiddenField)ri.FindControl("OrderItemIdHiddenField"); HiddenField AssetIdHiddenField = (HiddenField)ri.FindControl("AssetIdHiddenField"); FileSizeMessageLabel ImageFileSizeMessageLabel = (FileSizeMessageLabel)ri.FindControl("ImageFileSizeMessageLabel"); int orderItemId = Convert.ToInt32(OrderItemIdHiddenField.Value); int assetImageSizeId = (ImageOptionsPlaceHolder.Visible) ? AssetImageSizeDropDownList1.SelectedId : 0; int assetId = Convert.ToInt32(AssetIdHiddenField.Value); DownloadFormat downloadFormat = DownloadFormatDropDownList1.SelectedDownloadFormat; SelectedOrderItems.AddUpdate(orderItemId, downloadFormat, assetImageSizeId); Asset asset = Asset.Get(assetId); string filename = AssetImageManager.GetResizedAssetImage(asset, assetImageSizeId, downloadFormat, true); long filesize = FileUtils.GetFileSize(filename); ImageFileSizeMessageLabel.SetFileSize(filesize); } break; } } }
/// <summary> /// Download protected application from project /// </summary> /// <param name="downloadKey"></param> /// <param name="format"></param> /// <returns></returns> internal MemoryStream DownloadApplication(string downloadKey, DownloadFormat format = DownloadFormat.Default) { try { if (string.IsNullOrEmpty(downloadKey)) { Parent.CustomLogger?.LogCritical("The download key is necessary when obtaining a file."); throw new ArgumentNullException(nameof(downloadKey)); } Parent.CustomLogger?.LogDebug("Initiating the request to download an application."); using var stream = new MemoryStream(); var request = new RestRequest("/app/download") { ResponseWriter = responseStream => { using (responseStream) { responseStream.CopyTo(stream); } } } .AddQueryParameter("key", downloadKey) .AddQueryParameter("format", format == DownloadFormat.Zip ? "zip" : "default"); var _ = _client.DownloadData(request); Parent.CustomLogger?.LogDebug("The application has been downloaded successfully."); return(stream); } catch (Exception e) { Parent.CustomLogger?.LogCritical("An error occurred while downloading the file."); throw new ArgumentNullException($"An error occurred while downloading the file: {e.Message}"); } }
public Stream DownloadApplicationAsStream(ProtectedApplicationDto protectedApplication, DownloadFormat format) => DownloadApplication(protectedApplication.DownloadKey, format);
public byte[] DownloadApplicationAsArray(string downloadKey, DownloadFormat format) => DownloadApplication(downloadKey, format).ToArray();
public async Task <Stream> DownloadApplicationAsStreamAsync(string downloadKey, DownloadFormat format) => await DownloadApplicationAsync(downloadKey, format);
public byte[] DownloadApplicationAsArray(ProtectedApplicationDto protectedApplication, DownloadFormat format) => DownloadApplication(protectedApplication.DownloadKey, format).ToArray();
public async Task <Stream> DownloadApplicationAsStreamAsync(ProtectedApplicationDto protectedApplication, DownloadFormat format) => await DownloadApplicationAsync(protectedApplication.DownloadKey, format);
public async Task <byte[]> DownloadApplicationAsArrayAsync(string downloadKey, DownloadFormat format) => (await DownloadApplicationAsync(downloadKey, format)).ToArray();
private string UpdateLink(DownloadFormat downloadLink) { var result = _downloadFormat.Put(downloadLink); return(result); }
/// <summary> /// 简单格式下载,只下载<paramref name="ds"/>的数据行 /// </summary> /// <param name="name">用户下载框中显示的保存文件名,例如:SN_08082600012.xls</param> /// <param name="prefix">内部生成的下载文件前缀,例如:SN</param> /// <param name="format">数据列的格式描述信息</param> /// <param name="ds"></param> /// <returns>返回下载文件的链接地址(使用download.aspx)</returns> public static string DownloadXls(string name, string prefix, IList <DownloadFormat> format, DataSet ds) { string fileName = prefix + DateTime.Now.ToString("_yyMMdd_HHmmss") + ".xls"; string filePath = DownloadFolder + fileName; ExcelApp excelapp = null; ExcelWorkbook excelBook = null; ExcelWorksheet excelSheet = null; try { excelapp = new ExcelApp(); excelapp.DisplayAlerts = false; excelBook = excelapp.NewWorkBook(); excelSheet = excelBook.Worksheets(1); int rowIndex = 1; for (int i = 0; i < format.Count; i++) { excelSheet.Cells(rowIndex, i + 1).Value = format[i].Title; } ExcelRange rg = excelSheet.Range(rowIndex, rowIndex, 1, format.Count); rg.SelectRange(); rg.Font.Bold = true; rg.HorizontalAlignment = 3; rg.Interior.SetColor(221, 221, 221); rowIndex++; #region 写文件 foreach (DataRow row in ds.Tables[0].Rows) { for (int i = 0; i < format.Count; i++) { DownloadFormat ft = format[i]; if (ft.ColumnIndex == null) { continue; } for (int j = 0; j < ft.ColumnIndex.Length; j++) { SetCellValue(excelSheet.Cells(rowIndex, i + 1), j, ft.Type, row, ft.ColumnIndex[j]); } } rowIndex++; } #endregion ExcelRange excelRange = excelSheet.Cells(); excelRange.SelectRange(); excelRange.AutoFit(); excelRange.Font.Size = 10; excelBook.SaveAs(filePath); } catch (Exception er) { throw er; } finally { if (excelSheet != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet.COMObject); } if (excelBook != null) { excelBook.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelBook.COMObject); } if (excelapp != null) { excelapp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelapp.COMObject); } } return("/download.aspx?type=p&name=" + Microsoft.JScript.GlobalObject.escape(name) + "&path=" + Microsoft.JScript.GlobalObject.escape(filePath)); }
public static string GetResizedAssetImage(Asset asset, int assetImageSizeId, DownloadFormat downloadFormat, bool create) { //--------------------------------------------------------------------------------------------------------- // Get asset file info //--------------------------------------------------------------------------------------------------------- AssetFileInfo fileInfo = new AssetFileInfo(asset); //--------------------------------------------------------------------------------------------------------- // Ensure asset file exists //--------------------------------------------------------------------------------------------------------- if (!fileInfo.FileExists) { return(string.Empty); } //--------------------------------------------------------------------------------------------------------- // No options specified //--------------------------------------------------------------------------------------------------------- if (assetImageSizeId == 0 && downloadFormat == DownloadFormat.Original) { return(fileInfo.FilePath); } //--------------------------------------------------------------------------------------------------------- // Only images can be resized //--------------------------------------------------------------------------------------------------------- if (!AssetTypeChecker.IsImage(asset.FileExtension)) { return(fileInfo.FilePath); } //--------------------------------------------------------------------------------------------------------- // PDFs are an exception as they are classified as images but cant be resized //--------------------------------------------------------------------------------------------------------- if (StringUtils.GetFileExtension(asset.Filename) == "pdf") { return(fileInfo.FilePath); } //--------------------------------------------------------------------------------------------------------- // Get the requested image size //--------------------------------------------------------------------------------------------------------- AssetImageSize ais = AssetImageSizeCache.Instance.GetById(assetImageSizeId); //--------------------------------------------------------------------------------------------------------- // Construct the path to the output filename //--------------------------------------------------------------------------------------------------------- string suffix = (StringUtils.IsBlank(ais.FileSuffix)) ? "original" : ais.FileSuffix; string reference = Path.GetFileNameWithoutExtension(asset.Filename) + "_" + suffix; string extension = GetDownloadFormat(downloadFormat, asset.FileExtension); string cacheFolder = VirtualPathUtility.AppendTrailingSlash(Path.Combine(Settings.CachedAssetFilesFolder, asset.AssetId.ToString())); string outputFilename = Path.Combine(cacheFolder, reference) + "." + extension; if (File.Exists(outputFilename)) { return(outputFilename); } if (!create) { return(string.Empty); } //--------------------------------------------------------------------------------------------------------- // Create the cache folder if it doesn't exist //--------------------------------------------------------------------------------------------------------- if (!Directory.Exists(cacheFolder)) { Directory.CreateDirectory(cacheFolder); m_Logger.DebugFormat("Created cache folder: {0}", cacheFolder); } //------------------------------------------------------------------------------------------------ // Now we've verified that we need to do some work. //------------------------------------------------------------------------------------------------ string tempPath = Path.Combine(Settings.TempFolder, asset.AssetId + "_" + Guid.NewGuid() + Path.GetExtension(fileInfo.FilePath)); //--------------------------------------------------------------------------------------------------------- // Create resized image //--------------------------------------------------------------------------------------------------------- if (ais.Width > 0 && ais.Height > 0) { ImageProcessingJob job = new ImageProcessingJob { SourceFilePath = fileInfo.FilePath, TargetFilePath = tempPath, Width = ais.Width, Height = ais.Height }; job.Go(); m_Logger.DebugFormat("Generated resized image for asset id: {0}, assetImageSize: {1}, height: {2}, width: {3} at: {4}", asset.AssetId, ais.Description, ais.Height, ais.Width, job.TargetFilePath); } //--------------------------------------------------------------------------------------------------------- // Ensure we've got our image //--------------------------------------------------------------------------------------------------------- if (!File.Exists(tempPath)) { File.Copy(fileInfo.FilePath, tempPath); m_Logger.DebugFormat("Original asset copied to: {0}", tempPath); } //--------------------------------------------------------------------------------------------------------- // Now convert the DPI to the value requested //--------------------------------------------------------------------------------------------------------- if (ais.DotsPerInch > 0) { ImageUtils.ChangeDPI(tempPath, ais.DotsPerInch); m_Logger.DebugFormat("Changed DPI of file: {0} to: {1}", tempPath, ais.DotsPerInch); } //------------------------------------------------------------------------------------------------ // Do download format conversion //------------------------------------------------------------------------------------------------ if (StringUtils.GetFileExtension(tempPath) != StringUtils.GetFileExtension(outputFilename)) { ImageUtils.ConvertFormat(tempPath, outputFilename); } //------------------------------------------------------------------------------------------------ // Ensure we've got the output file now //------------------------------------------------------------------------------------------------ if (!File.Exists(outputFilename)) { File.Move(tempPath, outputFilename); } //--------------------------------------------------------------------------------------------------------- // All done, return path //--------------------------------------------------------------------------------------------------------- return(outputFilename); }
public ReportDefinition CreateReportDefinition(ReportDefinition reportDefinition, string reportName, ReportDefinitionDateRangeType dateRageType, Selector selector, ClientSelector[] clients, DownloadFormat downloadFormat = DownloadFormat.GZIPPED_CSV) { reportDefinition.reportName = reportName; reportDefinition.dateRangeType = dateRageType; reportDefinition.reportType = ReportDefinitionReportType.AD_PERFORMANCE_REPORT; reportDefinition.selector = selector; reportDefinition.downloadFormat = downloadFormat; reportDefinition.downloadFormatSpecified = true; reportDefinition.clientSelectors = clients.ToArray(); return(reportDefinition); }
public override void ProcessRequest() { if (!SessionInfo.Current.User.IsNull) { //if valid user then process request //using normal AssetFileHandler base.ProcessRequest(); } else { // Get querystring values int assetId = GetIdFromFilename(); int assetImageSizeId = WebUtils.GetIntRequestParam("assetImageSizeId", 0); DownloadFormat downloadFormat = GeneralUtils.ParseEnum(WebUtils.GetRequestParam("AssetImageFormat"), DownloadFormat.Original); bool original = (WebUtils.GetIntRequestParam("original", 0) == 1); int lightboxSentId = WebUtils.GetIntRequestParam("lsid", 0); int senderId = WebUtils.GetIntRequestParam("suid", 0); string ticks = WebUtils.GetRequestParam("dst", string.Empty); // Ensure asset id is specified if (assetId == 0 || lightboxSentId == 0) { InvalidRequest(); return; } // Get the lightbox LightboxSent lightboxSent = LightboxSent.Get(lightboxSentId); //check that it's a valid lightboxsent object if (lightboxSent.IsNull) { InvalidRequest(); return; } // Check posted data - ensure that the sender id and ticks match (ie. to ensure user is not messing with the querystring) if (!lightboxSent.SenderId.Equals(senderId) || ticks.Length < 6 || !lightboxSent.DateSent.Ticks.ToString().Substring(0, 6).Equals(ticks.Substring(0, 6))) { InvalidRequest(); return; } // Make sure sender is a super user if (lightboxSent.Sender.UserRole != UserRole.SuperAdministrator) { InvalidRequest(); return; } //verify that lightbox has download links enabled if (!lightboxSent.DownloadLinks.GetValueOrDefault(false)) { InvalidRequest(); return; } //check that asset exists in the lightbox being sent LightboxAssetFinder finder = new LightboxAssetFinder { LightboxId = lightboxSent.LightboxId, AssetId = assetId }; LightboxAsset lightboxAsset = LightboxAsset.FindOne(finder); if (lightboxAsset.IsNull) { InvalidRequest(); return; } // Get the asset file info AssetFileInfo info = new AssetFileInfo(lightboxAsset.Asset); // Ensure file exists if (!info.FileExists) { InvalidRequest(); return; } // Asset file path string path = info.FilePath; // Always update the audit history for external downloads AuditLogManager.LogAssetAction(assetId, lightboxSent.Sender, AuditAssetAction.DownloadedAssetFile); AuditLogManager.LogUserAction(lightboxSent.Sender, AuditUserAction.DownloadAssetFromContactSheet, string.Format("Downloaded asset {0} via contact sheet, sent by: {1} download by: {2}", assetId, lightboxSent.Sender.FullName, lightboxSent.RecipientEmail)); DownloadAsset(lightboxAsset.Asset, path, original, downloadFormat, assetImageSizeId); } }
/// <summary> /// 模板格式+简单格式下载,先用<paramref name="items"/>中每个key, value替换模板中的标签(标签名称为key),再下载<paramref name="ds"/>的数据行 /// </summary> /// <param name="name">用户下载框中显示的保存文件名,例如:SN_08082600012.xls</param> /// <param name="prefix">内部生成的下载文件前缀,例如:SN</param> /// <param name="template">模板文件的物理路径(不是IIS虚拟路径)</param> /// <param name="items">标签的键、值对</param> /// <param name="rowIndex">数据行的开始位置(1开始的索引,即Excel中的行号)</param> /// <param name="ds"></param> /// <returns>返回下载文件的链接地址(使用download.aspx)</returns> public static string DownloadXls(string name, string prefix, string template, IDictionary <string, string> items, int rowIndex, IList <DownloadFormat> format, DataSet ds) { ExcelApp excelApp = null; ExcelWorkbook workbook = null; ExcelWorksheet sheet = null; string fileName = prefix + DateTime.Now.ToString("_yyMMdd_HHmmss") + ".xls"; string filePath = DownloadFolder + fileName; try { excelApp = new ExcelApp(); workbook = excelApp.Open(template, 0); workbook.SaveAs(filePath); sheet = workbook.Worksheets(1); //标签替换 ExcelRange range = sheet.Cells(); if (items != null) { foreach (KeyValuePair <string, string> kv in items) { range.Replace(kv.Key, kv.Value, false); } } //数据行 int index = rowIndex; foreach (DataRow row in ds.Tables[0].Rows) { for (int i = 0; i < format.Count; i++) { DownloadFormat ft = format[i]; if (ft.ColumnIndex == null) { continue; } for (int j = 0; j < ft.ColumnIndex.Length; j++) { SetCellValue(sheet.Cells(index, i + 1), j, ft.Type, row, ft.ColumnIndex[j]); } } index++; } workbook.Save(); } catch (Exception er) { throw er; } finally { if (sheet != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet.COMObject); } if (workbook != null) { workbook.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook.COMObject); } if (excelApp != null) { excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp.COMObject); } } return("/download.aspx?type=p&name=" + Microsoft.JScript.GlobalObject.escape(name) + "&path=" + Microsoft.JScript.GlobalObject.escape(filePath)); }
protected void CopyDownloadSettingsToAllButton_Click(object sender, EventArgs e) { bool found = false; Button btn = (Button)sender; int sourceAssetId = 0; DownloadFormat downloadFormat = DownloadFormat.Original; int assetImageSizeId = 0; foreach (RepeaterItem ri in OrderItemsRepeater.Items) { if (!GeneralUtils.ValueIsInList(ri.ItemType, ListItemType.Item, ListItemType.AlternatingItem)) { continue; } Button CopyDownloadSettingsToAllButton = (Button)ri.FindControl("CopyDownloadSettingsToAllButton"); if (CopyDownloadSettingsToAllButton.UniqueID != btn.UniqueID) { continue; } HiddenField AssetIdHiddenField = (HiddenField)ri.FindControl("AssetIdHiddenField"); DownloadFormatDropDownList DownloadFormatDropDownList1 = (DownloadFormatDropDownList)ri.FindControl("DownloadFormatDropDownList1"); AssetImageSizeDropDownList AssetImageSizeDropDownList1 = (AssetImageSizeDropDownList)ri.FindControl("AssetImageSizeDropDownList1"); sourceAssetId = Convert.ToInt32(AssetIdHiddenField.Value); downloadFormat = DownloadFormatDropDownList1.SelectedDownloadFormat; assetImageSizeId = AssetImageSizeDropDownList1.SelectedId; found = true; break; } if (!found) { return; } AssetFinder finder = new AssetFinder(); finder.AssetIdList.Add(0); finder.AssetIdList.AddRange(CurrentOrder.OrderItemList.Select(o => o.AssetId)); List <Asset> assetList = Asset.FindMany(finder); Asset sourceAsset = assetList.Where(a => a.AssetId == sourceAssetId).FirstOrDefault() ?? Asset.Empty; Debug.Assert(!sourceAsset.IsNull); foreach (OrderItem oi in CurrentOrder.OrderItemList) { // Get the asset for the order item Asset asset = assetList.Where(a => a.AssetId == oi.AssetId).FirstOrDefault() ?? Asset.Empty; // Non-images do not have download options so ignore them if (!AssetTypeChecker.IsImage(asset.FileExtension)) { continue; } // Update the selection SelectedOrderItems.AddUpdate(oi.OrderItemId.GetValueOrDefault(), downloadFormat, assetImageSizeId); } // Rebind the list Bind(CurrentPage); FeedbackLabel1.SetSuccessMessage("Download options updated successfully"); }
public Stream DownloadApplicationAsStream(string downloadKey, DownloadFormat format) => DownloadApplication(downloadKey, format);
public async Task <byte[]> DownloadApplicationAsArrayAsync(ProtectedApplicationDto protectedApplication, DownloadFormat format) => (await DownloadApplicationAsync(protectedApplication.DownloadKey, format)).ToArray();
public override void ProcessRequest() { // Get querystring values int assetId = GetIdFromFilename(); int assetImageSizeId = WebUtils.GetIntRequestParam("assetImageSizeId", 0); DownloadFormat downloadFormat = GeneralUtils.ParseEnum(WebUtils.GetRequestParam("AssetImageFormat"), DownloadFormat.Original); bool logDownload = (WebUtils.GetIntRequestParam("logDownload", 1) == 1); bool original = (WebUtils.GetIntRequestParam("original", 0) == 1); // Downloads should ALWAYS be logged from normal users, regardless of the querystring if (SessionInfo.Current.User.UserRole == UserRole.Normal) { logDownload = true; } // Ensure asset id is specified if (assetId == 0) { throw new HttpException(500, "Invalid asset id"); } // Get asset Asset asset = Asset.Get(assetId); // Make sure asset is valid if (asset.IsNull) { Context.Response.Redirect("~/Errors/AssetMissing.htm"); return; } // Check if user can download asset bool isAuthorised = EntitySecurityManager.CanUserDownloadAsset(SessionInfo.Current.User, asset); if (!isAuthorised) { throw new SecurityException("Access denied"); } // Get the asset file info AssetFileInfo info = new AssetFileInfo(asset); // Ensure file exists if (!info.FileExists) { Context.Response.Redirect("~/Errors/AssetFileMissing.htm"); return; } // Asset file path string path = info.FilePath; // Update the audit history if (logDownload) { AuditLogManager.LogAssetAction(assetId, SessionInfo.Current.User, AuditAssetAction.DownloadedAssetFile); AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.DownloadAsset, string.Format("Downloaded asset with AssetId: {0}", assetId)); } DownloadAsset(asset, path, original, downloadFormat, assetImageSizeId); }
public SelectedOrderItem(int orderItemId, DownloadFormat downloadFormat, int assetImageSizeId) : this(orderItemId) { DownloadFormat = downloadFormat; AssetImageSizeId = assetImageSizeId; }
private string SaveLinkDownload(DownloadFormat downloadFormat) { var formatId = _downloadFormat.Post(downloadFormat); return(formatId); }
public string Post(DownloadFormat formats) => _dbContext.DownloadFormats.Add(formats).Entity.Id;