banner



What Is Background Intelligent Transfer Service Downloading

Virtually BITS and downloading and uploading files

Programs nowadays often need to download files and data from the internet – maybe they need new content, new configurations, or the latest updates. The Windows Groundwork Intelligent Transfer Service (BITS) is an easy mode for programs to ask Windows to download files from or upload files to a remote HTTP or SMB file server. BITS will handle problems like network outages, expensive networks (when your user is on a cell programme and is roaming), and more.

In this blog post I'll bear witness how y'all can easily use BITS from a C# or other .Net linguistic communication program. To utilise $.25 from C++ using its native COM interface, run across the GitHub sample at https://github.com/Microsoft/Windows-classic-samples/tree/master/Samples/BacgroundIntelligenceTransferServicePolicy. Your program can create new downloads from and uploads to HTTP spider web servers and SMB file servers. Your program can also monitor Bits downloads and uploads. If your program runs as admin, you tin can monitor all the $.25 traffic on a auto. If you run just as a user, you lot tin can but monitor your ain Bits traffic.

The companion program from this blog post, the BITS Manager plan, is available both every bit source lawmaking on GitHub at https://github.com/Microsoft/BITS-Managing director and every bit a gear up-to-run executable at https://github.com/Microsoft/BITS-Manager/releases.

The BITS Manager program

What all can BITS exercise?

The most common use of Bits is to download files from the internet. But dig beneath the covers and yous'll find that the "Intelligent" in $.25 is well earned!

Bits is careful about the user'south experience

Many downloads (and uploads) demand to brand forward progress, but also want to be nice to the user and not interfere with the user's other piece of work. $.25 works to brand certain that downloads and uploads don't happen on costed networks and that the groundwork downloads and uploads don't injure the user's foreground feel. BITS does this past looking at both the computer's available network bandwidth and information about the local network. For uploads $.25 volition enable LEDBAT (when bachelor). LEDBAT is a new congestion command algorithm that's built into newer versions of Windows and Windows Server. Yous tin can likewise set different priorities for your transfers and so that the more than important downloads and uploads happen outset.

$.25 gives you control over transfer operations. Yous tin can specify what your cost requirements are to enable transfers on expensive (roaming) networks and the priority of each download or upload. You can gear up a transfer to be a foreground priority transfer and have the transfer happen correct away or fix your transfer to be a low priority transfer and be extra nice to your user. Meet https://docs.microsoft.com/en-u.s.a./windows/desktop/Bits/best-practices-when-using-$.25 for BITS best practices.

Bits tin exist managed past an Information technology department

An enterprise IT department might take a preference nearly how much bandwidth to allocate to groundwork transfers at different times of the day or might want to command how long a transfer is allowed to take. BITS has rich Group Policy and MDM policies for just these scenarios. See https://docs.microsoft.com/en-us/windows/client-direction/mdm/policy-csp-bits for more than details on controlling $.25 with MDM and https://docs.microsoft.com/en-us/windows/desktop/Bits/group-policies for the available Grouping Policies.

Quick start: download a file from the spider web

To download a file from the web using the Bits Manager sample plan, select JobsàQuick File Download. The file download dialog pops up:

Quick file download in the BITS Manager sample program.

Type in a URL to download. The Local file field volition be automatically updated with a potential download filename taken from the segments portion of the URL. When you tap OK, a $.25 job will be created, the remote URL and local file will exist added to the job, and the job volition be resumed. The job volition then automatically download as advisable and will exist switched to a final state at the end.

To accept your program download a file with $.25, you lot need to create a Bits managing director, create a job, add the URL and the local file names, and and so resume the job. So y'all demand to wait until the file is washed transferring and then complete the job. These steps are shown in this snippet.

In add-on to this code, a version one.v BITSReference DLL has been added to the C# project's references, and a using directive added to the C# file.

Sample Code

[code lang="csharp"]

