PageRenderTime 18ms CodeModel.GetById 1ms app.highlight 12ms RepoModel.GetById 2ms 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
 18using System;
 19using System.Linq;
 20using System.Net;
 21using System.Windows.Forms;
 22
 23namespace CSFTPDownload
 24{
 25    public partial class MainForm : Form
 26    {
 27
 28        FTPClientManager client = null;
 29
 30        NetworkCredential currentCredentials = null;
 31
 32        public MainForm()
 33        {
 34            InitializeComponent();
 35        }
 36
 37        #region URL navigation
 38
 39        /// <summary>
 40        /// Handle the Click event of btnConnect.
 41        /// </summary>
 42        private void btnConnect_Click(object sender, EventArgs e)
 43        {
 44
 45            // Connect to server specified by tbFTPServer.Text.
 46            Connect(this.tbFTPServer.Text.Trim());
 47
 48        }
 49
 50        void Connect(string urlStr)
 51        {
 52            try
 53            {
 54                Uri url = new Uri(urlStr);
 55
 56                // The schema of url must be ftp. 
 57                if (!url.Scheme.Equals("ftp", StringComparison.OrdinalIgnoreCase))
 58                {
 59                    throw new ApplicationException("The schema of url must be ftp. ");
 60                }
 61
 62                // Set the url to the folder that contains this file. 
 63                if (url.IsFile)
 64                {
 65                    url = new Uri(url, "..");
 66                }
 67
 68                // Show the Form UICredentialsProvider to get new Credentials.
 69                using (UICredentialsProvider provider =
 70                    new UICredentialsProvider(this.currentCredentials))
 71                {
 72
 73                    // Show the Form UICredentialsProvider as a dialog.
 74                    var result = provider.ShowDialog();
 75
 76                    // If user typed the Credentials and pressed the "OK" button.
 77                    if (result == System.Windows.Forms.DialogResult.OK)
 78                    {
 79
 80                        // Reset the current Credentials.
 81                        this.currentCredentials = provider.Credentials;
 82
 83                    }
 84                    else
 85                    {
 86                        return;
 87                    }
 88                }
 89
 90                // Initialize the FTPClient instance.
 91                client = new FTPClientManager(url, currentCredentials);
 92
 93                client.UrlChanged += new EventHandler(client_UrlChanged);
 94                client.StatusChanged += new EventHandler(client_StatusChanged);
 95                client.ErrorOccurred += new EventHandler<ErrorEventArgs>(client_ErrorOccurred);
 96                client.FileDownloadCompleted +=
 97                    new EventHandler<FileDownloadCompletedEventArgs>(client_FileDownloadCompleted);
 98                client.NewMessageArrived +=
 99                    new EventHandler<NewMessageEventArg>(client_NewMessageArrived);
100
101                // List the sub directories and files.
102                RefreshSubDirectoriesAndFiles();
103            }
104
105
106            catch (System.Net.WebException webEx)
107            {
108                if ((webEx.Response as FtpWebResponse).StatusCode == FtpStatusCode.NotLoggedIn)
109                {
110                    // Reconnect the server.
111                    Connect(urlStr);
112
113                    return;
114                }
115                else
116                {
117                    MessageBox.Show(webEx.Message);
118                }
119            }
120            catch (Exception ex)
121            {
122                MessageBox.Show(ex.Message);
123            }
124        }
125
126        /// <summary>
127        /// Log the message of FTPClient.
128        /// </summary>
129        void client_NewMessageArrived(object sender, NewMessageEventArg e)
130        {
131            this.Invoke(new EventHandler<NewMessageEventArg>(
132                client_NewMessageArrivedHandler),sender,e);
133        }
134
135        void client_NewMessageArrivedHandler(object sender, NewMessageEventArg e)
136        {
137            string log = string.Format("{0} {1}",
138                 DateTime.Now, e.NewMessage);
139            this.lstLog.Items.Add(log);
140            this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
141        }
142
143
144        /// <summary>
145        /// Log the FileDownloadCompleted event when a file was downloaded.
146        /// </summary>
147        void client_FileDownloadCompleted(object sender, FileDownloadCompletedEventArgs e)
148        {
149            this.Invoke(new EventHandler<FileDownloadCompletedEventArgs>(
150                 client_FileDownloadCompletedHandler), sender, e);
151        }
152
153        void client_FileDownloadCompletedHandler(object sender, FileDownloadCompletedEventArgs e)
154        {
155            string log = string.Format("{0} Download from {1} to {2} is completed. Length: {3}. ",
156                DateTime.Now, e.ServerPath, e.LocalFile.FullName, e.LocalFile.Length);
157
158            this.lstLog.Items.Add(log);
159            this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
160        }
161
162        /// <summary>
163        /// Log the ErrorOccurred event if there was an error.
164        /// </summary>
165        void client_ErrorOccurred(object sender, ErrorEventArgs e)
166        {
167            this.Invoke(new EventHandler<ErrorEventArgs>(
168                  client_ErrorOccurredHandler), sender, e);
169        }
170
171        void client_ErrorOccurredHandler(object sender, ErrorEventArgs e)
172        {
173            this.lstLog.Items.Add(
174                string.Format("{0} {1} ", DateTime.Now, e.ErrorException.Message));
175
176            var innerException = e.ErrorException.InnerException;
177
178            // Log all the innerException.
179            while (innerException != null)
180            {
181                this.lstLog.Items.Add(
182                              string.Format("\t\t\t {0} ", innerException.Message));
183                innerException = innerException.InnerException;
184            }
185
186            this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
187        }
188
189        /// <summary>
190        /// Refresh the UI if the Status of the FTPClient changed.
191        /// </summary>
192        void client_StatusChanged(object sender, EventArgs e)
193        {
194
195            this.Invoke(new EventHandler(client_StatusChangedHandler), sender, e);
196        }
197
198        void client_StatusChangedHandler(object sender, EventArgs e)
199        {
200
201            // Disable all the buttons if the client is downloading file.
202            if (client.Status == FTPClientManagerStatus.Downloading)
203            {
204                btnBrowseDownloadPath.Enabled = false;
205                btnConnect.Enabled = false;
206                btnDownload.Enabled = false;
207                btnNavigateParentFolder.Enabled = false;
208                lstFileExplorer.Enabled = false;
209            }
210            else
211            {
212                btnBrowseDownloadPath.Enabled = true;
213                btnConnect.Enabled = true;
214                btnDownload.Enabled = true;
215                btnNavigateParentFolder.Enabled = true;
216                lstFileExplorer.Enabled = true;
217            }
218
219            string log = string.Format("{0} FTPClient status changed to {1}. ",
220               DateTime.Now, client.Status.ToString());
221
222            this.lstLog.Items.Add(log);
223            this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
224        }
225
226        /// <summary>
227        /// Handle the UrlChanged event of the FTPClient.
228        /// </summary>
229        void client_UrlChanged(object sender, EventArgs e)
230        {
231            this.Invoke(new EventHandler(client_UrlChangedHandler), sender, e);
232        }
233
234        void client_UrlChangedHandler(object sender, EventArgs e)
235        {
236            RefreshSubDirectoriesAndFiles();
237
238            string log = string.Format("{0} The current url changed to {1}. ",
239              DateTime.Now, client.Url);
240
241            this.lstLog.Items.Add(log);
242            this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
243        }
244
245        /// <summary>
246        /// Handle the DoubleClick event of lstFileExplorer.
247        /// </summary>
248        private void lstFileExplorer_DoubleClick(object sender, EventArgs e)
249        {
250            // if only one item is selected and the item represents a folder, then navigate
251            // to a subDirectory.
252            if (lstFileExplorer.SelectedItems.Count == 1
253                && (lstFileExplorer.SelectedItem as FTPFileSystem).IsDirectory)
254            {
255                this.client.Naviagte(
256                    (lstFileExplorer.SelectedItem as FTPFileSystem).Url);
257            }
258        }
259
260        /// <summary>
261        /// Handle the Click event of btnNavigateParentFolder.
262        /// </summary>
263        /// <param name="sender"></param>
264        /// <param name="e"></param>
265        private void btnNavigateParentFolder_Click(object sender, EventArgs e)
266        {
267
268            // Navigate to the parent folder.
269            this.client.NavigateParent();
270        }
271
272        /// <summary>
273        /// List the sub directories and files.
274        /// </summary>
275        void RefreshSubDirectoriesAndFiles()
276        {
277            lbCurrentUrl.Text = string.Format("Current Path: {0}", client.Url);
278
279            var subDirs = client.GetSubDirectoriesAndFiles();
280
281            // Sort the list.
282            var orderedDirs = from dir in subDirs
283                              orderby dir.IsDirectory descending, dir.Name
284                              select dir;
285
286            lstFileExplorer.Items.Clear();
287            foreach (var subdir in orderedDirs)
288            {
289                lstFileExplorer.Items.Add(subdir);
290            }
291        }
292
293
294        #endregion
295
296        #region Download File/Folders
297
298        /// <summary>
299        /// Handle the Click event of btnBrowseDownloadPath.
300        /// </summary>
301        private void btnBrowseDownloadPath_Click(object sender, EventArgs e)
302        {
303            BrowserDownloadPath();
304        }
305
306        /// <summary>
307        /// Handle the Click event of btnDownload.
308        /// </summary>
309        private void btnDownload_Click(object sender, EventArgs e)
310        {
311
312            // One or more files / folders should be selected in the File Explorer.
313            if (lstFileExplorer.SelectedItems.Count == 0)
314            {
315                MessageBox.Show(
316                    "Please select one or more files / folders in the File Explorer",
317                    "No file is selected");
318                return;
319            }
320
321            // If the tbDownloadPath.Text is empty, then show a FolderBrowserDialog.
322            if (string.IsNullOrEmpty(tbDownloadPath.Text)
323                && BrowserDownloadPath() != System.Windows.Forms.DialogResult.OK)
324            {
325                return;
326            }
327
328
329            var directoriesAndFiles = 
330                lstFileExplorer.SelectedItems.Cast<FTPFileSystem>().ToList();
331
332            // Download the selected items.
333            client.DownloadDirectoriesAndFiles(directoriesAndFiles, tbDownloadPath.Text);
334
335        }
336
337        /// <summary>
338        /// Show a FolderBrowserDialog.
339        /// </summary>
340        DialogResult BrowserDownloadPath()
341        {
342            using (FolderBrowserDialog folderBrowser = new FolderBrowserDialog())
343            {
344                if (!string.IsNullOrEmpty(tbDownloadPath.Text))
345                {
346                    folderBrowser.SelectedPath = tbDownloadPath.Text;
347                }
348                var result = folderBrowser.ShowDialog();
349                if (result == System.Windows.Forms.DialogResult.OK)
350                {
351                    tbDownloadPath.Text = folderBrowser.SelectedPath;
352                }
353                return result;
354            }
355        }
356        #endregion
357    }
358}