private void CancelJobs() { if (MessageBox.Show(this, "Are you sure you want to cancel (delete) the job?", "Deleting the job...?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { BitsManager.PerformActions(this.GetSelectedJobGuids(), BitsJobActions.CANCEL_JOB); } }
private void Form1_Load(object sender, EventArgs e) { if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Downloads")) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Downloads"); } _downloadManager = new BitsManager(); _downloadManager.OnJobModified += downloadManager_OnJobModified; _downloadManager.OnJobTransferred += downloadManager_OnJobTransferred; _downloadManager.EnumJobs(JobOwner.CurrentUser); foreach (var job in _downloadManager.Jobs.Values) { if (job.State == JobState.Transferred) { job.Complete(); } else { AddJobFlags(job); } } _colIDs = new ColumnIDs(dataGridView1); dataGridView1.Rows.AddRange(GetDownloadJobsAsRows().ToArray()); }
private void RefreshList(Dictionary <Guid, BitsJob> jobs) { CheckAndAddNewJobs(jobs); for (int i = 0; i < lstDownloads.Items.Count; i++) { if (lstDownloads.Items[i] == null) { continue; } Guid g = (Guid)lstDownloads.Items[i].Tag; BitsJob j = jobs[g]; lstDownloads.Items[i].SubItems[2] = new ListViewItem.ListViewSubItem(lstDownloads.Items[i], (j.PercentComplete).ToString("00.00 %", CultureInfo.InvariantCulture)); lstDownloads.Items[i].SubItems[3] = new ListViewItem.ListViewSubItem(lstDownloads.Items[i], j.JobStateDescription); if (j.BytesTotal == ulong.MaxValue) { lstDownloads.Items[i].SubItems[5] = new ListViewItem.ListViewSubItem(lstDownloads.Items[i], "?"); } if ((lstDownloads.Items[i].SubItems[5].Text == "?") && (j.JobState == BitsJobState.TRANSFERRING)) { lstDownloads.Items[i].SubItems[5] = new ListViewItem.ListViewSubItem(lstDownloads.Items[i], (j.BytesTotal / 1048576.0).ToString("N", CultureInfo.InvariantCulture)); } lstDownloads.Items[i].SubItems[6] = new ListViewItem.ListViewSubItem(lstDownloads.Items[i], (j.BytesTransferred / 1048576.0).ToString("N", CultureInfo.InvariantCulture)); if (this.tsmiAutoRestart.Checked && ((j.JobState == BitsJobState.ERROR || (j.JobState == BitsJobState.TRANSIENT_ERROR)))) { BitsManager.ResumeJob(j.Guid); } } ColourJobs(); AutoCompleteJobs(); MakeFirstJobsActive(); UpdateStatusInfo(); }
// Methods public JobDetailsForm(JobWrapper wrapper) { this.wrapper = wrapper; this.manager = wrapper.Manager; this.job = wrapper.BitsJob; this.InitializeComponent(); this.bitsJobDetails.InitControl(wrapper); this.Text = this.job.DisplayName; }
private void Form1_Load(object sender, EventArgs e) { _manager = new BitsManager(); _manager.EnumJobs(JobOwner.CurrentUser); foreach (var job in _manager.Jobs.Values) { listBox1.Items.Add(job.DisplayName); } }
private void AddJob() { AddJob addjob = new AddJob(); addjob.AutoStartJob = this.tsmiAutoStart.Checked; if (addjob.ShowDialog(this) == DialogResult.OK) { BitsManager.AddJob(addjob.Url, addjob.JobName, addjob.Directory, addjob.AutoStartJob); } }
private void MakeFirstJobsActive() { if (_activeJobs == ActiveJobs.Manual) { return; } int activeJobsNum = 0; switch (_activeJobs) { case ActiveJobs.One: activeJobsNum = 1; break; case ActiveJobs.Three: activeJobsNum = 3; break; case ActiveJobs.Five: activeJobsNum = 5; break; case ActiveJobs.All: activeJobsNum = lstDownloads.Items.Count; break; } int counter = 0; for (int i = 0; i < lstDownloads.Items.Count; i++, counter++) { Guid g = (Guid)lstDownloads.Items[i].Tag; if (!_bitsJobs.ContainsKey(g)) { continue; } BitsJob j = _bitsJobs[g]; if ((counter < activeJobsNum) && (j.JobState != BitsJobState.TRANSFERRING && j.JobState != BitsJobState.TRANSFERRED && j.JobState != BitsJobState.CONNECTING && j.JobState != BitsJobState.QUEUED)) { BitsManager.ResumeJob(g); } else { if ((counter >= activeJobsNum) && (j.JobState != BitsJobState.SUSPENDED)) { BitsManager.SuspendJob(g); } } } }
private void RefreshJobs() { _bitsJobs = BitsManager.GetAllJobs(); if (!_listFilled) { FillList(_bitsJobs); } else { RefreshList(_bitsJobs); } }
public static void CancelRunningJob() { if (Settings.Instance.BitsJobId.HasValue) { using (var bitsManager = new BitsManager()) { BitsJob runningJob; if (bitsManager.EnumJobs().TryGetValue(Settings.Instance.BitsJobId.Value, out runningJob)) { runningJob.Cancel(); } } Settings.Instance.BitsJobId = null; Settings.Instance.Save(); } }
/// <summary>Reports a download error.</summary> /// <param name="sender">The object that called the event.</param> /// <param name="e">The <c>SharpBits.Base.ErrorNotificationEventArgs</c> instance containing the event data.</param> static void ReportDownloadError(object sender, ErrorNotificationEventArgs e) { if (e.Job == null) { return; } if (e.Job.DisplayName != jobName) { return; } if (e.Job.State != JobState.Error) { return; } errorOccurred = true; if (e.Job.State != JobState.Canceled) { e.Job.Cancel(); } try { manager.Dispose(); manager = null; } catch (ObjectDisposedException) { } string error = null; if (e.Error != null) { error = " " + e.Error.Description + " " + e.Error.ContextDescription; if (e.Error.File != null) { error += " " + e.Error.File.RemoteName; } } Utilities.ReportError(new WebException(error), ErrorType.DownloadError); return; }
public void InitializeControl(BitsManager bitsManager) { if (bitsManager == null) { base.Enabled = false; } else { this.bitsManager = bitsManager; Settings.Default.ShowAllJobs = !Settings.Default.ShowAllJobs; this.ShowAllJobs(); bitsManager.OnJobError += new EventHandler <ErrorNotificationEventArgs>(this.manager_OnJobErrorEvent); bitsManager.OnJobModified += new EventHandler <NotificationEventArgs>(this.manager_OnJobModifiedEvent); bitsManager.OnJobTransferred += new EventHandler <NotificationEventArgs>(this.manager_OnJobTransferredEvent); bitsManager.OnJobAdded += new EventHandler <NotificationEventArgs>(this.manager_OnJobAdded); } }
private void AutoCompleteJobs( ) { for (int i = 0; i < lstDownloads.Items.Count; i++) { Guid g = (Guid)lstDownloads.Items[i].Tag; if (!_bitsJobs.ContainsKey(g)) { continue; } BitsJob j = _bitsJobs[g]; if (j.JobState == BitsJobState.TRANSFERRED) { notifyIcon.ShowBalloonTip(1000, "Download complete", String.Format("Downloading job: {0} finished", j.DisplayName), ToolTipIcon.Info); BitsManager.CompleteJob(j.Guid); } } ShutdownWindows(); }
private static bool CheckRunningJob(BitsManager bitsManager) { if (Settings.Instance.BitsJobId.HasValue) { BitsJob runningJob; if (bitsManager.EnumJobs().TryGetValue(Settings.Instance.BitsJobId.Value, out runningJob)) { if (runningJob.State == JobState.Transferred) { _logger.Debug("Download completed"); Settings.Instance.BitsJobId = null; Settings.Instance.Save(); runningJob.Complete(); } else if (runningJob.State == JobState.Error) { var error = runningJob.Error; _logger.Error($"Download of {error.File.RemoteName} failed: {error.Description}\n{error.ContextDescription}"); Settings.Instance.BitsJobId = null; Settings.Instance.Save(); runningJob.Cancel(); } else if (runningJob.State == JobState.TransientError) { var error = runningJob.Error; _logger.Warn("Download of {0} is failing: {1}\n{2}", error.File.RemoteName, error.Description, error.ContextDescription); } else if (runningJob.State == JobState.Transferring) { var progress = runningJob.Progress; _logger.Debug( $"Download is in progress (files {progress.FilesTransferred} of {progress.FilesTotal}, bytes {progress.BytesTransferred} of {progress.BytesTotal})"); } return(true); } else { Settings.Instance.BitsJobId = null; Settings.Instance.Save(); } } return(false); }
/// <summary>Reports when a download completes.</summary> /// <param name="sender">The object that called the event.</param> /// <param name="e">The <c>SharpBits.Base.NotificationEventArgs</c> instance containing the event data.</param> static void ReportDownloadComplete(object sender, NotificationEventArgs e) { if (e.Job == null) { return; } if (e.Job.DisplayName != jobName) { return; } if (e.Job.State != JobState.Transferred) { return; } IsDownloading = false; e.Job.Complete(); if (cancelDownload) { Environment.Exit(0); } if (DownloadCompleted != null) { DownloadCompleted(null, new DownloadCompletedEventArgs(errorOccurred)); } manager.OnJobTransferred -= ReportDownloadComplete; manager.OnJobError -= ReportDownloadError; manager.OnJobModified -= ReportDownloadProgress; try { manager.Dispose(); manager = null; } catch (ObjectDisposedException) { } }
private void Form_Load(object sender, EventArgs e) { try { ServiceController controller = new ServiceController("BITS"); if (controller.Status != ServiceControllerStatus.Running) { this.OutputMessage(string.Format("{0} was {1}. Service will be started now.", controller.DisplayName, controller.Status.ToString().ToLower(CultureInfo.CurrentCulture)), MessageLevel.Information); controller.Start(); } else { this.OutputMessage(string.Format("{0} is {1}", controller.DisplayName, controller.Status.ToString().ToLower(CultureInfo.CurrentCulture)), MessageLevel.Information); } } catch (Exception exception) { this.OutputMessage(exception.Message, MessageLevel.Error); this.jobListControl.InitializeControl(null); return; } this.manager = new BitsManager(); this.manager.OnInterfaceError += new EventHandler <BitsInterfaceNotificationEventArgs>(this.manager_OnInterfaceError); this.manager.OnJobAdded += new EventHandler <NotificationEventArgs>(this.manager_OnJobAdded); this.manager.OnJobRemoved += new EventHandler <NotificationEventArgs>(this.manager_OnJobRemoved); this.manager.OnJobError += new EventHandler <ErrorNotificationEventArgs>(this.manager_OnJobError); this.manager.OnJobTransferred += new EventHandler <NotificationEventArgs>(this.manager_OnJobTransferred); this.jobListControl.OnJobListOwnerChanged += new EventHandler(this.jobListControl_OnJobListOwnerChanged); this.jobListControl.InitializeControl(this.manager); while (this.ctxMainForm.Items.Count > 0) { ToolStripItem item = this.ctxMainForm.Items[0]; this.ctxMainForm.Items.RemoveAt(0); this.jobListControl.ContextMenuStrip.Items.Add(item); } this.txtMessages.ContextMenuStrip = this.jobListControl.ContextMenuStrip; this.ContextMenuStrip = this.jobListControl.ContextMenuStrip; this.SetApplicationHints(); }
private bool DownloadMovies() { using (var bitsManager = new BitsManager()) { bitsManager.OnInterfaceError += (sender, args) => _logger.Error("BITS error: {0}\n{1}", args.Message, args.Description); if (CheckRunningJob(bitsManager)) { return(false); } var moviesToDownload = _movies .Where(m => string.IsNullOrEmpty(m.LocalPath) || !File.Exists(m.LocalPath)) .Take(200) .ToList(); if (moviesToDownload.Any()) { var job = bitsManager.CreateJob("AerialForWindows", JobType.Download); job.Priority = JobPriority.Low; job.MinimumRetryDelay = 5 * 60; // 5 minutes job.NoProgressTimeout = 30 * 60; // 30 minutes foreach (var movie in moviesToDownload) { var localPath = GetLocalPathForMovie(movie); movie.LocalPath = localPath; job.AddFile(movie.DownloadUrl, localPath); } job.Resume(); Settings.Instance.BitsJobId = job.JobId; Settings.Instance.Save(); _logger.Debug($"Startet download of {moviesToDownload.Count} files"); return(true); } return(false); } }
public JobWrapper(BitsManager manager, Guid jobId) : this() { this.manager = manager; this.jobId = jobId; }
public void AddJob(string url, string jobName, string directory) { BitsManager.AddJob(url, jobName, directory, true); }
/// <summary>Downloads the updates using BITS.</summary> /// <param name="appUpdates">The application updates to download.</param> /// <param name="downloadName">The name of the job.</param> /// <param name="downloadLocation">The directory where the files are downloaded are stored.</param> /// <param name="isPriority">If set to <c>True</c> the updates will download with priority.</param> public static void DownloadUpdates( Collection <Sui> appUpdates, string downloadName, string downloadLocation, bool isPriority = false) { downloadDirectory = downloadLocation; jobName = downloadName; if (appUpdates == null) { throw new ArgumentNullException(@"appUpdates"); } if (appUpdates.Count < 1) { throw new ArgumentOutOfRangeException(@"appUpdates"); } IsDownloading = true; // It's a new manager class manager = new BitsManager(); // Assign the event handlers manager.OnJobTransferred -= ReportDownloadComplete; manager.OnJobError -= ReportDownloadError; manager.OnJobModified -= ReportDownloadProgress; manager.OnJobTransferred += ReportDownloadComplete; manager.OnJobError += ReportDownloadError; manager.OnJobModified += ReportDownloadProgress; // Load the BITS Jobs for the entire machine and current user manager.EnumJobs(); manager.EnumJobs(JobOwner.AllUsers); int jobCount = 0; // Loops through the jobs, if a Seven Update job is found, try to resume, if not cancel it. foreach (var job in manager.Jobs.Values.Where(job => job.DisplayName == jobName).ToList()) { jobCount++; job.EnumerateFiles(); if (job.Files.Count < 1) { job.Cancel(); jobCount--; } if (job.State == JobState.Suspended) { job.Resume(); } if (job.State == JobState.Transferred) { job.Complete(); IsDownloading = false; if (DownloadCompleted != null) { DownloadCompleted(null, new DownloadCompletedEventArgs(false)); } return; } if ((job.State != JobState.Error && job.State != JobState.TransientError) && job.ErrorCount <= 0) { continue; } Utilities.ReportError( new WebException(job.Error.Description + " " + job.Error.ErrorCode), ErrorType.DownloadError); job.Cancel(); jobCount--; } if (jobCount > 0) { return; } BitsJob bitsJob = manager.CreateJob(jobName, JobType.Download); bitsJob.Priority = isPriority ? JobPriority.Foreground : JobPriority.Normal; bitsJob.NotificationOptions = NotificationOptions.JobErrorOccurred | NotificationOptions.JobModified | NotificationOptions.JobTransferred; bitsJob.NoProgressTimeout = 60; bitsJob.MinimumRetryDelay = 60; foreach (var update in appUpdates) { DownloadUpdates(update, ref bitsJob); } bitsJob.EnumerateFiles(); if (bitsJob.Files.Count > 0) { bitsJob.Resume(); } else { bitsJob.Cancel(); IsDownloading = false; if (DownloadCompleted != null) { DownloadCompleted(null, new DownloadCompletedEventArgs(false)); } } }
private void MakeAllJobsActive() { BitsManager.PerformActions(_bitsJobs.Keys.ToList <Guid>(), BitsJobActions.RESUME_JOB); }
private void ResumeJobs() { BitsManager.PerformActions(GetSelectedJobGuids(), BitsJobActions.RESUME_JOB); }
private void SuspendJobs() { BitsManager.PerformActions(GetSelectedJobGuids(), BitsJobActions.SUSPEND_JOB); }
private void CompleteJobs() { BitsManager.PerformActions(this.GetSelectedJobGuids(), BitsJobActions.COMPLETE_JOB); }
static void Main(string[] args) { BitsManager manager = new BitsManager(); System.Console.WriteLine("Bits Version is {0}", BitsManager.BitsVersion); if (BitsManager.BitsVersion >= BitsVersion.Bits2_0) { //BitsJob newJob = manager.CreateJob("TestJob2", JobType.Download); //Collection<FileRange> fileRanges = new Collection<FileRange>(); //fileRanges.Add(new FileRange(0, 1000)); //fileRanges.Add(new FileRange(2000, 1000)); //fileRanges.Add(new FileRange(4000, 1000)); //fileRanges.Add(new FileRange(6000, 1000)); //fileRanges.Add(new FileRange(8000, 1000)); //newJob.AddFileWithRanges("http://localhost/bits/en_windows_sharepoint_services_3.0.exe", "C:\\temp\\download.file", fileRanges); } else { // BitsJob newJob = manager.CreateJob("TestJob", JobType.Upload); // newJob.AddFile("http://localhost/bits/UploadReply.file", "C:\\temp\\download.file"); // string program = @"C:\Program Files\TextPad 5\TextPad.exe"; //newJob.NotifyCommandLineProgram = program; //newJob.NotifyCommandLineParameters = "C:\\Temp\\New Text Document.cs"; //newJob.NotificationFlags = NotificationFlags.JobTransferred | NotificationFlags.JobErrorOccured; } manager.EnumJobs(JobOwner.CurrentUser); System.Console.WriteLine("Job Count for current user: {0}", manager.Jobs.Count.ToString()); foreach (BitsJob job in manager.Jobs.Values) { System.Console.WriteLine("Displayname for job: {0}", job.DisplayName); System.Console.WriteLine("Description: {0}", job.Description); System.Console.WriteLine("Owner: {0}", job.Owner); System.Console.WriteLine("Owner Name: {0}", job.OwnerName); System.Console.WriteLine("Priority: {0}", job.Priority.ToString()); job.EnumFiles(); System.Console.WriteLine("File Count for current job: {0}", job.Files.Count.ToString()); foreach (BitsFile file in job.Files) { System.Console.WriteLine("File Name: {0}", file.LocalName); System.Console.WriteLine("Remote File Name: {0}", file.RemoteName); System.Console.WriteLine("Bytes total: {0}", file.Progress.BytesTotal.ToString()); System.Console.WriteLine("Bytes transfered: {0}", file.Progress.BytesTransferred.ToString()); System.Console.WriteLine("File Completed: {0}", file.Progress.Completed.ToString()); if (BitsManager.BitsVersion >= BitsVersion.Bits2_0) { System.Console.WriteLine("File Ranges for current job: {0}", file.FileRanges.Count.ToString()); foreach (FileRange range in file.FileRanges) { System.Console.WriteLine("File Range Offset: {0}", range.InitialOffset); System.Console.WriteLine("File Range Length: {0}", range.Length); } } } System.Console.WriteLine("Job Id: {0}", job.JobId.ToString()); System.Console.WriteLine("Job State: {0}", job.State.ToString()); System.Console.WriteLine("Job CreationTime: {0}", job.JobTimes.CreationTime.ToString()); System.Console.WriteLine("Job ModificationTime: {0}", job.JobTimes.ModificationTime.ToString()); System.Console.WriteLine("Job TransferCompletionTime: {0}", job.JobTimes.TransferCompletionTime.ToString()); System.Console.WriteLine("Job Type: {0}", job.JobType.ToString()); job.ProxySettings.ProxyUsage = ProxyUsage.AutoDetect; System.Console.WriteLine("Proxy Usage: {0}", job.ProxySettings.ProxyUsage.ToString()); System.Console.WriteLine("Proxy List: {0}", job.ProxySettings.ProxyList); System.Console.WriteLine("Proxy Bypass List: {0}", job.ProxySettings.ProxyBypassList); System.Console.WriteLine("Error Count for current job: {0}", job.ErrorCount.ToString()); BitsError error = job.Error; if (null != error) { System.Console.WriteLine("Error Code: {0}", error.ErrorCode.ToString()); System.Console.WriteLine("Error Description: {0}", error.Description); System.Console.WriteLine("Error Context: {0}", error.ErrorContext.ToString()); System.Console.WriteLine("Error Context Description: {0}", error.ContextDescription); System.Console.WriteLine("Error Protocol: {0}", error.Protocol); } //job.NotificationFlags = NotificationFlags.JobTransferred | NotificationFlags.JobErrorOccured; System.Console.WriteLine("Notification Flags: {0}", job.NotificationFlags.ToString()); System.Console.WriteLine("Notify CommandLine: {0}", job.NotifyCommandLineProgram); System.Console.WriteLine("CommandLine Parameters: {0}", job.NotifyCommandLineParameters); // System.Console.WriteLine("Reply File Name: {0}", job.ReplyFileName); // job.Resume(); // System.Threading.Thread.Sleep(1000); //job.Suspend(); // job.Complete(); //job.Cancel(); } System.Console.Write("Press any key to close"); Console.ReadKey(); }
public BitsUrlDownloader(string applicationName) { manager = new BitsManager(); this.applicationName = applicationName; }