Exemple #1
0
        public async Task DownloadSong(SongInfo song, string path)
        {
            // Reset Download progress.
            SongDownloadProgress = 0;

            using (var client = new System.Net.WebClient())
            {
                if (!string.IsNullOrEmpty(Settings.Credentials))
                {
                    var rawCreds = Settings.Credentials.Split(':');
                    if (rawCreds != null && rawCreds.Length > 1)
                    {
                        client.Credentials = new System.Net.NetworkCredential(rawCreds[0], rawCreds[1]);
                    }
                }

                client.DownloadProgressChanged += (sender, e) =>
                {
                    if (e.TotalBytesToReceive >= 0)
                    {
                        SongDownloadProgress = (double)e.BytesReceived / e.TotalBytesToReceive;

                        return;
                    }

                    var contentLength = long.Parse(client.ResponseHeaders[System.Net.HttpResponseHeader.ContentLength]);
                    if (contentLength > 0)
                    {
                        SongDownloadProgress = (double)e.BytesReceived / contentLength;

                        return;
                    }

                    // Unknown content length. Throw error.
                    throw new HttpRequestException("Unknown download size.");
                };
                client.DownloadFileCompleted += (sender, e) =>
                {
                    //TODO
                };

                var uri = new Uri($"{Settings.ServiceUri}/jcf/{song.Sku}");
                try
                {
                    await client.DownloadFileTaskAsync(uri, path);
                }
                catch (System.Net.WebException e)
                {
                    // Windows does not properly follow redirects.
                    // See https://github.com/lukesampson/scoop/pull/3902
                    if (!e.Message.Contains("302") || string.IsNullOrEmpty(e.Response.Headers["Location"]))
                    {
                        throw;
                    }

                    await client.DownloadFileTaskAsync(new Uri(e.Response.Headers["Location"]), path);
                }
            }
        }
        private async Task <string> RetrieveCsv(string ukPostcodeCsvUrl)
        {
            var zipPath = GetTempPath();
            var csvPath = GetTempPath();
            var net     = new System.Net.WebClient();

            await net.DownloadFileTaskAsync(new Uri(ukPostcodeCsvUrl), zipPath);

            net.Dispose();

            _logger.LogInformation($"LocationSyncJob - ZIP Downloaded");

            try
            {
                ZipFile.ExtractToDirectory(zipPath, csvPath);
                _logger.LogInformation($"LocationSyncJob - CSV Extracted");
            }
            finally
            {
                File.Delete(zipPath);
                _logger.LogInformation($"LocationSyncJob - ZIP Deleted");
            }

            return(Path.Combine(csvPath, UkPostcodeCsvFilename));
        }
        public async Task DoDownload()
        {
            var enclosure = VersionInfo.First().Enclosures.First(e => e.InstallerType == Updater.CurrentInstallerType);

            if (Updater.CurrentInstallerType == InstallerType.Archive ||
                Updater.CurrentInstallerType == InstallerType.ServiceArchive)
            {
                downloadPath = enclosure.Url.AbsolutePath;
                this.State   = UpdateActionState.Downloaded;
                return;
            }
            using (var client = new System.Net.WebClient())
                using (cancelSource.Token.Register(() => client.CancelAsync(), true)) {
                    client.DownloadProgressChanged += (sender, args) => {
                        this.Progress = args.ProgressPercentage / 100.0;
                    };
                    this.State = UpdateActionState.Downloading;
                    try {
                        downloadPath = System.IO.Path.Combine(
                            Shell.GetKnownFolder(Shell.KnownFolder.Downloads),
                            System.IO.Path.GetFileName(enclosure.Url.AbsolutePath));
                        await client.DownloadFileTaskAsync(
                            enclosure.Url.ToString(),
                            downloadPath);

                        this.State = UpdateActionState.Downloaded;
                    }
                    catch (System.Net.WebException) {
                        this.State = UpdateActionState.Aborted;
                    }
                }
        }
Exemple #4
0
        public async Task DownloadFileAsync(Uri fileUri, string localFilePath, Action <int> progressChanged = null, Action <bool, Exception> completed = null)
        {
            var filePath = GetFilePath(localFilePath);

            using (var client = new System.Net.WebClient())
            {
                client.DownloadProgressChanged += (o, e) =>
                {
                    progressChanged?.Invoke(e.ProgressPercentage);
                };
                client.DownloadFileCompleted += (o, e) =>
                {
                    completed?.Invoke(!e.Cancelled && e.Error == null, e.Error);
                };

                try
                {
                    await client.DownloadFileTaskAsync(fileUri, filePath);
                }
                catch (Exception ex)
                {
                    completed?.Invoke(false, ex);
                }
            }
        }
        static StackObject *DownloadFileTaskAsync_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.String @fileName = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.String @address = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Net.WebClient instance_of_this_method = (System.Net.WebClient) typeof(System.Net.WebClient).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.DownloadFileTaskAsync(@address, @fileName);

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Exemple #6
0
        public static async Task <DownloadResult> DownloadAsync(VersionDescription version, Action <float> onprogress, CancellationToken ct)
        {
            var enclosure = version.Enclosures.First(e => e.InstallerType == Updater.CurrentInstallerType);

            if (Updater.CurrentInstallerType == InstallerType.Archive ||
                Updater.CurrentInstallerType == InstallerType.ServiceArchive)
            {
                return(new DownloadResult(null, version, enclosure));
            }
            using (var client = new System.Net.WebClient())
                using (ct.Register(() => client.CancelAsync(), false)) {
                    if (onprogress != null)
                    {
                        client.DownloadProgressChanged += (sender, args) => {
                            onprogress(args.ProgressPercentage / 100.0f);
                        };
                    }
                    var filepath =
                        System.IO.Path.Combine(
                            GetDownloadPath(),
                            System.IO.Path.GetFileName(enclosure.Url.AbsolutePath));
                    await client.DownloadFileTaskAsync(enclosure.Url.ToString(), filepath).ConfigureAwait(false);

                    return(new DownloadResult(filepath, version, enclosure));
                }
        }
