/// <summary> /// Download the installer from Github API, run the installer in separate process /// </summary> /// <param name="update">Which version to retrieve</param> /// <returns>True on success</returns> public async Task <bool> DownloadVersion(Downloadable update) { var content = await _httpClient.GetAsync(update.Url); if (content.IsSuccessStatusCode) { var file = Path.GetTempPath() + Path.GetFileName(update.Url.Segments.Last()); File.WriteAllBytes(file, await content.Content.ReadAsByteArrayAsync()); // Get uninstall product code from registry string code = ""; var uninstallKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall"); var progs = uninstallKey.GetSubKeyNames(); foreach (string s in progs) { string dname = (string)uninstallKey.OpenSubKey(s).GetValue("DisplayName", ""); if (dname == Assembly.GetExecutingAssembly().GetCustomAttribute <AssemblyProductAttribute>().Product) { code = s; } } // Run uninstaller, installer in new process Process proc = new Process(); string cmd = "start /wait msiexec /x \"" + code + "\" /passive && start /wait msiexec /i \"" + file + "\""; proc.StartInfo.FileName = Environment.GetEnvironmentVariable("ComSpec"); proc.StartInfo.Arguments = "/c " + cmd; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.Start(); return(true); } return(false); }
public void GoToDetails(Downloadable <Brew> parameter) { if (parameter.Value.HasDetails) { Locator.Details.Brew = parameter; Locator.Main.GoTo <Details>(); } }
private IEnumerator StartDownload() { Downloadable toDownload = s_Queue.Dequeue(); yield return(StartCoroutine("OnDownload", toDownload)); Debug.Log("downloaded: " + toDownload.Url); toDownload.Callback(m_Downloader); StartNextDownload(); }
public void UpdateProgress(Downloadable File) { if (File.Completed) { Close(); } textBox1.Text = File.URL; label9.Text = downloader.DownloadStatus.ToString(); label11.Text = NetworkHelper.DataFormatter(File.Downloaded) + " ( " + File.Percent.ToString("0.00") + "% )"; label12.Text = NetworkHelper.DataFormatter(File.TransferRate) + "/Sec"; label14.Text = "No"; Text = downloader.File.FileName; if (File.DownloadType != DownloadTypes.MultiplePartResumable) { rangeProgressBar1.Visible = false; } if (File.DownloadType != DownloadTypes.SinglePartUnknownSize) { label10.Text = NetworkHelper.DataFormatter(File.Size); label13.Text = NetworkHelper.TimeLeft(File.TransferRate, File.Downloaded, File.Size); progressBar1.Maximum = (int)File.Size; progressBar1.Value = (int)File.Downloaded; if (File.DownloadType == DownloadTypes.MultiplePartResumable) { label14.Text = "Yes"; button1.Visible = true; if (rangeProgressBar1.Visible == false) { rangeProgressBar1.Visible = true; } if (File.RangeList != null) { rangeProgressBar1.Ranges = GetRangeEquivalent(File.RangeList); } rangeProgressBar1.Invalidate(); } else { button1.Visible = false; } } else { button1.Enabled = false; label10.Text = File.Size.ToString(); label13.Text = "Undefined"; } }
public void GoTo(Downloadable <Brew> downloadable) { if (BrewDownloader.Instance.IsDownloaded(downloadable.Value)) { Process.Start(BrewDownloader.Instance.BrewPath(downloadable.Value)); } else { downloadable.State = DownloadState.WaitingToDownload; } }
private void parser_Redownload(object sender, Downloadable file) { Invoke((MethodInvoker) delegate() { Downloader downloader = new Downloader(file); downloader.Timeout = SettingsWindow.GeneralSettings.Timeout; downloader.OnError += Down_OnError; downloader.OnDownloadFinished += Downloader_OnProgress; downloader.OnProgress += Downloader_OnProgress; DownloaderList.Add(downloader); downloader.Download(); UpdateChangesInGrid(); }); }
public async Task Download(Downloadable <Brew> downloadable) { string brewPath = BrewPath(downloadable.Value); ClearUnfinishedDownloads(brewPath); if (IsDownloaded(downloadable.Value)) { downloadable.State = DownloadState.Downloaded; return; } Directory.CreateDirectory(BrewPath(downloadable.Value)); string fileName = $"{Guid.NewGuid().ToString("N")}.{TempFileExtension}"; string filePath = Path.Combine(brewPath, fileName); WebClient client = new WebClient(); client.DownloadProgressChanged += (_, e) => { downloadable.TotalSize = ByteSize.FromBytes(e.TotalBytesToReceive); downloadable.DownloadedSize = ByteSize.FromBytes(e.BytesReceived); if (!downloadable.IsTotalSizeUnknown) { downloadable.Percentage = e.ProgressPercentage; } }; client.DownloadFileCompleted += (_, e) => { if (e.Cancelled || e.Error != null) { downloadable.State = e.Cancelled ? DownloadState.WaitingToDownload : DownloadState.DownloadFailed; ClearUnfinishedDownloads(brewPath); } else { downloadable.State = DownloadState.Downloaded; var contentDisposition = client.ResponseHeaders["content-disposition"]; if (contentDisposition != null) { string realFileName = ClearInvalidFileNameChars(contentDisposition?.Split(';')?.Last()?.Split('=')?.Last() ?? Path.GetFileName(new Uri(downloadable.Value.DownloadUri).LocalPath), string.Empty); string realFilePath = Path.Combine(brewPath, realFileName); File.Move(filePath, realFilePath); } } downloadable.Clear(); }; downloadable.State = DownloadState.Downloading; downloadable.CancellationTokenSource = new CancellationTokenSource(); await Try.ItAsync(async() => await client.DownloadFileTaskAsync(downloadable.Value.DownloadUri, filePath, downloadable.CancellationTokenSource.Token)); }
private void ReDownload(Downloader d) { Downloadable file = new Downloadable() { URL = d.File.URL, DegreeOfParallelism = (uint)SettingsWindow.GeneralSettings.MaxConnection, FilePath = SettingsWindow.GeneralSettings.StoragePath }; DownloaderList.Remove(d); HeaderParser parser = new HeaderParser(file); parser.OnParseSuccess += parser_Redownload; parser.OnError += Down_OnError; parser.ParseHeader(); }
/// <summary> /// Downloads the song in the background if it's not already available offline. /// </summary> /// <param name="track"></param> public async Task SubmitDownload(MusicItem track) { await BeforeDownload(track); try { var maybeLocalUri = await PhoneLocalLibrary.Instance.LocalUriIfExists(track); if (maybeLocalUri == null) { // For Subsonic, the response may be transcoded audio, in which case the // path to the track, which has the original file extension as stored on // the server, may be incorrect (example: response is transcoded to .mp3, // path is .flac). // TODO: Ensure that the file is stored locally with the correct extension, // that is, find out whether the response is transcoded. var destination = LocalLibrary.AbsolutePathTo(track); var downloadUri = MusicProvider.DownloadUriFor(track); // Only downloads tracks that are stored as MP3s, because this app does not support other local file formats. if (destination.EndsWith("mp3")) { var downloadable = new Downloadable(downloadUri, destination); if (LoadTransfersCount() < 3) { AddTransfer(downloadUri, destination); } else { // add the download to persistent storage from which it will be taken // later when there are fewer concurrent downloads DownloadDataContext.Add(downloadable); } } } } catch (PathTooLongException) { // Thrown if track.Path is about over 190 characters long, but I'm not sure what // the limit is and I don't want to be too defensive with this so I catch and // suppress the exception when it occurs. // The exception says "The specified path, file name, or both are too long. // The fully qualified file name must be less than 260 characters, and the // directory name must be less than 248 characters.", however, I don't know // the length of the fully qualified path name, so 190 chars is an estimate. AddMessage("Download of " + track.Name + " failed. The path is too long: " + track.Path); } }
private void ReDownload(string directURL = null, string FileName = null) { if (dataGridView1.Rows.Count <= 0 && directURL == null) { return; } int ind = -1; if (dataGridView1.Rows.Count > 0) { ind = dataGridView1.Rows.IndexOf(dataGridView1.SelectedRows[0]); } if (ind >= 0 || directURL != null) { if (ind >= 0) { DownloaderList[ind].Pause(); } Downloadable file = new Downloadable() { URL = directURL == null?DownloaderList[ind].File.URL:directURL, FileName = FileName == null?DownloaderList[ind].File.FileName:FileName, DegreeOfParallelism = (uint)SettingsWindow.GeneralSettings.MaxConnection, FilePath = SettingsWindow.GeneralSettings.StoragePath }; if (FileName != null) { file.FileName = FileName; } if (directURL == null) { DownloaderList.Remove(DownloaderList[ind]); } HeaderParser parser = new HeaderParser(file); parser.OnParseSuccess += parser_Redownload; parser.OnError += Down_OnError; parser.ParseHeader(); } }
private void Parser_OnParseSuccess(object sender, Downloadable File) { Invoke((MethodInvoker) delegate() { if (GetDuplicateDownloaderIndex(File.URL) == -1) { DownloadNowWindow dnw = new DownloadNowWindow(); dnw.URL = File.URL; dnw.FullFilePath = File.FullFilePath; dnw.FileName = File.FileName; dnw.FilePath = File.FilePath; dnw.FileSize = File.Size; var res = dnw.ShowDialog(); if (res == DialogResult.OK) { File.FileName = dnw.FileName; File.FilePath = dnw.FilePath; Downloader downloader = new Downloader(); downloader.Timeout = SettingsWindow.GeneralSettings.Timeout; downloader.File = File; downloader.OnProgress += Downloader_OnProgress; downloader.OnDownloadFinished += Downloader_OnProgress; downloader.OnError += Down_OnError; DownloaderList.Add(downloader); downloader.Download(); } } else { var r = MessageBox.Show("Download File Already added , Do you want to over write it", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question); switch (r) { case DialogResult.Yes: ReDownload(DownloaderList[GetDuplicateDownloaderIndex(File.URL)]); break; } } }); }
private void AddURL(string URL = null) { AddURLWindow auw = new AddURLWindow(); if (URL != null) { auw.URL = URL; } DialogResult res = auw.ShowDialog(); if (res == DialogResult.OK) { Downloadable file = new Downloadable() { URL = auw.URL, DegreeOfParallelism = (uint)SettingsWindow.GeneralSettings.MaxConnection, FilePath = SettingsWindow.GeneralSettings.StoragePath }; HeaderParser parser = new HeaderParser(file); parser.OnParseSuccess += Parser_OnParseSuccess; parser.OnError += Down_OnError; parser.ParseHeader(); } }
public async Task DownloadAsync(Downloadable <Brew> downloadable) => await BrewDownloader.Instance.Download(downloadable);
public ActionResult CreateBulkEnrollment(HttpPostedFileBase file) { // Make sure the user is logged in and that they have permission if (!IsUserLoggedIn) { return(RedirectToLogin()); } if (!UserHasPermission(PermissionName.UnitOffering)) { return(RedirectToPermissionDenied()); } //Create data which needs to be outside the try-catch block FileCSV data = null; int uploadCount = 0; int failCount = 0; Downloadable errorFile = null; // Enter a try-catch block to make sure any exceptions are caught try { // Decode the CSV file data = new FileCSV(file); // Make sure the headers are correct // This will throw an exception if not data.ValidateHeaders(new string[] { "Unit", // 0 "TeachingPeriod", // 1 "Year", // 2 "Student" // 3 }); // Loop through each row of data // Generate the list of results foreach (string[] row in data.Row) { try { //var unit = db.GetUnitForName( row[ 0 ] ); //if( unit == null ) // throw new DataException( "Unit doesn't exist. " ); //var teachingPeriod = db.GetTeachingPeriodForName( row[ 1 ] ); //if( teachingPeriod == null ) // throw new DataException( "TeachingPeriod doesn't exist. " ); //var year = db.GetYearForYearValue( Int32.Parse( row[ 2 ] ) ); //if( year == null ) // throw new DataException( "Year doesn't exist. " ); var unitOffering = db.GetUnitOfferingForDetails(row[0], row[1], Int32.Parse(row[2])); if (unitOffering == null) { throw new DataException("UnitOffering doesn't exist. "); } var student = db.GetUserForUsername(row[3]); if (student == null) { throw new DataException("Convenor doesn't exist. "); } EnrollmentProcessor.InsertEnrollmentModel(unitOffering.UnitOfferingId, student.UserId); data.SetComment(row, ""); uploadCount++; } catch (Exception e) { data.SetComment(row, e.Message); failCount++; } } // Generate and record the error file, if required if (failCount > 0) { errorFile = Downloadable.CreateCSV(data.GenerateErrorFile( ), "errors.csv"); } } catch (Exception e) { // Record error message for View TempData["UploadError"] = e.Message; } // Record item counts for View if (uploadCount > 0) { TempData["UploadCount"] = uploadCount; } if (failCount > 0) { TempData["FailCount"] = failCount; } Session[FileCSV.SessionLabelUploadErrorLog] = (failCount > 0) ? errorFile : null; // All file processing has been completed // Go to normal create page return(RedirectToAction("Index", "UnitOffering")); }
public ActionResult CreateBulk(HttpPostedFileBase file) { // Make sure the user is logged in and that they have permission if (!IsUserLoggedIn) { return(RedirectToLogin()); } if (!UserHasPermission(PermissionName.User)) { return(RedirectToPermissionDenied()); } // Create data which needs to be outside the try-ctach block FileCSV data = null; int uploadCount = 0; int failCount = 0; Downloadable errorFile = null; // Enter a try-catch block to make sure any exceptions are caught try { // Decode the CSV file data = new FileCSV(file); // Make sure the headers are correct // This will throw an exception if not data.ValidateHeaders(new string[] { "Username", // 0 "FirstName", // 1 "LastName", // 2 "Email", // 3 "PhoneNo", // 4 "Password" // 5 }); // Loop through each row of data // Generate the list of results foreach (string[] row in data.Row) { // Generate a password salt // Hash the password string passwordSalt = UserLogin.CreatePasswordSalt(); string password = UserLogin.HashPassword(row[5], passwordSalt); // Create the user within the database try { CreateUser( row[0], // Username row[1], // FirstName row[2], // LastName row[3], // Email Convert.ToInt32(row[4]), // PhoneNo password, passwordSalt); data.SetComment(row, ""); uploadCount++; } catch (Exception e) { data.SetComment(row, e.Message); failCount++; } } // Generate and record the error file, if required if (failCount > 0) { errorFile = Downloadable.CreateCSV(data.GenerateErrorFile(), "errors.csv"); } } catch (Exception e) { // Record error message for View TempData["UploadError"] = e.Message; } // Record item counts for View if (uploadCount > 0) { TempData["UploadCount"] = uploadCount; } if (failCount > 0) { TempData["FailCount"] = failCount; } Session[FileCSV.SessionLabelUploadErrorLog] = (failCount > 0) ? errorFile : null; // All file processing has been completed // Go to the normal create page return(RedirectToAction("Create", "User")); }
private IEnumerator OnDownload(Downloadable toDownload) { m_Downloader = new WWW(toDownload.Url); yield return(m_Downloader); }