PageRenderTime 43ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/Visual Studio 2008/CSFTPDownload/MainForm.cs

#
C# | 358 lines | 222 code | 63 blank | 73 comment | 21 complexity | 0b7517276b5c331d7fb16aefc95b1bb5 MD5 | raw file
  1. /****************************** Module Header ******************************\
  2. * Module Name: MainForm.cs
  3. * Project: CSFTPDownload
  4. * Copyright (c) Microsoft Corporation.
  5. *
  6. * This is the main form of this application. It is used to initialize the UI and
  7. * handle the events.
  8. *
  9. * This source is subject to the Microsoft Public License.
  10. * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
  11. * All other rights reserved.
  12. *
  13. * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
  14. * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
  15. * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
  16. \***************************************************************************/
  17. using System;
  18. using System.Linq;
  19. using System.Net;
  20. using System.Windows.Forms;
  21. namespace CSFTPDownload
  22. {
  23. public partial class MainForm : Form
  24. {
  25. FTPClientManager client = null;
  26. NetworkCredential currentCredentials = null;
  27. public MainForm()
  28. {
  29. InitializeComponent();
  30. }
  31. #region URL navigation
  32. /// <summary>
  33. /// Handle the Click event of btnConnect.
  34. /// </summary>
  35. private void btnConnect_Click(object sender, EventArgs e)
  36. {
  37. // Connect to server specified by tbFTPServer.Text.
  38. Connect(this.tbFTPServer.Text.Trim());
  39. }
  40. void Connect(string urlStr)
  41. {
  42. try
  43. {
  44. Uri url = new Uri(urlStr);
  45. // The schema of url must be ftp.
  46. if (!url.Scheme.Equals("ftp", StringComparison.OrdinalIgnoreCase))
  47. {
  48. throw new ApplicationException("The schema of url must be ftp. ");
  49. }
  50. // Set the url to the folder that contains this file.
  51. if (url.IsFile)
  52. {
  53. url = new Uri(url, "..");
  54. }
  55. // Show the Form UICredentialsProvider to get new Credentials.
  56. using (UICredentialsProvider provider =
  57. new UICredentialsProvider(this.currentCredentials))
  58. {
  59. // Show the Form UICredentialsProvider as a dialog.
  60. var result = provider.ShowDialog();
  61. // If user typed the Credentials and pressed the "OK" button.
  62. if (result == System.Windows.Forms.DialogResult.OK)
  63. {
  64. // Reset the current Credentials.
  65. this.currentCredentials = provider.Credentials;
  66. }
  67. else
  68. {
  69. return;
  70. }
  71. }
  72. // Initialize the FTPClient instance.
  73. client = new FTPClientManager(url, currentCredentials);
  74. client.UrlChanged += new EventHandler(client_UrlChanged);
  75. client.StatusChanged += new EventHandler(client_StatusChanged);
  76. client.ErrorOccurred += new EventHandler<ErrorEventArgs>(client_ErrorOccurred);
  77. client.FileDownloadCompleted +=
  78. new EventHandler<FileDownloadCompletedEventArgs>(client_FileDownloadCompleted);
  79. client.NewMessageArrived +=
  80. new EventHandler<NewMessageEventArg>(client_NewMessageArrived);
  81. // List the sub directories and files.
  82. RefreshSubDirectoriesAndFiles();
  83. }
  84. catch (System.Net.WebException webEx)
  85. {
  86. if ((webEx.Response as FtpWebResponse).StatusCode == FtpStatusCode.NotLoggedIn)
  87. {
  88. // Reconnect the server.
  89. Connect(urlStr);
  90. return;
  91. }
  92. else
  93. {
  94. MessageBox.Show(webEx.Message);
  95. }
  96. }
  97. catch (Exception ex)
  98. {
  99. MessageBox.Show(ex.Message);
  100. }
  101. }
  102. /// <summary>
  103. /// Log the message of FTPClient.
  104. /// </summary>
  105. void client_NewMessageArrived(object sender, NewMessageEventArg e)
  106. {
  107. this.Invoke(new EventHandler<NewMessageEventArg>(
  108. client_NewMessageArrivedHandler),sender,e);
  109. }
  110. void client_NewMessageArrivedHandler(object sender, NewMessageEventArg e)
  111. {
  112. string log = string.Format("{0} {1}",
  113. DateTime.Now, e.NewMessage);
  114. this.lstLog.Items.Add(log);
  115. this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
  116. }
  117. /// <summary>
  118. /// Log the FileDownloadCompleted event when a file was downloaded.
  119. /// </summary>
  120. void client_FileDownloadCompleted(object sender, FileDownloadCompletedEventArgs e)
  121. {
  122. this.Invoke(new EventHandler<FileDownloadCompletedEventArgs>(
  123. client_FileDownloadCompletedHandler), sender, e);
  124. }
  125. void client_FileDownloadCompletedHandler(object sender, FileDownloadCompletedEventArgs e)
  126. {
  127. string log = string.Format("{0} Download from {1} to {2} is completed. Length: {3}. ",
  128. DateTime.Now, e.ServerPath, e.LocalFile.FullName, e.LocalFile.Length);
  129. this.lstLog.Items.Add(log);
  130. this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
  131. }
  132. /// <summary>
  133. /// Log the ErrorOccurred event if there was an error.
  134. /// </summary>
  135. void client_ErrorOccurred(object sender, ErrorEventArgs e)
  136. {
  137. this.Invoke(new EventHandler<ErrorEventArgs>(
  138. client_ErrorOccurredHandler), sender, e);
  139. }
  140. void client_ErrorOccurredHandler(object sender, ErrorEventArgs e)
  141. {
  142. this.lstLog.Items.Add(
  143. string.Format("{0} {1} ", DateTime.Now, e.ErrorException.Message));
  144. var innerException = e.ErrorException.InnerException;
  145. // Log all the innerException.
  146. while (innerException != null)
  147. {
  148. this.lstLog.Items.Add(
  149. string.Format("\t\t\t {0} ", innerException.Message));
  150. innerException = innerException.InnerException;
  151. }
  152. this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
  153. }
  154. /// <summary>
  155. /// Refresh the UI if the Status of the FTPClient changed.
  156. /// </summary>
  157. void client_StatusChanged(object sender, EventArgs e)
  158. {
  159. this.Invoke(new EventHandler(client_StatusChangedHandler), sender, e);
  160. }
  161. void client_StatusChangedHandler(object sender, EventArgs e)
  162. {
  163. // Disable all the buttons if the client is downloading file.
  164. if (client.Status == FTPClientManagerStatus.Downloading)
  165. {
  166. btnBrowseDownloadPath.Enabled = false;
  167. btnConnect.Enabled = false;
  168. btnDownload.Enabled = false;
  169. btnNavigateParentFolder.Enabled = false;
  170. lstFileExplorer.Enabled = false;
  171. }
  172. else
  173. {
  174. btnBrowseDownloadPath.Enabled = true;
  175. btnConnect.Enabled = true;
  176. btnDownload.Enabled = true;
  177. btnNavigateParentFolder.Enabled = true;
  178. lstFileExplorer.Enabled = true;
  179. }
  180. string log = string.Format("{0} FTPClient status changed to {1}. ",
  181. DateTime.Now, client.Status.ToString());
  182. this.lstLog.Items.Add(log);
  183. this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
  184. }
  185. /// <summary>
  186. /// Handle the UrlChanged event of the FTPClient.
  187. /// </summary>
  188. void client_UrlChanged(object sender, EventArgs e)
  189. {
  190. this.Invoke(new EventHandler(client_UrlChangedHandler), sender, e);
  191. }
  192. void client_UrlChangedHandler(object sender, EventArgs e)
  193. {
  194. RefreshSubDirectoriesAndFiles();
  195. string log = string.Format("{0} The current url changed to {1}. ",
  196. DateTime.Now, client.Url);
  197. this.lstLog.Items.Add(log);
  198. this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
  199. }
  200. /// <summary>
  201. /// Handle the DoubleClick event of lstFileExplorer.
  202. /// </summary>
  203. private void lstFileExplorer_DoubleClick(object sender, EventArgs e)
  204. {
  205. // if only one item is selected and the item represents a folder, then navigate
  206. // to a subDirectory.
  207. if (lstFileExplorer.SelectedItems.Count == 1
  208. && (lstFileExplorer.SelectedItem as FTPFileSystem).IsDirectory)
  209. {
  210. this.client.Naviagte(
  211. (lstFileExplorer.SelectedItem as FTPFileSystem).Url);
  212. }
  213. }
  214. /// <summary>
  215. /// Handle the Click event of btnNavigateParentFolder.
  216. /// </summary>
  217. /// <param name="sender"></param>
  218. /// <param name="e"></param>
  219. private void btnNavigateParentFolder_Click(object sender, EventArgs e)
  220. {
  221. // Navigate to the parent folder.
  222. this.client.NavigateParent();
  223. }
  224. /// <summary>
  225. /// List the sub directories and files.
  226. /// </summary>
  227. void RefreshSubDirectoriesAndFiles()
  228. {
  229. lbCurrentUrl.Text = string.Format("Current Path: {0}", client.Url);
  230. var subDirs = client.GetSubDirectoriesAndFiles();
  231. // Sort the list.
  232. var orderedDirs = from dir in subDirs
  233. orderby dir.IsDirectory descending, dir.Name
  234. select dir;
  235. lstFileExplorer.Items.Clear();
  236. foreach (var subdir in orderedDirs)
  237. {
  238. lstFileExplorer.Items.Add(subdir);
  239. }
  240. }
  241. #endregion
  242. #region Download File/Folders
  243. /// <summary>
  244. /// Handle the Click event of btnBrowseDownloadPath.
  245. /// </summary>
  246. private void btnBrowseDownloadPath_Click(object sender, EventArgs e)
  247. {
  248. BrowserDownloadPath();
  249. }
  250. /// <summary>
  251. /// Handle the Click event of btnDownload.
  252. /// </summary>
  253. private void btnDownload_Click(object sender, EventArgs e)
  254. {
  255. // One or more files / folders should be selected in the File Explorer.
  256. if (lstFileExplorer.SelectedItems.Count == 0)
  257. {
  258. MessageBox.Show(
  259. "Please select one or more files / folders in the File Explorer",
  260. "No file is selected");
  261. return;
  262. }
  263. // If the tbDownloadPath.Text is empty, then show a FolderBrowserDialog.
  264. if (string.IsNullOrEmpty(tbDownloadPath.Text)
  265. && BrowserDownloadPath() != System.Windows.Forms.DialogResult.OK)
  266. {
  267. return;
  268. }
  269. var directoriesAndFiles =
  270. lstFileExplorer.SelectedItems.Cast<FTPFileSystem>().ToList();
  271. // Download the selected items.
  272. client.DownloadDirectoriesAndFiles(directoriesAndFiles, tbDownloadPath.Text);
  273. }
  274. /// <summary>
  275. /// Show a FolderBrowserDialog.
  276. /// </summary>
  277. DialogResult BrowserDownloadPath()
  278. {
  279. using (FolderBrowserDialog folderBrowser = new FolderBrowserDialog())
  280. {
  281. if (!string.IsNullOrEmpty(tbDownloadPath.Text))
  282. {
  283. folderBrowser.SelectedPath = tbDownloadPath.Text;
  284. }
  285. var result = folderBrowser.ShowDialog();
  286. if (result == System.Windows.Forms.DialogResult.OK)
  287. {
  288. tbDownloadPath.Text = folderBrowser.SelectedPath;
  289. }
  290. return result;
  291. }
  292. }
  293. #endregion
  294. }
  295. }