public IActionResult GetLogo(string solnid) { solnid = solnid.SplitOnLast(CharConstants.DOT).First() + StaticFileConstants.DOTPNG; DownloadFileResponse dfs = null; ActionResult resp = new EmptyResult(); try { HttpContext.Response.Headers[HeaderNames.CacheControl] = "private, max-age=2628000"; dfs = this.FileClient.Get <DownloadFileResponse> (new DownloadLogoExtRequest { SolnId = solnid.Split(CharConstants.DOT)[0], }); if (dfs.StreamWrapper != null) { dfs.StreamWrapper.Memorystream.Position = 0; resp = new FileStreamResult(dfs.StreamWrapper.Memorystream, GetMime(solnid)); } } catch (Exception e) { Console.WriteLine("Exception: " + e.Message.ToString()); } return(resp); }
public DownloadFileResponse Get(DownloadLogoExtRequest request) { DownloadFileResponse dfs = new DownloadFileResponse(); MemoryStream ms = null; byte[] fb = new byte[0]; string sFilePath = string.Format("../StaticFiles/{0}/logo/{1}", request.SolnId, request.SolnId); try { if (!System.IO.File.Exists(sFilePath)) { string qry_refId = @"SELECT filestore_sid , V.filedb_con_id FROM eb_files_ref_variations V INNER JOIN eb_solutions S ON V.eb_files_ref_id = S.logorefid WHERE S.isolution_id = :solid;" ; DbParameter[] parameters = { this.InfraConnectionFactory.DataDB.GetNewParameter("solid", EbDbTypes.String, request.SolnId), }; var dt = this.InfraConnectionFactory.DataDB.DoQuery(qry_refId, parameters); if (dt.Rows.Count == 0) { throw new Exception("filestore_sid not found - FileRefId:" + request.ImageInfo.FileRefId + " Quality:" + request.ImageInfo.ImageQuality); } else { Console.WriteLine(" Calling FilesDB.DownloadFileById :(InfraconId =" + Convert.ToInt32(dt.Rows[0][1]) + " ,filestoreid =" + dt.Rows[0][0].ToString()); fb = this.InfraConnectionFactory.FilesDB.DownloadFileById(dt.Rows[0][0].ToString(), EbFileCategory.SolLogo, Convert.ToInt32(dt.Rows[0][1])); if (fb != null) { EbFile.Bytea_ToFile(fb, sFilePath); } } } if (File.Exists(sFilePath)) { ms = new MemoryStream(File.ReadAllBytes(sFilePath)); dfs.StreamWrapper = new MemorystreamWrapper(ms); } else { throw new Exception("File Not Found"); } } catch (Exception ee) { Log.Info("Exception:" + ee.ToString()); } return(dfs); }
public IActionResult GetImageQualById(string filename, string qlty) { DownloadFileResponse dfs = null; HttpContext.Response.Headers[HeaderNames.CacheControl] = "private, max-age=31536000"; ActionResult resp = new EmptyResult(); DownloadImageByIdRequest dfq = new DownloadImageByIdRequest(); try { dfq.ImageInfo = new ImageMeta { FileRefId = Convert.ToInt32(filename.SplitOnLast(CharConstants.DOT).First()), FileCategory = EbFileCategory.Images, ImageQuality = Enum.Parse <ImageQuality>(qlty) }; Console.WriteLine("Image Info: " + dfq.ImageInfo.ToJson()); this.FileClient.Timeout = new TimeSpan(0, 5, 0); dfs = this.FileClient.Get <DownloadFileResponse>(dfq); if (dfs.StreamWrapper != null) { Console.WriteLine("Image Size: " + dfs.StreamWrapper.Memorystream.Length); dfs.StreamWrapper.Memorystream.Position = 0; resp = new FileStreamResult(dfs.StreamWrapper.Memorystream, GetMime(filename)); } } catch (Exception e) { Console.WriteLine("Exception: " + e.StackTrace.ToString() + e.Message.ToString()); } return(resp); }
public IActionResult GetFileByRefId(string filename) { DownloadFileResponse dfs = null; HttpContext.Response.Headers[HeaderNames.CacheControl] = "private, max-age=31536000"; ActionResult resp = new EmptyResult(); try { dfs = this.FileClient.Get <DownloadFileResponse> (new DownloadFileByRefIdRequest { FileDetails = new FileMeta { FileRefId = Convert.ToInt32(filename.SplitOnLast(CharConstants.DOT).First()), FileCategory = EbFileCategory.File } }); if (dfs.StreamWrapper != null) { dfs.StreamWrapper.Memorystream.Position = 0; resp = new FileStreamResult(dfs.StreamWrapper.Memorystream, GetMime(filename)); } } catch (Exception e) { Console.WriteLine("Exception: " + e.StackTrace.ToString() + e.Message.ToString()); } return(resp); }
public IActionResult GetInfraImages(string refid, string quality) { DownloadFileResponse dfs = null; ActionResult resp = new EmptyResult(); try { this.FileClient.Timeout = new TimeSpan(0, 5, 0); dfs = this.FileClient.Get <DownloadFileResponse> (new DownloadInfraImgRequest { ImageInfo = new ImageMeta { FileRefId = Convert.ToInt32(refid.SplitOnLast(CharConstants.DOT).First()), FileCategory = EbFileCategory.Images, ImageQuality = Enum.Parse <ImageQuality>(quality) }, RefId = refid.Split(CharConstants.DOT)[0] }); if (dfs.StreamWrapper != null) { dfs.StreamWrapper.Memorystream.Position = 0; resp = new FileStreamResult(dfs.StreamWrapper.Memorystream, GetMime(refid)); } } catch (Exception e) { Console.WriteLine("Exception: " + e.Message.ToString()); } return(resp); }
public void Print(string FileName) { using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient()) { try { DownloadFileResponse response = svc.DownloadFile(new DownloadFileRequest() { TargetContainer = "", TargetFileName = FileName }); if (response.Code == "0000") { if (response.ContentType == "application/pdf") { String fileName = response.FileName.Substring(response.FileName.IndexOf(@"\")); if (String.IsNullOrEmpty(fileName)) { ViewDocument(response.FileByteStream, Convert.ToInt64(response.Length), response.ContentType); } else { ViewDocument(response.FileByteStream, Convert.ToInt64(response.Length), response.ContentType, fileName); } } } } catch (Exception ex) { Response.Write(ex.Message); } } }
public IActionResult GetDP(string userid) { string uid = userid.Split(CharConstants.DOT).First(); string fname = userid.SplitOnLast(CharConstants.DOT).First() + StaticFileConstants.DOTPNG; DownloadFileResponse dfs = null; ActionResult resp = new EmptyResult(); try { dfs = this.FileClient.Get <DownloadFileResponse> (new DownloadDpRequest { ImageInfo = new ImageMeta { FileName = uid, FileType = StaticFileConstants.PNG, FileCategory = EbFileCategory.Dp } }); if (dfs.StreamWrapper != null) { dfs.StreamWrapper.Memorystream.Position = 0; HttpContext.Response.Headers[HeaderNames.CacheControl] = "private, max-age=2628000"; resp = new FileStreamResult(dfs.StreamWrapper.Memorystream, GetMime(fname)); } } catch (Exception e) { Console.WriteLine("Exception: " + e.Message.ToString()); resp = new EmptyResult(); } return(resp); }
public byte[] DownloadFile(string url) { DownloadFileRequest request = new DownloadFileRequest(url); DownloadFileResponse response = this.DownloadFile(request); return(response.DownloadFileResult); }
public void ProcessRequest(HttpContext context) { // send the file in 10k chunks -- should help with mem consumption Stream stream = null; byte[] buffer = new Byte[10000]; // Length of the file: int length; // Total bytes to read: long dataToRead; try { CaseService svc = new CaseService(); // Retrieve the attachment DownloadFileResponse response = svc.RetrieveAttachment(context.Request["f"].ToString(), context.Request["u"].ToString()); AttachmentContract file = response.Attachment; stream = new MemoryStream(response.FileBytes); // Total bytes to read: dataToRead = Convert.ToInt64(file.FileSize); context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.FileName); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (context.Response.IsClientConnected) { // Read the data in buffer. length = stream.Read(buffer, 0, 10000); // Write the data to the current output stream. context.Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. context.Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception) { // Trap the error, if any. throw; } finally { if (stream != null) { //Close the file. stream.Close(); } } }
protected void btnDownload_Click(object sender, EventArgs e) { using (svc = new FileService.FileTransferServiceClient()) { DownloadFileResponse response = new DownloadFileResponse(); DTO.AttachFile attachFile = ((List <DTO.AttachFile>)Session["AttachFiles"]).FirstOrDefault(); String container = ""; String fileName = ""; response = svc.DownloadFile(new DownloadFileRequest() { TargetContainer = container, TargetFileName = attachFile.TargetFullName }); Page.Response.Clear(); Page.Response.BufferOutput = true; Page.Response.ContentType = response.ContentType; // Append header //Page.Response.AppendHeader("Content-Disposition", "attachment; filename=" + response.FileName); // Write the file to the Response const int bufferLength = 10000; byte[] buffer = new Byte[bufferLength]; int length = 0; Stream download = null; try { download = response.FileByteStream; // GetFile(fileName); do { if (Page.Response.IsClientConnected) { length = download.Read(buffer, 0, bufferLength); Page.Response.OutputStream.Write(buffer, 0, length); buffer = new Byte[bufferLength]; } else { length = -1; } }while (length > 0); Page.Response.Flush(); Page.Response.End(); } finally { if (download != null) { download.Close(); } } } }
public DownloadFileResponse Get(DownloadDpRequest request) { DownloadFileResponse dfs = new DownloadFileResponse(); MemoryStream ms = null; byte[] fb = new byte[0]; string sFilePath = string.Format("../StaticFiles/{0}/dp/{1}", request.SolnId, request.ImageInfo.FileName); try { if (!System.IO.File.Exists(sFilePath)) { string qry_refId = this.EbConnectionFactory.DataDB.EB_DOWNLOAD_DP; //AND V.imagequality_id = 150 DbParameter[] parameters = { this.EbConnectionFactory.DataDB.GetNewParameter("userid", EbDbTypes.Int32, Convert.ToInt32(request.ImageInfo.FileName)), }; var dt = this.EbConnectionFactory.DataDB.DoQuery(qry_refId, parameters); if (dt.Rows.Count == 0) { throw new Exception("filestore_sid not found - FileRefId:" + request.ImageInfo.FileRefId + " Quality:" + request.ImageInfo.ImageQuality); } else { request.ImageInfo.FileStoreId = dt.Rows[0][0].ToString(); request.ImageInfo.InfraConID = Convert.ToInt32(dt.Rows[0][1]); fb = this.EbConnectionFactory.FilesDB.DownloadFileById(request.ImageInfo.FileStoreId, EbFileCategory.Dp, request.ImageInfo.InfraConID); if (fb != null) { EbFile.Bytea_ToFile(fb, sFilePath); } } } if (File.Exists(sFilePath)) { ms = new MemoryStream(File.ReadAllBytes(sFilePath)); dfs.StreamWrapper = new MemorystreamWrapper(ms); } else { throw new Exception("File Not Found"); } } catch (Exception ee) { Log.Info("Exception:" + ee.ToString()); } return(dfs); }
private DownloadFileResponse DownloadFile(DownloadFileRequest request) { CFInvokeInfo info = new CFInvokeInfo(); info.Action = "http://tempuri.org/IUpdater/DownloadFile"; info.RequestIsWrapped = true; info.ReplyAction = "http://tempuri.org/IUpdater/DownloadFileResponse"; info.ResponseIsWrapped = true; DownloadFileResponse retVal = base.Invoke <DownloadFileRequest, DownloadFileResponse>(info, request); return(retVal); }
public XDocument DownloadIso20022(string fileReference, string softwareId) { DownloadFileRequest downloadFileRequest = new DownloadFileRequest(); downloadFileRequest.ApplicationRequest = GetDownloadFileApplicationRequest(fileReference, softwareId); downloadFileRequest.RequestHeader = GetRequestHeader(); DownloadFileResponse downloadFileResponse = _client.downloadFile(downloadFileRequest); VerifyHeadersAfterResponse(downloadFileRequest.RequestHeader, downloadFileResponse.ResponseHeader); XDocument file = DecryptAndUncompressDownloadFileResponse(downloadFileResponse.ApplicationResponse); return(file); }
protected void Page_Load(object sender, EventArgs e) { using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient()) { try { String targetImage = Request.QueryString["targetImage"].ToString(); DownloadFileResponse response = svc.DownloadFile(new DownloadFileRequest() { TargetContainer = "", TargetFileName = CryptoBase64.Decryption(targetImage) }); if (response.Code == "0000") { Int32 index = response.FileName.LastIndexOf(@"\"); String filename = response.FileName.Substring((index > 0) ? index + 1 : 0); if (response.ContentType == Utils.ContentTypeHelper.MimeType(".pdf") || response.ContentType == Utils.ContentTypeHelper.MimeType(".doc") || response.ContentType == Utils.ContentTypeHelper.MimeType(".docx") || response.ContentType == Utils.ContentTypeHelper.MimeType(".xls") || response.ContentType == Utils.ContentTypeHelper.MimeType(".xlsx")) { ShowDocument(response.FileByteStream, Convert.ToInt64(response.Length), response.ContentType, filename); } else if (response.ContentType == "application/octet-stream" && (filename.Substring(filename.LastIndexOf('.')) == ".docx" || filename.Substring(filename.LastIndexOf('.')) == ".doc" || filename.Substring(filename.LastIndexOf('.')) == ".xls" || filename.Substring(filename.LastIndexOf('.')) == ".xlsx" )) { ShowDocument(response.FileByteStream, Convert.ToInt64(response.Length), Utils.ContentTypeHelper.MimeType(filename.Substring(filename.LastIndexOf('.'))), filename); } else { ShowImage(response.FileByteStream, Convert.ToInt64(response.Length), response.ContentType, filename); } } } catch (Exception ex) { Response.Write(ex.Message); } } }
public DownloadFileResponse DownloadFile(DownloadFileRequest request) { DownloadFileResponse response = new DownloadFileResponse(); try { response = FileManagerService.RemoteFileCommand(request).Action(); } catch (Exception ex) { response.Code = "0001"; response.Message = ex.Message; } return(response); }
public override async Task DownloadFile(DownloadFileRequest request, IServerStreamWriter <DownloadFileResponse> responseStream, ServerCallContext context) { string filePath = Path.Combine(_filePath, string.Format("{0}_{1}_{2}", request.Username, request.Id, request.Filename)); // Example of exception if (File.Exists(filePath) == false) { _logger.LogError($"File '{filePath}' not found."); Metadata metadata = new Metadata() { { "Filename", filePath } }; throw new RpcException(new Status(StatusCode.NotFound, "Image file not found."), metadata, "More details for the exception..."); } DownloadFileResponse downloadResponse = new DownloadFileResponse(); downloadResponse.Info = new FileInfo(); downloadResponse.Status = TransferStatus.Success; byte[] image; try { image = File.ReadAllBytes(filePath); } catch (Exception) { _logger.LogError($"Exception while reading image file '{filePath}'."); throw new RpcException(Status.DefaultCancelled, "Exception while reading image file."); } int fileOffset = 0; byte[] fileChunk = new byte[FileChunkSize]; while (fileOffset < image.Length) { int length = Math.Min(FileChunkSize, image.Length - fileOffset); Buffer.BlockCopy(image, fileOffset, fileChunk, 0, length); fileOffset += length; ByteString byteString = ByteString.CopyFrom(fileChunk); downloadResponse.ChunkData = byteString; await responseStream.WriteAsync(downloadResponse).ConfigureAwait(false); } }
protected void Page_Load(object sender, EventArgs e) { using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient()) { DownloadFileResponse response = new DownloadFileResponse(); String targetImage = Request.QueryString["targetImage"].ToString(); response = svc.DownloadFile(new DownloadFileRequest() { TargetContainer = "", TargetFileName = CryptoBase64.Decryption(targetImage) }); if (response.Code == "0000") { ShowImage(response.FileByteStream, Convert.ToInt64(response.Length), response.ContentType); } } }
public DownloadFileResponse Action() { ConnectNetDrive(); DownloadFileResponse response = new DownloadFileResponse(); try { _targetPath = _targetPath.Replace('/', '\\'); System.IO.FileInfo fileInfo = new FileInfo(_targetPath); // check if exists if (!fileInfo.Exists) { throw new FileNotFoundException(Resources.errorDeleteFile_FileNotFound, _fileName); } response.HashCode = FileObject.GetHashSHA1(_targetPath); // open stream System.IO.FileStream stream = new FileStream(_targetPath, FileMode.Open, FileAccess.Read); // ดึง Content Type คืนไปฝั่ง Web ที Consume Service response.ContentType = ContentTypeHelper.MimeType(fileInfo.Name); response.FileName = _fileName; response.Length = fileInfo.Length; response.FileByteStream = stream; response.Code = "0000"; response.Message = Resources.infoDeleteContainer_001; } catch (Exception ex) { response.Code = "0001"; response.Message = ex.Message; } finally { DisConnectNetDrive(); } return(response); }
public virtual void GetFile(string pathRemoteFile, ref Stream fileStrem) { //DTO.RegistrationAttatchFile attachFile = new DTO.RegistrationAttatchFile(); //if (_attachFiles.Where(a => a.ATTACH_FILE_TYPE == type).Count() <= 0) // throw new RegisterationException("ไม่พบเอกสารแนบตามประเภทที่ต้องการ !!!"); //attachFile = _attachFiles.Where(a => a.ATTACH_FILE_TYPE == type).FirstOrDefault(); using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient()) { DownloadFileResponse response = svc.DownloadFile(new DownloadFileRequest() { TargetContainer = "", TargetFileName = pathRemoteFile }); if (response.Code != "0000") { throw new IOException(response.Message); } fileStrem = response.FileByteStream; } }
/// <summary> /// Gets bz-info header values. /// </summary> /// <param name="headers">The http request header.</param> /// <param name="response">The download file response.</param> public static void GetBzInfo(this HttpResponseHeaders headers, DownloadFileResponse response) { foreach (var header in headers.Select((KeyValuePair <string, IEnumerable <string> > x) => new { key = x.Key.ToLower(), value = x.Value.First() })) { if (header.key == "x-bz-file-id") { response.FileId = header.value; } if (header.key == "x-bz-file-name") { response.FileName = header.value.ToUrlDecode(); } if (header.key == "x-bz-content-sha1") { response.ContentSha1 = header.value; } if (header.key.StartsWith("x-bz-info-")) { response.FileInfo[header.key.Substring("x-bz-info-".Length)] = header.value.ToUrlDecode(); } } }
public IActionResult GetLocFiles(string filename) { filename = filename.SplitOnLast(CharConstants.DOT).First() + StaticFileConstants.DOTPNG; DownloadFileResponse dfs = null; ActionResult resp = new EmptyResult(); try { if (filename.StartsWith(StaticFileConstants.LOC)) { HttpContext.Response.Headers[HeaderNames.CacheControl] = "private, max-age=31536000"; dfs = this.FileClient.Get <DownloadFileResponse> (new DownloadFileRequest { FileDetails = new FileMeta { FileName = filename, FileType = StaticFileConstants.PNG, FileCategory = EbFileCategory.LocationFile } }); } if (dfs.StreamWrapper != null) { dfs.StreamWrapper.Memorystream.Position = 0; resp = new FileStreamResult(dfs.StreamWrapper.Memorystream, GetMime(filename)); } } catch (Exception e) { Console.WriteLine("Exception: " + e.Message.ToString()); resp = new EmptyResult(); } return(resp); }
/// <summary> /// Saves a <see cref="IFormFile"/> at the specified <paramref name="folderPath"/> location. /// </summary> /// <param name="file">The file to be saved.</param> /// <param name="folderPath">The location at which the file should be saved.</param> /// <returns>A <see cref="DownloadFileResponse"/> containing the path to the file, and the download status.</returns> public async Task <DownloadFileResponse> SaveFile(IFormFile file, string folderPath) { var response = new DownloadFileResponse { Status = DownloadFileStatus.InvalidFile }; if (file.Length > 0) { var fullPath = Path.Combine(folderPath, file.FileName); if (File.Exists(fullPath)) { _logger.LogInformation($"File already exists at path {fullPath}."); response.Status = DownloadFileStatus.AlreadyExists; return(response); } _logger.LogInformation($"File {file.FileName} is being prepared to be saved at path {fullPath}."); using (var stream = new FileStream(fullPath, FileMode.CreateNew)) { await file.CopyToAsync(stream); } _logger.LogInformation($"File saved to {fullPath}."); response.Status = DownloadFileStatus.Downloaded; response.FilePath = fullPath; return(response); } return(response); }
public ResultDownloadFileRequest(DownloadFileResponse response) : base(response) { _Response = response; }
/// <summary> /// Download File จาก File Server /// </summary> /// <param name="httpResponse">Current Response from Page</param> /// <param name="folderContrainner">Folder ที่เก็บไฟล์</param> /// <param name="fileName">ชื่อไฟล์</param> public void DownloadFile(System.Web.HttpResponse httpResponse, string folderContrainner, string fileName) { //ระบุตำแหน่งไฟล์และที่เก็บบน File Server //FileService.DownloadRequest requestData = new FileService.DownloadRequest(); //FileService.RemoteFileInfo fileInfo = new FileService.RemoteFileInfo(); //string resMsg = svc.DownloadFile(ref fileName, folderContrainner, out fileInfo.Length, out fileInfo.FileByteStream); DownloadFileResponse response = new DownloadFileResponse(); response = svc.DownloadFile(new DownloadFileRequest() { TargetContainer = folderContrainner, TargetFileName = fileName }); Stream fileStream = response.FileByteStream; httpResponse.Clear(); httpResponse.BufferOutput = true; // Set Response.ContentType httpResponse.ContentType = response.ContentType; //GetContentType(fileExtension); // Append header httpResponse.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); // Write the file to the Response const int bufferLength = 10000; byte[] buffer = new Byte[bufferLength]; int length = 0; Stream download = null; try { download = response.FileByteStream; // GetFile(fileName); do { if (httpResponse.IsClientConnected) { length = download.Read(buffer, 0, bufferLength); httpResponse.OutputStream.Write(buffer, 0, length); buffer = new Byte[bufferLength]; } else { length = -1; } }while (length > 0); httpResponse.Flush(); httpResponse.End(); } finally { if (download != null) { download.Close(); } } }
public DownloadFileResponse Get(DownloadFileByIdRequest request) { Console.WriteLine("In DownloadFileByIdRequest"); byte[] fb = new byte[0]; string sFilePath = string.Format("../StaticFiles/{0}/{1}", request.SolnId, request.FileDetails.FileRefId); MemoryStream ms = null; DownloadFileResponse dfs = new DownloadFileResponse(); try { if (!System.IO.File.Exists(sFilePath)) { EbFileCategory category = request.FileDetails.FileCategory; string Qry = this.EbConnectionFactory.DataDB.EB_DOWNLOAD_FILE_BY_ID; DbParameter[] parameters = { this.EbConnectionFactory.DataDB.GetNewParameter("fileref", EbDbTypes.Int32, request.FileDetails.FileRefId), }; EbDataTable t = this.EbConnectionFactory.DataDB.DoQuery(Qry, parameters); if (t.Rows.Count > 0) { request.FileDetails.FileStoreId = t.Rows[0]["filestore_sid"].ToString(); request.FileDetails.InfraConID = Convert.ToInt32(t.Rows[0]["filedb_con_id"]); } else { throw new Exception("File Not Found in Database , fileref = " + request.FileDetails.FileRefId); } fb = this.EbConnectionFactory.FilesDB.DownloadFileById(request.FileDetails.FileStoreId, category, request.FileDetails.InfraConID); if (fb != null) { EbFile.Bytea_ToFile(fb, sFilePath); } } if (File.Exists(sFilePath)) { ms = new MemoryStream(File.ReadAllBytes(sFilePath)); dfs.StreamWrapper = new MemorystreamWrapper(ms); dfs.FileDetails = new FileMeta { FileName = request.FileDetails.FileName, FileType = request.FileDetails.FileType, Length = request.FileDetails.Length, FileStoreId = request.FileDetails.FileStoreId, UploadDateTime = request.FileDetails.UploadDateTime, MetaDataDictionary = (request.FileDetails.MetaDataDictionary != null) ? request.FileDetails.MetaDataDictionary : new Dictionary <String, List <string> >() { }, }; } else { throw new Exception("File Not Found"); } } catch (FormatException e) { Console.WriteLine("ObjectId not in Correct Format: " + request.FileDetails.FileName); Console.WriteLine("Exception: " + e.ToString()); } catch (Exception e) { Log.Info("Exception:" + e.ToString()); } return(dfs); }
public static void HandleDownloadFileResponse(Client client, DownloadFileResponse packet) { string downloadPath = Path.Combine(Application.StartupPath, "Clients\\" + client.EndPoint.Address.ToString()); if (!Directory.Exists(downloadPath)) { Directory.CreateDirectory(downloadPath); } downloadPath = Path.Combine(downloadPath, packet.Filename); bool Continue = true; if (File.Exists(downloadPath)) { if (MessageBox.Show(string.Format("The file '{0}' already exists!\nOverwrite it?", packet.Filename), "Overwrite Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.Yes) { Continue = false; } } int index = 0; try { client.Value.FrmFm.Invoke((MethodInvoker) delegate { foreach (ListViewItem lvi in client.Value.FrmFm.lstTransfers.Items) { if (packet.ID.ToString() == lvi.SubItems[0].Text) { index = lvi.Index; break; } } }); } catch { } if (Continue) { new Thread(new ThreadStart(() => { try { client.Value.FrmFm.Invoke((MethodInvoker) delegate { client.Value.FrmFm.lstTransfers.Items[index].SubItems[1].Text = "Saving..."; }); using (FileStream stream = new FileStream(downloadPath, FileMode.Create)) { stream.Write(packet.FileByte, 0, packet.FileByte.Length); } client.Value.FrmFm.Invoke((MethodInvoker) delegate { client.Value.FrmFm.lstTransfers.Items[index].SubItems[1].Text = "Completed"; client.Value.FrmFm.lstTransfers.Items[index].ImageIndex = 1; }); } catch { } })).Start(); } else { try { client.Value.FrmFm.Invoke((MethodInvoker) delegate { client.Value.FrmFm.lstTransfers.Items[index].SubItems[1].Text = "Canceled"; client.Value.FrmFm.lstTransfers.Items[index].ImageIndex = 0; }); } catch { } } }
public DownloadFileResponse Get(DownloadImageByIdRequest request) { Console.WriteLine("In DownloadImageByIdRequest"); byte[] fb = new byte[0]; string sFilePath = string.Format("../StaticFiles/{0}/{1}/{2}", request.SolnId, request.ImageInfo.ImageQuality, request.ImageInfo.FileRefId); MemoryStream ms = null; DownloadFileResponse dfs = new DownloadFileResponse(); Console.WriteLine("Download Image Info: " + request.ImageInfo.ToJson()); try { if (!System.IO.File.Exists(sFilePath)) { Console.WriteLine("Image Not in Cache: " + sFilePath); EbFileCategory category = request.ImageInfo.FileCategory; string Qry = this.EbConnectionFactory.DataDB.EB_DOWNLOAD_IMAGE_BY_ID; DbParameter[] parameters = { this.EbConnectionFactory.DataDB.GetNewParameter("fileref", EbDbTypes.Int32, request.ImageInfo.FileRefId) }; EbDataTable t = this.EbConnectionFactory.DataDB.DoQuery(Qry, parameters); if (t.Rows.Count == 0) { throw new Exception("filestore_sid not found - FileRefId:" + request.ImageInfo.FileRefId + " Quality:" + request.ImageInfo.ImageQuality); } Dictionary <int, ImageMeta> sidAll = new Dictionary <int, ImageMeta>(); for (int i = 0; i < t.Rows.Count; i++) { sidAll.Add(Convert.ToInt32(t.Rows[i][0]), new ImageMeta() { FileStoreId = t.Rows[i][1].ToString(), InfraConID = Convert.ToInt32(t.Rows[i][2]) }); } if (sidAll.ContainsKey((int)request.ImageInfo.ImageQuality)) { request.ImageInfo.FileStoreId = sidAll[(int)request.ImageInfo.ImageQuality].FileStoreId; request.ImageInfo.InfraConID = sidAll[(int)request.ImageInfo.ImageQuality].InfraConID; } else { request.ImageInfo.FileStoreId = sidAll[(int)ImageQuality.original].FileStoreId; request.ImageInfo.InfraConID = sidAll[(int)ImageQuality.original].InfraConID; } fb = this.EbConnectionFactory.FilesDB.DownloadFileById(request.ImageInfo.FileStoreId, category, request.ImageInfo.InfraConID); if (fb != null) { EbFile.Bytea_ToFile(fb, sFilePath); } else { Console.WriteLine("No File Found in : FileStoreId: " + request.ImageInfo.FileStoreId); } } if (File.Exists(sFilePath)) { ms = new MemoryStream(File.ReadAllBytes(sFilePath)); dfs.StreamWrapper = new MemorystreamWrapper(ms); dfs.FileDetails = new FileMeta { FileName = request.ImageInfo.FileName, FileType = request.ImageInfo.FileType, Length = request.ImageInfo.Length, FileStoreId = request.ImageInfo.FileStoreId, UploadDateTime = request.ImageInfo.UploadDateTime, MetaDataDictionary = (request.ImageInfo.MetaDataDictionary != null) ? request.ImageInfo.MetaDataDictionary : new Dictionary <String, List <string> >() { }, }; } else { throw new Exception("File Not Found"); } } catch (FormatException e) { Console.WriteLine("ObjectId not in Correct Format: " + request.ImageInfo.FileName); Console.WriteLine("Exception: " + e.ToString()); } catch (Exception e) { Log.Info("Exception:" + e.ToString()); } return(dfs); }
public DownloadFileResponse Get(DownloadBotExtImgRequest request) { DownloadFileResponse dfs = new DownloadFileResponse(); MemoryStream ms = null; byte[] fb = new byte[0]; string sFilePath = string.Format("../StaticFiles/botExt/{0}", request.RefId); EbConnectionFactory ebConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); try { if (!System.IO.File.Exists(sFilePath)) { string qry_refId = @"SELECT B.imagequality_id, B.filestore_sid, B.filedb_con_id FROM eb_files_ref A, eb_files_ref_variations B WHERE A.id=B.eb_files_ref_id AND A.id=:fileref ORDER BY B.imagequality_id;"; DbParameter[] parameters = { ebConnectionFactory.DataDB.GetNewParameter("fileref", EbDbTypes.Int32, Convert.ToInt32(request.RefId)), }; EbDataTable t = ebConnectionFactory.DataDB.DoQuery(qry_refId, parameters); if (t.Rows.Count == 0) { throw new Exception("filestore_sid not found - FileRefId:" + request.ImageInfo.FileRefId + " Quality:" + request.ImageInfo.ImageQuality); } Dictionary <int, ImageMeta> sidAll = new Dictionary <int, ImageMeta>(); for (int i = 0; i < t.Rows.Count; i++) { if (!sidAll.ContainsKey(Convert.ToInt32(t.Rows[i][0]))) { sidAll.Add(Convert.ToInt32(t.Rows[i][0]), new ImageMeta() { FileStoreId = t.Rows[i][1].ToString(), InfraConID = Convert.ToInt32(t.Rows[i][2]) }); } } if (sidAll.ContainsKey((int)request.ImageInfo.ImageQuality)) { request.ImageInfo.FileStoreId = sidAll[(int)request.ImageInfo.ImageQuality].FileStoreId; request.ImageInfo.InfraConID = sidAll[(int)request.ImageInfo.ImageQuality].InfraConID; } else { request.ImageInfo.FileStoreId = sidAll[(int)ImageQuality.original].FileStoreId; request.ImageInfo.InfraConID = sidAll[(int)ImageQuality.original].InfraConID; } fb = ebConnectionFactory.FilesDB.DownloadFileById(request.ImageInfo.FileStoreId, request.ImageInfo.FileCategory, request.ImageInfo.InfraConID); if (fb != null) { EbFile.Bytea_ToFile(fb, sFilePath); } } if (File.Exists(sFilePath)) { ms = new MemoryStream(File.ReadAllBytes(sFilePath)); dfs.StreamWrapper = new MemorystreamWrapper(ms); dfs.FileDetails = new FileMeta { FileName = request.ImageInfo.FileName, FileType = request.ImageInfo.FileType, Length = request.ImageInfo.Length, FileStoreId = request.ImageInfo.FileStoreId, UploadDateTime = request.ImageInfo.UploadDateTime, MetaDataDictionary = (request.ImageInfo.MetaDataDictionary != null) ? request.ImageInfo.MetaDataDictionary : new Dictionary <String, List <string> >() { }, }; } else { throw new Exception("File Not Found"); } } catch (FormatException e) { Console.WriteLine("ObjectId not in Correct Format: " + request.ImageInfo.FileName); Console.WriteLine("Exception: " + e.ToString()); } catch (Exception e) { Log.Info("Exception:" + e.ToString()); } return(dfs); }
public static void HandleDownloadFileResponse(Client client, DownloadFileResponse packet) { string downloadPath = Path.Combine(Application.StartupPath, "Clients\\" + client.EndPoint.Address.ToString()); if (!Directory.Exists(downloadPath)) { Directory.CreateDirectory(downloadPath); } downloadPath = Path.Combine(downloadPath, packet.Filename); bool Continue = true; if (packet.CurrentBlock == 0 && File.Exists(downloadPath)) { if ( MessageBox.Show(string.Format("The file '{0}' already exists!\nOverwrite it?", packet.Filename), "Overwrite Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { Continue = false; } } if (client.Value.FrmFm == null) { new Packets.ServerPackets.DownloadFileCanceled(packet.ID).Execute(client); MessageBox.Show("Please keep the File Manager open.\n\nWarning: Download aborted", "Download aborted", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } int index = 0; try { client.Value.FrmFm.Invoke((MethodInvoker) delegate { foreach (ListViewItem lvi in client.Value.FrmFm.lstTransfers.Items) { if (packet.ID.ToString() == lvi.SubItems[0].Text) { index = lvi.Index; break; } } }); } catch { return; } if (Continue) { if (!string.IsNullOrEmpty(packet.CustomMessage)) { client.Value.FrmFm.Invoke((MethodInvoker) delegate { client.Value.FrmFm.lstTransfers.Items[index].SubItems[1].Text = packet.CustomMessage; client.Value.FrmFm.lstTransfers.Items[index].ImageIndex = 0; }); return; } FileSplit destFile = new FileSplit(downloadPath); if (!destFile.AppendBlock(packet.Block, packet.CurrentBlock)) { client.Value.FrmFm.Invoke((MethodInvoker) delegate { client.Value.FrmFm.lstTransfers.Items[index].SubItems[1].Text = destFile.LastError; client.Value.FrmFm.lstTransfers.Items[index].ImageIndex = 0; }); return; } decimal progress = Math.Round((decimal)((double)(packet.CurrentBlock + 1) / (double)packet.MaxBlocks * 100.0), 2); client.Value.FrmFm.Invoke( (MethodInvoker) delegate { client.Value.FrmFm.lstTransfers.Items[index].SubItems[1].Text = string.Format("Downloading...({0}%)", progress); }); if ((packet.CurrentBlock + 1) == packet.MaxBlocks) { client.Value.FrmFm.Invoke((MethodInvoker) delegate { client.Value.FrmFm.lstTransfers.Items[index].SubItems[1].Text = "Completed"; client.Value.FrmFm.lstTransfers.Items[index].ImageIndex = 1; }); } } else { client.Value.FrmFm.Invoke((MethodInvoker) delegate { client.Value.FrmFm.lstTransfers.Items[index].SubItems[1].Text = "Canceled"; client.Value.FrmFm.lstTransfers.Items[index].ImageIndex = 0; }); } }
protected void gv_SelectedIndexChanged(object sender, EventArgs e) { DTO.AttachFile attachFile = ((List <DTO.AttachFile>)Session["AttachFiles"]).FirstOrDefault(); String container = ""; String fileName = gv.Rows[gv.SelectedIndex].Cells[7].Text; using (svc = new FileService.FileTransferServiceClient()) { DownloadFileResponse response = new DownloadFileResponse(); response = svc.DownloadFile(new DownloadFileRequest() { TargetContainer = container, TargetFileName = IAS.Utils.CryptoBase64.Decryption(fileName) }); if (response.Code == "0000") { ShowImage(response.FileByteStream, Convert.ToInt64(response.Length)); } } // Page.Response.Clear(); // Page.Response.BufferOutput = true; // Page.Response.ContentType = response.ContentType; // // Append header // Page.Response.AppendHeader("Content-Disposition", "attachment; filename=" + response.FileName); // // Write the file to the Response // //const int bufferLength = Convert.ToInt32(response.Length); // byte[] buffer = new Byte[Convert.ToInt32(response.Length)]; // //int length = 0; // //Stream download = null; // //response.FileByteStream.Write(buffer, 0, Convert.ToInt32(response.Length)); // //myImage.ImageUrl = Convert.ToBase64String(buffer).ToString(); // using (var memoryStream = new MemoryStream()) // { // response.FileByteStream.CopyTo(memoryStream); // buffer = memoryStream.ToArray(); // } // myImage.ImageUrl = Convert.ToBase64String(buffer).ToString(); // //try // //{ // // download = response.FileByteStream; // etFile(fileName); // // do // // { // // if (Page.Response.IsClientConnected) // // { // // length = download.Read(buffer, 0, bufferLength); // // Page.Response.OutputStream.Write(buffer, 0, length); // // myImage.ImageUrl = Convert.ToBase64String(buffer).ToString(); // // buffer = new Byte[bufferLength]; // // } // // else // // { // // length = -1; // // } // // } // // while (length > 0); // // Page.Response.Flush(); // // Page.Response.End(); // //} // //finally // //{ // // if (download != null) // // download.Close(); // //} //} }