Advertisement
Guest User

Untitled

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