Advertisement
Guest User

Untitled

a guest
Mar 7th, 2017
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 36.02 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Text;
  11.  
  12. namespace DownloaderPro
  13. {
  14. #region FileDownloader
  15. /// <summary>Class for downloading files in the background that supports info about their progress, the total progress, cancellation, pausing, and resuming. The downloads will run on a separate thread so you don't have to worry about multihreading yourself. </summary>
  16.  
  17. class FileDownloader : System.Object, IDisposable
  18. {
  19. #region Nested Types
  20. /// <summary>Simple struct for managing file info</summary>
  21. public struct FileInfo
  22. {
  23. /// <summary>The complete path of the file (directory + filename)</summary>
  24. public string Path;
  25. /// <summary>The name of the file</summary>
  26. public string Name;
  27.  
  28. /// <summary>Create a new instance of FileInfo</summary>
  29. /// <param name="path">The complete path of the file (directory + filename)</param>
  30. Form1 form1;
  31. public FileInfo(String path, Form1 form1)
  32. {
  33. this.form1 = form1;
  34. /*this.Path = path;
  35. var startIndex = Path.IndexOf("time=") + "time=".Length;
  36. var length = Path.IndexOf("&", startIndex) - startIndex;
  37. var time = Path.Substring(startIndex, length);
  38. this.Name = time;*/
  39.  
  40. this.Path = path;
  41. var startIndex = Path.IndexOf("animated/") + "animated/".Length;
  42. var length = Path.IndexOf("/", startIndex) - startIndex;
  43. var code = Path.Substring(startIndex, length);
  44. var countryName = form1.codeToFullNameMap[code];
  45. this.Name = countryName;
  46.  
  47. /*var startIndexCode = path.IndexOf("region=") + "region=".Length;
  48. var lengthCode = path.IndexOf("&", startIndexCode) - startIndexCode;
  49. var code = path.Substring(startIndexCode, lengthCode);
  50. this.Name = time + code;*/
  51. }
  52.  
  53. }
  54.  
  55. /// <summary>Holder for events that are triggered in the background worker but need to be fired in the main thread</summary>
  56. private enum Event
  57. {
  58. CalculationFileSizesStarted,
  59.  
  60. FileSizesCalculationComplete,
  61. DeletingFilesAfterCancel,
  62.  
  63. FileDownloadAttempting,
  64. FileDownloadStarted,
  65. FileDownloadStopped,
  66. FileDownloadSucceeded,
  67.  
  68. ProgressChanged
  69. };
  70.  
  71. /// <summary>Holder for the action that needs to be invoked</summary>
  72. private enum InvokeType
  73. {
  74. EventRaiser,
  75. FileDownloadFailedRaiser,
  76. CalculatingFileNrRaiser
  77. };
  78. #endregion
  79.  
  80. #region Events
  81. /// <summary>Occurs when the file downloading has started</summary>
  82. public event EventHandler Started;
  83. /// <summary>Occurs when the file downloading has been paused</summary>
  84. public event EventHandler Paused;
  85. /// <summary>Occurs when the file downloading has been resumed</summary>
  86. public event EventHandler Resumed;
  87. /// <summary>Occurs when the user has requested to cancel the downloads</summary>
  88. public event EventHandler CancelRequested;
  89. /// <summary>Occurs when the user has requested to cancel the downloads and the cleanup of the downloaded files has started</summary>
  90. public event EventHandler DeletingFilesAfterCancel;
  91. /// <summary>Occurs when the file downloading has been canceled by the user</summary>
  92. public event EventHandler Canceled;
  93. /// <summary>Occurs when the file downloading has been completed (without canceling it)</summary>
  94. public event EventHandler Completed;
  95. /// <summary>Occurs when the file downloading has been stopped by either cancellation or completion</summary>
  96. public event EventHandler Stopped;
  97.  
  98. /// <summary>Occurs when the busy state of the FileDownloader has changed</summary>
  99. public event EventHandler IsBusyChanged;
  100. /// <summary>Occurs when the pause state of the FileDownloader has changed</summary>
  101. public event EventHandler IsPausedChanged;
  102. /// <summary>Occurs when the either the busy or pause state of the FileDownloader have changed</summary>
  103. public event EventHandler StateChanged;
  104.  
  105. /// <summary>Occurs when the calculation of the file sizes has started</summary>
  106. public event EventHandler CalculationFileSizesStarted;
  107. /// <summary>Occurs when the calculation of the file sizes has started</summary>
  108. public event CalculatingFileSizeEventHandler CalculatingFileSize;
  109. /// <summary>Occurs when the calculation of the file sizes has been completed</summary>
  110. public event EventHandler FileSizesCalculationComplete;
  111.  
  112. /// <summary>Occurs when the FileDownloader attempts to get a web response to download the file</summary>
  113. public event EventHandler FileDownloadAttempting;
  114. /// <summary>Occurs when a file download has started</summary>
  115. public event EventHandler FileDownloadStarted;
  116. /// <summary>Occurs when a file download has stopped</summary>
  117. public event EventHandler FileDownloadStopped;
  118. /// <summary>Occurs when a file download has been completed successfully</summary>
  119. public event EventHandler FileDownloadSucceeded;
  120. /// <summary>Occurs when a file download has been completed unsuccessfully</summary>
  121. public event FailEventHandler FileDownloadFailed;
  122.  
  123. /// <summary>Occurs every time a block of data has been downloaded</summary>
  124. public event EventHandler ProgressChanged;
  125. #endregion
  126.  
  127. #region Fields
  128. // Default amount of decimals
  129. private const Int32 default_decimals = 2;
  130.  
  131. // Delegates
  132. public delegate void FailEventHandler(object sender, Exception ex);
  133. public delegate void CalculatingFileSizeEventHandler(object sender, Int32 fileNr);
  134.  
  135. // The download worker
  136. private BackgroundWorker bgwDownloader = new BackgroundWorker();
  137.  
  138. // Preferences
  139. private Boolean m_supportsProgress, m_deleteCompletedFiles;
  140. private Int32 m_packageSize, m_stopWatchCycles;
  141.  
  142. // State
  143. private Boolean m_disposed = false;
  144. private Boolean m_busy, m_paused, m_canceled;
  145. private Int64 m_currentFileProgress, m_totalProgress, m_currentFileSize;
  146. private Int32 m_currentSpeed, m_fileNr;
  147. private int countFilesNames = 0;
  148.  
  149. // Data
  150. private String m_localDirectory;
  151. private List<FileInfo> m_files = new List<FileInfo>();
  152. private Int64 m_totalSize;
  153.  
  154. #endregion
  155.  
  156. #region Constructors
  157. /// <summary>Create a new instance of a FileDownloader</summary>
  158.  
  159. public Form1 form1;
  160. public FileDownloader(Form1 form1)
  161. {
  162. this.form1 = form1;
  163. this.initizalize(false);
  164. }
  165.  
  166. /// <summary>Create a new instance of a FileDownloader</summary>
  167. /// <param name="supportsProgress">Optional. Boolean. Should the FileDownloader support total progress statistics?</param>
  168. public FileDownloader(Boolean supportsProgress)
  169. {
  170. this.initizalize(supportsProgress);
  171. }
  172.  
  173. private void initizalize(Boolean supportsProgress)
  174. {
  175. // Set the bgw properties
  176. bgwDownloader.WorkerReportsProgress = true;
  177. bgwDownloader.WorkerSupportsCancellation = true;
  178. bgwDownloader.DoWork += new DoWorkEventHandler(bgwDownloader_DoWork);
  179. bgwDownloader.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgwDownloader_RunWorkerCompleted);
  180. bgwDownloader.ProgressChanged += new ProgressChangedEventHandler(bgwDownloader_ProgressChanged);
  181.  
  182. // Set the default class preferences
  183. this.SupportsProgress = supportsProgress;
  184. this.PackageSize = 4096;
  185. this.StopWatchCyclesAmount = 5;
  186. this.DeleteCompletedFilesAfterCancel = true;
  187. }
  188. #endregion
  189.  
  190. #region Public methods
  191. public void Start() { this.IsBusy = true; }
  192.  
  193. public void Pause() { this.IsPaused = true; }
  194.  
  195. public void Resume() { this.IsPaused = false; }
  196.  
  197. public void Stop() { this.IsBusy = false; }
  198. public void Stop(Boolean deleteCompletedFiles)
  199. {
  200. this.DeleteCompletedFilesAfterCancel = deleteCompletedFiles;
  201. this.Stop();
  202. }
  203.  
  204. public void Dispose()
  205. {
  206. Dispose(true);
  207. GC.SuppressFinalize(this);
  208. }
  209.  
  210. #region Size formatting functions
  211. /// <summary>Format an amount of bytes to a more readible notation with binary notation symbols</summary>
  212. /// <param name="size">Required. Int64. The raw amount of bytes</param>
  213. public static string FormatSizeBinary(Int64 size)
  214. {
  215. return FileDownloader.FormatSizeBinary(size, default_decimals);
  216. }
  217.  
  218. /// <summary>Format an amount of bytes to a more readible notation with binary notation symbols</summary>
  219. /// <param name="size">Required. Int64. The raw amount of bytes</param>
  220. /// <param name="decimals">Optional. Int32. The amount of decimals you want to have displayed in the notation</param>
  221. public static string FormatSizeBinary(Int64 size, Int32 decimals)
  222. {
  223. // By De Dauw Jeroen - April 2009 - jeroen_dedauw@yahoo.com
  224. String[] sizes = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB" };
  225. Double formattedSize = size;
  226. Int32 sizeIndex = 0;
  227. while (formattedSize >= 1024 && sizeIndex < sizes.Length)
  228. {
  229. formattedSize /= 1024;
  230. sizeIndex += 1;
  231. }
  232. return Math.Round(formattedSize, decimals) + sizes[sizeIndex];
  233. }
  234.  
  235. /// <summary>Format an amount of bytes to a more readible notation with decimal notation symbols</summary>
  236. /// <param name="size">Required. Int64. The raw amount of bytes</param>
  237. public static string FormatSizeDecimal(Int64 size)
  238. {
  239. return FileDownloader.FormatSizeDecimal(size, default_decimals);
  240. }
  241.  
  242. /// <summary>Format an amount of bytes to a more readible notation with decimal notation symbols</summary>
  243. /// <param name="size">Required. Int64. The raw amount of bytes</param>
  244. /// <param name="decimals">Optional. Int32. The amount of decimals you want to have displayed in the notation</param>
  245. public static string FormatSizeDecimal(Int64 size, Int32 decimals)
  246. {
  247. // By De Dauw Jeroen - April 2009 - jeroen_dedauw@yahoo.com
  248. String[] sizes = { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
  249. Double formattedSize = size;
  250. Int32 sizeIndex = 0;
  251. while (formattedSize >= 1000 && sizeIndex < sizes.Length)
  252. {
  253. formattedSize /= 1000;
  254. sizeIndex += 1;
  255. }
  256. return Math.Round(formattedSize, decimals) + sizes[sizeIndex];
  257. }
  258. #endregion
  259.  
  260. #endregion
  261.  
  262. #region Protected methods
  263. protected virtual void Dispose(Boolean disposing)
  264. {
  265. if (!m_disposed)
  266. {
  267. if (disposing)
  268. {
  269. // Free other state (managed objects)
  270. bgwDownloader.Dispose();
  271. }
  272. // Free your own state (unmanaged objects)
  273. // Set large fields to null
  274. this.Files = null;
  275. }
  276. }
  277. #endregion
  278.  
  279. #region Private methods
  280. private void bgwDownloader_DoWork(object sender, DoWorkEventArgs e)
  281. {
  282. Int32 fileNr = 0;
  283. countFilesNames = 0;
  284.  
  285. if (this.SupportsProgress) { calculateFilesSize(); }
  286.  
  287. if (!Directory.Exists(this.LocalDirectory)) { Directory.CreateDirectory(this.LocalDirectory); }
  288.  
  289. while (fileNr < this.Files.Count && !bgwDownloader.CancellationPending)
  290. {
  291. m_fileNr = fileNr;
  292. downloadFile(fileNr);
  293.  
  294. if (bgwDownloader.CancellationPending)
  295. {
  296. fireEventFromBgw(Event.DeletingFilesAfterCancel);
  297. cleanUpFiles(this.DeleteCompletedFilesAfterCancel ? 0 : m_fileNr, this.DeleteCompletedFilesAfterCancel ? m_fileNr + 1 : 1);
  298. }
  299. else
  300. {
  301. fileNr += 1;
  302. }
  303. }
  304. }
  305.  
  306. private void calculateFilesSize()
  307. {
  308. fireEventFromBgw(Event.CalculationFileSizesStarted);
  309. m_totalSize = 0;
  310.  
  311. for (Int32 fileNr = 0; fileNr < this.Files.Count; fileNr++)
  312. {
  313. bgwDownloader.ReportProgress((Int32)InvokeType.CalculatingFileNrRaiser, fileNr + 1);
  314. try
  315. {
  316. HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(this.Files[fileNr].Path);
  317. HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
  318. m_totalSize += webResp.ContentLength;
  319. webResp.Close();
  320. }
  321. catch (Exception err)
  322. {
  323. // to find out what to do and what to report when it's getting here
  324. // it can't get the file size what to do ?
  325. }
  326. }
  327. fireEventFromBgw(Event.FileSizesCalculationComplete);
  328. }
  329.  
  330. private void fireEventFromBgw(Event eventName)
  331. {
  332. bgwDownloader.ReportProgress((int)InvokeType.EventRaiser, eventName);
  333. }
  334.  
  335. private void downloadFile(Int32 fileNr)
  336. {
  337. FileStream writer = null;
  338. m_currentFileSize = 0;
  339. fireEventFromBgw(Event.FileDownloadAttempting);
  340.  
  341. FileInfo file = this.Files[fileNr];
  342. FileInfo fileFirstDateTime = this.Files[0];
  343. FileInfo fileLastDateTime = this.Files[19];
  344. Int64 size = 0;
  345.  
  346. Byte[] readBytes = new Byte[this.PackageSize];
  347. Int32 currentPackageSize;
  348. System.Diagnostics.Stopwatch speedTimer = new System.Diagnostics.Stopwatch();
  349. Int32 readings = 0;
  350. Exception exc = null;
  351.  
  352. // Problem here with the FileStream writer
  353. // Maybe the file name is wrong to find what to do and how to fix
  354. // To try to add here try and catch around the FileStream writer
  355.  
  356. if (form1.checkBox1.Text == "Download satellite images")
  357. {
  358. writer = LocalDirectorySettings(file);
  359. }
  360. else
  361. {
  362. writer = LocalDirectorySettings(file);
  363. //writer = new FileStream(this.LocalDirectory + "\\" + file.Name + ".gif", System.IO.FileMode.Create);
  364. }
  365.  
  366.  
  367. HttpWebRequest webReq;
  368. HttpWebResponse webResp = null;
  369.  
  370. try
  371. {
  372. webReq = (HttpWebRequest)System.Net.WebRequest.Create(this.Files[fileNr].Path);
  373. webResp = (HttpWebResponse)webReq.GetResponse();
  374.  
  375. size = webResp.ContentLength;
  376. }
  377. catch (Exception ex) { exc = ex; }
  378.  
  379. m_currentFileSize = size;
  380. fireEventFromBgw(Event.FileDownloadStarted);
  381.  
  382. if (exc != null)
  383. {
  384. bgwDownloader.ReportProgress((Int32)InvokeType.FileDownloadFailedRaiser, exc);
  385. }
  386. else
  387. {
  388. m_currentFileProgress = 0;
  389. while (m_currentFileProgress < size && !bgwDownloader.CancellationPending)
  390. {
  391. while (this.IsPaused) { System.Threading.Thread.Sleep(100); }
  392.  
  393. speedTimer.Start();
  394.  
  395. currentPackageSize = webResp.GetResponseStream().Read(readBytes, 0, this.PackageSize);
  396.  
  397. m_currentFileProgress += currentPackageSize;
  398. m_totalProgress += currentPackageSize;
  399. fireEventFromBgw(Event.ProgressChanged);
  400. try
  401. {
  402. writer.Write(readBytes, 0, currentPackageSize);
  403. }
  404. catch(Exception eee)
  405. {
  406. string myeee = eee.ToString();
  407. }
  408. readings += 1;
  409.  
  410. if (readings >= this.StopWatchCyclesAmount)
  411. {
  412. m_currentSpeed = (Int32)(this.PackageSize * StopWatchCyclesAmount * 1000 / (speedTimer.ElapsedMilliseconds + 1));
  413. speedTimer.Reset();
  414. readings = 0;
  415. }
  416. }
  417.  
  418. speedTimer.Stop();
  419. writer.Close();
  420. webResp.Close();
  421. if (!bgwDownloader.CancellationPending) { fireEventFromBgw(Event.FileDownloadSucceeded); }
  422. }
  423. fireEventFromBgw(Event.FileDownloadStopped);
  424. }
  425.  
  426. public string fileName;
  427. public FileStream LocalDirectorySettings(FileInfo file)
  428. {
  429. try
  430. {
  431. /*var startIndex = file.Path.IndexOf("region=") + "region=".Length;
  432. var length = file.Path.IndexOf("&", startIndex) - startIndex;
  433. var code = file.Path.Substring(startIndex, length);
  434. var countryName = form1.codeToFullNameMap[code];
  435.  
  436. string firstDT = ParseDateTime(this.Files[0]);
  437. string lastDT = ParseDateTime(this.Files[19]);
  438. string subDirectoryDT = firstDT + "---" + lastDT;
  439.  
  440. string countryPath = Path.Combine(form1.mainPath, countryName);
  441. LocalDirectory = countryPath + "\\" + subDirectoryDT;*/
  442. string path = Path.Combine(LocalDirectory, file.Name);
  443. string pathWithTimeAndDateStamp = Path.Combine(path, DateTime.Now.ToString("ddMMyyyy_HHmmss"));
  444. fileName = Path.Combine(pathWithTimeAndDateStamp, file.Name + "---" + DateTime.Now.ToString("ddMMyyyy_HHmmssfff") + ".gif");
  445.  
  446. if (!Directory.Exists(pathWithTimeAndDateStamp))
  447. {
  448. Directory.CreateDirectory(pathWithTimeAndDateStamp);
  449. }
  450.  
  451. return new FileStream(fileName, System.IO.FileMode.Create);
  452. }
  453. catch (Exception err)
  454. {
  455. throw;
  456. }
  457. }
  458.  
  459. private string ParseDateTime(FileInfo file)
  460. {
  461. var startIndexTimeDate = file.Path.IndexOf("time=") + "time=".Length;
  462. var lengthTimeDate = file.Path.IndexOf("&", startIndexTimeDate) - startIndexTimeDate;
  463. var timeDate = file.Path.Substring(startIndexTimeDate, lengthTimeDate);
  464.  
  465. var date = DateTime.ParseExact(timeDate, "yyyyMMddHHmm", CultureInfo.InvariantCulture);
  466. var dirName = date.ToString("dd-MM-HH-mm-yyyy"); //01-02-20-15-2017
  467.  
  468. return dirName;
  469. }
  470.  
  471. private void cleanUpFiles(Int32 start, Int32 length)
  472. {
  473. Int32 last = length < 0 ? this.Files.Count -1 : start + length - 1;
  474.  
  475. for (Int32 fileNr = start; fileNr <= last; fileNr++)
  476. {
  477. String fullPath = this.LocalDirectory + "\\" + this.Files[fileNr].Name;
  478. if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); }
  479. }
  480. }
  481.  
  482. private void bgwDownloader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  483. {
  484. m_paused = false;
  485. m_busy = false;
  486.  
  487. if (this.HasBeenCanceled)
  488. {
  489. if (Canceled != null) { this.Canceled(this, new EventArgs()); }
  490. }
  491. else
  492. {
  493. if (Completed != null)
  494. {
  495. this.Completed(this, new EventArgs());
  496. }
  497. }
  498.  
  499. if (Stopped != null) { this.Stopped(this, new EventArgs()); }
  500. if (IsBusyChanged != null) { this.IsBusyChanged(this, new EventArgs()); }
  501. if (StateChanged != null) { this.StateChanged(this, new EventArgs()); }
  502. }
  503.  
  504. private void bgwDownloader_ProgressChanged(object sender, ProgressChangedEventArgs e)
  505. {
  506. switch ((InvokeType)e.ProgressPercentage)
  507. {
  508. case InvokeType.EventRaiser:
  509. switch ((Event)e.UserState)
  510. {
  511. case Event.CalculationFileSizesStarted:
  512. if (CalculationFileSizesStarted != null) { this.CalculationFileSizesStarted(this, new EventArgs()); }
  513. break;
  514. case Event.FileSizesCalculationComplete:
  515. if (FileSizesCalculationComplete != null) { this.FileSizesCalculationComplete(this, new EventArgs()); }
  516. break;
  517. case Event.DeletingFilesAfterCancel:
  518. if (DeletingFilesAfterCancel != null) { this.DeletingFilesAfterCancel(this, new EventArgs()); }
  519. break;
  520.  
  521. case Event.FileDownloadAttempting:
  522. if (FileDownloadAttempting != null) { this.FileDownloadAttempting(this, new EventArgs()); }
  523. break;
  524. case Event.FileDownloadStarted:
  525. if (FileDownloadStarted != null) { this.FileDownloadStarted(this, new EventArgs()); }
  526. break;
  527. case Event.FileDownloadStopped:
  528. if (FileDownloadStopped != null) { this.FileDownloadStopped(this, new EventArgs()); }
  529. break;
  530. case Event.FileDownloadSucceeded:
  531. if (FileDownloadSucceeded != null) { this.FileDownloadSucceeded(this, new EventArgs()); }
  532. break;
  533. case Event.ProgressChanged:
  534. if (ProgressChanged != null) { this.ProgressChanged(this, new EventArgs()); }
  535. break;
  536. }
  537. break;
  538. case InvokeType.FileDownloadFailedRaiser:
  539. if (FileDownloadFailed != null) { this.FileDownloadFailed(this, (Exception)e.UserState); }
  540. break;
  541. case InvokeType.CalculatingFileNrRaiser:
  542. if (CalculatingFileSize != null) { this.CalculatingFileSize(this, (Int32)e.UserState); }
  543. break;
  544. }
  545. }
  546.  
  547. public static Image[] GetFramesFromAnimatedGIF(Image IMG)
  548. {
  549. List<Image> IMGs = new List<Image>();
  550. int Length = IMG.GetFrameCount(FrameDimension.Time);
  551.  
  552. for (int i = 0; i < Length; i++)
  553. {
  554. IMG.SelectActiveFrame(FrameDimension.Time, i);
  555. IMGs.Add(new Bitmap(IMG));
  556. IMG.Dispose();
  557. }
  558.  
  559. return IMGs.ToArray();
  560. }
  561.  
  562. #endregion
  563.  
  564. #region Properties
  565. /// <summary>Gets or sets the list of files to download</summary>
  566. public List<FileInfo> Files
  567. {
  568. get { return m_files; }
  569. set
  570. {
  571. if (this.IsBusy)
  572. {
  573. throw new InvalidOperationException("You can not change the file list during the download");
  574. }
  575. else
  576. {
  577. if (this.Files != null) m_files = value;
  578. }
  579. }
  580. }
  581.  
  582. /// <summary>Gets or sets the local directory in which files will be stored</summary>
  583. public String LocalDirectory
  584. {
  585. get { return m_localDirectory; }
  586. set
  587. {
  588. if (this.LocalDirectory != value) { m_localDirectory = value; }
  589. }
  590. }
  591.  
  592. /// <summary>Gets or sets if the FileDownloader should support total progress statistics. Note that when enabled, the FileDownloader will have to get the size of each file before starting to download them, which can delay the operation.</summary>
  593. public Boolean SupportsProgress
  594. {
  595. get { return m_supportsProgress; }
  596. set
  597. {
  598. if (this.IsBusy)
  599. {
  600. throw new InvalidOperationException("You can not change the SupportsProgress property during the download");
  601. }
  602. else
  603. {
  604. m_supportsProgress = value;
  605. }
  606. }
  607. }
  608.  
  609. /// <summary>Gets or sets if when the download process is cancelled the complete downloads should be deleted</summary>
  610. public Boolean DeleteCompletedFilesAfterCancel
  611. {
  612. get { return m_deleteCompletedFiles; }
  613. set { m_deleteCompletedFiles = value; }
  614. }
  615.  
  616. /// <summary>Gets or sets the size of the blocks that will be downloaded</summary>
  617. public Int32 PackageSize
  618. {
  619. get { return m_packageSize; }
  620. set
  621. {
  622. if (value > 0)
  623. {
  624. m_packageSize = value;
  625. }
  626. else
  627. {
  628. throw new InvalidOperationException("The PackageSize needs to be greather then 0");
  629. }
  630. }
  631. }
  632.  
  633. /// <summary>Gets or sets the amount of blocks that need to be downloaded before the progress speed is re-calculated. Note: setting this to a low value might decrease the accuracy</summary>
  634. public Int32 StopWatchCyclesAmount
  635. {
  636. get { return m_stopWatchCycles; }
  637. set
  638. {
  639. if (value > 0)
  640. {
  641. m_stopWatchCycles = value;
  642. }
  643. else
  644. {
  645. throw new InvalidOperationException("The StopWatchCyclesAmount needs to be greather then 0");
  646. }
  647. }
  648. }
  649.  
  650. /// <summary>Gets or sets the busy state of the FileDownloader</summary>
  651. public Boolean IsBusy
  652. {
  653. get { return m_busy; }
  654. set
  655. {
  656. if (this.IsBusy != value)
  657. {
  658. m_busy = value;
  659. m_canceled = !value;
  660. if (this.IsBusy)
  661. {
  662. m_totalProgress = 0;
  663. bgwDownloader.RunWorkerAsync();
  664.  
  665. if (Started != null) { this.Started(this, new EventArgs()); }
  666. if (IsBusyChanged != null) { this.IsBusyChanged(this, new EventArgs()); }
  667. if (StateChanged != null) { this.StateChanged(this, new EventArgs()); }
  668. }
  669. else
  670. {
  671. m_paused = false;
  672. bgwDownloader.CancelAsync();
  673. if (CancelRequested != null) { this.CancelRequested(this, new EventArgs()); }
  674. if (StateChanged != null) { this.StateChanged(this, new EventArgs()); }
  675. }
  676. }
  677. }
  678. }
  679.  
  680. /// <summary>Gets or sets the pause state of the FileDownloader</summary>
  681. public Boolean IsPaused
  682. {
  683. get { return m_paused; }
  684. set
  685. {
  686. if (this.IsBusy)
  687. {
  688. if (this.IsPaused != value)
  689. {
  690. m_paused = value;
  691. if (this.IsPaused)
  692. {
  693. if (Paused != null) { this.Paused(this, new EventArgs()); }
  694. }
  695. else
  696. {
  697. if (Resumed != null) { this.Resumed(this, new EventArgs()); }
  698. }
  699. if (IsPausedChanged != null) { this.IsPausedChanged(this, new EventArgs()); }
  700. if (StateChanged != null) { this.StateChanged(this, new EventArgs()); }
  701. }
  702. }
  703. else
  704. {
  705. throw new InvalidOperationException("You can not change the IsPaused property when the FileDownloader is not busy");
  706. }
  707. }
  708. }
  709.  
  710. /// <summary>Gets if the FileDownloader can start</summary>
  711. public Boolean CanStart
  712. {
  713. get { return !this.IsBusy; }
  714. }
  715.  
  716. /// <summary>Gets if the FileDownloader can pause</summary>
  717. public Boolean CanPause
  718. {
  719. get { return this.IsBusy && !this.IsPaused && !bgwDownloader.CancellationPending; }
  720. }
  721.  
  722. /// <summary>Gets if the FileDownloader can resume</summary>
  723. public Boolean CanResume
  724. {
  725. get { return this.IsBusy && this.IsPaused && !bgwDownloader.CancellationPending; }
  726. }
  727.  
  728. /// <summary>Gets if the FileDownloader can stop</summary>
  729. public Boolean CanStop
  730. {
  731. get { return this.IsBusy && !bgwDownloader.CancellationPending; }
  732. }
  733.  
  734. /// <summary>Gets the total size of all files together. Only avaible when the FileDownloader suports progress</summary>
  735. public Int64 TotalSize
  736. {
  737. get
  738. {
  739. if (this.SupportsProgress)
  740. {
  741. return m_totalSize;
  742. }
  743. else
  744. {
  745. throw new InvalidOperationException("This FileDownloader that it doesn't support progress. Modify SupportsProgress to state that it does support progress to get the total size.");
  746. }
  747. }
  748. }
  749.  
  750. /// <summary>Gets the total amount of bytes downloaded</summary>
  751. public Int64 TotalProgress
  752. {
  753. get { return m_totalProgress; }
  754. }
  755.  
  756. /// <summary>Gets the amount of bytes downloaded of the current file</summary>
  757. public Int64 CurrentFileProgress
  758. {
  759. get { return m_currentFileProgress; }
  760. }
  761.  
  762. /// <summary>Gets the total download percentage. Only avaible when the FileDownloader suports progress</summary>
  763. public Double TotalPercentage()
  764. {
  765. return this.TotalPercentage(default_decimals);
  766. }
  767.  
  768. /// <summary>Gets the total download percentage. Only avaible when the FileDownloader suports progress</summary>
  769. public Double TotalPercentage(Int32 decimals)
  770. {
  771. if (this.SupportsProgress)
  772. {
  773. return Math.Round((Double)this.TotalProgress / this.TotalSize * 100, decimals);
  774. }
  775. else
  776. {
  777. throw new InvalidOperationException("This FileDownloader that it doesn't support progress. Modify SupportsProgress to state that it does support progress.");
  778. }
  779. }
  780.  
  781. /// <summary>Gets the percentage of the current file progress</summary>
  782. public Double CurrentFilePercentage()
  783. {
  784. return this.CurrentFilePercentage(default_decimals);
  785. }
  786.  
  787. /// <summary>Gets the percentage of the current file progress</summary>
  788. public Double CurrentFilePercentage(Int32 decimals)
  789. {
  790. return Math.Round((Double)this.CurrentFileProgress / this.CurrentFileSize * 100, decimals);
  791. }
  792.  
  793. /// <summary>Gets the current download speed in bytes</summary>
  794. public Int32 DownloadSpeed
  795. {
  796. get { return m_currentSpeed; }
  797. }
  798.  
  799. /// <summary>Gets the FileInfo object representing the current file</summary>
  800. public FileInfo CurrentFile
  801. {
  802. get { return this.Files[m_fileNr]; }
  803. }
  804.  
  805. /// <summary>Gets the size of the current file in bytes</summary>
  806. public Int64 CurrentFileSize
  807. {
  808. get { return m_currentFileSize; }
  809. }
  810.  
  811. /// <summary>Gets if the last download was canceled by the user</summary>
  812. public Boolean HasBeenCanceled
  813. {
  814. get { return m_canceled; }
  815. }
  816. #endregion
  817.  
  818. }
  819. #endregion
  820. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement