4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains C# code to download a single file based on a URI.
16 using System
.ComponentModel
;
17 using System
.Diagnostics
;
20 using System
.Reflection
;
21 using System
.Runtime
.InteropServices
;
22 using System
.Threading
;
24 ///////////////////////////////////////////////////////////////////////////////
26 #region Assembly Metadata
27 [assembly
: AssemblyTitle("GetFile Tool")]
28 [assembly
: AssemblyDescription("Download a single file based on a URI.")]
29 [assembly
: AssemblyCompany("SQLite Development Team")]
30 [assembly
: AssemblyProduct("SQLite")]
31 [assembly
: AssemblyCopyright("Public Domain")]
32 [assembly
: ComVisible(false)]
33 [assembly
: Guid("5c4b3728-1693-4a33-a218-8e6973ca15a6")]
34 [assembly
: AssemblyVersion("1.0.*")]
37 [assembly
: AssemblyConfiguration("Debug")]
39 [assembly
: AssemblyConfiguration("Release")]
43 ///////////////////////////////////////////////////////////////////////////////
48 /// This enumeration is used to represent all the possible exit codes from
51 internal enum ExitCode
54 /// The file download was a success.
59 /// The command line arguments are missing (i.e. null). Generally,
60 /// this should not happen.
65 /// The wrong number of command line arguments was supplied.
70 /// The URI specified on the command line could not be parsed as a
71 /// supported absolute URI.
76 /// The file name portion of the URI specified on the command line
77 /// could not be extracted from it.
82 /// The temporary directory is either invalid (i.e. null) or does not
83 /// represent an available directory.
88 /// An exception was caught in <see cref="Main" />. Generally, this
89 /// should not happen.
94 /// The file download was canceled. This tool does not make use of
95 /// the <see cref="WebClient.CancelAsync" /> method; therefore, this
96 /// should not happen.
101 /// The file download encountered an error. Further information about
102 /// this error should be displayed on the console.
107 ///////////////////////////////////////////////////////////////////////////
109 internal static class Program
113 /// This is used to synchronize multithreaded access to the
114 /// <see cref="previousPercent" /> and <see cref="exitCode"/>
117 private static readonly object syncRoot
= new object();
119 ///////////////////////////////////////////////////////////////////////
122 /// This event will be signed when the file download has completed,
123 /// even if the file download itself was canceled or unsuccessful.
125 private static EventWaitHandle doneEvent
;
127 ///////////////////////////////////////////////////////////////////////
130 /// The previous file download completion percentage seen by the
131 /// <see cref="DownloadProgressChanged" /> event handler. This value
132 /// is never decreased, nor is it ever reset to zero.
134 private static int previousPercent
= 0;
136 ///////////////////////////////////////////////////////////////////////
139 /// This will be the exit code returned by this tool after the file
140 /// download completes, successfully or otherwise. This value is only
141 /// changed by the <see cref="DownloadFileCompleted" /> event handler.
143 private static ExitCode exitCode
= ExitCode
.Success
;
146 ///////////////////////////////////////////////////////////////////////
148 #region Private Support Methods
150 /// This method displays an error message to the console and/or
151 /// displays the command line usage information for this tool.
153 /// <param name="message">
154 /// The error message to display, if any.
156 /// <param name="usage">
157 /// Non-zero to display the command line usage information.
159 private static void Error(
165 Console
.WriteLine(message
);
167 string fileName
= Path
.GetFileName(
168 Process
.GetCurrentProcess().MainModule
.FileName
);
170 Console
.WriteLine(String
.Format(
171 "usage: {0} <uri> [fileName]", fileName
));
174 ///////////////////////////////////////////////////////////////////////
177 /// This method attempts to determine the file name portion of the
180 /// <param name="uri">
181 /// The URI to process.
184 /// The file name portion of the specified URI -OR- null if it cannot
187 private static string GetFileName(
194 string pathAndQuery
= uri
.PathAndQuery
;
196 if (String
.IsNullOrEmpty(pathAndQuery
))
199 int index
= pathAndQuery
.LastIndexOf('/');
201 if ((index
< 0) || (index
== pathAndQuery
.Length
))
204 return pathAndQuery
.Substring(index
+ 1);
208 ///////////////////////////////////////////////////////////////////////
210 #region Private Event Handlers
212 /// This method is an event handler that is called when the file
213 /// download completion percentage changes. It will display progress
214 /// on the console. Special care is taken to make sure that progress
215 /// events are not displayed out-of-order, even if duplicate and/or
216 /// out-of-order events are received.
218 /// <param name="sender">
219 /// The source of the event.
222 /// Information for the event being processed.
224 private static void DownloadProgressChanged(
226 DownloadProgressChangedEventArgs e
231 int percent
= e
.ProgressPercentage
;
235 if (percent
> previousPercent
)
239 if ((percent
% 10) == 0)
240 Console
.Write(" {0}% ", percent
);
242 previousPercent
= percent
;
248 ///////////////////////////////////////////////////////////////////////
251 /// This method is an event handler that is called when the file
252 /// download has completed, successfully or otherwise. It will
253 /// display the overall result of the file download on the console,
254 /// including any <see cref="Exception" /> information, if applicable.
255 /// The <see cref="exitCode" /> field is changed by this method to
256 /// indicate the overall result of the file download and the event
257 /// within the <see cref="doneEvent" /> field will be signaled.
259 /// <param name="sender">
260 /// The source of the event.
263 /// Information for the event being processed.
265 private static void DownloadFileCompleted(
267 AsyncCompletedEventArgs e
274 if (previousPercent
< 100)
280 Console
.WriteLine("Canceled");
284 exitCode
= ExitCode
.DownloadCanceled
;
289 Exception error
= e
.Error
;
293 Console
.WriteLine("Error: {0}", error
);
297 exitCode
= ExitCode
.DownloadError
;
302 Console
.WriteLine("Done");
307 if (doneEvent
!= null)
312 ///////////////////////////////////////////////////////////////////////
314 #region Program Entry Point
316 /// This is the entry-point for this tool. It handles processing the
317 /// command line arguments, setting up the web client, downloading the
318 /// file, and saving it to the file system.
320 /// <param name="args">
321 /// The command line arguments.
324 /// Zero upon success; non-zero on failure. This will be one of the
325 /// values from the <see cref="ExitCode" /> enumeration.
327 private static int Main(
332 // NOTE: Sanity check the command line arguments.
337 return (int)ExitCode
.MissingArgs
;
340 if ((args
.Length
< 1) || (args
.Length
> 2))
343 return (int)ExitCode
.WrongNumArgs
;
347 // NOTE: Attempt to convert the first (and only) command line
348 // argument to an absolute URI.
352 if (!Uri
.TryCreate(args
[0], UriKind
.Absolute
, out uri
))
354 Error("Could not create absolute URI from argument.", false);
355 return (int)ExitCode
.BadUri
;
359 // NOTE: If a file name was specified on the command line, try to
360 // use it (without its directory name); otherwise, fallback
361 // to using the file name portion of the URI.
363 string fileName
= (args
.Length
== 2) ?
364 Path
.GetFileName(args
[1]) : null;
366 if (String
.IsNullOrEmpty(fileName
))
369 // NOTE: Attempt to extract the file name portion of the URI
372 fileName
= GetFileName(uri
);
374 if (fileName
== null)
376 Error("Could not extract file name from URI.", false);
377 return (int)ExitCode
.BadFileName
;
382 // NOTE: Grab the temporary path setup for this process. If it is
383 // unavailable, we will not continue.
385 string directory
= Path
.GetTempPath();
387 if (String
.IsNullOrEmpty(directory
) ||
388 !Directory
.Exists(directory
))
390 Error("Temporary directory is invalid or unavailable.", false);
391 return (int)ExitCode
.BadTempPath
;
397 // HACK: For use of the TLS 1.2 security protocol because some
398 // web servers fail without it. In order to support the
399 // .NET Framework 2.0+ at compilation time, must use its
400 // integer constant here.
402 ServicePointManager
.SecurityProtocol
=
403 (SecurityProtocolType
)0xC00;
405 using (WebClient webClient
= new WebClient())
408 // NOTE: Create the event used to signal completion of the
411 doneEvent
= new ManualResetEvent(false);
414 // NOTE: Hookup the event handlers we care about on the web
415 // client. These are necessary because the file is
416 // downloaded asynchronously.
418 webClient
.DownloadProgressChanged
+=
419 new DownloadProgressChangedEventHandler(
420 DownloadProgressChanged
);
422 webClient
.DownloadFileCompleted
+=
423 new AsyncCompletedEventHandler(
424 DownloadFileCompleted
);
427 // NOTE: Build the fully qualified path and file name,
428 // within the temporary directory, where the file to
429 // be downloaded will be saved.
431 fileName
= Path
.Combine(directory
, fileName
);
434 // NOTE: If the file name already exists (in the temporary)
435 // directory, delete it.
437 // TODO: Perhaps an error should be raised here instead?
439 if (File
.Exists(fileName
))
440 File
.Delete(fileName
);
443 // NOTE: After kicking off the asynchronous file download
444 // process, wait [forever] until the "done" event is
448 "Downloading \"{0}\" to \"{1}\"...", uri
, fileName
);
450 webClient
.DownloadFileAsync(uri
, fileName
);
456 return (int)exitCode
;
462 // NOTE: An exception was caught. Report it via the console
463 // and return failure.
465 Error(e
.ToString(), false);
466 return (int)ExitCode
.Exception
;