Esempio n. 1
0
        public void DownloadIntoFolderTest()
        {
            string        targetFolderPath = Path.Combine(Path.GetTempPath(), "downloader test folder");
            DirectoryInfo targetFolder     = new DirectoryInfo(targetFolderPath);

            DownloadConfiguration config = new DownloadConfiguration {
                BufferBlockSize       = 1024,
                ChunkCount            = 1,
                ParallelDownload      = false,
                MaxTryAgainOnFailover = 100,
                OnTheFlyDownload      = true
            };
            DownloadService downloader = new DownloadService(config);

            downloader.DownloadFileAsync(DownloadTestHelper.File1KbUrl, targetFolder).Wait();
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, downloader.Package.TotalFileSize);
            downloader.Clear();
            downloader.DownloadFileAsync(DownloadTestHelper.File150KbUrl, targetFolder).Wait();
            Assert.AreEqual(DownloadTestHelper.FileSize150Kb, downloader.Package.TotalFileSize);
            downloader.Clear();

            Assert.IsTrue(targetFolder.Exists);
            FileInfo[] downloadedFiles = targetFolder.GetFiles();
            long       totalSize       = downloadedFiles.Sum(file => file.Length);

            Assert.AreEqual(DownloadTestHelper.FileSize1Kb + DownloadTestHelper.FileSize150Kb, totalSize);
            Assert.IsTrue(downloadedFiles.Any(file => file.Name == DownloadTestHelper.File1KbName));
            Assert.IsTrue(downloadedFiles.Any(file => file.Name == DownloadTestHelper.File150KbName));

            targetFolder.Delete(true);
        }
Esempio n. 2
0
        public void StopResumeOnTheFlyDownloadTest()
        {
            var stopCount = 0;
            var downloadCompletedSuccessfully = false;
            var expectedFileSize = DownloadTestHelper.FileSize150Kb; // real bytes size
            var address          = DownloadTestHelper.File150KbUrl;
            var file             = new FileInfo(Path.GetTempFileName());
            var config           = new DownloadConfiguration()
            {
                BufferBlockSize       = 1024,
                ChunkCount            = 8,
                ParallelDownload      = false,
                MaxTryAgainOnFailover = 100,
                OnTheFlyDownload      = true
            };
            var progressCount = config.ChunkCount * (int)Math.Ceiling((double)expectedFileSize / config.ChunkCount / config.BufferBlockSize);
            var downloader    = new DownloadService(config);

            downloader.DownloadProgressChanged += delegate { Interlocked.Decrement(ref progressCount); };
            downloader.DownloadFileCompleted   += (s, e) =>
            {
                if (e.Cancelled)
                {
                    Interlocked.Increment(ref stopCount);
                }
                else if (e.Error == null)
                {
                    downloadCompletedSuccessfully = true;
                }
            };

            downloader.CancelAfterDownloading(10);                       // Stopping after start of downloading.
            downloader.DownloadFileAsync(address, file.FullName).Wait(); // wait to download stopped!
            Assert.AreEqual(1, stopCount);
            downloader.CancelAfterDownloading(10);                       // Stopping after resume of downloading.
            downloader.DownloadFileAsync(downloader.Package).Wait();     // resume download from stooped point.
            Assert.AreEqual(2, stopCount);
            Assert.IsFalse(downloadCompletedSuccessfully);
            downloader.DownloadFileAsync(downloader.Package).Wait(); // resume download from stooped point, again.

            Assert.IsTrue(file.Exists);
            Assert.AreEqual(expectedFileSize, downloader.Package.TotalFileSize);
            Assert.AreEqual(expectedFileSize, file.Length);
            Assert.IsTrue(progressCount <= 0);
            Assert.AreEqual(2, stopCount);
            Assert.IsTrue(downloadCompletedSuccessfully);

            file.Delete();
        }
        public void Download1KbWithFilenameTest()
        {
            // arrange
            var downloadCompletedSuccessfully = false;
            var file       = new FileInfo(Path.GetTempFileName());
            var downloader = new DownloadService(Config);

            downloader.DownloadFileCompleted += (s, e) => {
                if (e.Cancelled == false && e.Error == null)
                {
                    downloadCompletedSuccessfully = true;
                }
            };

            // act
            downloader.DownloadFileAsync(DownloadTestHelper.File1KbUrl, file.FullName).Wait();

            // assert
            Assert.IsTrue(downloadCompletedSuccessfully);
            Assert.IsTrue(file.Exists);
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, file.Length);
            Assert.IsTrue(DownloadTestHelper.AreEqual(DownloadTestHelper.File1Kb, file.OpenRead()));

            file.Delete();
        }
