Пример #1
0
        static int _m_CopyToAsync(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                System.IO.Stream gen_to_be_invoked = (System.IO.Stream)translator.FastGetCSObj(L, 1);


                int gen_param_count = LuaAPI.lua_gettop(L);

                if (gen_param_count == 2 && translator.Assignable <System.IO.Stream>(L, 2))
                {
                    System.IO.Stream _destination = (System.IO.Stream)translator.GetObject(L, 2, typeof(System.IO.Stream));

                    System.Threading.Tasks.Task gen_ret = gen_to_be_invoked.CopyToAsync(
                        _destination);
                    translator.Push(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 3 && translator.Assignable <System.IO.Stream>(L, 2) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3))
                {
                    System.IO.Stream _destination = (System.IO.Stream)translator.GetObject(L, 2, typeof(System.IO.Stream));
                    int _bufferSize = LuaAPI.xlua_tointeger(L, 3);

                    System.Threading.Tasks.Task gen_ret = gen_to_be_invoked.CopyToAsync(
                        _destination,
                        _bufferSize);
                    translator.Push(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 4 && translator.Assignable <System.IO.Stream>(L, 2) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3) && translator.Assignable <System.Threading.CancellationToken>(L, 4))
                {
                    System.IO.Stream _destination = (System.IO.Stream)translator.GetObject(L, 2, typeof(System.IO.Stream));
                    int _bufferSize = LuaAPI.xlua_tointeger(L, 3);
                    System.Threading.CancellationToken _cancellationToken; translator.Get(L, 4, out _cancellationToken);

                    System.Threading.Tasks.Task gen_ret = gen_to_be_invoked.CopyToAsync(
                        _destination,
                        _bufferSize,
                        _cancellationToken);
                    translator.Push(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }

            return(LuaAPI.luaL_error(L, "invalid arguments to System.IO.Stream.CopyToAsync!"));
        }
Пример #2
0
        public static async System.Threading.Tasks.Task DownloadAsync(this System.Net.Http.HttpClient client
                                                                      , string requestUri
                                                                      , System.IO.Stream destination
                                                                      , System.IProgress <float> progress = null
                                                                      , System.Threading.CancellationToken cancellationToken = default)
        {
            // Get the http headers first to examine the content length
            using (System.Net.Http.HttpResponseMessage response = await client.GetAsync(
                       requestUri,
                       System.Net.Http.HttpCompletionOption.ResponseHeadersRead)
                   )
            {
                long?contentLength = response.Content.Headers.ContentLength;

                using (System.IO.Stream download = await response.Content.ReadAsStreamAsync())
                {
                    // Ignore progress reporting when no progress reporter was
                    // passed or when the content length is unknown
                    if (progress == null || !contentLength.HasValue)
                    {
                        await download.CopyToAsync(destination);

                        return;
                    }

                    // Convert absolute progress (bytes downloaded) into relative progress (0% - 100%)
                    System.Progress <long> relativeProgress = new System.Progress <long>(
                        delegate(long totalBytes)
                    {
                        if (contentLength.Value == 0)
                        {
                            progress.Report(99.99999f);
                            return;
                        }

                        float reportedValue = (float)totalBytes * 100.0f / contentLength.Value;
                        if (reportedValue == 100.0f)
                        {
                            reportedValue = 99.99999f;
                        }

                        progress.Report(reportedValue);
                    }
                        );

                    // Use extension method to report progress while downloading
                    await download.CopyToAsync(destination, 81920, relativeProgress, cancellationToken);

                    progress.Report(100.0f);
                } // End Using download
            }     // End Using response
        }         // End Task DownloadAsync
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public async Task <String> GetCertifyFile()
        {
            String result = String.Empty;

            String id = "85c9f279-4245-4aaa-b394-af826b021d0c";

            // Request Data
            sms.didimo.es.GetCertifyFileRequest request = new sms.didimo.es.GetCertifyFileRequest {
                UserName = this.userName,
                Password = this.password,
                Id       = id
            };

            // Execute
            System.IO.Stream certifyStream = await this.api.GetCertifyFileAsync(request);

            String fileName      = String.Format("message_{0}.pdf", id);
            String fileDirectory = @"C:\SMSCertifies\sms.didimo\";

            using (System.IO.FileStream fs = new System.IO.FileStream(System.IO.Path.Combine(fileDirectory, fileName), System.IO.FileMode.OpenOrCreate))
            {
                await certifyStream.CopyToAsync(fs);
            }

            result = String.Format("File saved on {0}", System.IO.Path.Combine(fileDirectory, fileName));

            return(result);
        }
        private static Task CopyToAsync(Stream stream, Stream destination)
        {
#if NET45PLUS
            return(stream.CopyToAsync(destination));
#else
            return(StreamExtensions.CopyToAsync(stream, destination));
#endif
        }
Пример #5
0
        public static async Task <string> SaveStreamAsync(string itemId, string filename, System.IO.Stream sourceStream, string dataFilesPath)
        {
            IFolder localStorage = FileSystem.Current.LocalStorage;

            string targetPath = await GetLocalFilePathAsync(itemId, filename, dataFilesPath);

            var targetFile = await localStorage.CreateFileAsync(targetPath, CreationCollisionOption.ReplaceExisting);

            using (var targetStream = await targetFile.OpenAsync(FileAccess.ReadAndWrite)) {
                await sourceStream.CopyToAsync(targetStream);
            }

            return(targetPath);
        }
        public async Task <FileSystemResult <IFile> > CreateAssetAsync(string name, Stream readstream, CancellationToken token, IProgress <FileProgress> progress, Dictionary <string, object> properties)
        {
            string ext = Path.GetExtension(name);

            if ((ext != "png") && (ext != "jpg") && (ext != "jpeg") && (ext != "gif"))
            {
                return(new FileSystemResult <IFile>("Google Drive only supports 'thumbnail' asset, acceptable formats are, jpg, png and gif"));
            }
            string mime;

            switch (ext)
            {
            case "png":
                mime = "image/png";
                break;

            case "jpeg":
            case "jpg":
                mime = "image/jpeg";
                break;

            default:
                mime = "image/gif";
                break;
            }
            MemoryStream ms = new MemoryStream();
            await readstream.CopyToAsync(ms, 16384, token);

            MemoryFile file = new MemoryFile(FullName + ":thumbnail", "thumbnail", mime, ms.ToArray());
            File       f    = new File {
                Thumbnail = new File.ThumbnailData {
                    MimeType = mime, Image = Convert.ToBase64String(ms.ToArray())
                }
            };
            string url = GooglePatch.FormatRest(Id);
            FileSystemResult <string> ex = await FS.OAuth.CreateMetadataStream <string>(url, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(f)), "application/json", new HttpMethod("PATCH"));

            if (!ex.IsOk)
            {
                return(new FileSystemResult <IFile>(ex.Error));
            }
            Assets.Clear();
            Assets.Add(file);
            return(new FileSystemResult <IFile>(file));
        }