individual $.25.IBackgroundCopyJob DownloadFile(string URL, string filename)
{
// The _mgr value is set like this: _mgr = new BITS.BackgroundCopyManager1_5();
if (_mgr == nix)
{
return null;
}

BITS.GUID jobGuid;
BITS.IBackgroundCopyJob job;
_mgr.CreateJob("Quick download", BITS.BG_JOB_TYPE.BG_JOB_TYPE_DOWNLOAD,
out jobGuid, out job);
endeavour
{
chore.AddFile(URL, filename);
}
catch (System.Runtime.InteropServices.COMException ex)
{
MessageBox.Show(
String.Format(Backdrop.Resources.ErrorBitsException,
ex.HResult,
ex.Bulletin),
Properties.Resources.ErrorTitle
);
job.Cancel();
render task;
}
catch (System.UnauthorizedAccessException)
{
MessageBox.Show(Properties.Resources.ErrorUnauthorizedAccessMessage,
Backdrop.Resources.ErrorUnauthorizedAccessTitle);
job.Cancel();
return chore;
}
catch (System.ArgumentException ex)
{
MessageBox.Show(
String.Format(Properties.Resources.ErrorMessage, ex.Message),
Properties.Resources.ErrorTitle
);
job.Abolish();
render job;
}

attempt
{
SetJobProperties(job); // Set job backdrop every bit needed
job.SetNotifyFlags(
(UInt32)BitsNotifyFlags.JOB_TRANSFERRED
+ (UInt32)BitsNotifyFlags.JOB_ERROR);
job.SetNotifyInterface(this);
// Will call JobTransferred, JobError, JobModification based on notify flags
chore.Resume();
}
take hold of (Arrangement.Runtime.InteropServices.COMException ex)
{
MessageBox.Show(
String.Format(
Properties.Resources.ErrorBitsException,
ex.HResult,
ex.Bulletin),
Properties.Resources.ErrorTitle
);
task.Cancel();
}
// Unless there was an error, the job is now running. We can exit
// and information technology will continue automatically.
return job; // Return the job that was created
}

public void JobTransferred(Bits.IBackgroundCopyJob pJob)
{
pJob.Complete();
}

public void JobError($.25.IBackgroundCopyJob pJob, $.25.IBackgroundCopyError pError)
{
pJob.Cancel();
}

public void JobModification($.25.IBackgroundCopyJob pJob, uint dwReserved)
{
// JobModification has to be to satisfy the interface. But unless
// the call to SetNotifyInterface includes the BG_NOTIFY_JOB_MODIFICATION flag,
// this method won't be chosen.
}

[/code]

You have to resume the task at the start because all jobs first off suspended, and you have to complete the chore and then that $.25 removes it from its internal database of jobs. The full life cycle of a BITS chore is explained at https://docs.microsoft.com/en-u.s.a./windows/desktop/Bits/life-cycle-of-a-bits-chore.

Using Bits from C#

Connecting COM-oriented $.25 and .Internet

In this sample, the .NET lawmaking uses .Net wrappers for the Bits COM interfaces. The wrappers are in the generated BITSReference DLL files. The BITSReference DLL files are created using the MIDL and TLBIMP tools on the $.25 IDL (Interface Definition Language) files. The IDL files, MIDL and TLBIMP are all part of the Windows SDK. The steps are fully defined in the BITS documentation at https://docs.microsoft.com/en-us/windows/desktop/Bits/bits-dot-net.

The automatically defined wrapper classes can be recreated at any time so that yous tin can easily make use of the latest updates to the BITS APIs without depending on a third-party wrapper library.

The sample uses several different versions of the BITSReference DLL files. Every bit the numbers increment, more features are available. The 1_5 version is suitable for running on Windows 7 SP1; the 5_0 version is usable in all versions of Windows 10.

If you don't desire to build your ain reference DLL file, yous can use the ones that were used to build the sample. They are copied over when you install the sample program and volition be in the aforementioned directory as the sample EXE.

Add the BITSReference DLLs every bit references

In Visual Studio 2017, in the Solution Explorer:

  1. Right-click References and click "Add Reference …"
  2. In the Reference Managing director dialog that pops upwards, click the "Browse…" push on the bottom-right of the dialog.
  3. In the "Select the files to reference…" file picker that pops up, navigate to the DLL (BITSReference1_5.dll) and click "Add." The file picker dialog will shut.
  4. In the "Reference Director" dialog box, the DLL should exist added to the list of possible references and will be checked. Click OK to add the reference.

Keep calculation until you've added all the reference DLLs that you'll be using.

Adding the BITSReference DLLs as references

Add using directives

In your code it's best to add together a set of using directives to your C# file. Once you lot do this, switching to a new version of BITS becomes much easier. The sample has four unlike using directives for different versions of BITS. BITS 1.5 is usable even on Windows 7 machines and has many of the basic BITS features, so that'south a skillful starting point for your lawmaking. The Bits What's New documentation at https://docs.microsoft.com/en-us/windows/desktop/Bits/what-s-new contains a list of the changes to $.25. In the Bits Manager sample plan, BITS4 is used for the HTTP options, BITS5 is used for task options like Dynamic and cost flags, and BITS10_2 is used for the custom HTTP verb setting.

[code lang="csharp"]

// Set up the BITS namespaces
using BITS = BITSReference1_5;
using BITS4 = BITSReference4_0;
using BITS5 = BITSReference5_0;
using BITS10_2 = BITSReference10_2;