Exemple #7
0
        public async Task <bool> ProcessFromUrl(string url, string sourceFilename)
        {
            var extension = new FileInfo(sourceFilename).Extension;

            using (var wc = new System.Net.WebClient()) {
                string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + $".{extension}";
                await wc.DownloadFileTaskAsync(new Uri(url), fileName);

                if (System.IO.File.Exists(fileName))
                {
                    if (extension.Equals(".doc"))
                    {
                        fileName = await DocHelpers.ConvertToDocx(fileName);
                    }

                    if (System.IO.File.Exists(fileName))
                    {
                        var id = DateTime.Now.GetNextWeekday(DayOfWeek.Monday).ToString("ddMMyy");
                        await _createHtmlFile(id, fileName);

                        var week = await _processFile(id, fileName);

                        if (week != null)
                        {
                            Console.WriteLine("Sending to cosmos");
                            await _service.Create(week);

                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
        public async System.Threading.Tasks.Task DoDownload()
        {
            var client = new System.Net.WebClient();

            client.DownloadProgressChanged += (sender, args) => {
                this.Progress = args.ProgressPercentage / 100.0;
            };
            cancelSource.Token.Register(() => {
                client.CancelAsync();
            }, true);
            this.State = UpdateActionState.Downloading;
            try {
                downloadPath = System.IO.Path.Combine(
                    Shell.GetKnownFolder(Shell.KnownFolder.Downloads),
                    System.IO.Path.GetFileName(SelectedEnclosure.Url.AbsolutePath));
                await client.DownloadFileTaskAsync(
                    selectedEnclosure.Url.ToString(),
                    downloadPath);

                this.State = UpdateActionState.Downloaded;
            }
            catch (System.Net.WebException) {
                this.State = UpdateActionState.Aborted;
            }
        }
        static async Task <string> DoDownload(Uri source, string dstpath)
        {
            int progress      = -1;
            var appcastReader = new AppCastReader();
            var versions      = await appcastReader.DownloadVersionInfoTaskAsync(source, CancellationToken.None).ConfigureAwait(false);

            var version   = versions.OrderByDescending(ver => ver.PublishDate).First();
            var enclosure = version.Enclosures.Where(enc => enc.InstallerType == InstallerType.Archive).First();

            using (var client = new System.Net.WebClient()) {
                var locker = new Object();
                client.DownloadProgressChanged += (sender, args) => {
                    lock (locker) {
                        if (args.ProgressPercentage > progress)
                        {
                            progress = args.ProgressPercentage;
                            Console.WriteLine($"Downloading... {progress}%");
                        }
                    }
                };
                var filepath =
                    System.IO.Path.Combine(
                        dstpath,
                        System.IO.Path.GetFileName(enclosure.Url.AbsolutePath));
                await client.DownloadFileTaskAsync(enclosure.Url.ToString(), filepath).ConfigureAwait(false);

                return(filepath);
            }
        }
Exemple #10
0
        private static async System.Threading.Tasks.Task <bool> checkForUpdates()
        {
            System.Net.WebClient                webClient  = new System.Net.WebClient();
            System.Net.Http.HttpClient          httpClient = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage result     = null;
            var    strTempPath      = Path.GetTempPath() + "PassWatch.exe";
            string strServerVersion = null;

            // Get server/remote version.
            if (config.AutoUpdateServiceURI.StartsWith("http"))
            {
                result = await httpClient.GetAsync(config.AutoUpdateServiceURI);

                strServerVersion = await result.Content.ReadAsStringAsync();
            }
            else if (File.Exists(config.AutoUpdateFileURI))
            {
                strServerVersion = FileVersionInfo.GetVersionInfo(config.AutoUpdateFileURI).FileVersion;
            }

            var serverVersion = Version.Parse(strServerVersion);

            var thisVersion = assem.GetName().Version;

            // Check if update is available.
            if (serverVersion > thisVersion)
            {
                // Remove temp file if exists.
                if (File.Exists(strTempPath))
                {
                    File.Delete(strTempPath);
                }
                // Get updated version.
                try
                {
                    // Download if URI is HTTP.
                    if (config.AutoUpdateFileURI.StartsWith("http"))
                    {
                        await webClient.DownloadFileTaskAsync(new Uri(config.AutoUpdateFileURI), strTempPath);
                    }
                    // Copy if URI is UNC path.
                    else if (File.Exists(config.AutoUpdateFileURI))
                    {
                        File.Copy(config.AutoUpdateFileURI, strTempPath);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error updating PassWatch.  See log for details.");
                    writeToLog("Error updating PassWatch.  " + ex.ToString());
                }
                // Start update process from temp file.
                Process.Start(strTempPath, "-update \"" + assem.Location + "\"");
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #11
0
        private static async Task DownloadHelper(
            DownloadableFile downloadableFile,
            int retry = 1,
            System.Net.DownloadProgressChangedEventHandler onDownloadProgressChanged = null
            )
        {
            if (downloadableFile.Url == null)
            {
                return;
            }

            //uncomment the following line to force re-download every time.
            //File.Delete(downloadableFile.LocalFile);
            if (!File.Exists(downloadableFile.LocalFile) || new FileInfo(downloadableFile.LocalFile).Length == 0)
            {
                try
                {
                    //Download the file
                    Trace.WriteLine("downloading file from:" + downloadableFile.Url + " to: " + downloadableFile.LocalFile);
                    System.Net.WebClient downloadClient = new System.Net.WebClient();

                    if (onDownloadProgressChanged != null)
                    {
                        downloadClient.DownloadProgressChanged += onDownloadProgressChanged;
                    }

                    FileInfo fi = new FileInfo(downloadableFile.LocalFile);
                    if (!fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }
                    await downloadClient.DownloadFileTaskAsync(new Uri(downloadableFile.Url), downloadableFile.LocalFile);
                }
                catch (Exception e)
                {
                    if (File.Exists(downloadableFile.LocalFile))
                    {
                        //The downloaded file may be corrupted, should delete it
                        File.Delete(downloadableFile.LocalFile);
                    }

                    if (retry > 0)
                    {
                        await DownloadHelper(downloadableFile, retry - 1);
                    }
                    else
                    {
#if UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE
                        UnityEngine.Debug.Log(e.StackTrace);
#else
                        Trace.WriteLine(e);
#endif
                        throw;
                    }
                }
            }
        }
Exemple #12
0
        private async System.Threading.Tasks.Task ManualInstallExtensionAsync()
        {
            try
            {
                var fileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"{Guid.NewGuid().ToString()}.vsix");
                if (Extension.VsixId == null)
                {   // this is not a VsiX extension it is most probably an MSI
                    fileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"{Guid.NewGuid().ToString()}.msi");
                }
                else
                {   // this is a VsiX extension
                    fileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"{Guid.NewGuid().ToString()}.VsiX");
                }

                using (var webClient = new System.Net.WebClient())
                {
                    // TODO: a good citizen would keep a list of known temp artifacts (like this one) and delete it on next start up.

                    Logger.Log("Marketplace OK"); // Marketplace ok

                    if (this.Extension.Installer != null)
                    {
                        Logger.Log("  " + "Downloading");
                        await webClient.DownloadFileTaskAsync(this.Extension.Installer, fileName);

                        Logger.Log("Downloading OK"); // Download ok

                        // Use the default windows file associations to invoke VSIXinstaller.exe or msi installer, since we don't know the path.
                        Logger.Log("  " + "Installing");

                        Process.Start(new ProcessStartInfo(fileName)
                        {
                            UseShellExecute = true
                        });

                        Logger.Log("Install OK"); // Install ok
                    }
                    else
                    {
                        Logger.Log("Opening download page for the user to manually download and install"); // Download ok
                        // We cannot install this extension directly. Take the user to the download page.
                        Process.Start(new ProcessStartInfo(this.Extension.Link)
                        {
                            UseShellExecute = true
                        });
                    }
                }
            }

            catch (Exception ex)
            {
                // TODO: perhaps we should handle specific exceptions and give custom error messages.

                Logger.Log("Install failed exception:" + ex.ToString());
            }
        }
Exemple #13
0
        public static void GenericDownload(string url, string filename)
        {
            string[] allowedMimetypes = Configuration.Config ["file"] ["mimetypes"].Split(' ');
            using (HttpClient client = new HttpClient()) {
                Task <HttpResponseMessage> msg = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url));
                msg.Wait();
                IEnumerable <String> types;
                IEnumerable <String> lengths;

                if (msg.Result.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new Exception("Server gave a " + msg.Result.StatusCode);
                }

                if (msg.Result.Content.Headers.TryGetValues("Content-Type", out types))
                {
                    if (!types.Any(x => allowedMimetypes.Contains(x)))
                    {
                        throw new Exception("Filetype not supported");
                    }
                    if (msg.Result.Content.Headers.TryGetValues("Content-Length", out lengths))
                    {
                        float length    = int.Parse(lengths.First()) / (float)Math.Pow(1024, 2);
                        float maxlength = float.Parse(Configuration.Config ["file"] ["size_limit"]);
                        if (length > maxlength)
                        {
                            throw new Exception("File is over " + maxlength + "MBs in size");
                        }
                    }
                    else
                    {
                        throw new Exception("Cannot gauge content size from headers. Bailing");
                    }
                }
                else
                {
                    throw new Exception("Server does not state a Content-Type. Bailing.");
                }
            }


            using (System.Net.WebClient client = new System.Net.WebClient()) {
                try {
                    string             fname = System.IO.Path.Combine(Configuration.Config ["mpc"] ["music_dir"], filename);
                    System.IO.FileInfo finfo = new System.IO.FileInfo(fname);
                    if (!client.DownloadFileTaskAsync(url, finfo.FullName).Wait(TimeSpan.FromSeconds(15)))
                    {
                        throw new Exception("File took too long to download");
                    }
                } catch (Exception e) {
                    Console.WriteLine("Issue downloading file", e);
                    throw new Exception("Couldn't download file");
                }
            }
        }
Exemple #14
0
        private static async Task DownloadHelper(
            DownloadableFile downloadableFile,
            int retry = 1,
            System.Net.DownloadProgressChangedEventHandler onDownloadProgressChanged = null
            )
        {
            if (downloadableFile.Url == null)
            {
                return;
            }

            //uncomment the following line to force re-download every time.
            //File.Delete(downloadableFile.LocalFile);
            if (!downloadableFile.IsLocalFileValid)
            {
                try
                {
                    //Download the file
                    Trace.WriteLine("downloading file from:" + downloadableFile.Url + " to: " + downloadableFile.LocalFile);
                    System.Net.WebClient downloadClient = new System.Net.WebClient();

                    if (onDownloadProgressChanged != null)
                    {
                        downloadClient.DownloadProgressChanged += onDownloadProgressChanged;
                    }

                    FileInfo fi = new FileInfo(downloadableFile.LocalFile);
                    if (!fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }
                    await downloadClient.DownloadFileTaskAsync(new Uri(downloadableFile.Url), downloadableFile.LocalFile);
                }
                catch (Exception e)
                {
                    if (!downloadableFile.IsLocalFileValid)
                    {
                        //The downloaded file may be corrupted, should delete it
                        File.Delete(downloadableFile.LocalFile);
                    }

                    if (retry > 0)
                    {
                        await DownloadHelper(downloadableFile, retry - 1);
                    }
                    else
                    {
                        Trace.WriteLine(e);
                        throw;
                    }
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Download sound to the local cache if it's not there or update it if
        /// <paramref name="overwriteCache"/> is true.
        /// </summary>
        /// <remarks>For local files it only checks whether the file in place or not.</remarks>
        /// <param name="clauseId">Clause Id.</param>
        /// <param name="soundUri">Sound Uri. It shouldn't be a local file.</param>
        /// <param name="dictionary">Name of the dictionary.</param>
        /// <param name="overwriteCache">Update file in the cache.</param>
        /// <returns>Uri to the local file.</returns>
        /// <exception cref="System.ArgumentNullException"/>
        /// <exception cref="System.IO.FileNotFoundException"/>
        public static async Task <Uri> UpdateSoundCache(int clauseId, string soundUri, string dictionary, bool overwriteCache)
        {
            if (String.IsNullOrEmpty(soundUri))
            {
                throw new ArgumentNullException(nameof(soundUri));
            }

            if (String.IsNullOrEmpty(dictionary))
            {
                throw new ArgumentNullException(nameof(dictionary));
            }


            var source = new Uri(soundUri);

            if (source.IsAbsoluteUri && !source.IsFile)
            { //Let's try to download this file
                DirectoryInfo sounds = GetSoundCacheFolderFor(dictionary);

                if (!sounds.Exists)
                {
                    sounds.Create();
                }

                var localFile = new FileInfo(
                    Path.Combine(sounds.FullName, MakeCachedFileName(clauseId, source)));

                if (!localFile.Exists || overwriteCache)
                { //It's not in the cache yet or need to update
                    using (var client = new System.Net.WebClient())
                    {
                        try { await client.DownloadFileTaskAsync(source, localFile.FullName); }
                        catch
                        {
                            localFile.Delete(); //Wrong file in the cache
                            throw;
                        }
                    }
                }

                source = new Uri(localFile.FullName); //Now it's path to local cached file
            }

            if (!File.Exists(source.LocalPath))
            {
                throw new FileNotFoundException(
                          String.Format(PrgResources.FileNotFoundError, source.LocalPath), source.LocalPath);
            }

            return(source);
        }
Exemple #16
0
        protected async override Task <object> ExecuteAsync(AsyncCodeActivityContext context)
        {
            var filename   = Filename.Get(context);
            var id         = _id.Get(context);
            var filepath   = LocalPath.Get(context);
            var ignorepath = IgnorePath.Get(context);
            // await global.webSocketClient.DownloadFileAndSave(filename, id, filepath, ignorepath);

            Uri baseUri = new Uri(global.openflowconfig.baseurl);

            filepath = Environment.ExpandEnvironmentVariables(filepath);

            var q = "{\"_id\": \"" + id + "\"}";

            if (!string.IsNullOrEmpty(filename))
            {
                q = "{\"filename\":\"" + filename + "\"}";
            }
            var rows = await global.webSocketClient.Query <JObject>("files", q, null, 100, 0, "{\"_id\": -1}");

            if (rows.Length == 0)
            {
                throw new Exception("File not found");
            }
            if (rows.Length == 0)
            {
                throw new Exception("File not found");
            }
            filename = rows[0]["filename"].ToString();
            id       = rows[0]["_id"].ToString();

            Uri downloadUri = new Uri(baseUri, "/download/" + id);
            var url         = downloadUri.ToString();

            // if(string.IsNullOrEmpty(filename)) filename = "temp."
            // if (System.IO.File.Exists(filepath) && !overwrite) return 42;
            using (var client = new System.Net.WebClient())
            {
                // client.Headers.Add("Authorization", "jwt " + global.webSocketClient);
                client.Headers.Add(System.Net.HttpRequestHeader.Authorization, global.webSocketClient.jwt);

                if (ignorepath)
                {
                    filename = System.IO.Path.GetFileName(filename);
                }
                await client.DownloadFileTaskAsync(new Uri(url), System.IO.Path.Combine(filepath, filename));
            }
            return(42);
        }
Exemple #17
0
 private async Task GetImgAsync(string uri, string fileInfo)
 {
     try
     {
         using (System.Net.WebClient webClient = new System.Net.WebClient())
         {
             string downloadToDirectory = imgFolder + "\\" + fileInfo;
             //set proxy or crdentials here
             webClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
             await webClient.DownloadFileTaskAsync(new Uri(uri), @downloadToDirectory);
         }
     }
     catch (Exception e)
     {
         richTextBox1.Text += "Failed to download File: " + fileInfo;
     }
 }
Exemple #18
0
        public async Task DownloadSong(SongInfo song, string path)
        {
            // Reset Download progress.
            SongDownloadProgress = 0;

            using (var client = new System.Net.WebClient())
            {
                if (!string.IsNullOrEmpty(Settings.Credentials))
                {
                    var rawCreds = Settings.Credentials.Split(':');
                    if (rawCreds != null && rawCreds.Length > 1)
                    {
                        client.Credentials = new System.Net.NetworkCredential(rawCreds[0], rawCreds[1]);
                    }
                }

                client.DownloadProgressChanged += (sender, e) =>
                {
                    if (e.TotalBytesToReceive >= 0)
                    {
                        SongDownloadProgress = (double)e.BytesReceived / e.TotalBytesToReceive;

                        return;
                    }

                    var contentLength = long.Parse(client.ResponseHeaders[System.Net.HttpResponseHeader.ContentLength]);
                    if (contentLength > 0)
                    {
                        SongDownloadProgress = (double)e.BytesReceived / contentLength;

                        return;
                    }

                    // Unknown content length. Throw error.
                    throw new HttpRequestException("Unknown download size.");
                };
                client.DownloadFileCompleted += (sender, e) =>
                {
                    //TODO
                };

                var uri = new Uri($"{Settings.ServiceUri}/{song.Id.ToString().ToUpper()}.zip");
                await client.DownloadFileTaskAsync(uri, path);
            }
        }
 protected async Task GetUpdateAsync(string applicationId)
 {
     try
     {
         using (var UpdateWebClient = new System.Net.WebClient())
         {
             await UpdateWebClient.DownloadFileTaskAsync(
                 new Uri(_updateOptions.UpdateUrl + $"software/download?application={applicationId}"),
                 _updateOptions.UpdateFilePath);
         }
     }
     catch (Exception)
     {
         throw new Exception(string.Format("{0}" + System.Environment.NewLine + "{1}",
                                           ServiceLocator.Default.GetInstance <ILanguageService>().GetString("Generic_No_internet_connection_available"),
                                           ServiceLocator.Default.GetInstance <ILanguageService>().GetString("Update_Cannot_install_update")));
     }
 }
        /// <summary>
        /// Downloads a file from HTTP to a local file on disk on the web server.
        /// </summary>
        /// <param name="httpUrl">The URL of the file to download.</param>
        /// <returns>A TempFileStream containing the file path and opened stream to the file.</returns>
        private async Task <TempFileStream> DownloadTempFileLocally(Uri httpUrl)
        {
            var appData = Path.Combine(hosting.ContentRootPath, "App_Data");

            if (!Directory.Exists(appData))
            {
                Directory.CreateDirectory(appData);
            }

            var tempFilePath = Path.Combine(appData, Path.GetRandomFileName());

            using (var downloader = new System.Net.WebClient())
            {
                await downloader.DownloadFileTaskAsync(httpUrl, tempFilePath);
            }

            return(TempFileStream.Open(tempFilePath));
        }
Exemple #21
0
        //static string GetFileNameFromUrl(string url)
        //{
        //    Uri uri;
        //    if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
        //        uri = new Uri(url);
        //    return System.IO.Path.GetFileName(uri.LocalPath);
        //}
        protected async override Task <object> ExecuteAsync(AsyncCodeActivityContext context)
        {
            var url       = URL.Get(context);
            var filepath  = LocalPath.Get(context);
            var overwrite = Overwrite.Get(context);

            filepath = Environment.ExpandEnvironmentVariables(filepath);
            // if(string.IsNullOrEmpty(filename)) filename = "temp."
            if (System.IO.File.Exists(filepath) && !overwrite)
            {
                return(42);
            }
            using (var client = new System.Net.WebClient())
            {
                await client.DownloadFileTaskAsync(new Uri(url), filepath);
            }
            return(42);
        }
Exemple #22
0
        public async Task UploadWorld(CommandContext ctx, string world)
        {
            if (ctx.Message.Attachments.Count == 0)
            {
                throw new ArgumentNullException("Attachments", "The world must have an attachment");
            }

            if (string.IsNullOrWhiteSpace(world))
            {
                throw new ArgumentNullException("world");
            }

            //We are working
            await ctx.TriggerTypingAsync();

            //Download the file, then upload it again
            var url = ctx.Message.Attachments[0].Url;

            using (var client = new System.Net.WebClient())
            {
                string tmpname = Path.GetTempFileName();
                try
                {
                    //Throws unauth
                    await client.DownloadFileTaskAsync(new Uri(url), tmpname);

                    byte[] response = await client.UploadFileTaskAsync(new Uri($"http://localhost:8000/world/{world}"), tmpname);

                    await ctx.ReplyAsync(content : Encoding.UTF8.GetString(response));
                }
                catch (Exception e)
                {
                    await ctx.ReplyExceptionAsync(e);
                }
                finally
                {
                    if (File.Exists(tmpname))
                    {
                        File.Delete(tmpname);
                    }
                }
            }
        }
        //static string GetFileNameFromUrl(string url)
        //{
        //    Uri uri;
        //    if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
        //        uri = new Uri(url);
        //    return System.IO.Path.GetFileName(uri.LocalPath);
        //}
        protected async override Task <object> ExecuteAsync(AsyncCodeActivityContext context)
        {
            var username       = Username.Get(context);
            var password       = Password.Get(context);
            var url            = URL.Get(context);
            var filepath       = LocalPath.Get(context);
            var overwrite      = Overwrite.Get(context);
            var ignoresecurity = IgnoreSecurity.Get(context);

            filepath = Environment.ExpandEnvironmentVariables(filepath);
            // if(string.IsNullOrEmpty(filename)) filename = "temp."
            if (System.IO.File.Exists(filepath) && !overwrite)
            {
                return(42);
            }
            using (var client = new System.Net.WebClient())
            {
                var Expect100Continue = System.Net.ServicePointManager.Expect100Continue;
                var SecurityProtocol  = System.Net.ServicePointManager.SecurityProtocol;
                if (ignoresecurity)
                {
                    System.Net.ServicePointManager.Expect100Continue = true;
                    System.Net.ServicePointManager.SecurityProtocol  = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Ssl3;
                }
                if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password))
                {
                    client.Credentials = new System.Net.NetworkCredential(username, password);
                }
                var dir = System.IO.Path.GetDirectoryName(filepath);
                if (!System.IO.Directory.Exists(dir))
                {
                    System.IO.Directory.CreateDirectory(dir);
                }
                await client.DownloadFileTaskAsync(new Uri(url), filepath);

                if (ignoresecurity)
                {
                    System.Net.ServicePointManager.Expect100Continue = Expect100Continue;
                    System.Net.ServicePointManager.SecurityProtocol  = SecurityProtocol;
                }
            }
            return(42);
        }
Exemple #24
0
        protected override async Task ProcessRecordAsync()
        {
            try
            {
                Uri baseUri = new Uri(global.openflowconfig.baseurl);

                var q = "{\"_id\": \"" + Id + "\"}";
                if (!string.IsNullOrEmpty(Filename))
                {
                    q = "{\"filename\":\"" + Filename + "\"}";
                }
                var rows = await global.webSocketClient.Query <JObject>("files", q, null, 100, 0, "{\"_id\": -1}");

                if (rows.Length == 0)
                {
                    throw new Exception("File not found");
                }
                Filename = rows[0]["filename"].ToString();
                Id       = rows[0]["_id"].ToString();

                string Path = this.SessionState.Path.CurrentFileSystemLocation.Path;

                Uri downloadUri = new Uri(baseUri, "/download/" + Id);
                var url         = downloadUri.ToString();
                using (var client = new System.Net.WebClient())
                {
                    // client.Headers.Add("Authorization", "jwt " + global.webSocketClient);
                    client.Headers.Add(System.Net.HttpRequestHeader.Authorization, global.webSocketClient.jwt);

                    Filename = System.IO.Path.GetFileName(Filename);
                    await client.DownloadFileTaskAsync(new Uri(url), System.IO.Path.Combine(Path, Filename));

                    WriteObject(new System.IO.FileInfo(System.IO.Path.Combine(Path, Filename)));
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
            }
            Id       = null;
            Filename = null;
        }
Exemple #25
0
        public async Task <string> DownloadToTempFile(string url)
        {
            url = url?.Trim();
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(nameof(url));
            }

            bool isValidUri = Uri.TryCreate(url, UriKind.Absolute, out Uri validatedURI);

            if (!isValidUri)
            {
                throw new ArgumentException($"URI {url} is not valid");
            }

            string tempFilePath = Path.Combine(Path.GetTempPath(), validatedURI.Segments.LastOrDefault());

            await _webClient.DownloadFileTaskAsync(validatedURI, tempFilePath).ConfigureAwait(false);

            return(tempFilePath);
        }
Exemple #26
0
        public static void DownloadFile(this ICakeContext context, Uri address, FilePath outputPath)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }
            if (outputPath == null)
            {
                throw new ArgumentNullException("outputPath");
            }

            context.Log.Verbose("Downloading file: {0}", address);

            // We track the last posted value since the event seems to fire many times for the same value.
            var percentComplete = 0;

            using (var http = new System.Net.WebClient())
            {
                http.DownloadProgressChanged += (sender, e) =>
                {
                    // Only write to log if the value changed and only ever 5%.
                    if (percentComplete != e.ProgressPercentage && e.ProgressPercentage % 5 == 0)
                    {
                        percentComplete = e.ProgressPercentage;
                        context.Log.Verbose("Downloading file: {0}%", e.ProgressPercentage);
                    }
                };

                // Download file async so we get the progress events, but block for it to complete anyway.
                http.DownloadFileTaskAsync(address, outputPath.FullPath).Wait();
            }

            context.Log.Verbose("Download complete, saved to: {0}", outputPath.FullPath);
        }
Exemple #27
0
        private async static Task downloadFileAsyncQueue(string remoteUrl, string localUrl)
        {
            if (downloads == null) downloads = new List<Tuple<string, string>>();
            if (!downloads.Contains(new Tuple<string, string>(remoteUrl, localUrl)))
            {
                downloads.Add(new Tuple<string, string>(remoteUrl, localUrl));
                while (downloading)
                {
                    await Task.Delay(100);
                }

                downloading = true;
                //Debug.WriteLine("begin downloading..." + localUrl);
                try
                {
                    using (System.Net.WebClient webClient = new System.Net.WebClient())
                    {
                        await webClient.DownloadFileTaskAsync(new Uri(remoteUrl), localUrl);
                    }
                }
                catch(Exception e)
                {
                    Debug.WriteLine(e);
                    downloading = false;
                }
                //Debug.WriteLine("done downloading");
                downloading = false;
            }
            else
            {
                while(downloads.Count > 0)
                {
                    await Task.Delay(100);
                }
            }        
        }
Exemple #28
0
        public async Task DownloadSong(SongInfo song, string path)
        {
            // Reset Download progress.
            SongDownloadProgress = 0;

            using (var client = new System.Net.WebClient())
            {
                client.DownloadProgressChanged += (sender, e) =>
                {
                    if (e.TotalBytesToReceive >= 0)
                    {
                        SongDownloadProgress = (double)e.BytesReceived / e.TotalBytesToReceive;

                        return;
                    }

                    var contentLength = long.Parse(client.ResponseHeaders[System.Net.HttpResponseHeader.ContentLength]);
                    if (contentLength > 0)
                    {
                        SongDownloadProgress = (double)e.BytesReceived / contentLength;

                        return;
                    }

                    // Unknown content length. Throw error.
                    throw new HttpRequestException("Unknown download size.");
                };
                client.DownloadFileCompleted += (sender, e) =>
                {
                    //TODO
                };

                var uri = new Uri($"{Settings.ServiceUri}/download?id={song.Id.ToString().ToUpper()}");
                await client.DownloadFileTaskAsync(uri, path);
            }
        }
        //private void DownloadCancel()
        //{

        //    PrgrsBr.Value = 0.0;
        //    Progress.Content = "キャンセルされました";
        //}


        async private Task DownloadExec()
        {
            string URL      = URLTB.Text;
            string destpath = Destination.Text;

            bool createnewdir = WhetherCreateDirectory.IsChecked ?? false;
            bool createddir   = false;

            ///URLのチェック///
            if (URL.Length == 0)
            {
                goto noURL;
            }
            if (URL.IndexOf(guitarlistdotnet) != 0)
            {
                goto invalidURL;
            }
            string[] tokens = URL.Substring(guitarlistdotnet.Length).Split('/');
            if (tokens.Length != 3)
            {
                goto invalidURL;
            }
            string[] tokens2 = tokens[2].Split('.');
            if (tokens2.Length != 2)
            {
                goto invalidURL;
            }
            if (tokens2[1] != "php" || (tokens2[0] != tokens[1] && tokens2[0] != (tokens[1] + "2")))
            {
                goto invalidURL;
            }

            ///URLのエラー///
            goto validURL;
noURL:
            MessageBox.Show("URLを入力してください。", "URL入力なし", MessageBoxButton.OK, MessageBoxImage.Error);
            Progress.Content = "エラー";
            URLTB.Focus();
            return;

invalidURL:
            MessageBox.Show("URLが不正です。", "不正なURL", MessageBoxButton.OK, MessageBoxImage.Error);
            Progress.Content = "エラー";
            URLTB.Focus();
            return;

validURL:

            ///保存先のチェック///
            if (destpath.Length == 0)
            {
                MessageBox.Show("保存先を入力してください。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                Progress.Content = "エラー";
                Destination.Focus();
                return;
            }
            if (createnewdir)
            {
                if (!Directory.Exists(destpath))
                {
                    MessageBox.Show("不正なディレクトリ名です。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                    Progress.Content = "エラー";
                    Destination.Focus();
                    return;
                }
                if (destpath[destpath.Length - 1] != '\\')
                {
                    destpath += '\\';
                }
                destpath += tokens[1];
                destpath += '\\';
                if (!Directory.Exists(destpath))
                {
                    try
                    {
                        Directory.CreateDirectory(destpath);
                        createddir = true;
                    } catch (Exception)
                    {
                        MessageBox.Show("フォルダを作成できませんでした。", "フォルダ作成エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                        Progress.Content = "エラー";
                        Destination.Focus();
                        return;
                    }
                }
            }
            else
            {
                if (!Directory.Exists(destpath))
                {
                    try
                    {
                        if (!Directory.GetParent(destpath).Exists)
                        {
                            throw new Exception();
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("不正なディレクトリ名です。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                        Progress.Content = "エラー";
                        Destination.Focus();
                        return;
                    }
                    if (MessageBox.Show("フォルダが存在しません。新規作成しますか?", "フォルダなし", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        try
                        {
                            Directory.CreateDirectory(destpath);
                            createddir = true;
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("フォルダを作成できませんでした。", "フォルダ作成エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                            Progress.Content = "エラー";
                            Destination.Focus();
                            return;
                        }
                    }
                    else
                    {
                        Progress.Content = "エラー";
                        return;
                    }
                }
            }

            ///前処理///
            string targetdir = guitarlistdotnet + tokens[0] + '/' + tokens[1] + '/';
            string jsaddr    = targetdir + tokens[1] + ".js";
            string imgdir    = targetdir + "img/";
            string JSFile;
            string JSLine;
            string searchstr = "photo[pn++]=\"" + imgdir;

            if (destpath[destpath.Length - 1] != '\\')
            {
                destpath += '\\';
            }

            ///// JavaScriptファイルを解析して画像点数を割り出す /////
            Progress.Content = "画像枚数確認中・・・";
            WebClient wc = new WebClient();

            try
            {
                JSFile = await wc.DownloadStringTaskAsync(jsaddr); //javascriptファイルをダウンロード
            }
            catch (Exception)
            {
                MessageBox.Show("JavaScriptファイルがダウンロードできなかったため、画像枚数を確認できませんでした。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                Progress.Content = "エラー";
                wc.Dispose();
                if (createddir)
                {
                    Directory.Delete(destpath);
                }
                return;
            }

            ///// 画像枚数を数え上げる /////
            int imgnum = 0;
            var sr     = new System.IO.StringReader(JSFile);

            while ((JSLine = await sr.ReadLineAsync()) != null)
            {
                if (JSLine.IndexOf(searchstr) == 0)
                {
                    imgnum++;
                }
            }
            if (imgnum == 0)
            {
                MessageBox.Show("JavaScriptファイルの解析が上手く行かず、画像枚数を確認できませんでした。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                Progress.Content = "エラー";
                wc.Dispose();
                if (createddir)
                {
                    Directory.Delete(destpath);
                }
                return;
            }
            string fmt = "D" + (keta(imgnum).ToString());

            PrgrsBr.Maximum = imgnum;


            ///// 画像をダウンロード /////
            try {
                for (int i = 1; i <= imgnum; i++)
                {
                    Progress.Content = "画像ダウンロード中・・・(" + (i.ToString()) + "/" + (imgnum.ToString()) + "枚)";
                    string filename   = (i.ToString()) + ".png";
                    string filenamezr = (i.ToString(fmt)) + ".png";
                    await wc.DownloadFileTaskAsync(imgdir + filename, destpath + filenamezr);

                    PrgrsBr.Value += 1.0;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("画像ダウンロード中にエラーが発生しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                Progress.Content = "エラー";
                PrgrsBr.Value    = 0.0;
                wc.Dispose();
                if (createddir)
                {
                    Directory.Delete(destpath, true);
                }
                return;
            }
            wc.Dispose();
            PrgrsBr.Value    = 0.0;
            Progress.Content = "ダウンロード完了!";
            if (MessageBox.Show("ダンロードが完了しました。フォルダを開きますか?", "ダウンロード完了", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                System.Diagnostics.Process.Start(destpath);
            }
        }
Exemple #30
0
        /// <summary>
        /// Downloads the Android SDK
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="destinationDirectory">Destination directory, or ./tools/androidsdk if none is specified.</param>
        /// <param name="specificVersion">Specific version, or latest if none is specified.</param>
        public async Task DownloadSdk(DirectoryInfo destinationDirectory = null, string specificVersion = null, Action <int> progressHandler = null)
        {
            if (destinationDirectory == null)
            {
                destinationDirectory = AndroidSdkHome;
            }

            if (destinationDirectory == null)
            {
                throw new DirectoryNotFoundException("Android SDK Directory Not specified.");
            }

            if (!destinationDirectory.Exists)
            {
                destinationDirectory.Create();
            }

            var http = new HttpClient();

            http.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
            http.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
            http.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
            http.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");

            string platformStr;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                platformStr = "win";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                platformStr = "mac";
            }
            else
            {
                platformStr = "linux";
            }

            // Use the default known version
            string sdkUrl = "";

            if (string.IsNullOrWhiteSpace(specificVersion))
            {
                try
                {
                    var data = await http.GetStringAsync(REPOSITORY_URL);

                    var xdoc = new System.Xml.XmlDocument();
                    xdoc.LoadXml(data);

                    var urlNode = xdoc.SelectSingleNode($"//remotePackage[@path='cmdline-tools;{ANDROID_SDKMANAGER_DEFAULT_ACQUIRE_VERSION}']/archives/archive/complete/url[contains(text(),'{platformStr}')]");

                    sdkUrl = REPOSITORY_URL_BASE + urlNode.InnerText;
                }
                catch
                {
                }
            }
            else
            {
                // User passed a specific version to use
                sdkUrl = string.Format(REPOSITORY_SDK_PATTERN, platformStr, specificVersion);
            }

            if (string.IsNullOrWhiteSpace(sdkUrl))
            {
                sdkUrl = string.Format(REPOSITORY_SDK_PATTERN, platformStr, REPOSITORY_SDK_DEFAULT_VERSION);
            }


            var sdkDir = new DirectoryInfo(destinationDirectory.FullName);

            if (!sdkDir.Exists)
            {
                sdkDir.Create();
            }

            var sdkZipFile = new FileInfo(Path.Combine(destinationDirectory.FullName, "androidsdk.zip"));


            if (!sdkZipFile.Exists)
            {
                int prevProgress = 0;
                var webClient    = new System.Net.WebClient();

                webClient.DownloadProgressChanged += (s, e) =>
                {
                    var progress = e.ProgressPercentage;

                    if (progress > prevProgress)
                    {
                        progressHandler?.Invoke(progress);
                    }

                    prevProgress = progress;
                };
                await webClient.DownloadFileTaskAsync(sdkUrl, sdkZipFile.FullName);
            }

            ZipFile.ExtractToDirectory(sdkZipFile.FullName, sdkDir.FullName);
        }
Exemple #31
0
        // Call on MainWindow.Loaded event to check on start-up.
        public static async Task CheckForUpdates(bool Silent)
        {
            if (ServiceURI == null || RemoteFileURI == null)
            {
                throw new Exception("AutoUpdater - RemoteFileURI and ServiceURI must be set.");
            }
            try
            {
                System.Net.WebClient       webClient  = new System.Net.WebClient();
                System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
                var result = await httpClient.GetAsync(ServiceURI);

                var strServerVersion = await result.Content.ReadAsStringAsync();

                var serverVersion = Version.Parse(strServerVersion);
                var thisVersion   = Application.ResourceAssembly.ManifestModule.Assembly.GetName().Version;
                if (serverVersion > thisVersion)
                {
                    var strFilePath  = System.IO.Path.GetTempPath() + FileName;
                    var dialogResult = System.Windows.MessageBox.Show("A new version of " + AppName + " is available!  Would you like to download it now?  It's a no-fuss, instant process.", "New Version Available", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (dialogResult == MessageBoxResult.Yes)
                    {
                        if (System.IO.File.Exists(strFilePath))
                        {
                            System.IO.File.Delete(strFilePath);
                        }
                        var windowProgress = new System.Windows.Window();
                        windowProgress.DragMove();
                        windowProgress.Height                = 150;
                        windowProgress.Width                 = 400;
                        windowProgress.WindowStyle           = WindowStyle.None;
                        windowProgress.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        var progressControl = new DownloadProgressControl();
                        windowProgress.Content             = progressControl;
                        webClient.DownloadProgressChanged += (sender, args) => {
                            progressControl.progressBar.Value = args.ProgressPercentage;
                        };
                        windowProgress.Show();
                        await webClient.DownloadFileTaskAsync(new Uri(RemoteFileURI), strFilePath);

                        windowProgress.Close();
                        var psi = new ProcessStartInfo(strFilePath, "-wpfautoupdate \"" + Application.ResourceAssembly.ManifestModule.Assembly.Location + "\"");

                        // Check if target directory is writable with current privileges.  If not, start update process as admin.
                        try
                        {
                            var installPath = Path.GetDirectoryName(Application.ResourceAssembly.ManifestModule.Assembly.Location);
                            var fi          = new FileInfo(Path.Combine(installPath, "Test.txt"));
                            fi.Create();
                            fi.Delete();
                        }
                        catch
                        {
                            psi.Verb = "runas";
                        }
                        Process.Start(psi);
                        Application.Current.Shutdown();
                        return;
                    }
                }
                else
                {
                    if (!Silent)
                    {
                        MessageBox.Show(AppName + " is up-to-date.", "No Updates", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch
            {
                if (!Silent)
                {
                    MessageBox.Show("Unable to contact the server.  Check your network connection or try again later.", "Server Unreachable", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
                return;
            }
        }
		public async System.Threading.Tasks.Task DoDownload()
		{
			var client = new System.Net.WebClient();
			client.DownloadProgressChanged += (sender, args) => {
				this.Progress = args.ProgressPercentage/100.0;
			};
			cancelSource.Token.Register(() => {
				client.CancelAsync();
			}, true);
			this.State = UpdateActionState.Downloading;
			try {
				downloadPath = System.IO.Path.Combine(
					Shell.GetKnownFolder(Shell.KnownFolder.Downloads),
					System.IO.Path.GetFileName(SelectedEnclosure.Url.AbsolutePath));
				await client.DownloadFileTaskAsync(
					selectedEnclosure.Url.ToString(),
					downloadPath);
				this.State = UpdateActionState.Downloaded;
			}
			catch (System.Net.WebException) {
				this.State = UpdateActionState.Aborted;
			}
		}