public async Task <FileDownloadResponse> DownloadAsync(FileDownloadRequest filedownloadRequest)
        {
            CloudBlobContainer cloudBlobContainer = GetBlobContainerConfig(filedownloadRequest.UserId);
            bool isContainerExists = await cloudBlobContainer.ExistsAsync();

            if (!isContainerExists)
            {
                throw new ResourceNotExistsException($"userId: {filedownloadRequest.FileName} does not exists");
            }
            //Get blob reference
            var  blobReference = cloudBlobContainer.GetBlockBlobReference(filedownloadRequest.FileName);
            bool isExists      = await blobReference.ExistsAsync();

            if (!isExists)
            {
                throw new ResourceNotExistsException($"Provided File {filedownloadRequest.FileName} does not exists");
            }
            var stream = new MemoryStream();
            await blobReference.DownloadToStreamAsync(stream);

            stream.Position = 0;
            FileDownloadResponse response = new FileDownloadResponse {
                ContentType = ContentTypeHelper.GetContentType(blobReference.Name), MemoryStream = stream
            };

            return(response);
        }
Beispiel #2
0
        public void FileDownloadRequestManager(FileDownloadRequest message)
        {
            DownloadClient downloadClient = null;

            foreach (DownloadClient client in clients)
            {
                if (message.SenderID == client.id)
                {
                    downloadClient = client;
                    break;
                }
            }
            if (File.Exists(UploadDirr + message.FileName) && downloadClient != null)
            {
                downloadClient.tcpSocket.Send(serializer.Serialize(new FileHeadderMessage(ClientIP, message.FileName)));
                using (FileStream File = new FileStream(UploadDirr + message.FileName, FileMode.Open))
                {
                    byte[] arr = new byte[SIZE];
                    do
                    {
                        File.Read(arr, 0, SIZE);
                        downloadClient.tcpSocket.Send(serializer.Serialize(new FilePartMessage(ClientIP, arr)));
                    }while (File.CanRead);
                }
                GeneralFunction.CloseSocket(ref downloadClient.tcpSocket);
                GeneralFunction.CloseThread(ref downloadClient.listenTcpThread);
            }
        }
Beispiel #3
0
        public async Task Download(string path)
        {
            IsDownloading = true;
            try
            {
                var data = new FileDownloadRequest()
                {
                    Path = path
                };
                var request = new SocketData(Request, SocketDataAction.FileDownloadRequest, data);
                Client.Session.Send(request);
                var resp = await Client.Session.WaitForNextReceiveAsync(Config.Instance.CommandTimeout, true);

                var file = resp.Get <RemoteFile>();
                TransportFileProgressEventArgs e = new TransportFileProgressEventArgs(Client.Session, file, 0);
                await ReceiveFileAsync(Client.Session, file);
            }
            catch (Exception ex)
            {
                App.Log(LogLevel.Error, "下载文件失败", ex);
                throw;
            }
            finally
            {
                IsDownloading = false;
            }
        }
Beispiel #4
0
        public void FileDownloadRequestManager(FileDownloadRequest message)
        {
            int    HostID       = FindHostID(message.FileName);
            Client HostClient   = null;
            Client SenderClient = null;

            if (HostID != NOTFOUND)
            {
                foreach (Client client in clients)
                {
                    if (client.id == HostID)
                    {
                        HostClient = client;
                    }
                    if (client.id == message.SenderID)
                    {
                        SenderClient = client;
                    }
                }
            }
            if (SenderClient != null && HostClient != null)
            {
                SendMessageClient(new ClientEndpoint(ServerIP, HostClient.ClientEndpoint, message.FileName), SenderClient);
            }
        }
        public void Execute()
        {
            var request = new FileDownloadRequest(_fileHeader.Guid);
            FileDownloadResponse response = _serverConnection.SendFileDownloadRequest(request);

            _eventAggregator.Publish(new FileDownloaded(response.File));
        }