Пример #7
0
 /// <summary>
 ///		Descarga un archivo de forma asíncrona
 /// </summary>
 public async Task DownloadFileAsync(string uri, string fileName)
 {
     try
     {
         using (HttpClient client = GetHttpClient())
             using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri))
                 using (System.IO.Stream responseStream = await(await client.SendAsync(request)).Content.ReadAsStreamAsync())
                     using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create,
                                                                                       System.IO.FileAccess.Write,
                                                                                       System.IO.FileShare.None, 2000, true))
                     {
                         await responseStream.CopyToAsync(fileStream);
                     }
     }
     catch (Exception exception)
     {
         System.Diagnostics.Debug.WriteLine($"Excepción cuando se descarga el archivo {exception.Message}");
     }
 }
Пример #8
0
        public static async Task downloadInterflowFile_async(String apiKey, String path, String file, String outFile)
        {
            /*
             *   intput:
             *           apiKey - api key for interflow
             *           path   - directory in interflow to download newest file from
             *           file   - name of the file to fetch
             *           outFile- the output directory to write the file to.
             *
             *    description:
             *           Gets the contents of the specified file in an interflow directory
             *
             *    output:
             *           Task (async)
             */

            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
                client.Timeout = TimeSpan.FromMinutes(30);

                var queryString = HttpUtility.ParseQueryString(string.Empty);
                queryString["directoryPath"] = path;
                var uri = "https://interflow.azure-api.net/api/downloads/file?fileName=" + file + "&" + queryString;

                using (var request = new HttpRequestMessage(HttpMethod.Get, uri))
                {
                    using
                    (
                        System.IO.Stream contentStream = await(await client.SendAsync(request)).Content.ReadAsStreamAsync(),
                        stream = new System.IO.FileStream(outFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None, 4096, true)
                    )
                    {
                        await contentStream.CopyToAsync(stream);
                    }
                }
                client.Dispose();
            }
        }
        public async Task SaveHostedContentBlob(ChatMessage message, ChatMessageHostedContent hostedContent, IChatMessageHostedContentsCollectionRequestBuilder detailRequestBuilder)
        {
            var messageHostedcontentRequest = detailRequestBuilder[hostedContent.Id].Content.Request();

            System.IO.Stream messageHostedcontentValue = null;
            for (int i = 1; i <= MgGraphRequester.MaxRetry; i++)
            {
                try
                {
                    _Logger.LogTrace($"GraphURI({i}): {messageHostedcontentRequest.RequestUrl}");
                    messageHostedcontentValue = await messageHostedcontentRequest.GetAsync();

                    break;
                }
                catch (ServiceException mgsex)
                {
                    if (mgsex.StatusCode == System.Net.HttpStatusCode.BadRequest)//Special case. hosted content will not return a 404 if not available :(
                    {
                        return;
                    }
                    else
                    {
                        if (!await MgGraphRequester.ShouldContinue(mgsex, i))
                        {
                            return;
                        }
                    }
                }
            }


            var blobFile = GetBackupMessageHostedContentBlob(_Options.Path, _TeamId, _ChannelId, message, hostedContent);

            using System.IO.FileStream fs = System.IO.File.Create(blobFile);
            _Logger.LogTrace($"BlobFile: {blobFile}");
            await messageHostedcontentValue.CopyToAsync(fs);
        }
        public static async Task HandleRoute(HttpContext context)
        {
            DefaultTusConfiguration config = context.RequestServices.GetRequiredService <DefaultTusConfiguration>();

            if (!(config.Store is ITusReadableStore store))
            {
                return;
            }

            string   fileId = (string)context.Request.RouteValues["fileId"];
            ITusFile file   = await store.GetFileAsync(fileId, context.RequestAborted);

            if (file == null)
            {
                context.Response.StatusCode = 404;
                await context.Response.WriteAsync($"File with id {fileId} was not found.", context.RequestAborted);

                return;
            }

            System.IO.Stream fileStream = await file.GetContentAsync(context.RequestAborted);

            Dictionary <string, Metadata> metadata = await file.GetMetadataAsync(context.RequestAborted);

            context.Response.ContentType   = GetContentTypeOrDefault(metadata);
            context.Response.ContentLength = fileStream.Length;

            if (metadata.TryGetValue("name", out var nameMeta))
            {
                context.Response.Headers.Add("Content-Disposition",
                                             new[] { $"attachment; filename=\"{nameMeta.GetString(Encoding.UTF8)}\"" });
            }

            using (fileStream)
                await fileStream.CopyToAsync(context.Response.Body, 81920, context.RequestAborted);
        }