Esempio n. 4
0
        public override void PageDisplayed()
        {
            // GetApplication.SetNextPage <...> ();
            // GetApplication.PushNextPage <...> ();

            Task.Run(async() =>
            {
                var cancellationToken = new CancellationTokenSource();
                await downloader.DownloadFileAsync(
                    "http://download.thinkbroadband.com/1MB.zip",
                    cancellationToken.Token,
                    (message) =>
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        await this.DisplayAlert(
                            "Download Failed",
                            message,
                            "Ok");
                    });
                },
                    () =>
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        await this.DisplayAlert(
                            "Download Complete",
                            "Download has completed",
                            "Ok");
                    });
                });
            });
        }
Esempio n. 5
0
    public async void StartAsync()
    {
        try
        {
            HtmlWeb web     = new HtmlWeb();
            var     htmlDoc = web.Load(url);
            string  title   = this.Title(htmlDoc);

            foreach (HtmlNode link in htmlDoc.DocumentNode.SelectNodes("//a[@class='image'][@href]"))
            {
                string url = link.Attributes["href"].Value;
                itemName = link.Attributes["title"].Value;
                // download here
                string filepath = String.Format(@"{0}\{1}\{2}", dest, title, itemName);
                Console.WriteLine(filepath);
                await downloader.DownloadFileAsync(url, filepath);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("error StartAsync");
            Console.WriteLine(e);
            MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
Esempio n. 6
0
        public void DownloadPdf150KTest()
        {
            var expectedFileSize = DownloadTestHelper.FileSize150Kb; // real bytes size
            var address          = DownloadTestHelper.File150KbUrl;
            var file             = new FileInfo(Path.GetTempFileName());
            var config           = new DownloadConfiguration()
            {
                BufferBlockSize       = 1024,
                ChunkCount            = 1,
                ParallelDownload      = false,
                MaxTryAgainOnFailover = 100,
                OnTheFlyDownload      = true
            };
            var progressCount = config.ChunkCount * (int)Math.Ceiling((double)expectedFileSize / config.ChunkCount / config.BufferBlockSize);
            var downloader    = new DownloadService(config);

            downloader.DownloadProgressChanged += delegate { Interlocked.Decrement(ref progressCount); };

            downloader.DownloadFileAsync(address, file.FullName).Wait();
            Assert.IsTrue(file.Exists);
            Assert.AreEqual(expectedFileSize, downloader.Package.TotalFileSize);
            Assert.AreEqual(expectedFileSize, file.Length);
            Assert.IsTrue(progressCount <= 0);

            file.Delete();
        }
        private async Task DownloadPatchAsync(PatchDownload download, int index)
        {
            var outFile = GetPatchFile(download.Patch);

            Log.Information("Downloading patch {0} at {1} to {2}", download.Patch.VersionId, download.Patch.Url, outFile.FullName);

            Actives[index] = download;

            if (outFile.Exists && IsHashCheckPass(download.Patch, outFile))
            {
                download.State    = PatchState.Downloaded;
                Slots[index]      = true;
                Progresses[index] = download.Patch.Length;
                return;
            }

            var dlService = new DownloadService(_downloadOpt);

            dlService.DownloadProgressChanged += (sender, args) =>
            {
                Progresses[index] = args.BytesReceived;
                Speeds[index]     = dlService.DownloadSpeed;
            };

            dlService.DownloadFileCompleted += (sender, args) =>
            {
                if (args.Error != null)
                {
                    Log.Error(args.Error, "Download failed for {0}", download.Patch.VersionId);
                    MessageBox.Show($"Download FAILED for {download.Patch.VersionId}.\nPlease try again.\n\n" + args.Error, "XIVLauncher Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Environment.Exit(0);
                    return;
                }

                if (args.Cancelled)
                {
                    Log.Error("Download cancelled for {0}", download.Patch.VersionId);
                    MessageBox.Show($"Download CANCELLED for {download.Patch.VersionId}.\nPlease try again.\n\n" + args.Error, "XIVLauncher Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Environment.Exit(0);
                }

                // Let's just bail for now, need better handling of this later
                if (!IsHashCheckPass(download.Patch, outFile))
                {
                    Log.Error("HashCHeck failed for {0} after DL", download.Patch.VersionId);
                    MessageBox.Show($"IsHashCheckPass FAILED for {download.Patch.VersionId}.\nPlease try again.", "XIVLauncher Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    outFile.Delete();
                    Environment.Exit(0);
                    return;
                }

                download.State = PatchState.Downloaded;
                Slots[index]   = true;

                Log.Verbose("Patch at {0} downloaded completely", download.Patch.Url);
            };

            await dlService.DownloadFileAsync(download.Patch.Url, outFile.FullName);
        }
        public void StopResumeDownloadTest()
        {
            // arrange
            var expectedStopCount             = 5;
            var stopCount                     = 0;
            var cancellationsOccurrenceCount  = 0;
            var downloadFileExecutionCounter  = 0;
            var downloadCompletedSuccessfully = false;
            var downloader                    = new DownloadService(Config);

            downloader.DownloadFileCompleted += (s, e) => {
                if (e.Cancelled && e.Error != null)
                {
                    cancellationsOccurrenceCount++;
                }
                else
                {
                    downloadCompletedSuccessfully = true;
                }
            };
            downloader.DownloadStarted += delegate {
                if (expectedStopCount > stopCount)
                {
                    // Stopping after start of downloading
                    downloader.CancelAsync();
                    stopCount++;
                }
            };

            // act
            downloader.DownloadFileAsync(DownloadTestHelper.File150KbUrl, Path.GetTempFileName()).Wait();
            while (expectedStopCount > downloadFileExecutionCounter++)
            {
                downloader.DownloadFileAsync(downloader.Package).Wait(); // resume download from stopped point.
            }

            // assert
            Assert.IsTrue(File.Exists(downloader.Package.FileName));
            Assert.AreEqual(DownloadTestHelper.FileSize150Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(expectedStopCount, stopCount);
            Assert.AreEqual(expectedStopCount, cancellationsOccurrenceCount);
            Assert.IsTrue(downloadCompletedSuccessfully);

            File.Delete(downloader.Package.FileName);
        }
Esempio n. 9
0
        static async Task Main(string[] args)
        {
            var chunkCount = 8;

            DownloadList = File.Exists(DownloadListFile)
                ? JsonConvert.DeserializeObject <List <DownloadItem> >(File.ReadAllText(DownloadListFile))
                : null;

            DownloadList ??= new List <DownloadItem>
            {
                new DownloadItem {
                    FileName = Path.Combine(Path.GetTempPath(), "100MB.zip"), Url = "http://ipv4.download.thinkbroadband.com/100MB.zip"
                }
            };

            var options = new ProgressBarOptions
            {
                ForegroundColor     = ConsoleColor.Green,
                ForegroundColorDone = ConsoleColor.DarkGreen,
                BackgroundColor     = ConsoleColor.DarkGray,
                BackgroundCharacter = '\u2593'
            };

            ChildOption = new ProgressBarOptions
            {
                ForegroundColor   = ConsoleColor.Yellow,
                BackgroundColor   = ConsoleColor.DarkGray,
                ProgressCharacter = '─'
            };

            var downloadOpt = new DownloadConfiguration()
            {
                ParallelDownload      = true,         // download parts of file as parallel or not
                BufferBlockSize       = 10240,        // usually, hosts support max to 8000 bytes
                ChunkCount            = chunkCount,   // file parts to download
                MaxTryAgainOnFailover = int.MaxValue, // the maximum number of times to fail.
                OnTheFlyDownload      = true,         // caching in-memory mode
                Timeout = 1000                        // timeout (millisecond) per stream block reader
            };
            var ds = new DownloadService(downloadOpt);

            ds.ChunkDownloadProgressChanged += OnChunkDownloadProgressChanged;
            ds.DownloadProgressChanged      += OnDownloadProgressChanged;
            ds.DownloadFileCompleted        += OnDownloadFileCompleted;

            foreach (var downloadItem in DownloadList)
            {
                Console.Clear();
                ConsoleProgress        = new ProgressBar(10000, $"Downloading {Path.GetFileName(downloadItem.FileName)} file", options);
                ChildConsoleProgresses = new ConcurrentDictionary <string, ChildProgressBar>();

                await ds.DownloadFileAsync(downloadItem.Url, downloadItem.FileName).ConfigureAwait(false);

                ds.Clear();
            }
        }
Esempio n. 10
0
        private static async Task <DownloadService> DownloadFile(DownloadItem downloadItem)
        {
            _currentDownloadService = new DownloadService(GetDownloadConfiguration());
            _currentDownloadService.ChunkDownloadProgressChanged += OnChunkDownloadProgressChanged;
            _currentDownloadService.DownloadProgressChanged      += OnDownloadProgressChanged;
            _currentDownloadService.DownloadFileCompleted        += OnDownloadFileCompleted;
            _currentDownloadService.DownloadStarted += OnDownloadStarted;

            if (string.IsNullOrWhiteSpace(downloadItem.FileName))
            {
                await _currentDownloadService.DownloadFileAsync(downloadItem.Url, new DirectoryInfo(downloadItem.FolderPath))
                .ConfigureAwait(false);
            }
            else
            {
                await _currentDownloadService.DownloadFileAsync(downloadItem.Url, downloadItem.FileName).ConfigureAwait(false);
            }

            return(_currentDownloadService);
        }
        public void DownloadOnMemoryStreamTypeTest()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            using var stream = downloader.DownloadFileAsync(DownloadTestHelper.File1KbUrl).Result;

            // assert
            Assert.IsTrue(stream is MemoryStream);
        }
Esempio n. 12
0
        private async void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            btnDownload.Content   = "Downloading...";
            btnDownload.IsEnabled = false;

            DownloadService downloadService = new DownloadService();

            downloadService.DownloadProgressChanged += DownloadService_DownloadProgressChanged;
            downloadService.DownloadFileCompleted   += DownloadService_DownloadFileCompleted;
            await downloadService.DownloadFileAsync(App.Argument.Url, tempRarFile);
        }
        public void DownloadOnMemoryStreamContentTest()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            using var stream = (MemoryStream)downloader.DownloadFileAsync(DownloadTestHelper.File1KbUrl).Result;

            // assert
            Assert.IsTrue(DownloadTestHelper.File1Kb.SequenceEqual(stream.ToArray()));
        }
        public void DownloadOnMemoryStreamSizeTest()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            using var stream = downloader.DownloadFileAsync(DownloadTestHelper.File1KbUrl).Result;

            // assert
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, stream.Length);
        }
Esempio n. 15
0
        private static async Task DownloadItem(KeyValuePair<string, string> item, Uri uri)
        {
            try
            {
                Logger.Log($"Starting download for {uri}").FireAndForget();

                bool isSmall = false;
                using (var client = new HttpClient())
                {
                    HttpRequestMessage m = new HttpRequestMessage(HttpMethod.Head, uri);

                    HttpResponseMessage resp = await client.SendAsync(m);

                    if (resp.Content.Headers.ContentLength < 100) { isSmall = true; }

                    if (resp.Content.Headers.ContentType != null && (resp.Content.Headers.ContentType.ToString() == "text/plain" || resp.Content.Headers.ContentType.ToString() == "text/json"))
                    {
                        isSmall = true;
                    }

                    m.Dispose();
                }

                Directory.CreateDirectory(Path.GetDirectoryName(NormalizePath(item.Key)));
                try
                {
                    if (isSmall)
                    {
                        DownloadService ds = new DownloadService(downloadOptSmall);
                        await RetryPolicy.ExecuteAsync(async () => { await ds.DownloadFileAsync(uri.ToString(), item.Key); });
                    }
                    else
                    {
                        await RetryPolicy.ExecuteAsync(async () => { await new DownloadService(downloadOpt).DownloadFileAsync(uri.ToString(), item.Key); });
                    }
                }
                catch (System.IO.InvalidDataException)
                {
                    await RetryPolicy.ExecuteAsync(async () => { await DownloadManually(uri, item.Key); });
                }

                Logger.Log($"Download for {uri} finished.").FireAndForget();
            }
            catch (System.Net.WebException e)
            {
                if (e.Message == "The remote server returned an error: (404) Not Found.")
                {
                    Logger.Log("Could not download " + uri + ": 404 not found.", LogType.ERROR).FireAndForget();
                }
                else { throw; }
            }
        }
Esempio n. 16
0
        private async Task DownloadImage(string image, string destination, int imageNum)
        {
            var    downloader   = new DownloadService();
            string tempFilePath = Path.GetTempFileName();
            string filePath     = Path.Combine(destination, GetFilenameFromUrl(image, imageNum));

            if (!File.Exists(filePath))
            {
                await downloader.DownloadFileAsync(image, tempFilePath, _source.Token);

                File.Move(tempFilePath, filePath);
            }
        }
Esempio n. 17
0
        private static async Task <DownloadService> DownloadFile(DownloadItem downloadItem,
                                                                 DownloadConfiguration downloadOpt)
        {
            DownloadService ds = new DownloadService(downloadOpt);

            ds.ChunkDownloadProgressChanged += OnChunkDownloadProgressChanged;
            ds.DownloadProgressChanged      += OnDownloadProgressChanged;
            ds.DownloadFileCompleted        += OnDownloadFileCompleted;
            ds.DownloadStarted += OnDownloadStarted;

            if (string.IsNullOrWhiteSpace(downloadItem.FileName))
            {
                await ds.DownloadFileAsync(downloadItem.Url, new DirectoryInfo(downloadItem.FolderPath))
                .ConfigureAwait(false);
            }
            else
            {
                await ds.DownloadFileAsync(downloadItem.Url, downloadItem.FileName).ConfigureAwait(false);
            }

            return(ds);
        }
Esempio n. 18
0
        public void SpeedLimitTest()
        {
            var speedPerSecondsHistory = new ConcurrentBag <long>();
            var lastTick         = 0L;
            var expectedFileSize = DownloadTestHelper.FileSize10Mb; // real bytes size
            var address          = DownloadTestHelper.File10MbUrl;
            var file             = new FileInfo(Path.GetTempFileName());
            var config           = new DownloadConfiguration()
            {
                BufferBlockSize       = 1024,
                ChunkCount            = 8,
                ParallelDownload      = true,
                MaxTryAgainOnFailover = 100,
                OnTheFlyDownload      = true,
                MaximumBytesPerSecond = 1024 * 1024 // 1MB/s
            };
            var progressCount = config.ChunkCount * (int)Math.Ceiling((double)expectedFileSize / config.ChunkCount / config.BufferBlockSize);
            var downloader    = new DownloadService(config);

            downloader.DownloadProgressChanged += (s, e) =>
            {
                Interlocked.Decrement(ref progressCount);
                if (Environment.TickCount64 - lastTick >= 1000)
                {
                    speedPerSecondsHistory.Add(e.BytesPerSecondSpeed);
                    lastTick = Environment.TickCount64;
                }
            };

            downloader.DownloadFileAsync(address, file.FullName).Wait(); // wait to download stopped!
            var avgSpeed = (long)speedPerSecondsHistory.Average();

            Assert.IsTrue(file.Exists);
            Assert.AreEqual(expectedFileSize, downloader.Package.TotalFileSize);
            Assert.AreEqual(expectedFileSize, file.Length);
            Assert.IsTrue(progressCount <= 0);
            Assert.IsTrue(avgSpeed <= config.MaximumBytesPerSecond);

            if (File.Exists(file.FullName))
            {
                try
                {
                    file.Delete();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
Esempio n. 19
0
    private void LoadFileFromUrl()
    {
        StartCoroutine(DownloadService.DownloadFileAsync(_url,
                                                         progress =>
        {
            _progressBar.value = progress;
        }, (path) =>
        {
            // Import and convert our model
            var data             = RuntimeConverter.ConvertToPointCloudData(path);
            _renderer.sourceData = data;

            _progressBar.gameObject.SetActive(false);
        }));
    }
Esempio n. 20
0
        private static async Task <DownloadService> Download(DownloadItem downloadItem, DownloadConfiguration downloadOpt)
        {
            var ds = new DownloadService(downloadOpt);

            ds.ChunkDownloadProgressChanged += OnChunkDownloadProgressChanged;
            ds.DownloadProgressChanged      += OnDownloadProgressChanged;
            ds.DownloadFileCompleted        += OnDownloadFileCompleted;


            Console.Clear();
            ConsoleProgress        = new ProgressBar(10000, $"Downloading {Path.GetFileName(downloadItem.FileName)} file", ProcessBarOption);
            ChildConsoleProgresses = new ConcurrentDictionary <string, ChildProgressBar>();
            await ds.DownloadFileAsync(downloadItem.Url, downloadItem.FileName).ConfigureAwait(false);

            return(ds);
        }
Esempio n. 21
0
        public void DownloadJson1KTest()
        {
            var downloadCompletedSuccessfully = false;
            var expectedFileSize = DownloadTestHelper.FileSize1Kb; // real bytes size
            var address          = DownloadTestHelper.File1KbUrl;
            var file             = new FileInfo(Path.GetTempFileName());
            var config           = new DownloadConfiguration()
            {
                AllowedHeadRequest    = false,
                BufferBlockSize       = 1024,
                ChunkCount            = 16,
                ParallelDownload      = false,
                MaxTryAgainOnFailover = 100,
                OnTheFlyDownload      = true
            };
            var progressCount = config.ChunkCount * (int)Math.Ceiling((double)expectedFileSize / config.ChunkCount / config.BufferBlockSize);
            var downloader    = new DownloadService(config);

            downloader.DownloadProgressChanged += delegate
            {
                Interlocked.Decrement(ref progressCount);
            };

            downloader.DownloadFileCompleted += (s, e) =>
            {
                if (e.Cancelled == false && e.Error == null)
                {
                    downloadCompletedSuccessfully = true;
                }
            };

            downloader.DownloadFileAsync(address, file.FullName).Wait();
            Assert.IsTrue(file.Exists);
            Assert.AreEqual(expectedFileSize, downloader.Package.TotalFileSize);
            Assert.AreEqual(expectedFileSize, file.Length);
            Assert.AreEqual(0, progressCount);

            using (var reader = file.OpenText())
            {
                var json = reader.ReadToEnd();
                var obj  = JsonConvert.DeserializeObject(json);
                Assert.IsNotNull(obj);
            }

            Assert.IsTrue(downloadCompletedSuccessfully);
            file.Delete();
        }
        public void Download16KbWithoutFilenameTest()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            downloader.DownloadFileAsync(DownloadTestHelper.File16KbUrl,
                                         new DirectoryInfo(DownloadTestHelper.TempDirectory)).Wait();

            // assert
            Assert.IsTrue(File.Exists(downloader.Package.FileName));
            Assert.IsTrue(downloader.Package.FileName.StartsWith(DownloadTestHelper.TempDirectory));
            Assert.AreEqual(DownloadTestHelper.FileSize16Kb, downloader.Package.TotalFileSize);
            Assert.IsTrue(DownloadTestHelper.AreEqual(DownloadTestHelper.File16Kb, File.OpenRead(downloader.Package.FileName)));

            File.Delete(downloader.Package.FileName);
        }
Esempio n. 23
0
        /// <summary>
        /// Кнопка Скачать
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ButtonStart_Click(object sender, EventArgs e)
        {
            //проверяем и получаем введенные адрес и путь
            if (!TryGetDownloadPathes(out (Uri uri, string path)downloadPathes))
            {
                return;
            }
            //создаем экз.сервиса скачивания
            var service = new DownloadService(downloadPathes.uri, downloadPathes.path);

            //выключаем кнопки
            SetFormState(FormState.Downloading);
            //готовим токен отмены и отображение процесса скачивания
            _tokenSource = new CancellationTokenSource();
            var token = _tokenSource.Token;
            //размер скачиваемого файла
            var sizeFile = 0L;
            //колбек отображения процесса скачки
            var progress = new Progress <int>(readed =>
            {
                _progressBar.Value = readed;
                _labelReport.Text  = $"{_progressBar.Value}%";
            });

            try
            {
                //размер
                sizeFile = await service.GetFileSize(token);

                _labelSize.Text = sizeFile.ToString() + " байт";
                //файл
                await service.DownloadFileAsync(token, progress);
            }
            catch (Exception ex)
            {
                var message = $"Oшибка: \n'{ex.Message}'";
                var caption = "Ошибка загрузки файла";
                MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                _tokenSource.Dispose();
                SetFormState(FormState.Initial);
            }
        }
Esempio n. 24
0
        private async void FileDownloadButton_Clicked(object sender, EventArgs e)
        {
            string fileUrl = $"https://dummyimage.com/2560x1600/08f24a/e61c6d.jpg&text=File+Number+{fileCounter}";

            ourLogger.LogInformation($"File Download Clicked For Downloading file {fileUrl}");
            var fileDownloadService = new DownloadService(DependencyService.Get <IFileService>());
            await Task.Factory.StartNew(async() =>
            {
                string filePath = await fileDownloadService.DownloadFileAsync(fileUrl, $"FileNumber{fileCounter}.jpg");
                if (filePath != null)
                {
                    ourLogger.LogInformation($"Downloaded file location: {filePath}");
                    DownloadImageFile.Source = ImageSource.FromFile(filePath);
                }
            });

            fileCounter++;
        }
Esempio n. 25
0
        private async void PostPinCode()
        {
            HttpClient client = new HttpClient();
            Uri        uri    = new Uri("https://api.socialscore.be/api/v1/tv/Pincode/" + pin_code);

            try
            {
                StringContent       content  = new StringContent("", Encoding.UTF8, "application/json");
                HttpResponseMessage response = await client.PostAsync(uri, content);

                var result = await response.Content.ReadAsStringAsync();

                App.appInfo = JsonConvert.DeserializeObject <ResultInfo>(result);

                IFileService    fileService     = DependencyService.Get <IFileService>();
                DownloadService downloadService = new DownloadService(fileService);
                await downloadService.DownloadFileAsync(App.appInfo.projectInfo.url);

                if (App.appInfo.isSuccess)
                {
                    await Navigation.PopAsync();

                    App.mngPreferences.SaveAllInfo(App.appInfo);
                    Page page = new MainPage();
                    await Navigation.PushAsync(page);
                }
                else
                {
                    await DisplayAlert(null, "Your PIN code is not valid. Please rewrite your PIN code.", "OK");

                    entry_pin_code.Focus();
                    entry_pin_code.CursorPosition = 5;
                }
            }
            catch (Exception er)
            {
                var lb = er.ToString();
                await DisplayAlert(null, "The server is not responding. Just a second and retry.", "OK");

                entry_pin_code.Focus();
                entry_pin_code.CursorPosition = 5;
            }
        }
Esempio n. 26
0
        private async void GetUrlsAndDownload(HtmlAgilityPack.HtmlDocument htmlDoc)
        {
            string title = this.GetTitle(htmlDoc);

            // check for illegal chars
            title = CheckIllegalChars(title);
            // scuffed af; having form controls in business logic
            listBox.Items.Insert(0, "Album: " + title);
            foreach (HtmlNode link in htmlDoc.DocumentNode.SelectNodes("//a[@class='image'][@href]"))
            {
                string url = link.Attributes["href"].Value;
                itemName = link.Attributes["title"].Value;
                // scuffed af; having form controls in business logic
                listBox.Items.Insert(0, "Downloading item: " + itemName);
                // download here
                string filepath = String.Format(@"{0}\{1}\{2}", dest, title, itemName);
                await downloader.DownloadFileAsync(url, filepath);
            }
        }
        public void DownloadProgressChangedTest()
        {
            // arrange
            var downloader           = new DownloadService(Config);
            var filename             = Path.GetTempFileName();
            var progressChangedCount = (int)Math.Ceiling((double)DownloadTestHelper.FileSize16Kb / Config.BufferBlockSize);
            var progressCounter      = 0;

            downloader.DownloadProgressChanged += (s, e) => Interlocked.Increment(ref progressCounter);

            // act
            downloader.DownloadFileAsync(DownloadTestHelper.File16KbUrl, filename).Wait();

            // assert
            // Note: some times received bytes on read stream method was less than block size!
            Assert.IsTrue(progressChangedCount <= progressCounter);

            File.Delete(filename);
        }
        protected async void CheckUpdate()
        {
            string guid       = mngPreferences.GetPrefereceStringValue("key_Guid");
            string lastUpdate = mngPreferences.GetPrefereceStringValue("key_LastUpdate");

            HttpClient client = new HttpClient();
            Uri        uri    = new Uri("https://api.socialscore.be/api/v1/tv/projectinfo/" + guid);

            try
            {
                HttpResponseMessage response = await client.GetAsync(uri);

                var result = await response.Content.ReadAsStringAsync();

                ProjectInfo projectInfo = JsonConvert.DeserializeObject <ProjectInfo>(result);

                if (projectInfo.lastUpdate != lastUpdate)
                {
                    mngPreferences.SaveProjectInfo(projectInfo);

                    IFileService    fileService     = DependencyService.Get <IFileService>();
                    DownloadService downloadService = new DownloadService(fileService);
                    await downloadService.DownloadFileAsync(App.appInfo.projectInfo.url);

                    Type CurPageType = MainPage.GetType();

                    if (ImInPinView == false)
                    {
                        MainPage = new NavigationPage(new Views.MainPage());
                    }
                }
            }
            catch (Exception er)
            {
                var lb = er.ToString();
            }
        }
        public void SpeedLimitTest()
        {
            // arrange
            double averageSpeed    = 0;
            var    progressCounter = 0;

            Config.MaximumBytesPerSecond = 128; // 128 Byte/s
            var downloader = new DownloadService(Config);

            downloader.DownloadProgressChanged += (s, e) => {
                averageSpeed = ((averageSpeed * progressCounter) + e.BytesPerSecondSpeed) / (progressCounter + 1);
                progressCounter++;
            };

            // act
            downloader.DownloadFileAsync(DownloadTestHelper.File1KbUrl, Path.GetTempFileName()).Wait();

            // assert
            Assert.IsTrue(File.Exists(downloader.Package.FileName));
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, downloader.Package.TotalFileSize);
            Assert.IsTrue(averageSpeed <= Config.MaximumBytesPerSecond, $"Average Speed: {averageSpeed} , Speed Limit: {Config.MaximumBytesPerSecond}");

            File.Delete(downloader.Package.FileName);
        }
Esempio n. 30
0
        public void DownloadJson1KTest()
        {
            var expectedFileSize = 20471; // real bytes size
            var address          = "https://file-examples.com/wp-content/uploads/2017/02/file_example_JSON_1kb.json";
            var file             = new FileInfo(Path.GetTempFileName());
            var config           = new DownloadConfiguration()
            {
                BufferBlockSize       = 1024,
                ChunkCount            = 16,
                ParallelDownload      = false,
                MaxTryAgainOnFailover = 100,
                OnTheFlyDownload      = true
            };
            var progressCount = config.ChunkCount * (int)Math.Ceiling((double)expectedFileSize / config.ChunkCount / config.BufferBlockSize);
            var downloader    = new DownloadService(config);

            downloader.DownloadProgressChanged += delegate
            {
                Interlocked.Decrement(ref progressCount);
            };

            downloader.DownloadFileAsync(address, file.FullName).Wait();
            Assert.IsTrue(file.Exists);
            Assert.AreEqual(expectedFileSize, downloader.Package.TotalFileSize);
            Assert.AreEqual(expectedFileSize, file.Length);
            Assert.AreEqual(0, progressCount);

            using (var reader = file.OpenText())
            {
                var json = reader.ReadToEnd();
                var obj  = JsonConvert.DeserializeObject(json);
                Assert.IsNotNull(obj);
            }

            file.Delete();
        }