Beispiel #6
0
    public async Task <byte[]> GetAsync(SIEType type, long?finYearID = null, SIEExportOptions exportOptions = null)
    {
        var request = new FileDownloadRequest()
        {
            Endpoint = Endpoint,
            Indices  = new List <string> {
                type.GetStringValue()
            }
        };

        if (finYearID != null)
        {
            request.Parameters.Add("financialyear", finYearID.ToString());
        }

        if (exportOptions != null)
        {
            foreach (var parameter in GetExportParameters(exportOptions))
            {
                request.Parameters.Add(parameter.Key, parameter.Value);
            }
        }

        return(await SendAsync(request).ConfigureAwait(false));
    }
        public void Execute()
        {
            var request = new FileDownloadRequest(_fileHeader.Guid);
            FileDownloadResponse response = _serverConnection.SendFileDownloadRequest(request);

            _eventAggregator.Publish(new FileDownloaded(response.File));
        }
Beispiel #8
0
        public override async Task FileDownload(FileDownloadRequest request,
                                                IServerStreamWriter <DataChunk> responseStream,
                                                ServerCallContext context)
        {
            try
            {
                const int chunkSize = 512 * 1024;
                var       client    = GetMinioClinet();

                var stats = await client.StatObjectAsync(BucketName, request.FileName);

                long offset = 0, remaningSize = stats.Size;
                while (remaningSize > 0)
                {
                    long length = remaningSize > chunkSize ? chunkSize : remaningSize;

                    using var chunk = new MemoryStream();
                    await client.GetObjectAsync(BucketName, request.FileName, offset : offset, length : length,
                                                (inputStream) =>
                    {
                        inputStream.CopyTo(chunk);
                    });

                    var data = ByteString.CopyFrom(chunk.ToArray());
                    await responseStream.WriteAsync(new DataChunk
                    {
                        Data = data,
                        Size = length
                    });

                    offset       += chunkSize + 1;
                    remaningSize -= chunkSize;
                }

                //await client.GetObjectAsync(BucketName, request.FileName, (inputStream) =>
                //{
                //    byte[] bytes = new byte[chunkSize];

                //    int bufferSize;
                //    while (!context.CancellationToken.IsCancellationRequested
                //        && (bufferSize = inputStream.Read(bytes)) > 0)
                //    {
                //        var chunk = ByteString.CopyFrom(bytes, 0, bufferSize);

                //        responseStream.WriteAsync(new DataChunk
                //        {
                //            Data = chunk,
                //            Size = bufferSize
                //        }).GetAwaiter().GetResult();
                //    }
                //});
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Handelt een bestand download af.
        /// </summary>
        /// <param name="request"></param>
        private void HandleFileDownloadRequest(FileDownloadRequest request, Client client)
        {
            string path   = NetworkUtils.GetAssociatedFile(Settings.Default.FileFolder, request.ID);
            bool   exists = File.Exists(path);

            if (exists)
            {
                client.Socket.BeginSendFile(path, SendFileCallback, client);
            }
        }
Beispiel #10
0
        /// <summary>
        /// ファイルダウンロード
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void FileDownloadButton_Click(object sender, RoutedEventArgs e)
        {
            string fileName = System.IO.Path.GetFileName(this.xDownloadFileNameTextBox.Text);

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter   = "txt files (*.txt)|*.txt";
            saveFileDialog.FileName = fileName;

            if (this.xDownloadFileNameTextBox.Text.Length == 0)
            {
                return;
            }

            if (saveFileDialog.ShowDialog() == false)
            {
                return;
            }

            this.FileDownloadButton.IsEnabled = false;
            this.CancelButton.IsEnabled       = true;
            this.xDownloadMessage.Text        = fileName + " ダウンロード中";

            FileDownloadRequest fileDownloadRequest = new FileDownloadRequest();

            fileDownloadRequest.FileName = this.xDownloadFileNameTextBox.Text;

            // gRPC サービスを呼び出す。
            //var response = this.grpcClient.GreeterClient.FileDownload(fileDownloadRequest);
            this._responseFileDownload = this.grpcClient.GreeterClient.FileDownload(fileDownloadRequest);

            try
            {
                using (var fs = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
                {
                    int offset = 0;

                    while (await this._responseFileDownload?.ResponseStream.MoveNext())
                    {
                        var    reply = this._responseFileDownload.ResponseStream.Current;
                        byte[] bin   = reply.Binary.ToByteArray();
                        fs.Write(bin, offset, (int)reply.FileSize);
                    }
                }

                this.xDownloadMessage.Text = "";
            }
            catch (RpcException rpcEx) when(rpcEx.StatusCode == StatusCode.Cancelled)
            {
                this.xDownloadMessage.Text = "ダウンロードをキャンセルしました。";
            }

            this.FileDownloadButton.IsEnabled = true;
            this.CancelButton.IsEnabled       = false;
        }
Beispiel #11
0
        private async Task <byte[]> BaseDownload(Dictionary <string, string> parameters, params string[] indices)
        {
            var request = new FileDownloadRequest()
            {
                Parameters = parameters ?? new Dictionary <string, string>(),
                Resource   = Resource,
                Indices    = indices.ToList()
            };

            return(await SendAsync(request).ConfigureAwait(false));
        }
        /// <summary>
        /// 根据文件ID,下载到本地
        /// </summary>
        public void downloadFile()
        {
            FileDownloadRequest request = new FileDownloadRequest();

            request.file_id   = "94b7ea6be791ca55cb21f76f5a9ebbc3";
            request.file_name = "D://contract//我的签署合同.pdf";

            try
            {
                bool isDownload = client.downloadFile(request);
                Console.WriteLine("文件下载保存本地是否成功:{0}", isDownload);
            }
            catch (Exception e)
            {
                Console.WriteLine("下载文件-异常:" + e.Message);
            }
        }
        protected async Task <byte[]> DoDownloadActionAsync(string documentNumber, Action action)
        {
            if (!action.IsDownloadAction())
            {
                throw new Exception("Invalid action type");
            }

            var request = new FileDownloadRequest()
            {
                Resource = Resource,
                Indices  = new List <string> {
                    documentNumber, action.GetStringValue()
                },
            };

            return(await SendAsync(request).ConfigureAwait(false));
        }
Beispiel #14
0
        public async Task <byte[]> GetAsync(SIEType type, long?finYearID = null)
        {
            var request = new FileDownloadRequest()
            {
                Resource = Resource,
                Indices  = new List <string> {
                    type.GetStringValue()
                }
            };

            if (finYearID != null)
            {
                request.Parameters.Add("financialyear", finYearID.ToString());
            }

            return(await SendAsync(request).ConfigureAwait(false));
        }
Beispiel #15
0
        /// <summary>
        /// ファイルダウンロード(サーバー ストリーミング メソッド)
        /// </summary>
        /// <param name="request"></param>
        /// <param name="responseStream">ストリーミング</param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task FileDownload(FileDownloadRequest request,
                                                IServerStreamWriter <FileDownloadStream> responseStream, ServerCallContext context)
        {
            const int BufferSize = 10240;

            byte[] buffer = new byte[BufferSize];

            string currentDir = Directory.GetCurrentDirectory();

            Console.WriteLine("$CurrentDirectory = {0}", currentDir);


            using (var fs = new FileStream(request.FileName, FileMode.Open, FileAccess.Read))
            {
                int downloadSize = 0;
                int readSize     = 0;

                while ((readSize = fs.Read(buffer, 0, BufferSize)) > 0)
                {
                    Console.WriteLine("ダウンロード リクエスト");

                    //クライアントからキャンセルされたら終了する。
                    if (context.CancellationToken.IsCancellationRequested)
                    {
                        Console.WriteLine("キャンセル リクエスト");
                        break;
                    }

                    FileDownloadStream fileDownloadStream = new FileDownloadStream();
                    fileDownloadStream.Binary   = Google.Protobuf.ByteString.CopyFrom(buffer);
                    fileDownloadStream.FileName = request.FileName;
                    fileDownloadStream.FileSize = readSize;

                    await responseStream.WriteAsync(fileDownloadStream);

                    await Task.Delay(TimeSpan.FromSeconds(1));

                    //await Task.Delay(TimeSpan.FromSeconds(1), context.CancellationToken);

                    downloadSize += readSize;

                    Console.WriteLine("{0}byte ダウンロード", downloadSize);
                }
            }
        }
Beispiel #16
0
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public bool downloadFile(FileDownloadRequest request)
        {
            bool isDownload = false;

            if (request.file_id == null || request.file_id.Trim() == string.Empty || request.file_name == null || request.file_name.Trim() == string.Empty)
            {
                BaseSignResponse baseSignResponse = new BaseSignResponse();
                baseSignResponse.result_code    = "4001";
                baseSignResponse.result_message = "参数校验异常";
                throw new SignServerException("参数校验异常", baseSignResponse, null);
            }
            string downloadUrl = baseUrl + ApiUrlConstant.FileManager.FileDownload + "?fileId=" + request.file_id + "&" + access_token_key + "=" + base.getToken().access_token;

            try
            {
                HttpWebRequest  httpWebRequest  = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(downloadUrl);
                HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
                if (httpWebResponse.ContentLength == -1)
                {
                    throw new SignServerException("文件下载异常", null, null);
                }
                Stream st    = httpWebResponse.GetResponseStream();
                Stream so    = new System.IO.FileStream(request.file_name, System.IO.FileMode.Create);
                byte[] by    = new byte[1024];
                int    osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
                httpWebResponse.Close();
                httpWebRequest.Abort();
                isDownload = true;
            }
            catch (Exception e) {
                throw new SignServerException("文件下载异常", null, e.Message);
            }
            return(isDownload);
        }
Beispiel #17
0
        public async Task <FileDownloadResponse> DownloadAsync(FileDownloadRequest fileDownloadReq)
        {
            var uploads  = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", fileDownloadReq.UserId, "uploads");
            var filePath = Path.Combine(uploads, fileDownloadReq.FileName);

            if (!System.IO.File.Exists(filePath))
            {
                return(null);
            }
            var memory = new MemoryStream();

            using (var stream = new FileStream(filePath, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;

            return(new FileDownloadResponse {
                MemoryStream = memory, ContentType = ContentTypeHelper.GetContentType(filePath)
            });
        }
Beispiel #18
0
        /// <summary>
        /// Bekijkt wat voor soort packet er is gestuurd.
        /// </summary>
        /// <param name="jsonData"></param>
        /// <param name="socket"></param>
        private void HandlePacket(dynamic jsonData, StateObject state)
        {
            string packetType = (string)jsonData.packetType;

            switch (packetType)
            {
            case nameof(FileInfoRequest):
                HandleFileInfoRequest(FileInfoRequest.ToClass(jsonData), state);
                break;

            case nameof(FileDownloadRequest):
                HandleFileDownloadRequest(FileDownloadRequest.ToClass(jsonData), state.Client);
                break;

            case nameof(FileUploadRequest):
                HandleFileUploadRequest(FileUploadRequest.ToClass(jsonData), state.Client);
                break;

            default:
                break;
            }
        }
Beispiel #19
0
        public async Task <IActionResult> Download([FromBody] FileDownloadRequest filedownloadReq)
        {
            var obj = await this._fileservice.DownloadAsync(filedownloadReq);

            return(File(obj.MemoryStream, obj.ContentType, filedownloadReq.FileName));
        }
Beispiel #20
0
 protected async Task <byte[]> SendAsync(FileDownloadRequest fortnoxRequest)
 {
     return(await SendAsync((BaseRequest)fortnoxRequest).ConfigureAwait(false));
 }