Пример #11
0
        public async Task <string> DownloadAndCacheImage(int index, string url)
        {
            var outputFile = CreateTempFile();

            var httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));

            httpReq.Method = "GET";
            using (var response = await httpReq.GetResponseAsync())
            {
                using (System.IO.Stream s = response.GetResponseStream())
                {
                    using (System.IO.FileStream fileStream = System.IO.File.OpenWrite(outputFile.AbsolutePath))
                    {
                        await s.CopyToAsync(fileStream);

                        await s.FlushAsync();

                        await fileStream.FlushAsync();
                    }
                }
            }

            return(outputFile.AbsolutePath);
        }
Пример #12
0
        public async System.Threading.Tasks.Task <SoftmakeAll.SDK.OperationResult <System.Byte[]> > DownloadAsync(System.String BucketName, System.Collections.Generic.Dictionary <System.String, System.String> StorageFileNames)
        {
            SoftmakeAll.SDK.CloudStorage.AWS.Environment.Validate();

            SoftmakeAll.SDK.OperationResult <System.Byte[]> OperationResult = new SoftmakeAll.SDK.OperationResult <System.Byte[]>();

            if ((System.String.IsNullOrWhiteSpace(BucketName)) || (StorageFileNames == null) || (StorageFileNames.Count == 0))
            {
                OperationResult.Message = "The BucketName and StorageFileName cannot be null.";
                return(OperationResult);
            }

            try
            {
                if (StorageFileNames.Count == 1)
                {
                    Amazon.S3.Model.GetObjectRequest GetObjectRequest = new Amazon.S3.Model.GetObjectRequest {
                        BucketName = BucketName, Key = StorageFileNames.First().Key
                    };
                    using (Amazon.S3.Model.GetObjectResponse GetObjectResponse = await SoftmakeAll.SDK.CloudStorage.AWS.Environment._S3Client.GetObjectAsync(GetObjectRequest))
                        using (System.IO.Stream Stream = GetObjectResponse.ResponseStream)
                            using (System.IO.MemoryStream MemoryStream = new System.IO.MemoryStream())
                            {
                                await Stream.CopyToAsync(MemoryStream);

                                OperationResult.Data = MemoryStream.ToArray();
                            }
                }
                else
                {
                    using (System.Threading.SemaphoreSlim SemaphoreSlim = new System.Threading.SemaphoreSlim(StorageFileNames.Count))
                    {
                        System.Collections.Generic.List <System.Threading.Tasks.Task> DownloadTasks = new System.Collections.Generic.List <System.Threading.Tasks.Task>();
                        foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> StorageFileName in StorageFileNames)
                        {
                            await SemaphoreSlim.WaitAsync();

                            DownloadTasks.Add(System.Threading.Tasks.Task.Run(async() =>
                            {
                                Amazon.S3.Model.GetObjectRequest GetObjectRequest = new Amazon.S3.Model.GetObjectRequest {
                                    BucketName = BucketName, Key = StorageFileName.Key
                                };
                                using (Amazon.S3.Model.GetObjectResponse GetObjectResponse = await SoftmakeAll.SDK.CloudStorage.AWS.Environment._S3Client.GetObjectAsync(GetObjectRequest))
                                    await GetObjectResponse.WriteResponseStreamToFileAsync(StorageFileName.Key, false, new System.Threading.CancellationToken());
                                SemaphoreSlim.Release();
                            }));
                        }

                        if (DownloadTasks.Any())
                        {
                            await System.Threading.Tasks.Task.WhenAll(DownloadTasks);
                        }
                    }

                    OperationResult.Data = SoftmakeAll.SDK.Files.Compression.CreateZipArchive(StorageFileNames);

                    foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> StorageFileName in StorageFileNames)
                    {
                        if (System.IO.File.Exists(StorageFileName.Key))
                        {
                            try { System.IO.File.Delete(StorageFileName.Key); } catch { }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (StorageFileNames.Count > 0)
                {
                    foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> StorageFileName in StorageFileNames)
                    {
                        if (System.IO.File.Exists(StorageFileName.Key))
                        {
                            try { System.IO.File.Delete(StorageFileName.Key); } catch { }
                        }
                    }
                }

                OperationResult.Message = ex.Message;
                return(OperationResult);
            }

            OperationResult.ExitCode = 0;
            return(OperationResult);
        }