[/code]

Brand a Bits IBackgroundCopyManager

The BITS IBackgroundCopyManager interface is the universal entry signal into all the $.25 classes similar the BITS jobs and files. In the sample BITS Director programme, a single _mgr object is created when the main window loads in MainWindow.xaml.cs.

[code lang="csharp"]

_mgr = new $.25.BackgroundCopyManager1_5();

[/lawmaking]

The _mgr object type is an IBackgroundCopyManager interface; that interface is implemented by the BackgroundCopyManager1_5 course. Each of the different $.25 reference DLL versions have classes whose proper noun includes a version number. For example, the BITS 10.2 reference DLL calls the class BackgroundCopyManager10_2. Just the form names are changed; the interface names are the same.

Create a job and add a file to a job

Create a new Bits job using the IBackgroundCopyManager interface and the CreateJob() method. The CreateJob() method takes in a string of the job name (information technology doesn't have to be unique) and returns a filled-in BITS Job GUID equally the unique identifier and a filled in IBackgroundCopyJob object. All versions of the managing director will make the original Bits one.0 version of the task. If you demand a new version of the job object, encounter the section on "Using newer BITS features" (hint: information technology'south just a cast).

Create a new job screen.

In the sample code, jobs are created in the MainWindow.xaml.cs file in the OnMenuCreateNewJob() method (it's called when you lot use the New Job carte du jour entry) and in the QuickFileDownloadWindow.xaml.cs file. Since we've already seen the quick file download lawmaking earlier, here's the code that'southward chosen when you use the "New Job" menu:

[code lang="csharp"]

BITS.GUID jobId;
BITS.IBackgroundCopyJob job;
_mgr.CreateJob(jobName, jobType, out jobId, out task);
try
{
dlg.SetJobProperties(job);
}
grab (System.Runtime.InteropServices.COMException ex)
{
// No need to cancel; the job will show up in the job listing and
// will be selected. The user should deal with information technology as they see fit.
MessageBox.Show(
String.Format(Properties.Resources.ErrorBitsException,
ex.HResult,
ex.Message),
Properties.Resource.ErrorTitle
);
}

RefreshJobList();

[/code]

In the code, the dlg variable is a CreateNewJobWindow dialog that pops up a window that lets yous enter in the job name and job properties. Once a job is created (with _mgr.CreateJob), the dialog has a SetJobProperties method to fill in the job property values. You must specify in the code that jobId and job are both out parameters.

Jobs are always created without any files and in a suspended state.

$.25 jobs are ever on a per-business relationship basis; this means that when a single user has several programs that all utilize $.25, all of the jobs from all of the programs will be displayed. If y'all need to write a program that makes some BITS jobs and sometime afterward modifies them (for example, to complete them), you should keep track of the task GUID values.

To add a file to a job, call Job.AddFile(remoteUri, localFile) where the remoteUri is a string with the remote filename, and the localFile is a cord with the local file. To start a transfer, call task.Resume(). $.25 will then make up one's mind when it's advisable to kickoff the task.

Enumerating Jobs and Files

The $.25 interfaces to enumerate (list) jobs and files can be tricky the first fourth dimension y'all use them. The key is that you first make an enumerator object and so you continue calling Side by side() on it until you don't get a job or file out. The example makes an enumerator for but the user's $.25 jobs; the complete code is below. The _mgr object is an instance of the IBackgroundCopyManager interface.

[code lang="csharp"]

BITS.IEnumBackgroundCopyJobs jobsEnum = zip;
uint njobFetched = 0;
$.25.IBackgroundCopyJob task = cypher;

_mgr.EnumJobs(0, out jobsEnum); // The 0 means get just the user's jobs
do
{
jobsEnum.Next(i, out chore, ref njobFetched);
if (njobFetched > 0)
{
// Practice something with the job
}
}
while (njobFetched > 0);

[/lawmaking]

Listing files is very similar merely uses a job's EnumFiles() to get the enumerator. The EnumFiles() method simply takes in the IBackgroundCopyFile object; there aren't any boosted settings.

Be notified when a job is modified or completed

$.25 has several means to allow you lot know when a job is modified or complete. The easiest notification mechanism is to phone call Job.SetNotifyInterface(IBackgroundCopyCallback callback). The callback object needs to implement the IBackgroundCopyCallback interface; that interface has iii methods that you will need to implement.

Y'all must offset declare that your form implements the callback:

[lawmaking lang="csharp"]

public partial class QuickFileDownloadWindow : Window, BITS.IBackgroundCopyCallback

[/code]

After you brand the job, call SetNotifyFlags and SetNotifyInterface:

[code lang="csharp"]

job.SetNotifyFlags(
(UInt32)BitsNotifyFlags.JOB_TRANSFERRED
+ (UInt32)BitsNotifyFlags.JOB_ERROR);
job.SetNotifyInterface(this);
// Will call JobTransferred, JobError, JobModification based on the notify flags

[/code]

You will also demand to implement the callback. The JobTransferred and JobError callbacks are gear up upwards to phone call the job.Complete and chore.Cancel methods to move the job into a final state.

[lawmaking lang="csharp"]

public void JobTransferred(BITS.IBackgroundCopyJob pJob)
{
pJob.Consummate();
}

public void JobError(BITS.IBackgroundCopyJob pJob, BITS.IBackgroundCopyError pError)
{
pJob.Abolish();
}

public void JobModification(BITS.IBackgroundCopyJob pJob, uint dwReserved)
{
// JobModification has to be to satisfy the interface. But unless
// the call to SetNotifyInterface includes the BG_NOTIFY_JOB_MODIFICATION flag,
// this method won't be called.
}

[/lawmaking]

In the sample lawmaking, the QuickFileDownloadWindow.xaml.cs file demonstrates how to use the IBackgroundCopyCallback interface. The UI of the sample code is updated by the master polling loop but could have been updated by the callbacks.

You can also register a command line for Bits to execute when the file is transferred. This lets you re-run your program afterwards the transfer is complete. Run into the Bits IBackgroundCopyJob2::SetNotifyCmdLine() method for more information.

Use a downloaded file

In one case y'all've got a file downloaded, the next affair you lot'll desire to practise is use information technology. The IBackgroundCopyFile'south GetLocalName(string) method is how you get the path of the downloaded file. Before you can utilize information technology, the task must exist in the ACKNOWLEDGED final state. If the job is in the CANCELLED last state, the result file won't exist. Alternately, if you lot set up the task as a high performance job (using the IBackgroundCopyJob5.SetProperty() method), the file volition be bachelor while it's being downloaded, or y'all tin access the temporary file past looking at the outcome from a phone call to the file's GetTemporaryName() method. In all cases, if BITS isn't washed with the file, you must open it with a file share Write flag.

In the sample code, the FileDetailViewControl.xaml.cs OnOpenFile() method gets the local name of the file and then uses the .NET System.Diagnostics.Process.Start() method to have the operating system open the file with the appropriate program.

[code lang="csharp"]

string Filename;
_file.GetLocalName(out Filename);
try
{
Organisation.Diagnostics.Process.Commencement(Filename);
}
catch (System.ComponentModel.Win32Exception ex)
{
MessageBox.Evidence(Cord.Format(Backdrop.Resource.ErrorMessage, ex.Message),
Properties.Resources.ErrorTitle);
}

[/code]

Using newer $.25 features

You'll find that y'all often have a BITS 1.0 version of an object and need a more than recent one to employ more than contempo BITS features.

For example, when yous make a task object with the IBackgroundCopyManager.CreateJob() method, the resulting job is always a version one.0 chore. To make a newer version, use a .Net cast to convert from an older blazon object to a newer blazon object. The cast will automatically call a COM QueryInterface equally advisable.

In this example, there's a Bits IBackgroundCopyJob object named "task", and we want to convert information technology to an IBackgroundCopyJob5 object named "job5″ so that we can call the Bits 5.0 GetProperty method. We merely cast to the IBackgroundCopyJob5 type like this:

[code lang="csharp"]

var job5 = job as BITS5.IBackgroundCopyJob5;

[/lawmaking]

The job5 variable volition exist initialized by .Net by using the correct QueryInterface. Information technology's important to note that .NET doesn't know about the real relationship between the BITS interfaces. If yous inquire for the wrong kind of interface, .Internet will try to go far for you and fail, and set job5 to null.

Attempt it out yourself today!

There are enough more features of BITS for you to use. Complete details are in the docs.microsoft.com documentation. The $.25 Director sample is available every bit a downloadable executable in the releases link on GitHub. The complete source lawmaking is besides available including the BITSReferenceDLL files that it uses. Assist for using the $.25 Manager and to explicate the source code organization is in the Bits-Director GitHub Wiki.

If you lot prefer coding in C or C++, the documentation will bespeak you to the existing samples.

Good luck, and happy Groundwork File Transfers!

What Is Background Intelligent Transfer Service Downloading,

Source: https://blogs.windows.com/windowsdeveloper/2019/01/17/using-background-intelligent-transfer-service-bits-from-net/

Posted by: bergerselmerry.blogspot.com

0 Response to "What Is Background Intelligent Transfer Service Downloading"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel