SetRequestHeader() 공개 메소드

public SetRequestHeader ( [ headerName, [ headerValue ) : void
headerName [
headerValue [
리턴 void
예제 #1
0
        /// <summary>
        /// Overrides the base execute logic to use the background downloader to download the file.
        /// </summary>
        protected async override void OnExecute()
        {
            BT.BackgroundDownloader downloader;
            if (this.Url.OriginalString.StartsWith(this.LiveClient.ApiEndpoint, StringComparison.OrdinalIgnoreCase))
            {
                if (base.RefreshTokenIfNeeded())
                {
                    return;
                }

                downloader = new BT.BackgroundDownloader();
                if (this.LiveClient.Session != null)
                {
                    downloader.SetRequestHeader(
                        ApiOperation.AuthorizationHeader,
                        AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken);
                }
                downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());
            }
            else
            {
                downloader = new BT.BackgroundDownloader();
            }

            downloader.Group = LiveConnectClient.LiveSDKDownloadGroup;
            this.cts         = new CancellationTokenSource();
            this.downloadOp  = downloader.CreateDownload(this.Url, this.OutputFile);
            var progressHandler = new Progress <BT.DownloadOperation>(this.OnDownloadProgress);

            LiveDownloadOperationResult result = null;
            Exception webError = null;

            try
            {
                this.downloadOp = await this.downloadOp.StartAsync().AsTask(this.cts.Token, progressHandler);

                result = this.OutputFile != null ?
                         new LiveDownloadOperationResult(this.OutputFile) :
                         new LiveDownloadOperationResult(this.downloadOp.GetResultStreamAt(0));
            }
            catch (TaskCanceledException)
            {
                result = new LiveDownloadOperationResult(null, true);
            }
            catch (Exception error)
            {
                webError = error;
            }

            if (webError != null)
            {
                result = await this.ProcessDownloadErrorResponse(webError);
            }

            this.OnOperationCompleted(result);
        }
        /// <summary>
        /// Overrides the base execute logic to use the background downloader to download the file.
        /// </summary>
        protected async override void OnExecute()
        {
            var loginResult = await this.LiveClient.Session.AuthClient.GetLoginStatusAsync();
            if (loginResult.Error != null)
            {
                this.taskCompletionSource.SetException(loginResult.Error);
                return;
            }
            else
            {
                var downloader = new BackgroundDownloader();
                downloader.SetRequestHeader(
                        ApiOperation.AuthorizationHeader,
                        AuthConstants.BearerTokenType + " " + loginResult.Session.AccessToken);
                downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());

                downloader.Group = LiveConnectClient.LiveSDKDownloadGroup;
                this.downloadOp = downloader.CreateDownload(this.Url, this.OutputFile);
                this.taskCompletionSource.SetResult(new LiveDownloadOperation(downloadOp));
            }
        }
        /// <summary>
        /// Overrides the base execute logic to use the background downloader to download the file.
        /// </summary>
        protected async override void OnExecute()
        {
            BT.BackgroundDownloader downloader;
            if (this.Url.OriginalString.StartsWith(this.LiveClient.ApiEndpoint, StringComparison.OrdinalIgnoreCase))
            {
                if (base.RefreshTokenIfNeeded())
                {
                    return;
                }

                downloader = new BT.BackgroundDownloader();
                if (this.LiveClient.Session != null)
                {
                    downloader.SetRequestHeader(
                        ApiOperation.AuthorizationHeader,
                        AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken);
                }
                downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());
            }
            else
            {
                downloader = new BT.BackgroundDownloader();
            }

            downloader.Group = LiveConnectClient.LiveSDKDownloadGroup;
            this.cts = new CancellationTokenSource();
            this.downloadOp = downloader.CreateDownload(this.Url, this.OutputFile);
            var progressHandler = new Progress<BT.DownloadOperation>(this.OnDownloadProgress);

            LiveDownloadOperationResult result = null;
            Exception webError = null;
            try
            {
                this.downloadOp = await this.downloadOp.StartAsync().AsTask(this.cts.Token, progressHandler);

                result = this.OutputFile != null ?
                         new LiveDownloadOperationResult(this.OutputFile) :
                         new LiveDownloadOperationResult(this.downloadOp.GetResultStreamAt(0));
            }
            catch (TaskCanceledException)
            {
                result = new LiveDownloadOperationResult(null, true);
            }
            catch (Exception error)
            {
                webError = error;
            }

            if (webError != null)
            {
                result = await this.ProcessDownloadErrorResponse(webError);
            }

            this.OnOperationCompleted(result);
        }
        internal async Task BackgroundDownload()
        {
            if (SelectedItem == null)
                await new MessageDialog("No File Selected").ShowAsync();

            FileSavePicker fileSavePicker = new FileSavePicker();
            fileSavePicker.SuggestedFileName = SelectedItem.Name;
            var ext = Path.GetExtension(SelectedItem.Name);
            fileSavePicker.FileTypeChoices.Add(ext, new string[] { ext });
            StorageFile saveFile = await fileSavePicker.PickSaveFileAsync();
            if (saveFile == null)
                return;

            var bgDownloader = new BackgroundDownloader();
            var test = Path.Combine(Config.FilesEndpointUri.ToString(), string.Format(Constants.ContentPathString, SelectedItem.Id));
            bgDownloader.SetRequestHeader(Constants.AuthHeaderKey, string.Format(Constants.V2AuthString, Client.Auth.Session.AccessToken));
            var download = bgDownloader.CreateDownload(new Uri(test), saveFile);

            var testRes = await download.StartAsync();
        }
예제 #5
0
 private BackgroundDownloader CreateDownloader()
 {
     BackgroundDownloader downloader = new BackgroundDownloader();
     downloader.SetRequestHeader("Cookie", "time=" + DateTime.Now);
     return downloader;
 }
예제 #6
0
        public async Task<IRandomAccessStream> DownloadPDFAsync(LibrelioLocalUrl magUrl, StorageFolder folder, IProgress<int> progress = null, CancellationToken cancelToken = default(CancellationToken))
        {
            //HttpClient client = new HttpClient();

            //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, magUrl.Url);

            //int read = 0;
            //int offset = 0;
            //byte[] responseBuffer = new byte[1024];

            //var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancelToken);
            //response.EnsureSuccessStatusCode();

            //var length = response.Content.Headers.ContentLength;

            //cancelToken.ThrowIfCancellationRequested();

            //var stream = new InMemoryRandomAccessStream();

            //using (var responseStream = await response.Content.ReadAsStreamAsync())
            //{
            //    do
            //    {
            //        cancelToken.ThrowIfCancellationRequested();

            //        read = await responseStream.ReadAsync(responseBuffer, 0, responseBuffer.Length);

            //        cancelToken.ThrowIfCancellationRequested();

            //        await stream.AsStream().WriteAsync(responseBuffer, 0, read);

            //        offset += read;
            //        uint val = (uint)(offset * 100 / length);
            //        if (val >= 100) val = 99;
            //        if (val <= 0) val = 1;
            //        progress.Report((int)val);
            //    }
            //    while (read != 0);
            //}

            //progress.Report(100);

            //await stream.FlushAsync();

            ////var folder = await AddMagazineFolderStructure(magUrl);
            ////var folder = await StorageFolder.GetFolderFromPathAsync(folderUrl);
            var file = await folder.CreateFileAsync(magUrl.FullName, CreationCollisionOption.ReplaceExisting);

            //using (var protectedStream = await DownloadManager.ProtectPDFStream(stream))
            //using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
            ////using (var unprotectedStream = await DownloadManager.UnprotectPDFStream(protectedStream))
            //{

            //    await RandomAccessStream.CopyAsync(protectedStream, fileStream.GetOutputStreamAt(0));

            //    await fileStream.FlushAsync();
            //}

            progress.Report(0);
            BackgroundDownloader downloader = new BackgroundDownloader();
            downloader.SetRequestHeader("user-agent", "LibrelioWinRT");
            DownloadOperation download = downloader.CreateDownload(new Uri(magUrl.Url), file);

            await HandleDownloadAsync(download, true, progress, cancelToken);

            progress.Report(100);

            var stream = await download.ResultFile.OpenAsync(FileAccessMode.ReadWrite);
            var protectedStram = await DownloadManager.ProtectPDFStream(stream);
            await RandomAccessStream.CopyAndCloseAsync(protectedStram.GetInputStreamAt(0), stream.GetOutputStreamAt(0));
            await protectedStram.FlushAsync();
            await stream.FlushAsync();
            protectedStram.Dispose();
            stream.Dispose();

            var pdfStream = new MagazineData();
            pdfStream.folderUrl = folder.Path + "\\";
            pdfStream.stream = stream;
            //var fileHandle =
            //    await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\test\testmagazine.pdf");

            //pdfStream.folderUrl = "C:\\Users\\Dorin\\Documents\\Magazines\\wind_355\\";
            //pdfStream.stream = await fileHandle.OpenReadAsync();

            return pdfStream.stream;
        }
예제 #7
0
        private async Task DownloadFileAsyncWithProgress(string url, StorageFile pdfFile, IProgress<int> progress = null, CancellationToken cancelToken = default(CancellationToken))
        {
            //HttpClient client = new HttpClient();

            //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            //int read = 0;
            //int offset = 0;
            //byte[] responseBuffer = new byte[2000];

            //var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancelToken);
            //response.EnsureSuccessStatusCode();

            //var length = response.Content.Headers.ContentLength;

            //byte[] img = await response.Content.ReadAsByteArrayAsync();

            //cancelToken.ThrowIfCancellationRequested();

            //var stream = new InMemoryRandomAccessStream();
            //DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0));

            //writer.WriteBytes(img);

            //await writer.StoreAsync();


            //var task1 = client.GetStreamAsync(new Uri(url));

            //var cancelation = new CancellationTokenSource();

            //var task2 = Task.Run(async () =>
            //{
            //    for (int i = 0; i < length; i += 9000)
            //    {
            //        await Task.Delay(1);
            //        int val = (int)(i * 100 / length);
            //        progress.Report(val);

            //        if (cancelation.Token.IsCancellationRequested)
            //        {
            //            progress.Report(99);
            //            return;
            //        }
            //    }
            //}, cancelation.Token);

            //var result = await task1;

            //cancelation.Cancel();
            //progress.Report(99);

            //await result.CopyToAsync(stream.AsStream());
            //await stream.FlushAsync();

            //await Task.Delay(670);

            //var responseStream = await response.Content.ReadAsStreamAsync();

            //do
            //{
            //    cancelToken.ThrowIfCancellationRequested();

            //    read = await responseStream.ReadAsync(responseBuffer, 0, responseBuffer.Length);

            //    cancelToken.ThrowIfCancellationRequested();

            //    await stream.AsStream().WriteAsync(responseBuffer, 0, read);

            //    offset += read;
            //    int val = (int)(offset * 100 / length);
            //    progress.Report(val);
            //}
            //while (read > 0);

            //await responseStream.FlushAsync();
            //responseStream.Dispose();
            //responseStream = null;
            //await stream.FlushAsync();

            //var protectedStream = await DownloadManager.ProtectPDFStream(stream);
            //var fileStream = await pdfFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
            //using (var unprotectedStream = await DownloadManager.UnprotectPDFStream(protectedStream))

            //await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

            //await stream.FlushAsync();
            //stream.Dispose();
            ///stream = null;
            //await protectedStream.FlushAsync();
            //protectedStream.Dispose();
            //protectedStream = null;
            //await fileStream.FlushAsync();
            //fileStream.Dispose();
            //fileStream = null;
            //pdfFile = null;

            progress.Report(0);
            BackgroundDownloader downloader = new BackgroundDownloader();
            downloader.SetRequestHeader("user-agent", "LibrelioWinRT");
            DownloadOperation download = downloader.CreateDownload(new Uri(url), pdfFile);

            await HandleDownloadAsync(download,  true, progress, cancelToken);

            progress.Report(100);

            var stream = await download.ResultFile.OpenAsync(FileAccessMode.ReadWrite);
            var protectedStram = await DownloadManager.ProtectPDFStream(stream);
            await RandomAccessStream.CopyAndCloseAsync(protectedStram.GetInputStreamAt(0), stream.GetOutputStreamAt(0));
            await protectedStram.FlushAsync();
            await stream.FlushAsync();
            protectedStram.Dispose();
            stream.Dispose();
        }
예제 #8
0
        public async void DownloadImage(Action<Uri, Exception> callback, string url, string fileName)
        {
            try
            {
                IStorageFolder tmpFolder = ApplicationData.Current.TemporaryFolder;

                if (!await CheckIfFileExists(tmpFolder, fileName))
                {
                    var storageFile = await tmpFolder.CreateFileAsync(fileName);

                    var downloader = new BackgroundDownloader();
                    downloader.SetRequestHeader(HttpRequestHeader.Authorization.ToString(),
                        "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(_applicationSettings.UserName + ":" + _applicationSettings.Password)));
                    var downloadOperation = await downloader.CreateDownload(new Uri(url), storageFile).StartAsync();

                    callback(new Uri(storageFile.Path, UriKind.Absolute), null);
                }
                else
                {
                    IStorageFile file = await tmpFolder.GetFileAsync(fileName);
                    callback(new Uri(file.Path, UriKind.Absolute), null);
                }
            }
            catch (HttpRequestException exception)
            {
                callback(null, exception);
            }
            catch (FormatException exception)
            {
                callback(null, exception);
            }

        }