Пример #13
0
 /// <inheritdoc/>
 public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
 {
     return(_underlyingStream.CopyToAsync(destination, bufferSize, cancellationToken));
 }
Пример #14
0
        public async Task DownloadLarge(string VideoUrl, string FileSaveDir, string FileName, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpReceiveProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Downloading..."
                    }); };
                using (HtpClient localHttpClient = new HtpClient(progressHandler))
                {
                    using (HttpResponseMessage ResPonse = await localHttpClient.GetAsync(new Uri(VideoUrl), HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false))
                    {
                        token.ThrowIfCancellationRequested();
                        if (ResPonse.IsSuccessStatusCode)
                        {
                            ResPonse.EnsureSuccessStatusCode();
                            // ''''''''''''''' write byte by byte to H.D '''''''''''''''''''''''''''''
                            string FPathname = System.IO.Path.Combine(FileSaveDir, FileName);
                            using (System.IO.Stream streamToReadFrom = await ResPonse.Content.ReadAsStreamAsync())
                            {
                                using (System.IO.Stream streamToWriteTo = System.IO.File.Open(FPathname, System.IO.FileMode.Create))
                                {
                                    await streamToReadFrom.CopyToAsync(streamToWriteTo, 1024, token);
                                }
                            }

                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = (string.Format("[{0}] Downloaded successfully.", FileName))
                            });
                        }
                        else
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = ((string.Format("Error code: {0}", ResPonse.ReasonPhrase)))
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new DailymotionException(ex.Message, 1001);
                }
            }
        }
Пример #15
0
        public async Task PrivateBucket_DownloadLargeFile(string DestinationFileID, string FileSaveDir, string FileName, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpReceiveProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Downloading..."
                    }); };
                HtpClient localHttpClient = new HtpClient(progressHandler);
                var       HtpReqMessage   = new HtpRequestMessage(HttpMethod.Get, new Uri(APIbase + $"b2_download_file_by_id?fileId={DestinationFileID}"));
                // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                using (HttpResponseMessage ResPonse = await localHttpClient.GetAsync(HtpReqMessage.RequestUri, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false))
                {
                    token.ThrowIfCancellationRequested();
                    if (ResPonse.StatusCode == HttpStatusCode.OK)
                    {
                        ResPonse.EnsureSuccessStatusCode();
                        // ''''''''''''''' write byte by byte to H.D '''''''''''''''''''''''''''''
                        string FPathname = System.IO.Path.Combine(FileSaveDir, FileName);
                        using (System.IO.Stream streamToReadFrom = await ResPonse.Content.ReadAsStreamAsync())
                        {
                            using (System.IO.Stream streamToWriteTo = System.IO.File.Open(FPathname, System.IO.FileMode.Create))
                            {
                                await streamToReadFrom.CopyToAsync(streamToWriteTo, 1024, token);
                            }
                        }
                        ReportCls.Report(new ReportStatus()
                        {
                            Finished = true, TextStatus = (string.Format("[{0}] Downloaded successfully.", FileName))
                        });
                    }
                    else
                    {
                        string result = await ResPonse.Content.ReadAsStringAsync();

                        var errorInfo = JsonConvert.DeserializeObject <JSON_Error>(result);
                        ReportCls.Report(new ReportStatus()
                        {
                            Finished = true, TextStatus = ((string.Format("Error code: {0}", string.IsNullOrEmpty(errorInfo._ErrorMessage) ? errorInfo.code : errorInfo._ErrorMessage)))
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new BackBlazeException(ex.Message, 1001);
                }
            }
        }
Пример #16
0
 public Task CopyAsync(System.IO.Stream inputStream, CancellationToken cancellationToken) =>
 inputStream.CopyToAsync(Destination, BlockSize, cancellationToken);
        private static Task CopyToAsync(Stream stream, Stream destination)
        {
#if NET45PLUS
            return stream.CopyToAsync(destination);
#else
            return StreamExtensions.CopyToAsync(stream, destination);
#endif
        }