Tuesday, January 22, 2008

Configuration Bits Server Extension

Network Communication

Background Intelligent Transfer Service

Fax Service

Message Queuing (MSMQ)

Network List Manager

Peer-to-Peer

Telephony Application Programming Interfaces

Background Intelligent Transfer Service

Purpose

Background Intelligent Transfer Service (BITS) transfers files (downloads or uploads) between a client and server and provides progress information related to the transfers. You can also download files from a peer.

Where Applicable

Use BITS for applications that need to:

  • Asynchronously transfer files in the foreground or background.
  • Preserve the responsiveness of other network applications.
  • Automatically resume file transfers after network disconnects and computer restarts.

Developer Audience

BITS is designed for C and C++ developers.

Run-Time Requirements

BITS version 3.0 is included in the Windows Vista and Windows Server 2008 operating systems.

For information about run-time requirements for a particular programming element, see the Requirements section of the reference page for that element.

For complete version history, see What's New.

Newsgroup

To get answers to your questions and to find out how other people are using BITS, subscribe to the BITS newsgroup (microsoft.windows.public.backgroundtransfer). The newsgroup server is msnews.microsoft.com. For information on newsgroups, see http://www.microsoft.com/communities and click Newsgroups.

Knowledge Base Articles

For a list of Knowledge Base (KB) articles for BITS, see KB331716.

In This Section

Topic 

Description 

About BITS

General information about BITS.

Using BITS

Procedural guide for developing BITS clients that transfer files between a client and server. 

BITS Reference

Reference information for the BITS programming interfaces. Also contains information about samples, tools, server settings for upload jobs, and the upload protocol. 

Best Practices

Information to consider when designing an application that uses BITS. 

What's New

The following table identifies what is new for each release of Background Intelligent Transfer Service (BITS).

Version 

Description of features 

Version 3.0 

New features:

  • Added Peer Caching which lets you download content from peers and also serve content to peers in a domain network.
  • Added notification for when a file is downloaded.
  • Added access to the temporary file while the download is in progress.
  • Added the ability to control HTTP redirects.
  • Added more group policies to control peer caching and limit download times.
  • Added diagnostic & troubleshooting events to the system event log.
  • Added support for User Account Control (UAC).

Note  BITS now uses group policies to limit the number of jobs and files you can create. This may affect applications that currently create a large number of jobs or add a large number of files to a job.

Included in the Windows Server 2008 and Windows Vista operating systems.

The version of %windir%\System32\QMgr.dll is 7.0.xxxx.xxxx. 

Version 2.5 

Added support for custom HTTP headers, certificate-based client authentication for secure HTTP transports, and IPv6. Also added the use of Internet gateway device (IGD) counters to more accurately calculate available bandwidth.

The 2.5 features are available in the Windows Server 2008, Windows Vista, and Windows XP SP3 operating systems.

You can also download BITS 2.5 for Windows Server 2003 SP2, Windows Server 2003 SP1, and Windows XP SP2. To download BITS 2.5, go to the Microsoft Download Center and install KB923845.

The version of %windir%\System32\QMgr.dll is 6.7.xxxx.xxxx.

Version 2.0 

Added support for performing concurrent foreground downloads, using server message block (SMB) paths for remote names, downloading ranges of a file, changing the prefix or complete name of a remote name, and limiting client bandwidth usage.

Included in Windows XP SP2 and Windows Server 2003 SP1. You can also download BITS 2.0 for Windows Server 2003, Windows XP SP1, Windows XP, Windows 2000 SP4, and Windows 2000 SP3. To download BITS 2.0, go to the Microsoft Download Center and install KB842773.

The version of %windir%\System32\QMgr.dll is 6.6.xxxx.xxxx. 

Version 1.5 

Added upload and upload-reply capability, command-line execution for events, explicit credentials, and support for Windows 2000.

Included in Windows Server 2003. A redistributable is available for Windows XP and Windows 2000 SP3 from the Microsoft Download Center.

The version of %windir%\System32\QMgr.dll is 6.5.xxxx.xxxx. 

Version 1.2 

Same functionality as version 1.0. Contains internal upgrades and improvements.

Included in Windows XP SP1 and Windows 2000 SP3.

The version of %windir%\System32\QMgr.dll is 6.2.xxxx.xxxx.

Version 1.0 

Initial release. Provides prioritized, throttled, and asynchronous downloads in the background or foreground. The downloads automatically resume after computer restarts and network disconnects.

Included in Windows XP.

The version of %windir%\System32\QMgr.dll is 6.0.xxxx.xxxx.

Version 3.0

The following interfaces were added for this version:

Added the following constants to use with the IBackgroundCopyJobHttpOptions::SetSecurityFlags method:

  • BG_HTTP_REDIRECT_POLICY_ALLOW_SILENT
  • BG_HTTP_REDIRECT_POLICY_ALLOW_REPORT
  • BG_HTTP_REDIRECT_POLICY_DISALLOW
  • BG_HTTP_REDIRECT_POLICY_MASK
  • BG_HTTP_REDIRECT_POLICY_ALLOW_HTTPS_TO_HTTP

Version 2.5

The following interface and enumeration were added for version 2.5:

Version 2.0

The following interfaces, structure, and topics were added for version 2.0:

For information on concurrent foreground downloads, see Remarks for BG_JOB_PRIORITY.

For information on using the SMB protocol, see BG_FILE_INFO.

Version 1.5

The following interfaces and topics were added for version 1.5:

About BITS

Use Background Intelligent Transfer Service (BITS) to transfer files asynchronously between a client and a server. There are three types of transfer jobs. A download job downloads files to the client, an upload job uploads a file to the server, and an upload-reply job uploads a file to the server and receives a reply file from the server application.

BITS 1.2 and earlier:  Upload and upload-reply jobs are not supported.

BITS continues to transfer files after an application exits if the user who initiated the transfer remains logged on and a network connection is maintained. BITS will not force a connection.

BITS suspends the transfer if a connection is lost or if the user logs off. BITS persists transfer information while the user is logged off, across network disconnects, and during computer restarts.

When the user logs on again, BITS resumes the user's transfer job. For more information, see Users and Network Connections.

BITS provides one foreground and three background priority levels that you use to prioritize transfer jobs. Higher priority jobs preempt lower priority jobs. Jobs at the same priority level share transfer time, which prevents a large job from blocking small jobs in the transfer queue. Lower priority jobs do not receive transfer time until all higher priority jobs are complete or in an error state.

Background transfers are optimal in that BITS uses idle network bandwidth to transfer the files and will increase or decrease the rate at which files are transferred based on the amount of idle network bandwidth available. If a network application begins to consume more bandwidth, BITS decreases its transfer rate to preserve the user's interactive experience.

If peer caching is enabled and the job permits downloading from a peer, BITS will try to download content from one or more peers. Downloading from a peer is much faster than downloading content from the Internet. Peer caching is disabled by default and jobs must explicitly permit downloading content from peers. An administrator can use group policy to enable peer caching. After enabling peer caching, the administrator can disable either downloading from a peer or serving content to a peer.

The following topics provide more detailed information about BITS:

Use the BITS interfaces to write applications that create and monitor transfer jobs. For details on using the BITS interfaces, see Using BITS.

Users and Network Connections

BITS transfers files only when the job owner is logged on and a network connection (LAN or modem) is established. BITS processes the transfer job using the security context of the job owner. The user who created the job is considered the owner of the job. However, a user with administrator privileges can take ownership of another user's job.

BITS suspends a job when the owner logs off or if the network connection is lost (BITS will not force a network connection). BITS resumes the job when the owner logs back on and a network connection is established. After the network connection is established, a short delay may occur before BITS begins transferring data.

If the network connection is lost, all jobs whose state is BG_JOB_STATE_QUEUED or BG_JOB_STATE_TRANSFERRING are moved to the BG_JOB_STATE_TRANSIENT_ERROR state with a BG_E_NETWORK_DISCONNECTED error code. When a network connection is established, all jobs in a BG_JOB_STATE_TRANSIENT_ERROR state, which may include any error code, are moved to the BG_JOB_STATE_QUEUED state.

For BITS to detect that a user is logged on, the user must use one of the following interactive logon options:

Running an application as another user (by using the RunAs command) is not an interactive logon; BITS will not run jobs associated with the specified user.

The LocalSystem, LocalService, and NetworkService system accounts are always logged on; therefore, jobs submitted by a service using these accounts always run. For information and limitations on using service accounts, see Service Accounts and BITS.

Users with a restricted token (a token that contains restricting SIDs) cannot create or modify jobs.

BITS 1.2 and earlier:  Users with a restricted token can create or modify jobs.

For details on how User Account Control (UAC) affects BITS, see User Account Control and BITS.

Service Accounts and BITS

You can use BITS to transfer files from a service. The service must use the LocalSystem, LocalService, or NetworkService system account. These accounts are always logged on; therefore, jobs submitted by a service using these accounts always run.

If a service running under a system account impersonates the user before calling BITS, BITS responds as it would for any user account (for example, the user needs to be logged on to the computer for the transfer to occur). The service should also use dynamic cloaking with the BITS interface pointers when impersonating the user. Cloaking is not inherited, therefore you must call the CoSetProxyBlanket function on each interface pointer that you receive from BITS (for example, the job pointer returned from calling the IBackgroundCopyManager::CreateJob method); it is not enough to set cloaking on the manager interface pointer. You can also call the CoInitializeSecurity function for the process instead of calling the CoSetProxyBlanket function on each interface pointer.

However, if the service does not impersonate the user, the following behaviors apply:

  • Jobs created by the service account are owned by that account. Because system accounts are always logged on, BITS transfers the files as long as the computer is running and there is a network connection.
  • System accounts should not use mapped network drive letters because the drive letters are specific to a session and the mapping may be lost after a computer restart.
  • Network authentication uses computer credentials for LocalSystem and NetworkService accounts and anonymous credentials for the LocalService account. BITS returns "access denied" if the access control list (ACL) for the source file limits access to a user account.
  • If a proxy requests user authentication, BITS passes the credentials you specify to the proxy. To specify proxy credentials for a job, call the IBackgroundCopyJob2::SetCredentials method. When calling SetCredentials, specify implicit credentials (see Authentication) and use negotiate as the authentication scheme.

    BITS 1.2 and earlier:  BITS does not support proxy credentials.

  • Microsoft Internet Explorer proxy settings are stored per-user and are not set for system accounts. To set the proxy settings for a job submitted by a system account, call the IBackgroundCopyJob::SetProxySettings method. Alternatively, you can use the /Util /SetIEProxy switches of BitsAdmin.exe to set Internet Explorer proxy settings for the LocalSystem, LocalService, or NetworkService system account. For details, see BitsAdmin Tool.

    Note that BITS does not recognize the proxy settings that are set using the Proxycfg.exe file.

Life Cycle of a BITS Job

The life cycle of a BITS job begins when you create a job. A job is a container that contains one or more files to transfer. A job also has properties that specify how BITS transfers the files and interacts with your application. For example, you can specify the priority of the job, whether the job is an upload or download job, and for which events you want to receive notification.

After you create the job, add one or more files (upload jobs can contain only one file) to the job and change any of the property values as appropriate for your application. When you add a file to the job, specify both the local (client) and remote (server) name of the file. The remote file name must use the HTTP, HTTPS, or SMB protocol. Files within a job are processed sequentially (first in, first out).

BITS 1.5 and earlier:  Supports only the HTTP and HTTPS protocols.

BITS automatically suspends jobs when they are created. You must resume the job to activate it in the transfer queue. You can suspend or resume a job at any time. Resuming the job moves the job from the suspended state to the queued state. The job stays in the queued state until the scheduler determines it is the job's turn to transfer files. All foreground jobs run concurrently with one background job. BITS processes the files within foreground jobs serially.

BITS 1.5 and earlier:  BITS processes one job at a time. Foreground jobs have the highest priority and run before background jobs.

When it is a job's turn to transfer files, the job moves to the connecting state while BITS connects to the remote server (specified in the remote file name). If BITS is able to connect to the remote server, the job moves to the transferring state where it stays until its time slice ends, the transfer is complete, an error occurs, or the application suspends the job.

The job moves between the queued, connecting, and transferring states until BITS transfers all files in the job. At that point, the job moves to the transferred state. BITS uses round-robin scheduling to schedule jobs that are at the same priority level. Each job is given a slice of time to process its files. If the job does not complete during its time slice, the job goes back to the queued state and the next job in the queue is activated. This prevents large jobs from blocking smaller jobs. Jobs are processed largely on a first in, first out (FIFO) basis; however, BITS cannot guarantee FIFO processing because of round-robin scheduling, job errors, and service restarts.

The transferred files are not available to the client until the application calls the IBackgroundCopyJob::Complete method to transfer ownership of the files from BITS to the user. Upload jobs are also set to the transferred state when the file is successfully received by the server. Upload-reply jobs are set to the transferred state after the file is successfully sent to the server and the reply from the server application is successfully transferred to the client.

If an error occurs, the job moves to either the fatal or transient error state. Fatal errors are errors that BITS cannot recover from or which require intervention to fix. If the application is able to fix the error, the application resumes the job and BITS moves the job to the queued state. Transient errors are errors that may resolve themselves. BITS retries jobs in the transient error state until the transfer is successful or the job times out. The job times out when no progress is made within an application-specified period. If the job times out, BITS moves the job to fatal error state.

For more information on job states, see BG_JOB_STATE.

Network Bandwidth

Background transfers use only idle network bandwidth in an effort to preserve the user's interactive experience with other network applications, such as Internet Explorer. BITS adjusts its use of the bandwidth as the user increases or decreases their use of the bandwidth. Note that BITS still transfers a small amount of data during high network use to ensure that BITS jobs make progress.

BITS monitors the network traffic at the Internet gateway device (IGD) or the client's network interface card (NIC) and uses only the idle portion of the network bandwidth.

BITS 2.0 and earlier:  BITS uses only the network interface card to measure network traffic; BITS is not aware of network conditions beyond the client.

If BITS uses the network interface card to measure traffic and there are no network applications running on the client, BITS will consume most of the available bandwidth. This does not mean the network beyond the client is idle; the network might be at full capacity.

This can be an issue if the client has a fast network adapter (10 Mbps) but is connected to the network via a slow link (56 Kbps) because BITS will compete for the full bandwidth instead of using only the available bandwidth on the slow link; BITS has no visibility of the network traffic beyond the client.

A gateway device that supports counters can eliminate this issue because BITS would measure the traffic on the slow link and use the bandwidth appropriately. If the device does not support counters, you can reduce the impact of this type of connection, by using the MaxInternetBandwidth policy to limit the bandwidth that BITS uses on the client computer. For details, see Group Policies.

If the computer contains multiple network interfaces, such as a modem, virtual private network (VPN), and several network interface cards (NIC), BITS calls the IP Helper function, GetBestInterface, to determine the interface that has the best route to the specified IP address. BITS will then monitor bandwidth usage on that interface.

Using an Internet Gateway Device (IGD) to Determine Usage

To use a gateway device, the device must support byte counters (the device must respond to the GetTotalBytesSent and GetTotalBytesReceived actions) and Universal Plug and Play (UPnP) must be enabled.

BITS will use the network interface card if:

  • The gateway device does not support the counters
  • UPnP is not enabled
  • The server is within the same subnet
  • The gateway device does not return the counter data in less than 200 ticks

If the user uses a public network profile, the profile must allow UPnP. By default, the private and domain network profiles do allow UPnP.

If a VPN connection is used, BITS uses the first device that UPnP returns.

Peer Caching

If the administrator enables peer caching and the job permits downloading content from a peer, BITS will try to download the content from one or more peers. Downloading from a peer is much faster than downloading content from the Internet. Peer caching is disabled by default and jobs must explicitly permit downloading content from peers. An administrator can use group policy to enable peer caching (see Group Policies). After enabling peer caching, the administrator can disable either downloading from a peer or serving content to a peer.

An application can also enable peer caching by calling the IBitsPeerCacheAdministration::SetConfigurationFlags method. However, these settings are overridden by the group policy settings, if set.

When peer caching is enabled, BITS creates a list of peers that are in the same subnet and belong to the same domain. The list will not include peers from a trusted domain. Peer caching can only be enabled in a domain environment.

BITS discovers the peers by:

  • Listening for peer servers that announce themselves. A peer server will announce itself once when it starts. BITS will add the peer server to the list if the client needs more peers in its list.
  • Broadcasting a request for peer servers when it needs more peers in its peer list. Peer servers that are available to serve content respond to the request.

BITS removes peer servers from the peer list if the server:

  • Failed authentication
  • Is offline (unavailable) for too long
  • Provided a certificate with errors

When a job requests content from a peer, BITS randomly chooses a subset of peers from the peer list and asks them if they have the content. BITS can download content only from authenticated peer servers. The client and server initially authenticate each other using Kerberos, and then exchange self-signed certificates for authentication during content discovery and download.

BITS downloads the content from the first authenticated peer to respond to the request. If one peer does not contain all of the content, BITS will download what it can from one or more of the peers before downloading the rest from the origin server. If none of the peers has the content or an error occurs while downloading from a peer, BITS downloads the content from the origin server.

The downloaded content becomes available to serve to other peers only after the application validates the files contents. If the application does not explicitly validate the file, the file is implicitly validated when the application completes the job.

By default, a peer server can serve content to only three clients simultaneously. If the server is currently busy serving three clients, there will be a delay in responding to other requests. BITS limits the bandwidth used to serve content to 1 MBps. You can use the MaxBandwidthServed group policy to change the limit.

Note  This feature is supported only in domain networks; peer caching is not supported on workgroups or home networks.

HTTP Requirements for BITS Downloads

BITS supports HTTP and HTTPS downloads and uploads and requires that the server supports the HTTP/1.1 protocol. For downloads, the HTTP server's Head method must return the file size and its Get method must support the Content-Range and Content-Length headers. As a result, BITS only transfers static file content and generates an error if you try to transfer dynamic content, unless the ASP, ISAPI, or CGI script supports the Content-Range and Content-Length headers.

BITS can use an HTTP/1.0 server as long as it meets the Head and Get method requirements.

To support downloading ranges of a file, the server must support the following requirements:

  • Allow MIME headers to include the standard Content-Range and Content-Type headers, plus a maximum of 180 bytes of other headers.
  • Allow a maximum of two CR/LFs between the HTTP headers and the first boundary string.
  • IIS Requirements for BITS Uploads
  • For uploads, BITS requires IIS 5.0 on Windows 2000 Server and IIS 6.0 on Windows Server 2003, and IIS 7.0 on Windows Server 2008; BITS does not support IIS 5.1 on Windows XP. The IIS virtual directory must be enabled for uploads and have the BITS IIS extensions configured.
  • On Windows Server 2008, use the Server Manager to install the BITS Server Extensions feature. From Server Manager, click Features in the left pane. In the Add Features Wizard, check BITS Server Extensions. Note that the IIS 6 Management Compatibility roles must be installed.
  • On Windows Server 2003, use the Windows Components Wizard to install the BITS server extension. From Control Panel, select Add or Remove Programs. Then, select Add/Remove Windows Components to display the Windows Components Wizard. The BITS server extension is a subcomponent of Internet Information Services (IIS) which is a sub-component of Web Application Server.
  • On Windows 2000 Server, use the BITS redistributable to install the BITS server extension. For details on the redistributable, see the description of features for version 1.5 in What's New.
  • For information on configuring IIS for uploads, see Setting Up the Server for Uploads.
  • For details on the properties that BITS adds to IIS, see BITS Server Settings for Upload Jobs.
  • Authentication
  • BITS supports basic authentication, Passport authentication, and several challenge/response authentication schemes. If the server or proxy requires user authentication, use the IBackgroundCopyJob2::SetCredentials method to specify the user's credentials. BITS uses the CryptoAPI to protect the credentials.
  • BITS 1.2 and earlier:  The SetCredentials method is not available.
  • Basic authentication requires the user name and password to be embedded in the URL, for example, HTTP://username:password@server/path/file. Because the user name and password are clear text, an administrator can enumerate the jobs in the transfer queue and see the user name and password. The user name and password can also be seen by a network monitor program that is on the same physical network link as the client and server (unless you use HTTPS).
  • Instead of embedding the user name and password in the URL, you should use the SetCredentials method to specify the user name and password for basic authentication. This prevents others from viewing the credentials. If you specify credentials in both places, BITS uses the user name and password from the URL.
  • For Passport authentication, BITS supports explicit credentials only, not implicit credentials tied to the account.
  • For challenge/response authentication, BITS impersonates the user and uses Snego to determine which challenge/response authentication to use, such as NTLM or the Kerberos protocol. For a list of challenge/response schemes that BITS supports, see BG_AUTH_SCHEME.
  • BITS jobs can fail if the virtual directory on the server has anonymous authentication and another authentication scheme enabled and if ACLs protect the virtual directory or download files. For example, a job fails with "access denied" if the virtual directory has anonymous and integrated authentication enabled and the file contains an ACL that allows only Ben to read the file. This occurs because the virtual directory allows anonymous access, so IIS does not explicitly authenticate Ben (Ben's credentials are not used to access the file and access is denied).
  • Using implicit credentials
  • To use the user's implicit (logon) credentials for NTLM or Kerberos authentication, call the IBackgroundCopyJob2::SetCredentials method and set the UserName and Password members of the BG_BASIC_CREDENTIALS structure to NULL. If you specify implicit credentials for a proxy, BITS will also use the implicit credentials for server authentication unless you specify explicit server credentials.
  • For additional information for services, see Service Accounts and BITS.
  • You could also change the LMCompatibilityLevel or UseLmCompat registry value; however, you should change these values only if you have an existing application that cannot be changed to call the SetCredentials method.
  • BITS will use implicit credentials for authentication if the LMCompatibilityLevel registry value is two or greater, and you have not called the SetCredentials method. The full path to the LMCompatibilityLevel registry value is HKLM\System\CurrentControlSet\Control\LSA\LmCompatibilityLevel.
  • Note that changing the LMCompatibilityLevel registry value can affect other applications and services running on the computer. For more information about using the LMCompatibilityLevel registry value, see KB147706.
  • If setting the LMCompatibilityLevel registry value is an issue, you can create the UseLMCompat registry value under HKLM\Software\Microsoft\Windows\CurrentVersion\BITS. The registry value is a DWORD. The following table lists the possible values for UseLMCompat:

Value 

Description 

0 

BITS will send implicit credentials whenever the server prompts for NTLM or Kerb credentials.

1 

BITS will send implicit credentials only if the client computer's LMCompatibilityLevel registry value is greater than or equal to 2.

Prior to BITS 1.5:  Not supported

2 

BITS will send implicit credentials only if the application called the SetCredentials method.

Prior to BITS 2.0:  Not supported

  • BITS will use the following default values for the UseLMCompat registry value if the registry value does not exist:

Operating system 

Value 

Windows 2000

0 

Windows XP 

0 

Windows XP SP1 

0 

Windows XP SP2 

1 

Windows XP SP3 

1 

Windows Server 2003 

1 

Windows Server 2003 R2 

1 

Windows Vista 

2 

Windows Server 2008 

2 

  • BITS 1.2 and earlier:  BITS uses implicit credentials for NTLM or Kerberos authentication. If you wrote an application based on BITS 1.0 or 1.2, the same application may not run using later versions of BITS if the LMCompatibilityLevel value is less than two. Note that the default LMCompatibilityLevel value for Windows XP and Windows 2000 is zero.
  • Using certificates for client/server authentication
  • In secure client/server communication, clients and servers can use digital certificates to mutually authenticate each other. BITS automatically supports certificate-based server authentication for secure HTTP transports. To provide BITS the client certificate needed for mutual authentication, call either the IBackgroundCopyJobHttpOptions::SetClientCertificateByID or IBackgroundCopyJobHttpOptions::SetClientCertificateByName method.
  • When a web site accepts but does not require an SSL client certificate, and the BITS job does not specify a client certificate, the job will fail with ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED (0x80072f0c).
  • Prior to Windows Vista:  BITS supports certificate-based server authentication for secure HTTP transports, but certificate-based client authentication is not supported.
  • Authentication scenarios not supported
  • The following table shows the authentication requests that BITS does not support.

Scenario not supported 

Windows 2000 

Windows XP 

Windows Server 2003 

Passport authentication on the server when the proxy requires authentication (using the HTTPS protocol).

Not supported 

Not supported 

Not supported 

Passport authentication when the auto-detect proxy setting is set. 

Not supported 

Not supported 

Not supported 

Any authentication scheme on the server when the proxy requires Digest authentication.

Not supported 

Not supported 

Not supported 

Negotiate authentication on the server when the proxy requires Basic authentication. 

Not supported 

Not supported 

 

Using HTTPS when the proxy requires digest authentication. 

Not supported 

Not supported

 

Group Policies

BITS uses the following Group Policies to configure BITS.

Policy 

Introduced 

Description 

JobInactivityTimeout 

BITS 1.0 

By default, BITS maintains information about a job for 90 days. If there is no activity against the job for this period of time, BITS cancels the job. Transfer progress or property changes reset the timer.

You may need to adjust this policy if the user does not log on or maintain a network connection for long periods of time.

MaxInternetBandwidth 

BITS 2.0 

Limits the network bandwidth that BITS uses for background transfers (this policy does not affect foreground transfers).

Specify a limit to use during a specific time interval and a limit to use at all other times. For example, limit the use of network bandwidth to 10 kilobits per second (Kbps) from 8:00 A.M. to 5:00 P.M. and use all available unused bandwidth the rest of the time.

Note  Changing the system clock does not affect the bandwidth limitation time interval. For example, if the current time is 2:00 P.M. and the bandwidth limitation interval begins at 3:00 P.M., moving the system clock forward one hour does not mean BITS will enforce the bandwidth limitation an hour early—the bandwidth limitation will still occur in one hour. To reflect the system clock change in BITS, you must restart the computer or the BITS service.

Specify the limit in kilobits per second. Base the limit on the size of the network link, not the size of the computer's network interface card (NIC). BITS uses approximately two kilobits if you specify a value less than two kilobits. To prevent BITS transfers from occurring, specify a limit of zero. If you specify a limit of zero, BITS places all background jobs in a transient error state (the error code is set to BG_E_BLOCKED_BY_POLICY). BITS places the jobs in the queued state after the time interval expires.

If you disable or do not configure this policy, BITS uses all available unused bandwidth.

Typically, you use this policy to prevent BITS transfers from competing for network bandwidth when the client has a fast network adapter (10 Mbps) but is connected to the network via a slow link (56 Kbps).

For information on how BITS uses network bandwidth, see Network Bandwidth.

MaxDownloadTime 

BITS 3.0 

Determines the length of time that BITS can spend actively tranferring the files in the job. The default is 90 days.

To override this policy for a specific job, call the IBackgroundCopyJob4::SetMaximumDownloadTime method.

MaxJobsPerMachine 

BITS 3.0 

Limits the number of jobs that users can create on the computer. The default is 300 jobs. This policy does not apply to a user with administrator privileges or service accounts.

MaxJobsPerUser 

BITS 3.0 

Limits the number of jobs that a user can create on the computer. The default is 60 jobs per user. This policy does not apply to a user with administrator privileges or service accounts.

MaxFilesPerJob 

BITS 3.0 

Limits the number of files that a user can add to a job. The default is 200 files per job. This policy does not apply to a user with administrator privileges or service accounts. 

MaxRangesPerFile

BITS 3.0 

Limits the number of ranges that a user can specify for a file. The default value is 500 ranges. This policy does not apply to a user with administrator privileges or service accounts. 

BITS uses the following Group Policies to enable and configure the peer cache.

Policy 

Introduced 

Description 

EnablePeerCaching 

BITS 3.0 

By default, peer caching is disabled. To enable peer caching, set this policy. Enabling peer caching allows BITS to download content from peers and to serve the content to peers.

To prevent BITS from downloading content from peers, set the DisablePeerCachingClient policy. To prevent BITS from serving content to peers, set the DisablePeerCachingServer.

A job controls if it can download content from a peer or serve content to peers. For details, see the IBackgroundCopyJob4::SetPeerCachingFlags method.

If this policy is not set, you can use the IBitsPeerCacheAdministration::SetConfigurationFlags method to enable peer caching; however, if the policy is set later, the policy will override the preference set by the SetConfigurationFlags method.

DisablePeerCachingClient 

BITS 3.0 

Set this policy to prevent BITS from downloading content from peers. 

DisablePeerCachingServer 

BITS 3.0 

Set this policy to prevent BITS from serving content to peers. 

MaxContentAge 

BITS 3.0 

Specifies the maximum length of time that a file can remain in the peer cache without being accessed. The default is 90 days.

If this policy is not set, you can use the IBitsPeerCacheAdministration::SetMaximumContentAge method to limit the time that a file can remain in the peer cache without being accessed; however, if the policy is set later, the policy will override the preference set by the method.

MaxCacheSize 

BITS 3.0 

Specifies the maximum amount of disk to use for the peer cache. The default is 1% of the disk.

If this policy is not set, you can use the IBitsPeerCacheAdministration::SetMaximumCacheSize method to set the size of the peer cache; however, if the policy is set later, the policy will override the preference set by the method.

MaxBandwidthServed 

BITS 3.0 

Limits the amount of network bandwidth to use when serving content to peers. The default is 1 MBps. 

Note  If the policy value is not set, BITS uses the default policy value.

To enable a BITS policy

  1. Open Group Policy by entering gpedit.msc /gpcomputer:"<computernamegoeshere>" in the Run window or at the command prompt in an MS-DOS window.
  2. BITS policies are located under Computer Configuration, Administrative Templates, Network, Background Intelligent Transfer Service.
  3. Right-click the policy and select Properties.
  4. Follow the directions for enabling and setting the policy.

BITS 1.5 and earlier:  The JobInactivityTimeout policy is located under Computer Configuration, Administrative Templates, Network.

The group policies for BITS are located in the registry at HKLM\Software\Policies\Microsoft\Windows\BITS. Note that only those policies that are configured are listed in the registry.


 

Send comments about this topic to Microsoft

File Transfer Consistency

BITS guarantees that the version of the file it transfers is consistent based on the file size and time stamp, not content (BITS does not protect against man-in-the-middle attacks). To verify the contents yourself, you can use the IBackgroundCopyFile3::GetTemporaryName method to get the name of the file that contains the downloaded content, verify the contents using your own mechanism, and then call the IBackgroundCopyFile3::SetValidationState method to indicate to BITS if the contents of the file is valid. If you set the validation state to FALSE and the content is from the origin server, the job goes into the error state. If the content is from a peer, BITS downloads the file from the origin server.

For downloads, if the file size or time stamp changes while BITS is transferring the file, BITS restarts the transfer of that file only. For example, if the download job contains two files and the files are updated on the server while BITS is transferring the second file, BITS restarts the transfer of the second file only. The first file, which already transferred successfully, is not updated to reflect the new changes.

Note that if you own the file being downloaded from the server, you should create a new URL for each new version of the file. If you use the same URL for new versions of the file, some proxy servers may serve stale data from their cache because they do not verify with the original server if the file is stale.

For uploads, if the file size or time stamp changes during the file transfer, BITS generates an error and the job is placed in the BG_JOB_STATE_ERROR state.

BITS does not synchronize transfer requests when one or more users request that the same file be transferred to the same location. BITS transfers the file for each request separately.

Internet Connection Sharing

BITS can force a dial-up connection for home networks that use Microsoft Internet Connection Sharing if Connection Sharing is configured to dial out when computers on the network access the Internet. To prevent a forced dial-up connection, disable the Establish a dial-up connection whenever a computer on my network attempts to access the Internet option on the Connection Sharing host computer that shares its Internet connection.

Computers connected to the Connection Sharing host computer assume they have a network connection, so BITS will try to transfer files. If the dial-up option is disabled on the host computer and the host computer does not have an active connection, the transfers will fail with a transient error. BITS will retry the transfers periodically.

BITS and System Restore

Not all versions of BITS use the same format to store jobs. If you return the computer to a restore point prior to a BITS upgrade, the old version of BITS may not be able to read the current job information. If this happens, BITS will delete the jobs list and create a new empty jobs list. As a result, the temporary files associated with the previous jobs list are not cleaned up; to reclaim the disk space, you must delete the files manually.

Users familiar with the Windows command line can avoid this problem by using the BITSAdmin tool (found on the Windows CD in the Support Tools directory) to clear the BITS jobs list before running System Restore. To clear the BITS jobs list, run the following command:

bitsadmin /reset /allusers

Note that you must have administrator privileges to run this command.

BITS Startup Type

The Startup Type for BITS is delayed auto-start.

Prior to Windows Vista:  The Startup Type for BITS is Manual. When a BITS job is created, the Startup Type changes to Automatic. The Startup Type returns to Manual when all jobs are complete or canceled.

You should not set the Startup Type to Disabled. Disabling BITS may break applications, such as Windows Update, that rely on BITS to transfer files.

User Account Control and BITS

In Windows Vista, when an administrator user logs onto the computer, two access tokens are created: a filtered standard user access token, and a full administrator access token. By default, all users, including administrators, log on a Windows Vista computer as standard users. (The exception are guests which log onto the computer with fewer user rights and privileges than standard users.)

A user in the administrator group can run a process with standard user access or in an elevated state (with administrator privileges). To run in an elevated state, the user can right-click the client and select Run as administrator.... BITS will run the job in either state as long as the user is logged onto the computer. However, if the user created the job or took ownership of the job in an elevated state, the user must be in the elevated state to retrieve or modify the job (otherwise, the call fails with Access Denied (0x80070005)). To determine the elevated state of a job, call the IBackgroundCopyJob4::GetOwnerElevationState method.

A standard user cannot enumerate jobs owned by other users. If a standard user (a user that is not in the administrators group) asks an administrator to provide credentials, and the user then creates a job, the job is created under the administrator's account and will run only when that administrator is logged on, not when the standard user is logged on. Also, the standard user will not be able to modify the job.

In addition to the elevated state, the integrity level of the token can determine if the user can modify a job. A client cannot modify jobs created by a token with a higher integrity level. In particular, many local-system tokens carry an integrity level higher than the integrity level of an elevated window, and so they cannot be modified by an administrator from an ordinary elevated command window. For example, Windows Update and SMS jobs run as LocalSystem which has a higher integrity level than an elevated token so an administrator cannot modify or delete these jobs. To modify these job, create a Task Scheduler task that runs as local system. The task can execute a console application that uses the BITS API, or the task could execute a script that calls BitsAdmin.exe. To determine the integrity level used, call the IBackgroundCopyJob4::GetOwnerIntegrityLevel method.

Using BITS

The following steps show how to perform a file transfer using the BITS interfaces.

To perform a file transfer

  1. Connect to the BITS service.
  2. Create a transfer job.
  3. Add files to the job.
  4. Start the job.
  5. Determine if BITS successfully transferred the files.
  6. Complete the job.

The previous steps show how to transfer files using the default property values for a job. You can change the default behavior by changing one or more of the job's property values. For example, you can change the priority that the job is processed relative to other jobs in the queue, specify your own proxy setting, and register to receive event notification when BITS has transferred the files. For more information, see Setting and Retrieving the Properties of a Job.

This section also contains the following topics:

For sample code that uses the BITS interfaces, see BITS Samples and Tools.

Best Practices When Using BITS

This section contains information you should consider when designing an application that uses BITS.

User context or service context

BITS transfers files only when the job's owner is logged on to the computer (the user must have logged on interactively). BITS does not support the RunAs command. Nor does BITS support terminal services logon on Windows 2000. For more details, see Users and Network Connections.

If you do not require a user's context for your application, consider writing a service running as LocalSystem, LocalService, or NetworkService instead. These system accounts are always logged on, so the transfer is not subject to a user logging off. However, if you impersonate a user when you create the job, the interactive logon rules apply. For more details, see Service Accounts and BITS.

Setting credentials for proxy and server authentication

If you expect the proxy or server to require user credentials, you must provide the credentials to BITS. To specify the credentials, call the IBackgroundCopyJob2::SetCredentials method. BITS supports Basic, Digest, Negotiate, NTLM, and Passport authentication schemes.

For details on authentication, see Authentication.

Specifying proxy settings for user accounts and service accounts

By default, BITS uses the user's Internet Explorer proxy settings. To override the user's Internet Explorer proxy settings, call the IBackgroundCopyJob::SetProxySettings method.

The Internet Explorer proxy settings do not apply to system accounts. If your application is a service running as LocalSystem, LocalService, or NetworkService, you must call IBackgroundCopyJob::SetProxySettings to specify the proxy settings. As an alternative, you can use the /Util /SetIEProxy switches of BitsAdmin.exe to set Internet Explorer proxy settings for the LocalSystem, LocalService, or NetworkService system account. For details, see BitsAdmin Tool.

BITS does not recognize the proxy settings that are set using the Proxycfg.exe file.

Scalability

If more than 100 jobs are in the queue, performance may start to decrease depending on the composition of the job. BITS uses the MaxJobsPerMachine policy setting to impose a hard limit on the number of jobs in the queue. Applications should limit the number of their jobs to about 10, so that multiple applications will have less of a chance of exceeding the 100-job guideline. Typically, an application with a large number of jobs to submit would first submit 10 jobs and then submit one at a time as each job finishes.

The number of files in the job should also be limited to a maximum of 10 files. If you want to transfer a large number of files for a job, consider creating a CAB file that contains all the files instead.

Jobs are persistent

Jobs remain in the queue until you call the IBackgroundCopyJob::Complete or IBackgroundCopyJob::Cancel method. The files in the job are not available to the user until you call Complete. Typically, you call Complete when the state of the job is BG_JOB_STATE_TRANSFERRED, and you call Cancel when the job is in the BG_JOB_STATE_TRANSIENT_ERROR or BG_JOB_STATE_ERROR state and can no longer make progress.

If you do not call the Complete method or the Cancel method within 90 days (default JobInactivityTimeout Group Policy), the service cancels the job. You should always call the Complete or the Cancel method and not rely on the JobInactivityTimeout policy to cleanup your jobs. Jobs left in the queue may prevent users from creating other jobs if the MaxJobsPerUser or MaxJobsPerMachine policy limit is reached.

When to use foreground or background priority

Unless the job is time critical or the user is actively waiting, you should always use a background priority. However, there are times when you may want to switch from background priority to foreground priority, for example, when the proxy or server does not support the Content-Range header, or antivirus software on the client removes the range header request. Swithing to foreground priority works only for those files whose file size is less than 2 GB. For an example, see the implementation for the IBackgroundCopyCallback::JobError method. Also note that if the foreground job is then interrupted due to a network disconnect or the user logging off, the job will fail because BITS will send a range request to try to restart the transfer from where it left off.

For information on the available priorities and how BITS uses the priority level to schedule jobs, see BG_JOB_PRIORITY.

Transient and fatal errors

Some errors are recoverable and some are not. For example, the error "Server is Unavailable" is a recoverable error, and the error "Access Denied" is a fatal error. BITS puts recoverable errors in a transient error state and tries the job again after a specified interval. If the job is unable to make progress, BITS moves the job to a fatal error state. Use the IBackgroundCopyJob::SetMinimumRetryDelay and IBackgroundCopyJob::SetNoProgressTimeout methods to control how BITS processes transient errors.

For foreground jobs, you should limit the amount of time you let a job stay in the transient error state and try to recover. Use the SetNoProgressTimeout method to limit the amount of time a job stays in the transient error state or to force the job into the fatal error state. If you let the job try to recover, you should use the SetMinimumRetryDelay method to set the minimum retry delay to 60 seconds or call the IBackgroundCopyJob::Resume method to activate the job again.

For more information, see BG_JOB_STATE, Life Cycle of a BITS Job, and Handling Errors.

Measuring network bandwidth usage

BITS uses the client's network adapter to measure available network bandwidth. Because BITS is not able to measure bandwidth beyond the client, BITS may congest the WAN link. To reduce congestion on the WAN link, you can use the MaxInternetBandwidth group policy to limit the amount of bandwidth that the client uses. For more information, see Network Bandwidth and Group Policies.

If you are writing an application that many clients will use to download files from a given server, you should consider a scheme that staggers the download requests so you do not overload the server with requests.

Connecting to the BITS Service

To connect to the BITS service, create an instance of the BackgroundCopyManager object as shown in the following example.

#define UNICODE

#define _WIN32_WINNT 0x0500

#include <windows.h>

#include "bits.h"


 

//Global variable that several of the code examples in this document reference.

IBackgroundCopyManager* g_pbcm = NULL;

HRESULT hr;


 

//Specify the appropriate COM threading model for your application.

hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

if (SUCCEEDED(hr))

{

hr = CoCreateInstance(__uuidof(BackgroundCopyManager), NULL,

CLSCTX_LOCAL_SERVER,

__uuidof(IBackgroundCopyManager),

(void**) &g_pbcm);

if (SUCCEEDED(hr))

{

//Use g_pbcm to create, enumerate, or retrieve jobs from the queue.

}

}

To test for a specific version of BITS, use one of the following symbolic class identifiers:

  • For BITS 3.0, use CLSID_BackgroundCopyManager3_0.
  • For BITS 2.5, use CLSID_BackgroundCopyManager2_5.
  • For BITS 2.0, use CLSID_BackgroundCopyManager2_0.
  • For BITS 1.5, use CLSID_BackgroundCopyManager1_5.
  • For BITS 1.0, use CLSID_BackgroundCopyManager.

The following example shows how to use one of the symbolic class identifiers.

hr = CoCreateInstance(CLSID_BackgroundCopyManager2_0, NULL,

CLSCTX_LOCAL_SERVER,

IID_IBackgroundCopyManager,

(void**) &g_pbcm);

if (SUCCEEDED(hr))

{

//BITS 2.0 is installed.

}

Use the methods of the IBackgroundCopyManager interface to create transfer jobs, enumerate jobs in the queue, and retrieve jobs.

To retrieve a pointer to the IBitsPeerCacheAdministration interface, call the IBackgroundCopyManager::QueryInterface method. The following example shows how to get the IBitsPeerCacheAdministration interface.

HRESULT hr = S_OK;

IBackgroundCopyManager* pbcm = NULL;

IBitsPeerCacheAdministration* pCacheAdmin = NULL;


 

hr = pbcm>QueryInterface(__uuidof(IBitsPeerCacheAdministration), (void**)&pCacheAdmin);

pbcm->Release();

if (FAILED(hr))

{

wprintf(L"pbcm->QueryInterface failed with 0x%x.\n", hr);

goto cleanup;

}

BITS requires that the client's interface proxies use either the IDENTIFY or IMPERSONATE level of impersonation. If the application does not call CoInitializeSecurity, COM uses IDENTIFY by default. BITS fails with E_ACCESSDENIED if the correct impersonation level is not set. If you provide a library that exercises the BITS interfaces, and an application that calls your library sets the impersonation level below IDENTIFY, then you will need to call CoSetProxyBlanket to set the correct impersonation level for each BITS interface that you call.

Before your application exits, release your copy of the IBackgroundCopyManager interface pointer, as shown in the following example.

if (g_pbcm)

{

g_pbcm->Release();

g_pbcm = NULL;

}

CoUninitialize();

Creating a Job

To create a transfer job, call the IBackgroundCopyManager::CreateJob method. After BITS creates the job, add files to the job and modify the job's properties as appropriate for your application. To activate the job in the queue, call the IBackgroundCopyJob::Resume method.

The CreateJob method creates a GUID that uniquely identifies the job. You use the GUID to retrieve the job from the transfer queue. The display name that you provide when you create the job is not unique; more than one job can use the same name.

BITS limits the number of jobs in the queue to 300 jobs and the number of jobs that a user can create to 60 job. These limits do not apply to administrators or services. To change these default limits, see Group Policies.

Prior to Windows Vista:  There are no limits to the number of jobs in the queue or the number of jobs that a user can create.

The following example shows how to create a download job. The example assumes the g_pbcm variable is a valid IBackgroundCopyManager interface pointer. For details on how to create the IBackgroundCopyManager interface pointer, see Connecting to the BITS Service.

HRESULT hr;

GUID JobId;

IBackgroundCopyJob* pJob = NULL;


 

//To create an upload job, replace BG_JOB_TYPE_DOWNLOAD with

//BG_JOB_TYPE_UPLOAD or BG_JOB_TYPE_UPLOAD_REPLY.

hr = g_pbcm->CreateJob(L"MyJobName", BG_JOB_TYPE_DOWNLOAD, &JobId, &pJob);

if (SUCCEEDED(hr))

{

//Save the JobId for later reference.

//Modify the job's property values.

//Add files to the job.

//Activate (resume) the job in the transfer queue.

}

To get the latest IBackgroundCopyJob interface, call the IBackgroundCopyJob::QueryInterface method. The following example shows how to get the IBackgroundCopyJob4 interface.

HRESULT hr = S_OK;

IBackgroundCopyJob* pJob = NULL;

IBackgroundCopyJob4* pJob4 = NULL;


 

hr = pJob->QueryInterface(__uuidof(IBackgroundCopyJob4), (void**)&pJob4);

pJob->Release();

if (FAILED(hr))

{

wprintf(L"pJob->QueryInterface failed with 0x%x.\n", hr);

goto cleanup;

}

Adding Files to a Job

A job contains one or more files that you want to transfer. Use one of the following methods to add files to a job:

IBackgroundCopyJob::AddFile

Adds a single file to a job.

IBackgroundCopyJob::AddFileSet

Adds one or more files to a job. If you are adding multiple files, it is more efficient to call this method than to call the AddFile method in a loop.

IBackgroundCopyJob3::AddFileWithRanges

Adds a single file to a job. Use this method if you want to download ranges of data from a file. You can use this method only for download jobs.

When you add a file to a job, you specify the remote name and the local name of the file. For details on the format of the local and remote file names, see the BG_FILE_INFO structure.

An upload job can contain only one file. The IBackgroundCopyJob::AddFile and IBackgroundCopyJob::AddFileSet methods return BG_E_TOO_MANY_FILES if you try to add more than one file to an upload job. If you need to upload more than one file, consider using a CAB or ZIP file.

For download jobs, BITS limits the number of files that a user can add to a job to 200 files and the number of ranges for a file to 500 ranges. These limits do not apply to administrators or services. To change these default limits, see Group Policies.

Prior to Windows Vista:  There are no limits to the number of files or ranges that you can add to a job.

The owner of the job or a user with administrator privileges can add files to the job anytime prior to calling the IBackgroundCopyJob::Complete method or the IBackgroundCopyJob::Cancel method.

If you need to change the remote name of the file after you add the file to the job, you can call the IBackgroundCopyJob3::ReplaceRemotePrefix method or the IBackgroundCopyFile2::SetRemoteName method. Use the ReplaceRemotePrefix method to change the server portion of the remote name when the server is unavailable or to let roaming users connect to the closest server. Use the SetRemoteName method to change the protocol used to transfer the file or to change the file name or path.

BITS creates a temporary file in the destination directory and uses the temporary file for the file transfer. To get the temporary file name, call the IBackgroundCopyFile3::GetTemporaryName method. BITS changes the temporary file name to the destination file name when you call the Complete method. BITS does not specify a security descriptor when it creates the temporary file (the file inherits the ACL information from the destination directory). If the transferred data is sensitive, the application should specify an appropriate ACL on the destination directory to prevent unauthorized access.

To maintain the owner and ACL information with the transferred file, call the IBackgroundCopyJob3::SetFileACLFlags method.

The owner of the job (the user who created the job or the administrator who took ownership of the job) must have permissions to the file on the server as well as the client. For example, to download a file the user must have read permissions on the server and write permissions to the local directory on the client.

The following example shows how to add a single file to the job. The example assumes the IBackgroundCopyJob interface pointer, pJob, is valid.

HRESULT hr;

IBackgroundCopyJob* pJob;


 

//Replace parameters with variables that contain valid paths.

hr = pJob->AddFile(L"http://ServerName/Path/File.Ext", L"d:\\Path\\File.Ext");

if (SUCCEEDED(hr))

{

//Do something.

}

The following example shows how to add multiple files to the job. The example assumes the IBackgroundCopyJob interface pointer, pJob, is valid and the local and remote names come from a list in the user interface.

HRESULT hr;

IBackgroundCopyJob* pJob;

BG_FILE_INFO* paFiles = NULL;

ULONG idx = 0;

ULONG nCount = 0; //Set to the number of files to add to the job.

LPWSTR pszLocalName = NULL; //Comes from the list in the user interface.

LPWSTR pszRemoteName = NULL; //Comes from the list in the user interface.


 

//Set nCount to the number of files to transfer.


 

//Allocate a block of memory to contain the array of BG_FILE_INFO structures.

//The BG_FILE_INFO structure contains the local and remote names of the

//file being transferred.

paFiles = (BG_FILE_INFO*) malloc(sizeof(BG_FILE_INFO) * nCount);

if (NULL == paFiles)

{

//Handle error

}

else

{

//Add local and remote file name pairs to the memory block.

for (idx=0; idx<nCount; idx++)

{

//Set pszLocalName to point to an LPWSTR that contains the local name or

//allocate memory for pszLocalName and copy the local name to pszLocalName.

(paFiles+idx)->LocalName = pszLocalName;


 

//Set pszRemoteName to point to an LPWSTR that contains the remote name or

//allocate memory for pszRemoteName and copy the remote name to pszRemoteName.

(paFiles+idx)->RemoteName = pszRemoteName;

}


 

//Add the files to the job.

hr = pJob->AddFileSet(nCount, paFiles);

if (SUCCEEDED(hr))

{

//Do Something.

}


 

//Free the memory block for the array of BG_FILE_INFO structures. If you allocated

//memory for the local and remote file names, loop through the array and free the

//memory for the file names before you free paFiles.

free(paFiles);

}

Setting and Retrieving the Properties of a Job

The owner of the job or a user with administrator privileges can set and retrieve the properties of the job at any time. For a complete list of properties that you can set and retrieve, see the IBackgroundCopyJob, IBackgroundCopyJob2, IBackgroundCopyJob3, and IBackgroundCopyJob4 interfaces.

Files also contain properties. For information on how to retrieve a file and its properties from a job, see Enumerating Files in a Job.

To transfer files, you do not need to change the default values of the job's properties—BITS uses default values that are appropriate for the typical application.

Setting the properties of a job

The following example shows how to set the properties that your application is most likely to change: priority, notify interface, notify flags, and reply file name. The example assumes the IBackgroundCopyJob interface pointer, pJob, is valid.

HRESULT hr;

IBackgroundCopyJob* pJob;

IBackgroundCopyJob4* pJob4 = NULL;

CNotifyInterface *pNotify = new CNotifyInterface();


 

hr = pJob->QueryInterface(__uuidof(IBackgroundCopyJob4), (void**)&pJob4);

pJob->Release();


 

//The default priority level for a job is BG_JOB_PRIORITY_NORMAL.

hr = pJob4->SetPriority(BG_JOB_PRIORITY_HIGH);

if (FAILED(hr))

{

//Handle error

}


 

//By default, an application must poll BITS for the status of a job.

//To specify an IBackgroundCopyCallback interface pointer that receives event

//notification based on the value of the notify flags property, set the notify

//interface property. For details on the CNotifyInterface example class, see the

//IBackgroundCopyCallback interface in the reference section.

hr = pJob4->SetNotifyInterface(pNotify);

if (SUCCEEDED(hr))

{

hr = pJob4->SetNotifyFlags(BG_NOTIFY_JOB_TRANSFERRED |

BG_NOTIFY_JOB_ERROR);

}

pNotify->Release();

if (FAILED(hr))

{

//Handle error - failed to setup notification callbacks

}


 

//Only set the reply file name if the job's type is BG_JOB_TYPE_UPLOAD_REPLY.

//If you do not set the file name before calling the IBackgroundCopyJob::Resume

//method, BITS generates a file name for you; the directory is the same as that

//specified for the local file name (the file being uploaded). To retrieve the

//file name, call the IBackgroundCopyJob2::GetReplyFileName method.

hr = pJob4->SetReplyFileName(L"<REPLYPATHGOESHERE>");

if (FAILED(hr))

{

//Handle error

}

pJob4->Release();

By default, BITS downloads content from the origin server. To download content from a peer, both the computer and the job must enable peer caching. To enable peer caching on the computer, set the EnablePeerCaching group policy setting. You can also call the IBitsPeerCacheAdministration::SetConfigurationFlags method to enable peer caching on the computer; however, the preference setting is overridden by the policy, if set. To enable peer caching for the job, you must call the IBackgroundCopyJob4::SetPeerCachingFlags method.

To specify custom headers, a client certificate for client authentication, and HTTP options like redirection policy, CRL checking, and specifying which certificate errors to ignore, use the IBackgroundCopyJobHttpOptions interface. To get the IBackgroundCopyJobHttpOptions interface, query any of the IBackgroundCopyJob interfaces.

Retrieving the properties of a job

The following example shows how to retrieve the display name, owner, progress, and state property values of a job. The example assumes the IBackgroundCopyJob interface pointer, pJob, is valid.

HRESULT hr;

IBackgroundCopyJob* pJob;

WCHAR* pszJobName = NULL;

WCHAR* pszOwnerSid = NULL;

BOOL bResult;

DWORD dwNameSize = 0;

DWORD dwDomainSize = 0;

WCHAR* pszName = NULL;

WCHAR* pszDomain = NULL;

WCHAR* pszFullOwnerName = NULL;

PSID pSid = NULL;

SID_NAME_USE eNameUse;

BG_JOB_PROGRESS Progress;

int PercentOfFiles = 0;

BG_JOB_PRIORITY Priority;

BG_JOB_STATE State;

//WCHAR *JobStates[] = { L"Queued", L"Connecting", L"Transferring",

// L"Suspended", L"Error", L"Transient Error",

// L"Transferred", L"Acknowledged", L"Canceled"

// };


 

//Name of the job to use in the user interface. The name is set when you

//create the job. You can use the SetDisplayName method to change the name.

hr = pJob->GetDisplayName(&pszJobName);

if (SUCCEEDED(hr))

{

//Use the name in a user interface or output.

CoTaskMemFree(pszJobName);

}


 

//The owner property contains the SID of the job's owner. The following code

//shows how to get the domain and user names associated with the SID.

hr = pJob->GetOwner(&pszOwnerSID);

if (SUCCEEDED(hr))

{

bResult = ConvertStringSidToSid(pszOwnerSid, &pSid);

CoTaskMemFree(pszOwnerSid);

if (bResult)

{

//Call LookupAccountSid twice. The first call retrieves the buffer size

//for name and domain and the second call retrieves the actual name and domain.

LookupAccountSid(NULL, pSid, NULL, &cbNameSize,

NULL, &cbDomainSize, &eNameUse);

LastError = GetLastError();

if (ERROR_INSUFFICIENT_BUFFER == LastError)

{

pszName = (WCHAR*)malloc(sizeof(WCHAR) * cbNameSize);

pszDomain = (WCHAR*)malloc(sizeof(WCHAR) * cbDomainSize);

if (pszName && pszDomain)

{

bResult = LookupAccountSid(NULL, pSid, pszName, &cbNameSize,

pszDomain, &cbDomainSize, &eNameUse);

if (bResult)

{

pszFullName = (WCHAR*)malloc(sizeof(WCHAR)*(cbDomainSize+1+cbNameSize+1));

if (pszFullName)

{

StringCchPrintf(pszFullName, cbDomainSize+1+cbNameSize+1, L"%s\\%s", pszDomain, pszName);

//Do something with pszFullName.

free(pszFullName);

}

}

}

if (pszDomain)

free(pszDomain);

if(pszName)

free(pszName);

}

else

{

//Handle error - most likely ERROR_NONE_MAPPED, could not find the SID.

}

LocalFree(pSid);

}

}


 

//The state property identifies the current state of the job. For example, the

//state of the job is BG_JOB_STATE_TRANSFERRING or BG_JOB_STATE_ERROR.

hr = pJob->GetState(&State);

if (SUCCEEDED(hr))

{

//Use JobStates[State] to set the text representation of the job's

//state in a user interface.

}


 

//Use the information contained in the BG_JOB_PROGRESS structure to determine the

//overall progress of the job. The structure contains information on the number of

//bytes and files transferred.

hr = pJob->GetProgress(&Progress);

if (SUCCEEDED(hr))

{

//Determine the progress of the job based on the number of files transferred.

if (Progress.FilesTotal > 0)

{

PercentOfFiles = 100*Progress.FilesTransferred/Progress.FilesTotal

}

//For an example that shows determining the progress of the job based on the

//number of bytes transferred, see the topic Determing the Progress of a Job.

}

Retrieving the Reply from an Upload-Reply Job

If you want to upload data to a server application and have it return data to the client, specify the job as a BG_JOB_TYPE_UPLOAD_REPLY job. The reply data is available to the client after the job enters the BG_JOB_STATE_TRANSFERRED state. To retrieve the reply, call one of the following methods:

Call these methods in your IBackgroundCopyCallback::JobTransferred method only if the reply is small and can be processed quickly so as to not block the callback thread. If you use command line notification instead of the callback, pass the job identifier to the executable file. The executable file uses the job identifier to call the Complete method to make the reply file available.

The following examples show how to use each method to retrieve the reply data.

Using GetReplyData

The following example shows how to retrieve the reply data using the IBackgroundCopyJob2::GetReplyData method. The example assumes the IBackgroundCopyJob interface pointer is valid, the type of the job is upload-reply, and the state of the job is BG_JOB_STATE_TRANSFERRED.

HRESULT hr;

IBackgroundCopyJob* pJob;

IBackgroundCopyJob2* pJob2 = NULL;

BYTE* pReply = NULL;

UINT64 ReplySize;


 

//Need to query the IBackgroundCopyJob interface for an IBackgroundCopyJob2

//interface pointer. The IBackgroundCopyJob2 interface contains the GetReplyData method.

hr = pJob->QueryInterface(__uuidof(IBackgroundCopyJob2), (void**)&pJob2);

if (SUCCEEDED(hr))

{

hr = pJob2->GetReplyData(&pReply, &ReplySize);

if (S_OK == hr))

{

if (pReply)

{

//Do something with the data.

CoTaskMemFree(pReply);

}

else

{

//The server application did not return a reply.

}

}

else if (BG_E_TOO_LARGE == hr)

{

//The reply exceeds 1 MB. To retrieve the reply, get the reply file name,

//complete the job, open the reply file, and read the reply.

}

else

{

//Handle the error

}


 

pJob2->Release(); //When done, release the interface.

}

else

{

//Handle error. QueryInterface will return E_NOINTERFACE if the version of BITS

//running on the computer is less than BITS 1.5.

}

Using GetReplyFileName

The following example shows how to retrieve the reply data using the IBackgroundCopyJob2::GetReplyFileName method. The example assumes the IBackgroundCopyJob interface pointer is valid, the type of job is upload-reply, and the state of the job is BG_JOB_STATE_TRANSFERRED.

HRESULT hr;

IBackgroundCopyJob* pJob;

IBackgroundCopyJob2* pJob2 = NULL;

WCHAR* pszFileName = NULL;


 

//Need to query the IBackgroundCopyJob interface for an IBackgroundCopyJob2

//interface pointer. The IBackgroundCopyJob2 interface contains the GetReplyFileName method.

hr = pJob->QueryInterface(__uuidof(IBackgroundCopyJob2), (void**)&pJob2);

if (SUCCEEDED(hr))

{

hr = pJob2->GetReplyFileName(&pszFileName);

if (SUCCEEDED(hr))

{

//Calling the Complete method removes the job from the queue,

//so make sure you maintain an interface pointer to this job

//or retrieve any job related information that you require

//when processing the reply.

hr = pJob->Complete();


 

//Open, read the file, and do something with the data.

CoTaskMemFree(pszFileName);

}


 

pJob2->Release(); //When done, release the interface.

}

else

{

//Handle error. QueryInterface will return E_NOINTERFACE if the version of BITS

//running on the computer is less than BITS 1.5.

}

Determining the Status of a Job

The status of a job refers to changes in the state of a job (for example, the job changes state from BG_JOB_STATE_TRANSFERRING to BG_JOB_STATE_TRANSFERRED) and progress in transferring the files. To capture changes in the status of a job, use the following options:

To get information about the progress of a job, see Determining the Progress of a Job.

Polling for the Status of the Job

By default, an application must poll for changes in the status of a job. To capture changes in the job's state, call the IBackgroundCopyJob::GetState method. To capture changes in the number of bytes and files transferred, call the IBackgroundCopyJob::GetProgress method. To retrieve progress information on the reply portion of an upload-reply job, call the IBackgroundCopyJob2::GetReplyProgress method. For an example that uses the progress information, see Determining the Progress of a Job.

The BG_JOB_STATE enumeration defines the states of a job, and the BG_JOB_PROGRESS structure contains information on the number of bytes and files transferred.

To use polling, you need to create a mechanism to initiate polling. For example, create a timer or use an "Update" button on the user interface. However, it might be easier to register for event notification and receive events when the state or progress changes. For information on event notification, see Registering a COM Callback.

The following example uses a timer to poll for the state of a job. The example assumes the IBackgroundCopyJob interface pointer is valid.

HRESULT hr;

IBackgroundCopyJob* pJob;

BG_JOB_STATE State;

HANDLE hTimer = NULL;

LARGE_INTEGER liDueTime;

//IBackgroundCopyError* pError = NULL;

//BG_JOB_PROGRESS Progress;

//WCHAR *JobStates[] = { L"Queued", L"Connecting", L"Transferring",

// L"Suspended", L"Error", L"Transient Error",

// L"Transferred", L"Acknowledged", L"Canceled"

// };


 

liDueTime.QuadPart = -10000000; //Poll every 1 second

hTimer = CreateWaitableTimer(NULL, FALSE, L"MyTimer");

SetWaitableTimer(hTimer, &liDueTime, 1000, NULL, NULL, 0);


 

do

{

WaitForSingleObject(hTimer, INFINITE);


 

//Use JobStates[State] to set the window text in a user interface.

hr = pJob->GetState(&State);

if (FAILED(hr))

{

//Handle error

}


 

if (BG_JOB_STATE_TRANSFERRED == State)

//Call pJob->Complete(); to acknowledge that the transfer is complete

//and make the file available to the client.

else if (BG_JOB_STATE_ERROR == State || BG_JOB_STATE_TRANSIENT_ERROR == State)

//Call pJob->GetError(&pError); to retrieve an IBackgroundCopyError interface

//pointer which you use to determine the cause of the error.

else if (BG_JOB_STATE_TRANSFERRING == State)

//Call pJob->GetProgress(&Progress); to determine the number of bytes

//and files transferred.

} while (BG_JOB_STATE_TRANSFERRED != State &&

BG_JOB_STATE_ERROR != State &&

BG_JOB_STATE_TRANSIENT_ERROR != State);

CancelWaitableTimer(hTimer);

CloseHandle(hTimer);

Registering a COM Callback

Instead of polling for changes in the status of a job, you can register to receive notification when the job's status changes. To receive notification, you must implement the IBackgroundCopyCallback2 interface. The interface contains the following methods that BITS calls depending on your registration:

For an example that implements the IBackgroundCopyCallback2 interface, see Example Code in the IBackgroundCopyCallback interface topic.

The IBackgroundCopyCallback2 interface provides notification for when a file is transferred. Typically, you use this method to validate the file so that the file is available for peers to download; otherwise, the file is not available to peers until you call the IBackgroundCopyJob::Complete method. To validate the file, call the IBackgroundCopyFile3::SetValidationState method.

To register your implementation with BITS, call the IBackgroundCopyJob::SetNotifyInterface method. To specify which methods BITS calls, call the IBackgroundCopyJob::SetNotifyFlags method.

The notification interface becomes invalid when your application terminates; BITS does not persist the notify interface. As a result, your application's initialization process should register existing jobs for which you want to receive notification. If you need to capture state and progress information that occurred since the last time your application was run, poll for state and progress information during application initialization.

Before exiting, your application should clear the callback interface pointer (SetNotifyInterface(NULL)). It is more efficient to clear the callback pointer than to let BITS discover that it is no longer valid.

Note that if more than one application calls the SetNotifyInterface method to set the notification interface for the job, the last application to call the SetNotifyInterface method is the one that will receive notifications—the other applications will not receive notifications.

The following example shows how to register for notifications. The example assumes the IBackgroundCopyJob interface pointer is valid. For details on the CNotifyInterface example class used in the following example, see the IBackgroundCopyCallback interface.

HRESULT hr;

IBackgroundCopyJob* pJob;

CNotifyInterface *pNotify = new CNotifyInterface();


 

if (pNotify)

{

hr = pJob->SetNotifyInterface(pNotify);

if (SUCCEEDED(hr))

{

hr = pJob->SetNotifyFlags(BG_NOTIFY_JOB_TRANSFERRED |

BG_NOTIFY_JOB_ERROR );

}

pNotify->Release();

pNotify = NULL;


 

if (FAILED(hr))

{

//Handle error - unable to register callbacks.

}

}

Registering to Execute a Program

You can register to have BITS execute a program based on job transferred and error events, but not job modified events. BITS executes the program in the user's context.

To register to execute a program

  1. Call the IBackgroundCopyJob::QueryInterface method to retrieve an IBackgroundCopyJob2 interface pointer. Specify __uuidof(IBackgroundCopyJob2) as the interface identifier.
  2. Call the IBackgroundCopyJob2::SetNotifyCmdLine method to specify the program to execute and any arguments required by the program, such as the job identifier.
  3. Call the IBackgroundCopyJob::SetNotifyFlags method to specify when the command line executes.

    You can only specify the BG_NOTIFY_JOB_TRANSFERRED and BG_NOTIFY_JOB_ERROR event flags. The BG_NOTIFY_JOB_MODIFICATION flag is ignored.

Note that BITS will not execute the program if you also registered to receive COM callbacks and the callback interface pointer is valid or the notification method that BITS calls returns a success code. However, if the notification method returns a failure code, such as E_FAIL, BITS will execute the command line.

BITS calls the CreateProcessAsUser function to launch the program. If you specify a parameter string, the first parameter must be the program name.

The following example shows how to register to execute a program when the job-transferred event occurs. The example assumes the IBackgroundCopyJob interface pointer is valid.

#define MAX_PARAMETER_LEN 4000


 

HRESULT hr;

IBackgroundCopyJob* pJob;

IBackgroundCopyJob2* pJob2 = NULL;

WCHAR szJobId[48];

WCHAR *pProgram = L"c:\\PATHHERE\\PROGRAMNAMEHERE.exe";

WCHAR szParameters[MAX_PARAMETER_LEN+1];

GUID JobId;

int rc;


 

hr = pJob->GetId(&JobId);

if (SUCCEEDED(hr)

{

rc = StringFromGUID2(JobId, szJobId, sizeof(szJobId));

if (rc)

{

StringCchPrintf(szParameters, MAX_PARAMETER_LEN+1, L"%s %s", pProgram, szJobId);

pJob->QueryInterface(__uuidof(IBackgroundCopyJob2), (void**)&pJob2);

hr = pJob2->SetNotifyCmdLine(pProgram, szParameters);

if (SUCCEEDED(hr))

{

hr = pJob->SetNotifyFlags(BG_NOTIFY_JOB_TRANSFERRED);

}

pJob2->Release();

if (FAILED(hr)

{

//Handle error - unable to register for command line notification.

}

}

}

When the state of the job becomes BG_JOB_STATE_TRANSFERRED, BITS executes the program specified in pProgram. The following example is a simple implementation of a program that takes a job identifier as an argument. The program assumes the correct number of arguments are passed to it.

#define UNICODE

#define _WIN32_WINNT 0x0500


 

#include <windows.h>

#include <comdef.h>

#include <wchar.h>

#include <stdio.h>

#include <strsafe.h>

#include "bits.h"


 

HRESULT wmain(int argc, wchar_t *argv[])

{

HRESULT hr;

IBackgroundCopyManager *pManager = NULL;

IBackgroundCopyJob *pJob = NULL;

GUID JobId;

WCHAR *pDisplayName = NULL;

WCHAR *pSuccessString = L" completed successfully.";

WCHAR *pMessage;


 

hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

hr = CoInitializeSecurity(NULL, -1, NULL, NULL,

RPC_C_AUTHN_LEVEL_CONNECT,

RPC_C_IMP_LEVEL_DELEGATE,

NULL, EOAC_NONE, 0);

hr = CoCreateInstance(__uuidof(BackgroundCopyManager),

NULL, CLSCTX_ANY,

__uuidof( IBackgroundCopyManager ), (void**) &pManager);


 

if (pManager)

{

hr = CLSIDFromString(argv[1], &JobId);

if (SUCCEEDED(hr))

{

hr = pManager->GetJob(JobId, &pJob);

if (SUCCEEDED(hr))

{

hr = pJob->GetDisplayName(&pDisplayName);

if (SUCCEEDED(hr))

{

pMessage = (WCHAR*)malloc((wcslen(pDisplayName) +

wcslen(pSuccessString) + 1)* sizeof(WCHAR));

if (pMessage)

{

StringCchPrintf(pMessage, wcslen(pDisplayName) + wcslen(pSuccessString) + 1,

L"%s%s", pDisplayName, pString);

MessageBox(HWND_DESKTOP, pMessage, L"MyProgram - Transferred", MB_OK);

free(pMessage);

}

else

{

hr = E_OUTOFMEMORY;

}

CoTaskMemFree(pDisplayName);

}

pJob->Release();

}

}

pManager->Release();

}


 

CoUninitialize();

return(hr);

}

Determining the Progress of a Job

BITS maintains progress information for each job. Use the progress information to determine how many bytes and files have been transferred.

To retrieve progress information for the job, call the IBackgroundCopyJob::GetProgress method as shown in the following example. The example assumes the IBackgroundCopyJob interface pointer is valid.

#define PROGRESS_COMPLETE_LEN 50


 

HRESULT hr;

IBackgroundCopyJob* pJob;

WCHAR szProgressComplete[PROGRESS_COMPLETE_LEN+1];

BG_JOB_PROGRESS Progress;


 

hr = pJob->GetProgress(&Progress);

if (FAILED(hr))

{

//Handle error

}


 

//Because the BytesTotal member can be 0 or BG_SIZE_UNKNOWN, you may not be able

//to determine a percentage value to display, such as 57%. It is best to display a

//string that shows the number of bytes transferred. For example, "123456 of

//999999" or "123456 of Unknown".

if (BG_SIZE_UNKNOWN == Progress.BytesTotal)

{

StringCchPrintf(szProgressComplete, PROGRESS_COMPLETE_LEN+1, L"%I64d of Unknown",

Progress.BytesTransferred);

}

else

{

StringCchPrintf(szProgressComplete, PROGRESS_COMPLETE_LEN+1, L"%I64d of %I64d",

Progress.BytesTransferred, Progress.BytesTotal);

}

To retrieve progress information on the reply portion of an upload reply job, call the IBackgroundCopyJob2::GetReplyProgress method as shown in the following example. The example assumes the IBackgroundCopyJob interface pointer is valid.

#define REPLY_COMPLETE_LEN 4


 

HRESULT hr;

IBackgroundCopyJob* pJob;

IBackgroundCopyJob2* pJob2 = NULL;

WCHAR szReplyComplete[REPLY_COMPLETE_LEN+1];

BG_JOB_REPLY_PROGRESS Progress;


 

pJob->QueryInterface(__uuidof(IBackgroundCopyJob2), (void**)&pJob2);

hr = pJob2->GetReplyProgress(&Progress);

if (SUCCEEDED(hr))

{

if (0 == Progress.BytesTotal) //The job type is not BG_JOB_TYPE_UPLOAD_REPLY

{

//Logic to deal with this case

}

else if (BG_SIZE_UNKNOWN == Progress.BytesTotal) //The reply has not begun

{

StringCchPrintf(szReplyComplete, REPLY_COMPLETE_LEN+1, L"0%%");

}

else

{

StringCchPrintf(szReplyComplete, REPLY_COMPLETE_LEN+1 L"%I64d%%",

100*Progress.BytesTransferred/Progress.BytesTotal);

}

}

Files also contain progress information. To retrieve the progress information, use the IBackgroundCopyFile::GetProgress method. For information on how to retrieve the files of a job, see Enumerating Files in a Job.

Completing and Canceling a Job

To complete a transfer job, call the IBackgroundCopyJob::Complete method. For download jobs, you can call the Complete method before all files in the job have been transferred (before the job's state is BG_JOB_STATE_TRANSFERRED). Only those files that BITS successfully transferred to the client before you called the Complete method are available to the user.

For upload jobs, call the Complete method only if the job's state is BG_JOB_STATE_TRANSFERRED. To determine when the job's state is BG_JOB_STATE_TRANSFERRED, poll the job's state property or register to receive BG_NOTIFY_JOB_TRANSFERRED event notification.

To cancel a transfer job, call the IBackgroundCopyJob::Cancel method. The Cancel method removes the job from the transfer queue and removes the temporary files from the client. Typically, you call this method if you are unable to resolve an error associated with the job.

The Cancel method cancels an upload if the upload is not complete. If the upload is complete, and the job is of type BG_JOB_TYPE_UPLOAD_REPLY, the method cancels the reply.

If you do not call the Complete method or the IBackgroundCopyJob::Cancel method within 90 days (default JobInactivityTimeout Group Policy), the service cancels the job. If the service cancels the job, the downloaded files and the reply file are not available to the client; job cancellation does not affect files that have been successfully uploaded. You should always call the Complete or the Cancel method and not rely on the JobInactivityTimeout policy to cleanup your jobs. Jobs left in the queue may prevent users from creating other jobs if the MaxJobsPerUser or MaxJobsPerMachine policy limit is reached.

Enumerating Jobs in the Transfer Queue

To enumerate jobs from the transfer queue, call the IBackgroundCopyManager::EnumJobs method. The method returns an IEnumBackgroundCopyJobs interface pointer that you use to enumerate the jobs in the queue.

To retrieve the user's jobs, set the first parameter of the EnumJobs method to 0. To retrieve all jobs in the queue, set the first parameter of the EnumJobs method to BG_JOB_ENUM_ALL_USERS. Only users with administrator privileges can retrieve all jobs in the transfer queue.

Note that the enumerated list is a snapshot of the jobs in the transfer queue at the time you call the EnumJobs method. However, the property values of those jobs reflect the current values of the job.

If you want to retrieve individual transfer jobs, call the IBackgroundCopyManager::GetJob method.

To enumerate files in a job, see Enumerating Files in a Job.

The following example shows how to enumerate jobs in the transfer queue. The g_XferManager variable in the example is an IBackgroundCopyManager interface pointer. For details on how to create the IBackgroundCopyManager interface pointer, see Connecting to the BITS Service.

HRESULT hr = 0;

IEnumBackgroundCopyJobs* pJobs = NULL;

IBackgroundCopyJob* pJob = NULL;

ULONG cJobCount = 0;

ULONG idx = 0;


 

//This example enumerates all jobs in the transfer queue. This call fails if the

//current user does not have administrator privileges. To enumerate jobs for only

//the current user, replace BG_JOB_ENUM_ALL_USERS with 0.

hr = g_XferManager->EnumJobs(BG_JOB_ENUM_ALL_USERS, &pJobs);

if (SUCCEEDED(hr))

{

//Get the count of jobs in the queue.

pJobs->GetCount(&cJobCount);


 

//Enumerate the jobs in the queue.

for (idx=0; idx<cJobCount; idx++)

{

hr = pJobs->Next(1, &pJob, NULL);

if (S_OK == hr)

{

//Retrieve or set job properties.


 

pJob->Release();

pJob = NULL;

}

else

{

//Handle error

break;

}

}


 

pJobs->Release();

pJobs = NULL;

}

Enumerating Files in a Job

To enumerate files in a job, call the IBackgroundCopyJob::EnumFiles method. The method returns an IEnumBackgroundCopyFiles interface pointer that you use to enumerate the files.

Note that the enumerated list is a snapshot of the files in the job at the time you call the EnumFiles method. However, the property values of those file objects reflect the current values of the file.

The following example shows how to enumerate files in a job and retrieve their properties. The example assumes the IBackgroundCopyJob interface pointer is valid.

HRESULT hr = 0;

IBackgroundCopyJob* pJob;

IEnumBackgroundCopyFiles* pFiles = NULL;

IBackgroundCopyFile* pFile = NULL;

IBackgroundCopyFile3* pFile3 = NULL;

WCHAR* pLocalFileName = NULL;

ULONG cFileCount = 0;

ULONG idx = 0;


 

hr = pJob->EnumFiles(&pFiles);

if (SUCCEEDED(hr))

{

//Get the count of files in the job.

pFiles->GetCount(&cFileCount);


 

//Enumerate the files in the job.

for (idx=0; idx<cFileCount; idx++)

{

hr = pFiles->Next(1, &pFile, NULL);

if (S_OK == hr)

{

// Query for the latest file interface.

hr = pFile->QueryInterface(__uuidof(IBackgroundCopyFile3), (void**)&pFile3);

pFile->Release();

if (FAILED(hr))

{

wprintf(L"pFile->QueryInterface failed with 0x%x.\n", hr);

goto cleanup;

}


 

// You can use the interface to retrieve the local and remote file

// names, get the ranges to download if only part of the file content

// is requested, determine the progress of the transfer, change the remote file

// name, get the name of the temporary file that BITS uses to download

// the file, determine if the file is downloaded from a peer, and set

// the validation state of the file so it can be shared with peers.


 

//Get the local name of the file.

hr = pFile3->GetLocalName(&pLocalFileName);

if (SUCCEEDED(hr))

{

//Do something with the file information.

}


 

CoTaskMemFree(pLocalFileName);

pFile3->Release();

pFile3 = NULL;

}

else

{

//Handle error

break;

}

}


 

pFiles->Release();

pFiles = NULL;

}

Handling Errors

There are two types of errors to handle in your application. The first error is a failed method call. Each method returns an HRESULT value. The reference page for each method identifies the return values that it is most likely to generate. For additional return values, see BITS Return Values. To get the message text associated with the return value, call the IBackgroundCopyManager::GetErrorDescription method.

The second type of error to handle is a job whose state transitions to BG_JOB_STATE_ERROR or BG_JOB_STATE_TRANSIENT_ERROR. To retrieve information related to these types of errors, call the job's IBackgroundCopyJob::GetError method. The method returns an IBackgroundCopyError interface pointer that contains information you use to determine the cause of the error. You can also receive error notification by registering to receive event notification. For details, see Registering a COM Callback.

BITS considers each job to be atomic. If one of the files in the job generates an error, the job remains in an error state until the error is resolved. Thus, you cannot delete the file that is causing the error from the job. However, if the error is caused by the server not being available or an invalid remote file, you can call the IBackgroundCopyJob3::ReplaceRemotePrefix or IBackgroundCopyFile2::SetRemoteName method to identify a new server or file name.

After determining the cause of the error, perform one of the following options:

For an upload-reply job, check the value of the BytesTotal member of the BG_JOB_REPLY_PROGRESS structure to determine if the error occurred on the upload or reply portion of the job. The error occurred on the upload if the value is BG_SIZE_UNKNOWN.

The following example shows how to retrieve an IBackgroundCopyError interface pointer. The example assumes the IBackgroundCopyJob interface pointer is valid.

HRESULT hr = 0;

HRESULT hrError = 0;

IBackgroundCopyJob* pJob;

IBackgroundCopyError* pError = NULL;

IBackgroundCopyFile* pFile = NULL;

WCHAR* pszDescription = NULL;

WCHAR* pszRemoteName = NULL;

BG_ERROR_CONTEXT Context;


 

hr = pJob->GetError(&pError);

if (SUCCEEDED(hr))

{

//Retrieve the HRESULT associated with the error. The context tells you

//where the error occurred, for example, in the transport, queue manager, the

//local file, or the remote file.

pError->GetError(&Context, &hrError);


 

//Retrieve a description associated with the HRESULT value.

hr = pError->GetErrorDescription(LANGIDFROMLCID(GetThreadLocale()), &pszDescription);

if (SUCCEEDED(hr))

{

if (BG_ERROR_CONTEXT_REMOTE_FILE == Context)

{

hr = pError->GetFile(&pFile);

if (SUCCEEDED(hr))

{

hr = pFile->GetRemoteName(&pszRemoteName);

if (SUCCEEDED(hr))

{

//Do something with the information.

CoTaskMemFree(pszRemoteName);

}

pFile->Release();

}

}

CoTaskMemFree(pszDescription);

}

pError->Release();

}

else

{

//Error information is not available.

}

Administering the Peer Cache

To improve download performance, BITS lets you download content from peer computers. To enable this feature, the administrator must enable the EnablePeerCaching group policy setting. If enabled, the peer can download content from peers and serve content to peers. The administrator can also use the DisablePeerCachingClient and DisablePeerCachingServer policy settings to prevent downloading content from a peer or serving content to peers, respectively.

If the group policy settings are not configured, an application can call the IBitsPeerCacheAdministration::SetConfigurationFlags method to set the peer caching preference for the computer. Note that these preferences are overridden by the group policy settings if they are set later. To determine if the computer enables peer caching, call the IBitsPeerCacheAdministration::GetConfigurationFlags method.

If peer caching is enabled, BITS will only cache the contents of a job if the job explicitly allows its content to be cached. BITS will also only download content from a peer if the job explicitly allows it. To enable peer caching for a job, call the IBackgroundCopyJob4::SetPeerCachingFlags method.

In addition to using Group Policy or the IBitsPeerCacheAdministration interface to enable peer caching, you can also use either method to change the default cache size and length of time that a non-accessed file remains in the cache. To change the defaults using the IBitsPeerCacheAdministration interface, call the SetMaximumCacheSize and SetMaximumContentAge methods. Since these methods set the preference settings, they are overridden by the group policy settings.

To list the peers from whom BITS will try to download content, call the IBitsPeerCacheAdministration::EnumPeers method.

To list the files in the cache that BITS will serve to peers, call the IBitsPeerCacheAdministration::EnumRecords method.

You should never have to manage the peer cache with regards to discovering peers or deleting cache records. This functionality was included in the IBitsPeerCacheAdministration interface for completeness.

Determining the Version of BITS on a Computer

To determine the version of BITS on the client computer, check the version of QMgr.dll. To find the version number of the DLL:

  • Locate QMgr.dll in %windir%\System32.
  • Right-click QMgr.dll and click Properties.
  • Click the Version tab.
  • Note the version number.

If the DLL also exists in %windir%\System32\Bits, repeat the previous steps. BITS uses the DLL with the higher version number.

The following table lists the versions of BITS and their corresponding QMgr.dll file version numbers.

BITS version 

QMgr.dll file version number 

BITS 3.0 

7.0.xxxx.xxxx 

BITS 2.5 

6.7.xxxx.xxxx 

BITS 2.0

6.6.xxxx.xxxx 

BITS 1.5 

6.5.xxxx.xxxx 

BITS 1.2 

6.2.xxxx.xxxx 

BITS 1.0 

6.0.xxxx.xxxx 

You can also use the symbolic class identifiers to determine the version of BITS that is registered on the computer. The following table lists the versions of BITS and their corresponding symbolic class identifiers. The CoCreateInstance function returns REGDB_E_CLASSNOTREG if the class is not registered.

BITS version 

Symbolic class identifier 

BITS 3.0 

CLSID_BackgroundCopyManager3_0 

BITS 2.5 

CLSID_BackgroundCopyManager2_5

BITS 2.0 

CLSID_BackgroundCopyManager2_0 

BITS 1.5 

CLSID_BackgroundCopyManager1_5 

BITS 1.2, 1.0 

CLSID_BackgroundCopyManager 

Setting Up the Server for Uploads

To upload files to a server using BITS, the server must have IIS and the BITS server extension ISAPI installed. For IIS requirements, see IIS Requirements for BITS Uploads.

For information on configuring the IIS virtual directory that BITS uses for uploads, see the following topics.

Note  Some IIS installations include the UrlScan filtering component. If UrlScan is enabled, the administrator must add the "BITS_POST" verb to UrlScan's list of allowed HTTP verbs. Otherwise, BITS client uploads will fail. For further details on enabling verbs in UrlScan, see the UrlScan documentation.

Setting Permissions on Virtual Directories

For security reasons, BITS does not upload files to a virtual directory that has scripting and execute permissions enabled. If you upload a file to a virtual directory that has these permissions enabled, the job fails with an error code of BG_E_SERVER_EXECUTE_ENABLED.

BITS does not require the virtual directory to be write enabled, so it is recommended that you turn off write access to the virtual directory.

The authenticated user (or IIS's Anonymous user for anonymous authentication) must have Change permissions on the physical directory to which the virtual directory is mapped; granting Write permissions does not suffice.

Specifying Permissions for Notifications

The authentication scheme you specify for the virtual directory and notification URL (see the BITSServerNotificationURL property) must be compatible. BITS uses the authentication scheme specified for the virtual directory to access the notification URL. The upload job fails if BITS is unable to access the notification URL due to authentication failure.

If the notification type (see the BITSServerNotificationType property) is by reference, the application must ensure the user has access to the referenced file (see the BITS-Request-DataFile-Name header). BITS sets the ACLs on the referenced file to those of the physical directory to which the virtual directory is mapped.

Note  The notified application must be able to map and access the remote file even if the notification URL is serviced by a Web server that is on a different computer than the physical upload directory. The BITS-Request-DataFile-Name header always contains a path specification that is relative to the computer hosting the BITS Extensions component. An application running on another computer might need to convert the path to an UNC path before accessing it.

BITS supports many combinations of authentication schemes. However, you should use the following authentication scheme for the virtual directory and the matching notification URL.

  • To support by reference notifications, the virtual directory should be configured to use NTLM (negotiate) authentication if the physical upload directory (the directory to which the virtual directory points) uses an authentication scheme other than anonymous. If the physical upload directory allows anonymous requests (no authentication), the virtual directory should enable anonymous (no authentication).

    The ACLs on the physical upload directory must be set such that the authenticated user can read files on the directory to which the notification URL points. BITS uses the ACLs of the physical upload directory to set the ACLs of temporary upload file (the BITS-Request-DataFile-Name header contains the path to the temporary file).

  • Because by value notifications do not require the notified application to access a temporary file that contains the upload contents, the authentication scheme can be either anonymous or negotiate (NTLM). The only requirement is that the authenticated user for the virtual directory must also be authorized to access the notification URL.

Specifying Permissions for Remote Shares

A virtual directory can point to a mapped drive on a different machine or a network share. If it points to a mapped network drive, the credentials used to map the drive should have full control on the remote share.

If the virtual directory points to a network share, BITS uses the virtual directory's Connect As user credentials to access the remote share. To access a remote share, the Connect As account needs to have privileges as described in the documentation for the LogonUser function. BITS logs on using LOGON32_LOGON_BATCH or LOGON32_LOGON_INTERACTIVE logon types. The Connect As user account needs Full-Access permissions to the remote share; granting Write permissions does not suffice.

When the physical upload directory is mapped to a network share, the identity of the caller requesting the notification URL is either the Connect As user, or the authenticated user of the physical upload directory (only available in IIS 6.0 and later, when the check box Always use the authenticated user's credentials when validating access to the network resource is selected on the Connect As dialog).

Writing a Script to Configure the Virtual Directory

You can use the default BITS IIS property values to upload a file to the server. The upload file is written to the URL as specified in the remote file name of the job. To upload the file to a server application and receive a reply, change the BITSServerNotificationType property to send the data by reference (sends the name of the file that contains the data) or by value (sends the data in the body of the request).

For a list and description of the properties that you can modify, see BITS IIS Extension Properties. Use the methods of the IBITSExtensionSetup interface to enable and disable the virtual directory for uploads.

The following example shows how to use Windows Script Host to create, configure, and enable an IIS virtual directory for BITS uploads.

if (WScript.Arguments.length < 2)

{

WScript.Echo("Usage: bitsvdir virtual_directory local_directory");

WScript.Quit(1);

}


 

VirtualDirectoryName = WScript.Arguments(0);

LocalDirectoryName = WScript.Arguments(1);


 

ServerObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT");

VirtualDir = ServerObj.Create("IIsWebVirtualDir", VirtualDirectoryName );


 

VirtualDir.Path = LocalDirectoryName;

VirtualDir.AppIsolated = 0;

VirtualDir.AccessScript = true;

VirtualDir.AccessRead = false;

VirtualDir.AccessWrite = false;

VirtualDir.SetInfo();


 

//Set BITS specific IIS configuration settings

VirtualDir.EnableBITSUploads();

VirtualDir.BITSMaximumUploadSize = "4294967296";

VirtualDir.SetInfo();


 

WScript.Echo( "Created virtual directory " + VirtualDirectoryName +

" with a local directory of " + LocalDirectoryName );

WScript.Quit( 0 );

To change the previous example to upload the data to a server application, add the following code before SetInfo.

VirtualDir.BITSServerNotificationType = 1;

VirtualDir.BITSServerNotificationURL = "http://myserver/mypath/myasp.asp";

The location of the upload file is passed to the server application, myasp.asp, in the BITS-Request-DataFile-Name header. To receive the upload file in the body of the request, set the BITSServerNotificationType property to 2.

For information on receiving the upload data in your server application, see Using BITS Notification Request/Response Headers.

Using the IIS UI to Configure the Virtual Directory

To use the IIS user interface to configure the virtual directory for BITS uploads, select Properties from the context menu of the virtual directory. Press the BITS Extension tab to access the BITS properties page (the BITS server extension ISAPI must be installed). Change the default property values as appropriate and enable the directory for uploads; you cannot upload files until the directory is enabled. For details on setting the property values, see the online Help.

Preventing Multiple Uploads

When you upload a file, BITS creates a session ID that identifies the upload session to both the BITS client and BITS server. If the connection between the BITS client and server is broken while BITS is uploading a file, the client will use the session ID to try to resume the upload.

If the BITS client connects to the same server as before, the server will recognize the session ID and the upload will resume from the point of interruption. However, if the client connects to a different server, the client must start the upload from the beginning because the new server does not have the session context or the previously uploaded data. BITS may connect to a different server when the BITS server is hosted on a Web farm and the BITS IIS extension property, BITSHostId, is not set. The BITSHostId property prevents restarts by forcing the BITS client to connect to the previous server's unique address instead of the shared server address.

The BITS server will attempt to send the upload file only once to the server application, but it is possible that the file may be sent more than one time. This can occur, for example, if the BITS server sends the file to the server application and then terminates while waiting for the reply from the server application. The BITS client will receive an error code from the HTTP layer, and retry the upload after a delay. If the server stays offline for longer than the BITSHostIdFallbackTimeout timeout, then the client will eventually send the request to the shared server address again; a different BITS server will receive the file and deliver it again to the server application.

A similar case can occur even with a single front-end server. For example, when the client has uploaded the entire file to the server, the final block causes the server to forward the file to the server application. If the BITS server or the server application terminate after the file is processed but before the acknowledgment is sent to the client, then the client will receive an error code and retry later. When the client retries, the BITS server will see that the final block has been uploaded, and it will again forward the file to the server application. If receiving the upload file multiple times is an issue for your server application, you should consider including a transaction identifier in the data.

Virtual Directory Cleanup

BITS extends IIS virtual directories to support uploads. Each virtual directory has a session time-out property (the IIS BITSSessionTimeout metabase property) that specifies the period of time in which the BITS client must make progress in uploading the file. If no progress is made during that period (the timer is reset when progress is made), BITS closes the session. The default session time-out is 14 days.

BITS adds a work item to the Task Scheduler for each virtual directory you create and enable. The work item deletes resources associated with the closed sessions. By default, the cleanup occurs every 12 hours. If two virtual directories point to the same physical directory, the cleanup process initiated by one of the directories deletes the resources associated with all closed sessions in the physical directory.

Use the BITS Extension tab or the Task Scheduler interfaces to change the cleanup schedule as appropriate for your application. You can also call the IBITSExtensionSetup::GetCleanupTask method to retrieve an interface pointer to the cleanup task associated with the virtual directory.

Note  If the Task Scheduler is disabled after the virtual directory is enabled, the virtual directory cleanup process will not work.

Upload Best Practices

Highloads may cause various server timeout conditions, which may in turn increase the load when the client retries. Also, a large number of outstanding connections will consume more server resources and make the situation worse. On top of that, if backend app is not written to handle high load conditions, it may crash or mal-behave. The app shall perform the following steps to limit the load on the backend.

If the server application is not written to handle high volumes, timeout conditions may occur, which may in turn increase the load when the client retries. Also, a large number of outstanding connections will consume more server resources.

When testing your server application, test with highest load possible. You should use multiple client machines, each with several concurrent, foreground BITS jobs, and measure the maximum throughput at the backend. If you cannot measure the throughput, you will have to estimate the throughput.

The server application should reside on a different URL from the upload URL (see the BITS IIS property, BITSServerNotificationURL).

It is good practice to limit the load on the application server based on proven throughput values. You should use the IIS properties, MaxBandwidth and MaxConnections, to limit the load on the application server.

Upload Limits

To limit the size of uploads, set the BITSMaximumUploadSize IIS extension property. In IIS 7, you may also have to modify the maxAllowedContentLength attribute. By default, the IIS 7 upload limit is 30 million bytes. For details and information on changing the IIS default, see KB942074.

Using BITS Notification Request/Response Headers

BITS can send the location of the upload file (by reference) to your server application or it can send the upload file in the body of the request (by value). To specify how BITS sends the upload file to your server application, set the IIS metabase property, BITSServerNotificationType. If you specify by reference, BITS passes the location of the file in the BITS-Request-DataFile-Name header. To send a reply, create and write your response to the file specified in the BITS-Response-DataFile-Name header.

Server applications that send the same reply to many clients should use by reference, so there is only one copy of the reply on the server. For example, in a software update application, the client would upload its software configuration to the server application. The server application determines which package the client needs and sends the URL of the package to BITS. Then, BITS downloads the package as the reply.

Server applications that generate unique replies for each client should use by value. For example, a server application that supports the purchase of music files would need to send a signed music file to the client. Because the signed music file is unique to the client, the server application would not store it on the server. By value is also useful for an application that is already written to accept Web client data directly.

For details on the request and response headers used between BITS and your server application, see Notification Protocol for Server Applications.

The following JScript example shows how to access the request and response files in a server application that uses by reference notification (BITS passes the location of the files in the headers).

[JScript]

var fso = new ActiveXObject ("Scripting.FileSystemObject")

var requestFileName = Request.ServerVariables ("HTTP_BITS-Request-DataFile-Name")

var responseFileName = Request.ServerVariables ("HTTP_BITS-Response-DataFile-Name")

var requestStream

var responseStream

var ForReading = 1

var ForWriting = 2

var TristateUseDefault = -2


 

//Open the upload data file as text stream for reading.

requestStream = fso.OpenTextFile(requestFileName, ForReading, false, TristateUseDefault);


 

//Do something with the uploaded data.


 

//Close the upload stream.

requestStream.Close()


 

//Open response data file as text stream for writing.

responseStream = fso.OpenTextFile(responseFileName, ForWriting, true, TristateUseDefault);


 

//Write a response to the response file.


 

//Close the response text stream

responseStream.Close()

If you want to use a different response file than the one specified in BITS-Response-DataFile-Name, call the Response.AddHeader method to add the BITS-Static-Response-URL as shown in the following example. If you specify a different response file, do not create the response file specified in BITS-Response-DataFile-Name.

[JScript]

Response.AddHeader "BITS-Static-Response-URL" "http://myserver/mypath/myfile"

The following VBScript example shows how to access the request and response data in a server application that uses by value notification (BITS passes the upload file as a stream of data in the body of the request and receives the response as a stream of data in the body of the response).

[C++]

dim byteCount

dim postData


 

'Read the posted data.

byteCount = Request.TotalBytes

postData = Request.BinaryRead (byteCount)


 

'Do something with the data.


 

'Write the reply.

Response.Write("Some reply")

Handling Server Application Errors

If the server application successfully processes the uploaded file, the application should return 200. If the application does not return 200, the BITS client uses the error code to determine if the error is a transient error or fatal error.

All 3xx error codes are transient errors except 300 - 305 and 307, which are fatal errors. All 4xx error codes are fatal errors except for 408 and 409, which are transient errors. All 5xx error codes are transient errors except 501 and 505, which are fatal errors. All other HTTP codes are considered transient errors. Note that a 403 error code is the only error code that prevents BITS from posting the upload file to the server application again.

To retrieve the error, call the IBackgroundCopyError::GetError method. The error context will be BG_ERROR_CONTEXT_REMOTE_APPLICATION.

BITS Reference

The Background Intelligent Transfer Service (BITS) reference section contains detailed information about the following API elements:

You use these API elements to create applications that transfer files between a client and a server. For sample code that uses the BITS interfaces, see BITS Samples and Tools.

For general information about BITS, see the BITS start page.

BITS Enumerations

The Background Intelligent Transfer Service (BITS) interfaces use the following enumerations.

Enumeration 

Description

BG_AUTH_SCHEME

Defines the authentication scheme to use when a proxy or server requests user authentication. 

BG_AUTH_TARGET

Defines if the credentials are used for proxy or server user authentication requests. 

BG_CERT_STORE_LOCATION

Defines the location of the certificate store.

BG_ERROR_CONTEXT

Defines the context in which an error occurred. 

BG_JOB_PRIORITY

Defines the priority level of a job. 

BG_JOB_PROXY_USAGE

Defines which proxy to use for file transfers. 

BG_JOB_STATE

Defines the different states of a job. 

BG_JOB_TYPE

Defines the type of transfer job, such as download. 

BG_AUTH_SCHEME Enumeration

The BG_AUTH_SCHEME enumeration defines the constant values that specify the authentication scheme to use when a proxy or server requests user authentication.

typedef enum {

BG_AUTH_SCHEME_BASIC = 1,

BG_AUTH_SCHEME_DIGEST,

BG_AUTH_SCHEME_NTLM,

BG_AUTH_SCHEME_NEGOTIATE,

BG_AUTH_SCHEME_PASSPORT

} BG_AUTH_SCHEME;

Constants

BG_AUTH_SCHEME_BASIC

Basic is a scheme in which the user name and password are sent in clear-text to the server or proxy.

BG_AUTH_SCHEME_DIGEST

Digest is a challenge-response scheme that uses a server-specified data string for the challenge.

BG_AUTH_SCHEME_NTLM

NTLM is a challenge-response scheme that uses the credentials of the user for authentication in a Windows network environment.

BG_AUTH_SCHEME_NEGOTIATE

Simple and Protected Negotiation protocol (Snego) is a challenge-response scheme that negotiates with the server or proxy to determine which scheme to use for authentication. Examples are the Kerberos protocol and NTLM.

BG_AUTH_SCHEME_PASSPORT

Passport is a centralized authentication service provided by Microsoft that offers a single logon for member sites.

Remarks

BITS supports passport authentication for explicit credentials only, not implicit credentials tied to the account.

The following table shows the authentication requests that BITS does not support.

Scenario not supported 

Windows Server 2003 

Windows XP 

Windows 2000 

Passport authentication on the server when the proxy requires authentication (using the HTTPS protocol). 

Not supported 

Not supported 

Not supported 

Any authentication scheme on the server when the proxy requires Digest authentication.

Not supported 

Not supported 

Not supported 

Negotiate authentication on the server when the proxy requires Basic authentication. 

 

Not supported 

Not supported 

Using HTTPS when the proxy requires digest authentication.

 

Not supported 

Not supported 

Requirements

Client 

Requires Windows Vista. 

Server 

Requires Windows Server 2008 or Windows Server 2003. 

Redistributable 

Requires BITS 1.5 on Windows XP and Windows 2000. 

Header 

Declared in Bits1_5.h; include Bits.h.

IDL 

Declared in Bits1_5.idl. 

BG_AUTH_TARGET Enumeration

The BG_AUTH_TARGET enumeration defines the constant values that specify whether the credentials are used for proxy or server user authentication requests.

typedef enum {

BG_AUTH_TARGET_SERVER = 1,

BG_AUTH_TARGET_PROXY

} BG_AUTH_TARGET;

Constants

BG_AUTH_TARGET_SERVER

Use credentials for server requests.

BG_AUTH_TARGET_PROXY

Use credentials for proxy requests.

Requirements

Client 

Requires Windows Vista. 

Server 

Requires Windows Server 2008 or Windows Server 2003. 

Redistributable 

Requires BITS 1.5 on Windows XP and Windows 2000. 

Header 

Declared in Bits1_5.h; include Bits.h. 

IDL 

Declared in Bits1_5.idl. 

BG_CERT_STORE_LOCATION Enumeration

The BG_CERT_STORE_LOCATION enumeration defines the location of the certificate store.

typedef enum {

BG_CERT_STORE_LOCATION_CURRENT_USER,

BG_CERT_STORE_LOCATION_LOCAL_MACHINE,

BG_CERT_STORE_LOCATION_CURRENT_SERVICE,

BG_CERT_STORE_LOCATION_SERVICES,

BG_CERT_STORE_LOCATION_USERS,

BG_CERT_STORE_LOCATION_CURRENT_USER_GROUP_POLICY,

BG_CERT_STORE_LOCATION_LOCAL_MACHINE_GROUP_POLICY,

BG_CERT_STORE_LOCATION_LOCAL_MACHINE_ENTERPRISE

} BG_CERT_STORE_LOCATION;

Constants

BG_CERT_STORE_LOCATION_CURRENT_USER

Use the current user's certificate store.

BG_CERT_STORE_LOCATION_LOCAL_MACHINE

Use the local computer's certificate store.

BG_CERT_STORE_LOCATION_CURRENT_SERVICE

Use the current service's certificate store.

BG_CERT_STORE_LOCATION_SERVICES

Use a specific service's certificate store.

BG_CERT_STORE_LOCATION_USERS

Use a specific user's certificate store.

BG_CERT_STORE_LOCATION_CURRENT_USER_GROUP_POLICY

Use the current user's group policy certificate store. In a network setting, stores in this location are downloaded to the client computer from the Group Policy Template (GPT) during computer startup or user logon.

BG_CERT_STORE_LOCATION_LOCAL_MACHINE_GROUP_POLICY

Use the local computer's certificate store. In a network setting, stores in this location are downloaded to the client computer from the Group Policy Template (GPT) during computer startup or user logon.

BG_CERT_STORE_LOCATION_LOCAL_MACHINE_ENTERPRISE

Use the enterprise certificate store. The enterprise store is shared across domains in the enterprise and downloaded from the global enterprise directory.

Remarks

For more information, see System Store Locations.

Requirements

Client 

Requires Windows Vista. 

Server 

Requires Windows Server 2008. 

Header 

Declared in Bits2_5.h; include Bits.h. 

IDL 

Declared in Bits2_5.idl. 

BG_ERROR_CONTEXT Enumeration

The BG_ERROR_CONTEXT enumeration defines the constant values that specify the context in which the error occurred.

typedef enum {

BG_ERROR_CONTEXT_NONE = 0,

BG_ERROR_CONTEXT_UNKNOWN = 1,

BG_ERROR_CONTEXT_GENERAL_QUEUE_MANAGER = 2,

BG_ERROR_CONTEXT_QUEUE_MANAGER_NOTIFICATION = 3,

BG_ERROR_CONTEXT_LOCAL_FILE = 4,

BG_ERROR_CONTEXT_REMOTE_FILE = 5,

BG_ERROR_CONTEXT_GENERAL_TRANSPORT = 6,

BG_ERROR_CONTEXT_REMOTE_APPLICATION = 7

} BG_ERROR_CONTEXT;

Constants

BG_ERROR_CONTEXT_NONE

An error has not occurred.

BG_ERROR_CONTEXT_UNKNOWN

The error context is unknown.

BG_ERROR_CONTEXT_GENERAL_QUEUE_MANAGER

The transfer queue manager generated the error.

BG_ERROR_CONTEXT_QUEUE_MANAGER_NOTIFICATION

The error was generated while the queue manager was notifying the client of an event.

BG_ERROR_CONTEXT_LOCAL_FILE

The error was related to the specified local file. For example, permission was denied or the volume was unavailable.

BG_ERROR_CONTEXT_REMOTE_FILE

The error was related to the specified remote file. For example, the URL was not accessible.

BG_ERROR_CONTEXT_GENERAL_TRANSPORT

The transport layer generated the error. These errors are general transport failures (these errors are not specific to the remote file).

BG_ERROR_CONTEXT_REMOTE_APPLICATION

The server application that BITS passed the upload file to generated an error while processing the upload file.

BITS 1.2 and earlier:  Not supported.

Requirements

Client 

Requires Windows Vista, Windows XP, or Windows 2000 Professional SP3. 

Server 

Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server SP3. 

Header 

Declared in Bits.h. 

BG_JOB_PRIORITY Enumeration

The BG_JOB_PRIORITY enumeration defines the constant values that specify the priority level of a job.

typedef enum {

BG_JOB_PRIORITY_FOREGROUND,

BG_JOB_PRIORITY_HIGH,

BG_JOB_PRIORITY_NORMAL,

BG_JOB_PRIORITY_LOW

} BG_JOB_PRIORITY;

Constants

BG_JOB_PRIORITY_FOREGROUND

Transfers the job in the foreground. Foreground transfers compete for network bandwidth with other applications, which can impede the user's network experience. This is the highest priority level.

BG_JOB_PRIORITY_HIGH

Transfers the job in the background with a high priority. Background transfers use idle network bandwidth of the client to transfer files. This is the highest background priority level.

BG_JOB_PRIORITY_NORMAL

Transfers the job in the background with a normal priority. Background transfers use idle network bandwidth of the client to transfer files. This is the default priority level.

BG_JOB_PRIORITY_LOW

Transfers the job in the background with a low priority. Background transfers use idle network bandwidth of the client to transfer files. This is the lowest background priority level.

Remarks

For background jobs, the priority level determines when the job is processed relative to other jobs in the transfer queue. Higher priority jobs preempt lower priority jobs. Jobs at the same priority level share transfer time, which prevents a large job from blocking the transfer queue. Lower priority jobs do not receive transfer time until all higher priority jobs are transferred or in an error state.

All foreground jobs run concurrently with one background job. BITS processes the files within foreground jobs serially.

BITS 1.5 and earlier:  BITS processes one job at a time. Foreground jobs have the highest priority and run before background jobs.

For more information, see Best Practices When Using BITS.

Requirements

Client 

Requires Windows Vista, Windows XP, or Windows 2000 Professional SP3. 

Server 

Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server SP3. 

Header 

Declared in Bits.h.

BG_JOB_PROXY_USAGE Enumeration

The BG_JOB_PROXY_USAGE enumeration defines constant values that specify which proxy to use for file transfers. You can define different proxy settings for each job.

typedef enum {

BG_JOB_PROXY_USAGE_PRECONFIG,

BG_JOB_PROXY_USAGE_NO_PROXY,

BG_JOB_PROXY_USAGE_OVERRIDE,

BG_JOB_PROXY_USAGE_AUTODETECT

} BG_JOB_PROXY_USAGE;

Constants

BG_JOB_PROXY_USAGE_PRECONFIG

Use the proxy and proxy bypass list settings defined by each user to transfer files. Settings are user-defined from Control Panel, Internet Options, Connections, Local Area Network (LAN) settings (or Dial-up settings, depending on the network connection).

BG_JOB_PROXY_USAGE_NO_PROXY

Do not use a proxy to transfer files. Use this option when you transfer files within a LAN.

BG_JOB_PROXY_USAGE_OVERRIDE

Use the application's proxy and proxy bypass list to transfer files. Use this option when you cannot trust that the system settings are correct. Also use this option when you want to transfer files using a special account, such as LocalSystem, to which the system settings do not apply.

BG_JOB_PROXY_USAGE_AUTODETECT

Automatically detect proxy settings. BITS detects proxy settings for each file in the job.

BITS 1.5 and earlier:  BG_JOB_PROXY_USAGE_AUTODETECT is not available.

Requirements

Client 

Requires Windows Vista, Windows XP, or Windows 2000 Professional SP3. 

Server 

Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server SP3. 

Header 

Declared in Bits.h. 

BG_JOB_STATE Enumeration

The BG_JOB_STATE enumeration defines constant values for the different states of a job.

typedef enum {

BG_JOB_STATE_QUEUED,

BG_JOB_STATE_CONNECTING,

BG_JOB_STATE_TRANSFERRING,

BG_JOB_STATE_SUSPENDED,

BG_JOB_STATE_ERROR,

BG_JOB_STATE_TRANSIENT_ERROR,

BG_JOB_STATE_TRANSFERRED,

BG_JOB_STATE_ACKNOWLEDGED,

BG_JOB_STATE_CANCELLED

} BG_JOB_STATE;

Constants

BG_JOB_STATE_QUEUED

Specifies that the job is in the queue and waiting to run. If a user logs off while their job is transferring, the job transitions to the queued state.

BG_JOB_STATE_CONNECTING

Specifies that BITS is trying to connect to the server. If the connection succeeds, the state of the job becomes BG_JOB_STATE_TRANSFERRING; otherwise, the state becomes BG_JOB_STATE_TRANSIENT_ERROR.

BG_JOB_STATE_TRANSFERRING

Specifies that BITS is transferring data for the job.

BG_JOB_STATE_SUSPENDED

Specifies that the job is suspended (paused). To suspend a job, call the IBackgroundCopyJob::Suspend method. BITS automatically suspends a job when it is created. The job remains suspended until you call the IBackgroundCopyJob::Resume, IBackgroundCopyJob::Complete, or IBackgroundCopyJob::Cancel method.

BG_JOB_STATE_ERROR

Specifies that a non-recoverable error occurred (the service is unable to transfer the file). If the error, such as an access-denied error, can be corrected, call the IBackgroundCopyJob::Resume method after the error is fixed. However, if the error cannot be corrected, call the IBackgroundCopyJob::Cancel method to cancel the job, or call the IBackgroundCopyJob::Complete method to accept the portion of a download job that transferred successfully.

BG_JOB_STATE_TRANSIENT_ERROR

Specifies that a recoverable error occurred. BITS will retry jobs in the transient error state based on the retry interval you specify (see IBackgroundCopyJob::SetMinimumRetryDelay). The state of the job changes to BG_JOB_STATE_ERROR if the job fails to make progress (see IBackgroundCopyJob::SetNoProgressTimeout).

BITS does not retry the job if a network disconnect or disk lock error occurred (for example, chkdsk is running) or the MaxInternetBandwidth Group Policy is zero.

BG_JOB_STATE_TRANSFERRED

Specifies that your job was successfully processed. You must call the IBackgroundCopyJob::Complete method to acknowledge completion of the job and to make the files available to the client.

BG_JOB_STATE_ACKNOWLEDGED

Specifies that you called the IBackgroundCopyJob::Complete method to acknowledge that your job completed successfully.

BG_JOB_STATE_CANCELLED

Specifies that you called the IBackgroundCopyJob::Cancel method to cancel the job (remove the job from the transfer queue).

BG_JOB_TYPE Enumeration

The BG_JOB_TYPE enumeration defines constant values that specify the type of transfer job, such as download.

typedef enum {

BG_JOB_TYPE_DOWNLOAD,

BG_JOB_TYPE_UPLOAD,

BG_JOB_TYPE_UPLOAD_REPLY

} BG_JOB_TYPE;

Constants

BG_JOB_TYPE_DOWNLOAD

Specifies that the job downloads files to the client.

BG_JOB_TYPE_UPLOAD

Specifies that the job uploads a file to the server.

BITS 1.2 and earlier:  Not supported.

BG_JOB_TYPE_UPLOAD_REPLY

Specifies that the job uploads a file to the server and receives a reply file from the server application.

BITS 1.2 and earlier:  Not supported.

BITS Interfaces

Use the following Background Intelligent Transfer Service (BITS) interfaces to transfer files and monitor jobs within the transfer queue.

Interface 

Description 

IBackgroundCopyCallback

Clients implement the IBackgroundCopyCallback interface to receive notification that a job is complete, has been modified, or is in error.

IBackgroundCopyError

Retrieves details of a job error. 

IBackgroundCopyFile

Retrieves the local and remote file names of a file transfer request in the job and its progress.

IBackgroundCopyFile2

Specifies a new remote name for the file and retrieves the list of ranges to download.

IBackgroundCopyFile3

Validates the file so that peers can request its content and retrieves the name of the temporary file. 

IBackgroundCopyJob

Adds files to the job, sets the priority level of the job, determines the state of the job, and starts and stops the job. 

IBackgroundCopyJob2

Retrieves reply data from an upload job, determines the progress of the reply data transfer to the client, requests command line execution, and provides credentials for a proxy and remote server. 

IBackgroundCopyJob3

Downloads ranges of a file, changes the prefix of a remote file name, and maintains the owner and ACL information with the file. 

IBackgroundCopyJob4

Enables peer caching, restrict download time, and inspect user token characteristics.  

IBackgroundCopyJobHttpOptions

Specifies client certificates for certificate-based client authentication and custom headers for HTTP requests.

IBackgroundCopyManager

Creates transfer jobs, retrieves an enumerator object of jobs in the queue, and retrieves individual jobs from the queue.

IBitsPeer

Gets information about a peer in the neighborhood. 

IBitsPeerCacheAdministration

Manage the pool of peers from which you can download content. 

IBitsPeerCacheRecord

Gets information about a file in the cache.

IEnumBackgroundCopyFiles

Enumerates files in the job. 

IEnumBackgroundCopyJobs

Enumerates jobs in the transfer queue. 

IEnumBitsPeerCacheRecords

Enumerates the records of the cache. 

IEnumBitsPeers

Enumerates the list of peers that BITS has discovered. 

BITS Return Values

The Bitsmsg.h file contains the following return value constants. The constants represent return values that BITS generates and HTTP return values that BITS captures. All other return values that you can receive are COM, RPC, or converted Windows return values (BITS uses the HRESULT_FROM_WIN32 macro to convert the Windows return values to HRESULT values).

Note that the Bitsmsg.h file contains additional return values not listed below.

BG_S_PARTIAL_COMPLETE (0x00200017)

A subset of the job's files transferred successfully before the IBackgroundCopyJob::Complete method was called. Those that were not complete were deleted.

BG_S_UNABLE_TO_DELETE_FILES (0x0020001A)

Unable to delete all temporary files associated with the job.

BG_S_OVERRIDDEN_BY_POLICY (0x00200055)

The configuration preference has been saved successfully, but the preference will not be used because a configured Group Policy setting overrides the preference.

BG_E_NOT_FOUND (0x80200001)

The requested job was not found.

BG_E_INVALID_STATE (0x80200002)

The requested action is not allowed in the current job state.

BG_E_EMPTY (0x80200003)

The job must contain one or more files before you can resume the job.

BG_E_FILE_NOT_AVAILABLE (0x80200004)

File information is not available because the error is not associated with a local or remote file.

BG_E_PROTOCOL_NOT_AVAILABLE (0x80200005)

Protocol information is not available because the error is not associated with the specified transfer protocol.

BG_E_DESTINATION_LOCKED (0x8020000D)

The destination file system volume, specified in the local file name, is locked.

BG_E_VOLUME_CHANGED (0x8020000E)

The destination volume, specified in the local file name, has changed. For example, the original floppy disk has been replaced with a different floppy disk.

BG_E_ERROR_INFORMATION_UNAVAILABLE (0x8020000F)

Error information is only available when the state of the job is BG_JOB_STATE_ERROR. The error information is not available after BITS begins transferring the job's data or the client exits.

BG_E_NETWORK_DISCONNECTED (0x80200010)

The network adapter is inactive or disconnected. All jobs are placed in the BG_JOB_STATE_TRANSIENT_ERROR state.

BG_E_MISSING_FILE_SIZE (0x80200011)

The server did not return the file size. BITS only transfers static content and requires the HTTP server to return the Content-Length header. The transfer request fails if the URL points to dynamic content.

BG_E_INSUFFICIENT_HTTP_SUPPORT (0x80200012)

The server does not support the HTTP/1.1 protocol.

BG_E_INSUFFICIENT_RANGE_SUPPORT (0x80200013)

The server does not support the Content-Range header. Typically, you receive this error when you try to download dynamic content. You can also receive this error if an intermediate proxy is removing the Content-Range or Content-Length header.

BG_E_REMOTE_NOT_SUPPORTED (0x80200014)

Remote use of BITS is not supported. For more information, see Users and Network Connections.

BG_E_NEW_OWNER_DIFF_MAPPING (0x80200015)

The network drive mapping for the local file is different for the current owner than for the previous owner.

BG_E_NEW_OWNER_NO_FILE_ACCESS (0x80200016)

The new owner has insufficient permissions to the temporary job files.

BG_E_PROXY_LIST_TOO_LARGE (0x80200018)

The HTTP proxy list is too long. The list must not exceed 32 KB.

BG_E_PROXY_BYPASS_LIST_TOO_LARGE (0x80200019)

The HTTP proxy bypass list is too long. The list must not exceed 32 KB.

BG_E_TOO_MANY_FILES (0x8020001C)

You cannot add more than one file to an upload job.

BG_E_LOCAL_FILE_CHANGED (0x8020001D)

The contents of the local file changed after the transfer process began. The contents of the local file cannot change after the transfer process begins on an upload or upload-reply job.

BG_E_TOO_LARGE (0x80200020)

The size of the upload file exceeds the maximum allowed upload size specified on the server.

BG_E_STRING_TOO_LONG (0x80200021)

The specified string is too long.

BG_E_CLIENT_SERVER_PROTOCOL_MISMATCH (0x80200022)

The client and server were unable to negotiate a protocol to use for the upload job.

BG_E_SERVER_EXECUTE_ENABLED (0x80200023)

Scripting or execute permissions are enabled on the IIS virtual directory associated with the job. To upload files to the virtual directory, disable the scripting and execute permissions on the virtual directory.

BG_E_USERNAME_TOO_LARGE (0x80200025)

The user name cannot exceed 300 characters.

BG_E_PASSWORD_TOO_LARGE (0x80200026)

The password cannot exceed 300 characters.

BG_E_INVALID_AUTH_TARGET (0x80200027)

The specified authentication target is not valid.

BG_E_INVALID_AUTH_SCHEME (0x80200028)

The specified authentication scheme is not valid.

BG_E_INVALID_RANGE (0x8020002B)

The specified byte range is invalid. The byte range must exist within the specified remote file.

BG_E_OVERLAPPING_RANGES (0x8020002C)

The list of byte ranges contains overlapping or duplicate ranges, which are not supported.

BG_E_BLOCKED_BY_POLICY (0x8020003E)

Group Policy settings prevent background jobs from running at this time. For details, see the MaxInternetBandwidth policy.

BG_E_INVALID_PROXY_INFO (0x8020003F)

Run-time error that indicates the proxy list or proxy bypass list that you specified using the IBackgroundCopyJob::SetProxySettings method is invalid.

BG_E_INVALID_CREDENTIALS (0x80200040)

The format of the supplied security credentials is not valid.

BG_E_RECORD_DELETED (0x80200042)

The cache record has been deleted. The attempt to update it has been abandoned.

BG_E_UPNP_ERROR (0x80200045)

A Universal Plug and Play (UPnP) error has occurred. Please check your Internet Gateway Device.

BG_E_PEERCACHING_DISABLED (0x80200047)

Peer-caching is disabled.

BG_E_BUSYCACHERECORD (0x80200048)

The cache record is in use and cannot be changed or deleted. Try again after a few seconds.

BG_E_TOO_MANY_JOBS_PER_USER (0x80200049)

The job count for the user has exceeded the per user job limit set by the MaxJobsPerUser Group Policy setting.

BG_E_TOO_MANY_JOBS_PER_MACHINE (0x80200050)

The job count for the computer has exceeded the per computer job limit set by the MaxJobsPerMachine Group Policy setting.

BG_E_TOO_MANY_FILES_IN_JOB (0x80200051)

The file count for the job has exceeded the per job file limit set by the MaxFilesPerJob Group Policy setting.

BG_E_TOO_MANY_RANGES_IN_FILE (0x80200052)

The range count for the file has exceeded the per file range limit set by the MaxRangesPerFile Group Policy setting.

BG_E_VALIDATION_FAILED (0x80200053)

The application requested data from a web site, but the response was not valid. For details, use Event Viewer to view the Application Logs\Microsoft\Windows\Bits-client\Operational log.

BG_E_MAXDOWNLOAD_TIMEOUT (0x80200054)

BITS timed out downloading the job. The download did not complete within the maximum download time set on the job or the MaxDownloadTime Group Policy setting.

BG_E_HTTP_ERROR_400 (0x80190190)

The server could not process the transfer request because the syntax of the remote file name is invalid.

BG_E_HTTP_ERROR_401 (0x80190191)

The user does not have permission to access the remote file. The requested resource requires user authentication.

BG_E_HTTP_ERROR_404 (0x80190194)

The requested URL does not exist on the server.

In IIS 7, this error can indicate

  • That BITS uploads are not enabled on the virtual directory (vdir) on the server.
  • That the upload size exceeds the maximum upload limit (for details, see the BITSMaximumUploadSize IIS extension property).

BG_E_HTTP_ERROR_407 (0x80190197)

The user does not have permission to access the proxy. The proxy requires user authentication.

BG_E_HTTP_ERROR_414 (0x8019019E)

The server cannot process the transfer request. The Uniform Resource Identifier (URI) in the remote file name is longer than the server can interpret.

BG_E_HTTP_ERROR_501 (0x801901F5)

The server does not support the functionality required to fulfill the request. In IIS 6, this error indicates that BITS uploads are not enabled on the virtual directory (vdir) on the server.

BG_E_HTTP_ERROR_503 (0x801901F7)

The service is temporarily overloaded and cannot process the request. Resume the job at a later time.

BG_E_HTTP_ERROR_504 (0x801901F8)

The transfer request timed out while waiting for a gateway. Resume the job at a later time.

BG_E_HTTP_ERROR_505 (0x801901F9)

The server does not support the HTTP protocol version specified in the remote file name.

The Bitsmsg.h header file contains additional HTTP return values not listed above that BITS uses internally. For information on these and other HTTP return values you can receive, see the RFC 2616 specification from the Internet Engineering Task Force at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.

BITS Samples and Tools

BITS includes the following samples in Windows SDK. The samples are located under <install dir>\Samples\Web. Each sample includes a Readme.txt file that explains how to install and run the sample. You can download the Windows SDK from http://www.microsoft.com/downloads/details.aspx?FamilyID=c2b1e300-f358-4523-b479-f53d234cdccf&DisplayLang=en. BITS is included in the Core SDK.

Sample

Purpose

BITS_IE

Shows how to use the BITS interfaces to download files from a server.

Controls

Shows how to use the BITS interfaces to control and configure BITS options, including using some of the peer cache administration methods.

Downloads

Shows how to use the BITS interfaces to download files from a server.

HTTPHeaders

Shows how to use the BITS interfaces to modify HTTP headers.

PeerCaching

Shows how to use the BITS interfaces to enable a job to download from a peer.

Uploads

Shows how to use the BITS interfaces to upload a file.

UploadSample

Shows how to use the BITS interfaces to upload a file to a server and receive a reply.

BITS provides the following tool.

Tool

Purpose

BITSAdmin

Command-line tool to create download or upload jobs and monitor their progress.

BITSAdmin Tool

BITSAdmin is a command-line tool that you can use to create download or upload jobs and monitor their progress.

The \Support\Tools\Support.cab file on the operating system installation CD contains the BITSAdmin tool. To unpack and install BITSAdmin, run the Setup.exe file in the Tools directory. If you do not have access to the installation CD, you can download the support tools from Windows XP Service Pack 2 Support Tools.

The BITSAdmin tool uses switches to identify the work to perform. Most switches require a Job parameter that you set to the job's display name or GUID. Note that a job's display name may not be unique. The /create and /list switches return a job's GUID.

By default, you can access information about your own jobs. To access information for another user's jobs, you must have administrator privileges. If the job was created in an elevated state, you must run BitsAdmin from an elevated window; otherwise, you will have read-only access to the job.

Many of the switches correspond to methods in the BITS interfaces. For additional details that may be relevant to using a switch, see the corresponding method.

Use the following switches to create a job, set and retrieve the properties of a job, and monitor the status of a job. For examples that show how to use some of these switches to perform tasks, see BITSAdmin Examples.

/AddFile Job RemoteURL LocalName

Adds a file to the specified job. RemoteURL is the URL of the file on the server. LocalName is the name of the file on the local computer. LocalName must contain an absolute path to the file.

/AddFileSet Job TextFile

Adds one or more files to the specified job. Each line in TextFile contains a remote and local file name. The names are space-delimited. Lines that begin with a # character are treated as a comment.

/AddFileWithRanges Job RemoteURL LocalName RangeList

Adds a file to the specified job. BITS downloads the specified ranges from the remote file. Switch is valid only for download jobs. RemoteURL is the URL of the file on the server. LocalName is the name of the file on the local computer. LocalName must contain an absolute path to the file.

RangeList is a comma-delimited list of offset:length pairs. For example, the following range list tells BITS to transfer 100 bytes from offset 0, 100 bytes from offset 2000, and the remaining bytes from offset 5000 to the end of the file.

0:100,2000:100,5000:eof

/Cancel Job

Removes the job from the transfer queue and deletes all temporary files associated with the job.

/Complete Job

Completes the job. The downloaded files are not available to you until you use this switch. Use this switch after the job moves to the transferred state. Otherwise, only those files that have been successfully transferred are available.

/Create [/type]
DisplayName

Creates a transfer job with the given DisplayName. You can specify /Download, /Upload, or /Upload-Reply for the type parameter. The default type is /Download.

BITS 1.2 and earlier:  The /Upload and /Upload-Reply types are not available.

Download jobs transfer data from a server to a local file. Upload jobs transfer data from a local file to a server. Upload-reply jobs transfer data from a local file to a server and receive a reply file from the server.

Use the /resume switch to activate the job in the transfer queue.

/GetAclFlags Job

Retrieves the ACL propagations flags. Displays one or more of the following flag values:

  • O — Copy owner information with file.
  • G — Copy group information with file.
  • D — Copy DACL information with file.
  • S — Copy SACL information with file.

/GetBytesTotal Job

Retrieves the size of the specified job.

/GetBytesTransferred Job

Retrieves the number of bytes transferred for the specified job.

/GetCompletionTime Job

Retrieves the time that the job finished transferring data.

/GetCreationTime Job

Retrieves the job creation time for the specified job.

/GetDescription Job

Retrieves the description of the specified job.

/GetDisplayName Job

Retrieves the display name of the specified job.

/GetError Job

Retrieves detailed error information for the specified job.

/GetErrorCount Job

Retrieves a count of the number of times the specified job generated a transient error.

/GetFilesTotal Job

Retrieves the number of files in the specified job.

/GetFilesTransferred Job

Retrieves the number of files transferred for the specified job.

/GetMinRetryDelay Job

Retrieves the length of time, in seconds, that the service waits after encountering a transient error before trying to transfer the file.

/GetModificationTime Job

Retrieves the last time the job was modified or data was successfully transferred.

/GetNoProgressTimeout Job

Retrieves the length of time, in seconds, that the service tries to transfer the file after a transient error occurs.

/GetNotifyCmdLine Job

Retrieves the command-line command to execute when the job finishes transferring data.

BITS 1.2 and earlier:  Not supported.

/GetNotifyFlags Job

Retrieves the notify flags for the specified job. The job can contain one or more of the following notification flags.

  • 0x0001 — Generate an event when all files in the job have been transferred.
  • 0x0002 — Generate an event when an error occurs.
  • 0x0004 — Disable notifications.
  • 0x0008 — Generate an event when the job is modified or transfer progress is made.

/GetNotifyInterface Job

Determines if the notify interface is registered for the specified job. Displays REGISTERED or UNREGISTERED.

/GetOwner Job

Retrieves the owner of the specified job.

/GetPriority Job

Retrieves the priority of the specified job. The priority is either FOREGROUND, HIGH, NORMAL, LOW, or UNKNOWN.

/GetProxyBypassList Job

Retrieves the proxy bypass list for the specified job. The bypass list contains the host names or IP addresses, or both, that are not to be routed through a proxy. The list can contain "<local>" to refer to all servers on the same LAN. The list is space-delimited.

/GetProxyList Job

Retrieves the proxy list for the specified job. The proxy list is the list of proxy servers to use. The list is comma-delimited.

/GetProxyUsage Job

Retrieves the proxy usage setting for the specified job. The possible values are:

  • PRECONFIG — Use the owner's Internet Explorer defaults.
  • NO_PROXY —Do not use a proxy server.
  • OVERRIDE — Use an explicit proxy list.

/GetReplyData Job

Retrieves the server's reply data in hexadecimal format. Valid only for upload-reply jobs.

BITS 1.2 and earlier:  Not supported.

/GetReplyFileName Job

Gets the path of the file that contains the server reply. Valid only for upload-reply jobs.

BITS 1.2 and earlier:  Not supported.

/GetReplyProgress Job

Retrieves the size and progress of the server reply. Valid only for upload-reply jobs.

BITS 1.2 and earlier:  Not supported.

/GetState Job

Retrieves the state of the specified job. The possible states are:

  • QUEUED — The job is waiting to run.
  • CONNECTING — BITS is contacting the server.
  • TRANSFERRING — BITS is transferring data.
  • SUSPENDED — The job is paused.
  • ERROR — A non-recoverable error occurred; the transfer will not be retried.
  • TRANSIENT_ERROR — A recoverable error occurred; the transfer retries when the minimum retry delay expires.
  • ACKNOWLEDGED — The job was completed.
  • CANCELLED — The job was canceled.

/GetType Job

Retrieves the job type of the specified job. The type can be DOWNLOAD, UPLOAD, UPLOAD-REPLY, or UNKNOWN.

/Help | /?

Displays the command-line usage.

/Info Job
[/verbose]

Displays summary information about the specified job. Use the /verbose parameter to provide detailed information about the job.

/List [/allusers]
[/verbose]

Lists the transfer jobs owned by the current user. To list jobs for all users, include the /allusers parameter. You must have administrator privileges to use the /allusers parameter. Use the /verbose parameter to provide detailed information about jobs.

/ListFiles Job

Lists the files in the specified job.

/Monitor [/allusers]
[/refresh Seconds]

Monitors jobs in the transfer queue that the current user owns. To monitor jobs for all users, include the /allusers parameter. You must have administrator privileges to use the allusers parameter. The /refresh parameter refreshes the data at an interval specified by Seconds. The default refresh period is every 5 seconds. To stop the refresh, enter CTRL+C.

/NoWrap

Does not wrap output to fit in a command window. By default, all switches, except the /Monitor switch, wrap the output. Specify before other switches.

/RawReturn

Returns data suitable for parsing. Strips new line characters and formatting from the output. Typically, you use this switch in conjunction with the /create and /get* switches to receive only the value. Specify before other switches.

/RemoveCredentials Job Target Scheme

Removes credentials from a job. Target can be either SERVER or PROXY. Scheme can be BASIC, DIGEST, NTLM, NEGOTIATE, or PASSPORT.

BITS 1.2 and earlier:  Not supported.

/ReplaceRemotePrefix Job OldPrefix NewPrefix

All files in the job whose remote URL begins with OldPrefix are changed to use NewPrefix.

/Reset /AllUsers

Cancels all jobs in the transfer queue that the current user owns. If you have administrator privileges, you can specify /AllUsers to cancel all jobs in the queue.

BITSAdmin 1.5 and earlier:  If you have administrator privileges, Reset cancels all jobs in the queue. The /AllUsers option is not supported.

/Resume Job

Activates a new or suspended job in the transfer queue.

/SetAclFlags Job flags

Sets the ACL propagations flags for the job. The flags indicate that you want to maintain the owner and ACL information with the file being downloaded. Specify one or more of the following flags. For example, to maintain the owner and group with the file, set flags to OG.

  • O — Copy owner information with file.
  • G — Copy group information with file.
  • D — Copy DACL information with file.
  • S — Copy SACL information with file.

/SetCredentials Job Target Scheme UserName Password

Adds credentials to a job. Target can be either SERVER or PROXY. Scheme can be BASIC, DIGEST, NTLM, NEGOTIATE, or PASSPORT.

BITS 1.2 and earlier:  Not supported.

/SetDescription Job Description

Sets the description of the specified job.

/SetDisplayName Job DisplayName

Sets the DisplayName of the specified job.

/SetMinRetryDelay Job RetryDelay

Sets the minimum length of time, in seconds, that BITS waits after encountering a transient error before trying to transfer the file.

/SetNoProgressTimeout Job Time-out

Sets the length of time, in seconds, that BITS tries to transfer the file after the first transient error occurs.

/SetNotifyCmdLine Job Program_Name[Program_Parameters]

Specify a command-line program to execute when the job finishes transferring data or is in error. You can specify NULL for Program_Name and Program_Parameters. If Program_Name is NULL, Program_Parameters must be NULL.

BITS 1.2 and earlier:  Not supported.

The following examples show how to use this switch:

bitsadmin /SetNotifyCmdLine MyJob
c:\winnt\system32\notepad.exe NULL

bitsadmin /SetNotifyCmdLine MyJob c:\handler.exe "c:\handler.exe parm1 parm2 parm3"

bitsadmin /SetNotifyCmdLine MyJob NULL NULL

/SetNotifyFlags Job NotifyFlags

Sets the event notification flags for the specified job. Specify one or more of the following notification flags. For example, to specify transferred and error events, set NotifyFlags to 0x0003.

  • 0x0001 — Generate an event when all files in the job have been transferred.
  • 0x0002 — Generate an event when an error occurs.
  • 0x0004 — Disable notifications.
  • 0x0008 — Generate an event when the job is modified or transfer progress is made.

/SetPriority Job Priority

Sets the priority of the specified job. The priority must be either FOREGROUND, HIGH, NORMAL, or LOW.

/SetProxySettings Job usage List Bypass

Sets the proxy settings for the specified job. The usage parameter can be one of the following values:

  • PRECONFIG — Use the owner's Internet Explorer defaults.
  • NO_PROXY — Do not use a proxy server.
  • OVERRIDE — Use an explicit proxy list and bypass list. A proxy and proxy bypass list must follow.

The List parameter contains a comma-delimited list of proxy servers to use. The Bypass parameter contains a space-delimited list of host names or IP addresses, or both, for which transfers are not to be routed through a proxy. This can be <local> to refer to all servers on the same LAN. Values of NULL or "" may be used for an empty proxy bypass list.

The following examples show possible uses of the switch:

bitsadmin /setproxysettings MyJob PRECONFIG

bitsadmin /setproxysettings MyJob NO_PROXY

bitsadmin /setproxysettings MyJob OVERRIDE proxy1:80 "<local>"

bitsadmin /setproxysettings MyJob OVERRIDE proxy1,proxy2,proxy3 NULL

/SetReplyFileName Job Path

Specify the path of the file that contains the server reply. Valid only for upload-reply jobs.

BITS 1.2 and earlier:  Not supported.

/Suspend Job

Suspends the specified job. To restart the job, use the /resume switch.

/TakeOwnership Job

Lets a user with administrative privileges take ownership of the specified job.

/Transfer name
[type]
[/priority job_priority]
[/ACLFlags flags]
remote_name local_name

Transfers one or more files. By default, BITSAdmin creates a download job that runs at NORMAL priority. BITSAdmin updates the command window with progress information until the transfer is complete or until a critical error occurs. BITSAdmin completes the job if it successfully transfers all the files and cancels the job if a critical error occurs. BITSAdmin does not create the job if it is unable to add files to the job or if you specify an invalid value for type or job_priority. Note that BITSAdmin continues to run if a transient error occurs. To end BITSAdmin, press Ctrl+C.

Use the name parameter to specify the name of the job.

The type parameter is optional. Use the type parameter to specify the type of job. Specify /download for a download job or /upload for an upload job.

The /priority parameter is optional. To specify the priority of the job, set the job_priority operand to FOREGROUND, HIGH, NORMAL, or LOW.

The /ACLFlags parameter is optional. The flags indicate that you want to maintain the owner and ACL information with the file being downloaded. Specify one or more of the following flags. For example, to maintain the owner and group with the file, set flags to OG.

  • O — Copy owner information with file.
  • G — Copy group information with file.
  • D — Copy DACL information with file.
  • S — Copy SACL information with file.

To transfer more than one file, specify multiple remote_name-local_name pairs. The pairs are space-delimited.

/Util /Help

Displays the command-line usage for the /Util switches. You can also specify /?.

BITSAdmin 1.5 and earlier:  Not supported.

/Util /GetIEProxy <Account>[/Conn <Connection Name>]

Retrieves the proxy usage for the given service account. This switch shows the value for each proxy usage, not just the proxy usage you specified for the service account.

Windows 2000 and BITSAdmin 1.5 and earlier:  Not supported.

Use the <account> parameter to specify the service account whose proxy settings you want to retrieve. Possible values are:

  • LOCALSYSTEM
  • NETWORKSERVICE
  • LOCALSERVICE

Use the /conn parameter to specify the modem connection to use. If you do not specify the /conn parameter, BITS uses the LAN connection. Specify the modem connection name immediately following the /conn parameter.

For details on setting the proxy usage for service accounts, see the /Util /SetIEProxy switch.

/Util /RepairService

If BITS fails to start, use this switch to fix known issues with various versions of BITS. For example, this switch resolves errors related to incorrect service configuration and dependencies on LANManworkstation service and the network directory. This switch generates output that indicates the issues that were resolved.

BITSAdmin 1.5 and earlier:  Not supported.

Note that if BITS recreates the service, the service description string may be set to English in a localized system.

/Util /SetIEProxy <Account> <Usage>
[/Conn <Connection Name>]

Specify proxy settings to use when transferring files using a service account.

Windows 2000 and BITSAdmin 1.5 and earlier:  Not supported.

Use the <account> parameter to specify the type of service account whose proxy usage you want to define. Possible values are:

  • LOCALSYSTEM
  • NETWORKSERVICE
  • LOCALSERVICE

Use the <usage> parameter to specify the form of proxy detection to use. Possible values are:

  • NO_PROXY—Do not use a proxy server.
  • AUTODETECT—Automatically detect the proxy settings.
  • MANUAL_PROXY—Use an explicit proxy list and bypass list. Specify the proxy list and bypass list immediately following the usage tag. For example, MANUAL_PROXY proxy1,proxy2 NULL.

    The proxy list is a comma-delimited list of proxy servers to use.

    The bypass list is a space-delimited list of host names or IP addresses, or both, for which transfers are not to be routed through a proxy. This can be <local> to refer to all servers on the same LAN. Values of NULL or "" may be used for an empty proxy bypass list.

  • AUTOSCRIPT—Same as AUTODETECT, except it also executes a script. Specify the script URL immediately following the usage tag. For example, AUTOSCRIPT http://server/proxy.js.
  • RESET—Same as NO_PROXY, except it removes the manual proxy URLs (if specified) and URLs discovered using automatic detection.

Note that each successive call using this switch does not replace the previously specified usage. For example, if you specify NO_PROXY, AUTODETECT, and MANUAL_PROXY on separate calls, BITS uses automatic detection to determine the proxy to use. If automatic detection fails, BITS uses MANUAL_PROXY.

Use the /conn parameter to specify the modem connection to use. If you do not specify the /conn parameter, BITS uses the LAN connection. Specify the modem connection name immediately following the /conn parameter.

The following examples show how to use the /Util /SetIEProxy switch:

bitsadmin /util /setieproxy localsystem AUTODETECT

bitsadmin /util /setieproxy localsystem MANUAL_PROXY proxy1,proxy2,proxy3 NULL

bitsadmin /util /setieproxy localsystem MANUAL_PROXY proxy1:80 "<local>"

/Util /Version [/Verbose]

Displays the version of BITS (for example 2.0) that is running. Use the verbose option to display information about the state of BITS.

BITSAdmin 1.5 and earlier:  Not supported.

/Wrap

Wraps output to fit in a command window. Specify before other switches. By default, all switches, except the /Monitor switch, wrap the output.

BITSAdmin Examples

The following examples show how to use the BITSAdmin tool to perform the most common tasks. For a complete list of switches and description of their use, see BITSAdmin Tool.

Transfer a File

The /transfer switch is a shortcut for performing the tasks listed below. This switch creates the job, adds the files to the job, activates the job in the transfer queue, and completes the job. BITSAdmin continues to show progress information in the MS-DOS window until the transfer completes or an error occurs.

bitsadmin /transfer myDownloadJob /download /priority normal http://downloadsrv/10mb.zip c:\10mb.zip

Create a Download Job

Use the /create switch to create a download job named myDownloadJob.

bitsadmin /create myDownloadJob

BITSAdmin returns a GUID that uniquely identifies the job. Use the GUID or job name in subsequent calls. The following text is sample output.

Created job {C775D194-090F-431F-B5FB-8334D00D1CB6}.

Next, use the /addfile switch to add one or more files to the download job.

Add Files to the Download Job

Use the /addfile switch to add a file to the job. Repeat this call for each file you want to add. If multiple jobs use myDownloadJob as their name, you must replace myDownloadJob with the job's GUID to uniquely identify the job.

bitsadmin /addfile myDownloadJob http://downloadsrv/10mb.zip c:\10mb.zip

To activate the job in the transfer queue, use the /resume switch.

Activate the Download Job

When you create a new job, BITS suspends the job. To activate the job in the transfer queue, use the /resume switch. If multiple jobs use myDownloadJob as their name, you must replace myDownloadJob with the job's GUID to uniquely identify the job.

bitsadmin /resume myDownloadJob

To determine the progress of the job, use the /list, /info, or /monitor switch.

Determine the Progress of the Download Job

Use the /info switch to determine the progress of a job. If multiple jobs use myDownloadJob as their name, you must replace myDownloadJob with the job's GUID to uniquely identify the job.

bitsadmin /info myDownloadJob /verbose

The /info switch returns the state of the job and the number of files and bytes transferred. When the state is TRANSFERRED, BITS has successfully transferred all files in the job. The /verbose argument provides complete details of the job. The following text is sample output.

GUID: {482FCAF0-74BF-469B-8929-5CCD028C9499} DISPLAY: myDownloadJob

TYPE: DOWNLOAD STATE: TRANSIENT_ERROR OWNER: domain\user

PRIORITY: NORMAL FILES: 0 / 1 BYTES: 0 / UNKNOWN

CREATION TIME: 12/17/2002 1:21:17 PM MODIFICATION TIME: 12/17/2002 1:21:30 PM

COMPLETION TIME: UNKNOWN

NOTIFY INTERFACE: UNREGISTERED NOTIFICATION FLAGS: 3

RETRY DELAY: 600 NO PROGRESS TIMEOUT: 1209600 ERROR COUNT: 0

PROXY USAGE: PRECONFIG PROXY LIST: NULL PROXY BYPASS LIST: NULL

ERROR FILE: http://downloadsrv/10mb.zip -> c:\10mb.zip

ERROR CODE: 0x80072ee7 - The server name or address could not be resolved

ERROR CONTEXT: 0x00000005 - The error occurred while the remote file was being

processed.

DESCRIPTION:

JOB FILES:

0 / UNKNOWN WORKING http://downloadsrv/10mb.zip -> c:\10mb.zip

NOTIFICATION COMMAND LINE: none

To receive information for all jobs in the transfer queue, use the /list or /monitor switch.

Completing the Download Job

When the state of the job is TRANSFERRED, BITS has successfully transferred all files in the job. However, the files are not available until you use the /complete switch. If multiple jobs use myDownloadJob as their name, you must replace myDownloadJob with the job's GUID to uniquely identify the job.

bitsadmin /complete myDownloadJob

Monitoring Jobs in the Transfer Queue

Use the /list, /monitor, or /info switch to monitor jobs in the transfer queue. The /list switch provides information for all jobs in the queue.

bitsadmin /list

The /list switch returns the state of the job and the number of files and bytes transferred for all jobs in the transfer queue. The following text is sample output.

{6AF46E48-41D3-453F-B7AF-A694BBC823F7} job1 SUSPENDED 0 / 0 0 / 0

{482FCAF0-74BF-469B-8929-5CCD028C9499} job2 TRANSIENT_ERROR 0 / 1 0 / UNKNOWN


 

Listed 2 job(s).

Use the /monitor switch to monitor all jobs in the queue. The /monitor switch refreshes the data every 5 seconds. To stop the refresh, enter CTRL+C.

bitsadmin /monitor

The /monitor switch returns the state of the job and the number of files and bytes transferred for all jobs in the transfer queue. The following text is sample output.

MONITORING BACKGROUND COPY MANAGER(5 second refresh)

{6AF46E48-41D3-453F-B7AF-A694BBC823F7} job1 SUSPENDED 0 / 0 0 / 0

{482FCAF0-74BF-469B-8929-5CCD028C9499} job2 TRANSIENT_ERROR 0 / 1 0 / UNKNOWN

{0B138008-304B-4264-B021-FD04455588FF} job3 TRANSFERRED 1 / 1 100379370 / 100379370

Deleting Jobs From the Transfer Queue

Use the /reset switch to remove all jobs from the transfer queue.

bitsadmin /reset

The following text is sample output.

{DC61A20C-44AB-4768-B175-8000D02545B9} canceled.

{BB6E91F3-6EDA-4BB4-9E01-5C5CBB5411F8} canceled.

2 out of 2 jobs canceled.

BITS Server Settings for Upload Jobs

This section contains the following topics.

Topic

Description

BITS IIS Extension Properties

Identifies the properties that BITS adds to IIS to support uploads.

BITS ADSI Extension

ADSI extension that you use to enable and disable BITS uploads.

Notification Protocol for Server Applications

Identifies the request and response headers that BITS uses to send the upload file to the server application and receive a reply file.

For information on configuring IIS for uploads, see Setting Up the Server for Uploads.

BITS IIS Extension Properties

Background Intelligent Transfer Service (BITS) uses an ISAPI to extend IIS to support upload jobs. The following table lists the properties that BITS adds to the IIS metabase for the virtual directory component. BITS uses these properties to determine how to upload the files. The BITS IIS extension properties are inheritable, except for BITSUploadEnabled.

Property

Description

BITSUploadEnabled

Data type: Boolean

Indicates whether BITS uploads are enabled on the virtual directory. If the setting is not present or is 0, BITS uploads are disabled.

This is a read-only property. To set this property, call the EnableBITSUploads or DisableBITSUploads method of the IBITSExtensionSetup interface.

BITSSessionTimeout

Data type: DWORD

Number of seconds the connection is maintained if no progress is made uploading the file; the timer is reset when progress is made. BITS closes the connection if the time-out is reached and cleans up data associated with the session.

Setting a short session time-out can be an issue for upload-reply jobs because the reply is only downloaded when the user is logged on and connected to the network. It is possible for the session to time out before the reply is downloaded, in which case the session is canceled and the reply file is deleted.

Note that BITS cancels the job if the JobInactivityTimeout Group Policy value (default is 90 days) is reached, regardless of this setting.

Default value is 1,209,600 (14 days).

BITSMaximumUploadSize

Data type: String

Maximum number of bytes that can be uploaded per job. Specify the maximum number of bytes as a decimal string; the string value must be less than or equal to "1844674407370955". An empty string is the same as specifying "1844674407370955".

Default value is an empty string.

Note  In IIS 7, the default upload limit is 30 million bytes. The value of the BITSMaximumUploadSize property cannot exceed the IIS limit. For details and information on changing the IIS default, see KB942074.

BITSServerNotificationType

Data type: DWORD

Specifies how to send the upload file to the server application. The possible values are: 0, 1, and 2.

A value of 0 means the file is not sent to the server application. BITS puts the upload file in the directory specified in the remote name (the remote name specified when you added the file to the job) without notifying the server application. If the file currently exists in the destination directory, it is replaced with the upload file.

A value of 1 means BITS passes the location of the upload file to the server application specified in the BITSServerNotificationURL property. The server application processes the file and generates a reply file, if needed. By default, BITS removes the upload and reply files from the server after it receives the response from the server application. To have BITS copy the upload file to the location specified by the remote file name in the job, include the BITS-Copy-File-To-Destination header in your response. If you do not include the header and you want to save the upload and reply files, you must copy the upload and reply files to a new location before responding.

A value of 2 means BITS passes the upload file in the body of the request to the server application specified in the BITSServerNotificationURL property. The server application processes the file and passes back the reply in the body of the response, if needed.

For details on the request and response headers, see Notification Protocol for Server Applications.

The server application must provide a response within five minutes. If the server application does not reply within five minutes, the job enters the transient error state. When the retry delay expires, the BITS server will send another notification to the server application (the server application should be written to handle duplicate notifications).

BITS 1.5:  The notification time-out is 30 seconds.

Default value is 0.

BITSServerNotificationURL

Data type: String

Optional. Contains the URL of the server application to which BITS posts the upload file. You must specify a URL if the value of the BITSServerNotificationType property is 1 or 2. The URL is limited to 2,200 characters, not including the null terminator. The URL must be an HTTP URL; BITS does not support HTTPS notification URLs.

If the URL is not available at the time of upload, BITS will retry the upload until the notification URL exists or until the retry period expires.

Note that if the remote name specified in the job contains a query string, the query string is appended to the URL that you specify. For example, if the remote name contains http://myserver/myvdir/subdir/file.asp?ACCOUNT=86433 and you specify the BITSServerNotificationURL setting as http://otherserver/myvdir2/bag.asp, the URL to which BITS posts is http://otherserver/myvdir2/bag.asp?ACCOUNT=86433.

If the original URL is http://myserver/myvdir/file.txt and the notification URL is myasp.asp, BITS uses http//myserver/myvdir/myasp.asp as the notification URL.

If the path and file name portion of the URL contains Unicode characters not in common to the code page on both the client and server, the URL translation will fail on the server and the BITS job will be placed in the error state. If the server portion of the URL contains Unicode characters, you must encode the server portion using Internationalized Domain Names (IDN).

BITSHostId

Data Type: String

Set this property if the server installation is a Web farm that does not use shared storage.

Specify the server name or IP address of the server to reconnect to after the upload process is interrupted. Typically, you specify the name of the server you are configuring. The URL is limited to 300 characters, not including the null terminator.

If you do not specify this property and the upload process is interrupted, it is possible that BITS will resume the job on another server in the farm. However, the previous server still contains the partial upload file from before the interruption. BITS removes the partial file after the BITSSessionTimeout expires.

Note  Do not use the BITSHostId property if SSL is used in a Web farm that uses Network Load Balancing (NLB) or DNS names with multiple IP addresses, unless you include the cluster name and individual server names in the certificate. (If the server name specified in BITSHostId does not match the common name on the certificate, the job will fail.) Instead, for NLB, set the Affinity parameter to Single to ensure that the client communicates with the same server in the future.

BITSHostIdFallbackTimeout

Data type: DWORD

Number of seconds the BITS client tries to reconnect to the BITSHostId server name before reverting to the host name specified in the remote file name of the job. The timer begins when BITS is unable to connect to the BITSHostId server. The timer is reset when the client successfully connects to the server.

Note that the no progress timeout value of the job (see IBackgroundCopyJob::SetNoProgressTimeout) should be longer than this timeout value. If not, the job will fail before fallback timeout value expires.

Set this property only if you set the BITSHostId property.

Default value is 86,400 (1 day).

BITSAllowOverwrites

Data type: Integer

Indicates whether an upload file can overwrite an existing file with the same name. The upload file overwrites the existing file if BITSAllowOverwrites is 1.

Default value is 0.

IIS 6.0:  You can set this property only from a script, you cannot set it using the BITS extension properties page in the IIS user interface.

BITSCleanupUseDefault

Data type: Boolean

Indicates whether the cleanup task uses the default schedules. By default, the cleanup task is run every 12 hours.

Set to 1 to use the default schedule; otherwise, 0 to specify a schedule.

To specify a schedule, use the BITSCleanupCount and BITSCleanupUnits properties.

The cleanup task cleans up the virtual directory by deleting jobs that have not been modified within the session time-out period (see BITSSessionTimeout).

The default is 1—use the default schedule.

IIS 6.0:  Not supported.

BITSCleanupCount

Data type: Integer

Specifies the interval to wait between running the cleanup task. The interval that you can specify depends on the units. For possible interval values, see the BITSCleanupUnits property.

This property is ignored if BITSCleanupUseDefault is 0.

IIS 6.0:  Not supported.

BITSCleanupUnits

Data type: Integer

Specifies the units for the cleanup interval specified in the BITSCleanupCount property. Possible values are:

Value

Units

0

Minutes. Possible values: 1 - 60.

1

Hours. Possible values: 1 - 24.

2

Days. Possible values: 1 -360.

The default unit is hours (1).

This property is ignored if BITSCleanupUseDefault is 0.

IIS 6.0:  Not supported.

BITSNumberOfSessionsLimit

Data type: Integer

Limits the number of upload sessions that can exist concurrently for a user. If the number of sessions for a user is more than this limit, when the cleanup task runs it will delete the most recent sessions until the number of sessions for the user is below the limit.

The default is 50 sessions.

IIS 6.0:  Not supported.

BITSSessionLimitEnable

Data type: Boolean

Indicates whether BITS limits the number of upload sessions per user. If the setting is not present or is 0, the limit is disabled.

To specify the limit, set the BITSNumberOfSessionsLimit property.

The default is 1.

IIS 6.0:  Not supported.

The following example shows how to set the BITS IIS extension properties using Windows Script Host. If the virtual directory points to a remote share, also set the UNCUserName and UNCPassword IIS properties.

if (WScript.Arguments.length < 2)

{

WScript.Echo("Usage: bitsvdir virtual_directory local_directory");

WScript.Quit(1);

}


 

VirtualDirectoryName = WScript.Arguments(0);

LocalDirectoryName = WScript.Arguments(1);


 

ServerObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT");

VirtualDir = ServerObj.Create("IIsWebVirtualDir", VirtualDirectoryName );


 

VirtualDir.Path = LocalDirectoryName;

VirtualDir.AppIsolated = 0;

VirtualDir.AccessScript = true;

VirtualDir.AccessRead = false;

VirtualDir.AccessWrite = false;

VirtualDir.SetInfo();


 

// Set BITS specific IIS configuration settings

VirtualDir.EnableBITSUploads();

VirtualDir.BITSMaximumUploadSize = "4294967296";

VirtualDir.SetInfo();


 

WScript.Echo( "Created virtual directory " + VirtualDirectoryName +

" with a local directory of " + LocalDirectoryName );

WScript.Quit( 0 );


 

Send comments about this topic to Microsoft

Build date: 1/15/2008

Tags : Add a tag

Add   Cancel

Community Content

  


 

Add Community Content

 

C# syntax to invoke the native method and set property for BITS upload automation.

      

Michael K. Kim   |   Edit   |   Show History

Please Wait  


 


For those who need the example code above in C# syntax

...

// Set Properties
VirtualDir.Properties["BITSMaximumUploadSize"][0] = "4294967296";
...

// Invoke native method
VirtualDir.Invoke("EnableBITSUploads", null);
...

VirtualDir..CommitChanges();
...

VirtualDir.Close();
...

Notification Protocol for Server Applications

BITS uses the BITSServerNotificationType property to determine how BITS sends the contents of the upload file to the server application. If the BITSServerNotificationType property is set to 1, BITS passes the location of the upload file in a header. If the BITSServerNotificationType property is set to 2, BITS passes the contents of the upload file in the body of the request.

For details on how BITS handles errors from the server application, see Handling server application errors.

Sending the location of the upload file in a header

BITS passes the location of the upload and reply files to the server application in the headers if the BITSServerNotificationType property is set to 1. The server application opens the upload file, processes the data, and then generates the reply file. By default, BITS removes the upload and reply files from the server after it receives the response from the server application. To have BITS copy the upload file to the location specified by the remote file name in the job, include the BITS-Copy-File-To-Destination header in your response. If you do not include the header and you want to save the upload and reply files, you must copy the upload and reply files to a new location before responding. The following table shows the request headers.

Request header

Description

BITS-Original-Request-URL

Contains the remote name specified in the job.

BITS-Request-DataFile-Name

Contains the full path to the uploaded data.

BITS-Response-DataFile-Name

Contains the full path to where BITS expects the server application to write the response.

The following table shows the response headers.

Response header

Description

BITS-Static-Response-URL

Optional. Contains the absolute URL (do not specify a relative URL) to a static data file to use as the response. The static data file must be accessible by the BITS client. If you use this header, do not create the response file specified in the BITS-Response-DataFile-Name request header.

Note that BITS does not delete this file for you.

BITS-Copy-File-To-Destination

Optional. By default, if the BITSServerNotificationType property is set to 1 or 2, the BITS server does not copy the upload file to the location specified by the remote file name in the job. To have BITS copy the file to the location specified by the remote file name in the job, send this response header. You can specify any value; BITS does not use the value. Note that the folders in the remote file path must exist.

The following request shows BITS sending the location of the upload file to the server application.

POST http://myserver/myvdir/handle_upload.asp?ACCOUNT=873112 HTTP/1.1

Host: myserver

BITS-Original-Request-URL: http://front-end-server/vdir

BITS-Request-DataFile-Name: c:\physical-path\BITS-Sessions\{5e53c221-f2d6-4bf2-

b994-1dc43ceaca8d}\request

BITS-Response-DataFile-Name: c:\physical-path\BITS-Sessions\{5e53c221-f2d6-4bf2-

b994-1dc43ceaca8d}\response

Content-Length: 0

The following shows the server application's reply to BITS; the reply is placed in the file specified by the BITS-Response-DataFile-Name request header.

HTTP/1.1 200 - OK

Content-Length: 0

Sending the upload file in the body of the request

BITS sends the upload file in the body of the request if the BITSServerNotificationType property is set to 2. Sending the upload file in the body of the request lets existing scripts and applications work with minimal modifications. The upload file and reply file are passed in the request and response, respectively. The following table shows the request header.

Request header

Description

BITS-Original-Request-URL

Contains the remote name specified in the job.

The following table shows the response headers.

Response header

Description

BITS-Static-Response-URL

Optional. Contains the absolute URL (do not specify a relative URL) to a static data file to use as the response. The static data file must be accessible by the BITS client. If you use this header, do not include the response in the stream.

Note that BITS does not delete this file for you.

BITS-Copy-File-To-Destination

Optional. If the BITSServerNotificationType property is set to 1 or 2, the BITS server does not copy the upload file to the location specified by the remote file name in the job. To have BITS copy the file to the location specified by the remote file name, send this response header. You can specify any value; BITS does not use the value. Note that the folders in the remote file path must exist.

The following request shows BITS passing the uploaded file to the server application in the body of the request.

POST http://myserver/myvdir/handle_upload.asp?ACCOUNT=873112 HTTP/1.1

Host: myserver

BITS-Original-Request-URL: http://front-end-server/vdir

Content-Length: 80000


 

80000 bytes of upload data goes here

The following reply shows the server application passing the reply data to BITS in the body of the response.

HTTP/1.1 200 - OK

Content-Length: 100


 

100 bytes of reply data goes here

Handling server application errors

See Handling Server Application Errors.


 

Send comments about this topic to Microsoft

Build date: 1/15/2008

BITS ADSI Extension

The BITS server provides the following ADSI extension interfaces to enable BITS uploads.

Interface

Description

IBITSExtensionSetup

Use to enable and disable BITS uploads to a virtual directory.

IBITSExtensionSetupFactory

Use to retrieve a pointer to an IBITSExtensionSetup interface in a setup program that installs the BITS server.

IBITSExtensionSetup Interface

Use the IBITSExtensionSetup interface to enable or disable BITS uploads to a virtual directory.

This interface is an ADSI extension. To get a pointer to this interface, call the ADsGetObject ADSI function as shown in Example Code.

If you use this interface from a setup program that also installs the BITS server, you must call the IBITSExtensionSetupFactory::GetObject method to get a pointer to this interface instead of calling the ADsGetObject function.

Methods in Vtable Order

The IBITSExtensionSetup interface inherits the methods of the IUnknown interface.

In addition, IBITSExtensionSetup defines the following methods.

Method

Description

EnableBITSUploads

Enables BITS uploads on the virtual directory to which the ADSI object points.

DisableBITSUploads

Disables BITS uploads on the virtual directory to which the ADSI object points.

GetCleanupTaskName

Returns the cleanup task name associated with the virtual directory.

GetCleanupTask

Returns an interface to the cleanup task associated with the virtual directory. The cleanup task removes orphaned files from the virtual directory.

Remarks

This interface is registered on the server when you install the BITS server extension. On Windows 2000 Server, use the BITS redistributable to install the BITS server extension. For details on the redistributable, see Run-time Requirements.

On Windows Server 2003, use the Windows Components Wizard to install the BITS server extension. From Control Panel, select Add or Remove Programs. Then, select Add/Remove Windows Components to display the Windows Components Wizard. The BITS server extension is a sub-component of Internet Information Services (IIS) which is a sub-component of Web Application Server.

Example Code [C++]

The following example shows how to use the ADsGetObject function to get a pointer to the IBITSExtensionSetup interface.

//Set the BITSUploadEnabled IIS configuration setting.

//The pszPath parameter contains the path to the directory service.

//For example, "IIS://<machine name>/w3svc/1/<virtual directory>".

//The Enable parameter contains true (enable) or false (disable).

HRESULT SetBITSUploadEnabledSetting(LPWSTR pszPath, bool Enable)

{

HRESULT hr;

IBITSExtensionSetup* pExtensionSetup = NULL;


 

hr = ADsGetObject(pszPath, __uuidof(IBITSExtensionSetup), &pExtensionSetup);

if (SUCCEEDED(hr))

{

if (Enable)

{

hr = pExtensionSetup->EnableBITSUploads();

}

else

{

hr = pExtensionSetup->DisableBITSUploads();

}


 

pExtensionSetup->Release();

}


 

return hr;

}

Requirements

Client

Requires Windows Vista.

Server

Requires Windows Server 2008 or Windows Server 2003.

Redistributable

Requires BITS 1.5 on Windows XP and Windows 2000.

Header

Declared in Bitscfg.h.

IDL

Declared in Bitscfg.idl.

DLL

Requires BitsMgr.dll.

IID

IID_IBITSExtensionSetup is defined as 29CFBBF7-09E4-4B97-B0BC-F2287E3D8EB3.

DisableBITSUploads Method of the IBITSExtensionSetup Interface

Use the DisableBITSUploads method to disable BITS upload on the virtual directory to which the ADSI object points. This method sets the BITSUploadEnabled IIS extension property.

HRESULT DisableBITSUploads();

Parameters

This method has no parameters.

Return Value

This method returns S_OK for success. Otherwise, the method failed.

Example Code

See the example for the IBITSExtensionSetup interface.

Requirements

Client

Requires Windows Vista.

Server

Requires Windows Server 2008 or Windows Server 2003.

Redistributable

Requires BITS 1.5 on Windows XP and Windows 2000.

Header

Declared in Bitscfg.h.

IDL

Declared in Bitscfg.idl.

DLL

Requires BitsMgr.dll.

IID

IID_IBITSExtensionSetup is defined as 29CFBBF7-09E4-4B97-B0BC-F2287E3D8EB3.

EnableBITSUploads Method of the IBITSExtensionSetup Interface

Use the EnableBITSUploads method to enable BITS upload on the virtual directory to which the ADSI object points. This method sets the BITSUploadEnabled IIS extension property.

HRESULT EnableBITSUploads();

Parameters

This method has no parameters.

Return Value

This method returns S_OK for success. Otherwise, the method failed.

Example Code

See the example for the IBITSExtensionSetup interface.

Remarks

This method turns off the scripting and execute permissions on the virtual directory; you cannot upload files to a virtual directory that has scripting and execute permissions enabled. If the permissions are restored after calling this method, the upload jobs fail with an error code of BG_E_SERVER_EXECUTE_ENABLED.

The EnableBITSUploads method fails if the Task Scheduler is disabled.

Requirements

Client

Requires Windows Vista.

Server

Requires Windows Server 2008 or Windows Server 2003.

Redistributable

Requires BITS 1.5 on Windows XP and Windows 2000.

Header

Declared in Bitscfg.h.

IDL

Declared in Bitscfg.idl.

DLL

Requires BitsMgr.dll.

IID

IID_IBITSExtensionSetup is defined as 29CFBBF7-09E4-4B97-B0BC-F2287E3D8EB3.

GetCleanupTask Method of the IBITSExtensionSetup Interface

Use the GetCleanupTask method to retrieve an interface pointer to the cleanup task associated with the virtual directory.

HRESULT GetCleanupTask(

[in] REFIID riid,

[out] IUnknown** ppTask

);

Parameters

riid

Identifies the task scheduler interface to return in ppTask. For a list of identifiers, see the ITaskScheduler::Activate method.

ppTask

A pointer to the interface specified by riid. Use the interface to modify the properties of the task. Release ppTask when done.

Return Value

This method returns S_OK for success. Otherwise, the method returns S_FALSE if a task has not been created for the virtual directory.

Remarks

When you create a virtual directory and enable it for BITS uploads, BITS adds a work item in the Task Scheduler. The work item cleans up the virtual directory once every 12 hours by deleting jobs that have not been modified within the time-out period. To specify the time-out period, set the BITSSessionTimeout IIS extension property.

To change the cleanup schedule, see the BITSCleanupUseDefault BITS IIS extension property.

Requirements

Client

Requires Windows Vista.

Server

Requires Windows Server 2008 or Windows Server 2003.

Redistributable

Requires BITS 1.5 on Windows XP and Windows 2000.

Header

Declared in Bitscfg.h.

IDL

Declared in Bitscfg.idl.

DLL

Requires BitsMgr.dll.

IID

IID_IBITSExtensionSetup is defined as 29CFBBF7-09E4-4B97-B0BC-F2287E3D8EB3.

GetCleanupTaskName Method of the IBITSExtensionSetup Interface

Use the GetCleanupTaskName method to retrieve the name of the cleanup task associated with the virtual directory.

HRESULT GetCleanupTaskName(

[out] BSTR* pTaskName

);

Parameters

pTaskName

Null terminated string containing the name of the cleanup task associated with the virtual directory. If NULL, BITS has not created a cleanup task for the virtual directory. When done, call the SysFreeString function to free pTaskName.

Return Value

This method returns S_OK for success. Otherwise, the method returns S_FALSE if a task name has not been specified for the virtual directory.

Remarks

When you create a virtual directory and enable it for BITS uploads, BITS adds a work item in the Task Scheduler. The work item cleans up the virtual directory once every 12 hours by deleting jobs that have not been modified within the time-out period. To specify the time-out period, set the BITSSessionTimeout IIS extension property.

Use the pTaskName name as an input parameter to the Schtasks.exe executable file, which you can use to change the properties of the cleanup task from a script.

Requirements

Client

Requires Windows Vista.

Server

Requires Windows Server 2008 or Windows Server 2003.

Redistributable

Requires BITS 1.5 on Windows XP and Windows 2000.

Header

Declared in Bitscfg.h.

IDL

Declared in Bitscfg.idl.

DLL

Requires BitsMgr.dll.

IID

IID_IBITSExtensionSetup is defined as 29CFBBF7-09E4-4B97-B0BC-F2287E3D8EB3.

IBITSExtensionSetupFactory Interface

Use the IBITSExtensionSetupFactory interface to get a pointer to the IBITSExtensionSetup interface. Only use this interface if you use the IBITSExtensionSetup interface in a setup program that also installs the BITS server. Because the IIS cache does not contain the BITS extensions added during setup, the extensions are not available using the ADsGetObject ADSI function. The IBITSExtensionSetupFactory interface provides a GetObject method, which accesses the BITS extensions and performs the same binding as the ADsGetObject function.

To get a pointer to the IBITSExtensionSetupFactory interface, call the CoCreateInstance function as shown in Example Code.

Methods in Vtable Order

The IBITSExtensionSetupFactory interface inherits the methods of the IUnknown interface.

In addition, IBITSExtensionSetupFactory defines the following method.

Method

Description

GetObject

Retrieves a pointer to the IBITSExtensionSetup interface.

Remarks

This interface is registered on the server when you install the BITS server extension. On Windows 2000 Server, use the BITS redistributable to install the BITS server extension. For details on the redistributable, see Run-time Requirements.

On Windows Server 2003, use the Windows Components Wizard to install the BITS server extension. From Control Panel, select Add or Remove Programs. Then, select Add/Remove Windows Components to display the Windows Components Wizard. The BITS server extension is a sub-component of Internet Information Services (IIS) which is a sub-component of Web Application Server.

Example Code [C++]

The following example shows how to use the IBITSExtensionSetupFactory interface to get a pointer to the IBITSExtensionSetup interface.

//Set the BITSUploadEnabled IIS configuration setting.

//The pszPath parameter contains the path to the directory service.

//For example, "IIS://<machine name>/w3svc/1/<virtual directory>".

//The Enable parameter contains true (enable) or false (disable).

HRESULT SetBITSUploadEnabledSetting(LPWSTR pszPath, bool Enable)

{

HRESULT hr;

IBITSExtensionSetupFactory* pExtensionSetupFactory = NULL;

IBITSExtensionSetup* pExtensionSetup = NULL;


 

hr = CoCreateInstance(__uuidof(BITSExtensionSetupFactory),

NULL, CLSCTX_INPROC_SERVER,

__UUIDOF(IBITSExtensionSetupFactory),

(void**)&pExtensionSetupFactory);


 

if (SUCCEEDED(hr))

{

hr = pExtensionSetupFactory->GetObject(BSTR(pszPath), &pExtensionSetup);

if (SUCCEEDED(hr))

{

if (Enable)

{

hr = pExtensionSetup->EnableBITSUploads();

}

else

{

hr = pExtensionSetup->DisableBITSUploads();

}


 

pExtensionSetup->Release();

}

pExtensionSetupFactory->Release();

}


 

return hr;

}

Requirements

Client

Requires Windows Vista.

Server

Requires Windows Server 2008 or Windows Server 2003.

Redistributable

Requires BITS 1.5 on Windows XP and Windows 2000.

Header

Declared in Bitscfg.h.

IDL

Declared in Bitscfg.idl.

DLL

Requires BitsMgr.dll.

IID

IID_IBITSExtensionSetupFactory is defined as D5D2D542-5503-4E64-8B48-72EF91A32EE1.

GetObject Method of the IBITSExtensionSetupFactory Interface

Use the GetObject method to retrieve a pointer to the IBITSExtensionSetup interface. This method performs the same binding that the ADsGetObject ADSI function performs.

HRESULT GetObject(

[in] BSTR Path,

[out] IBITSExtensionSetup** ppExtensionSetup

);

Parameters

Path

Null terminated string containing the path to the directory service. For example, "IIS://<machine name>/w3svc/1/<virtual directory>".

ppExtensionSetup

Use the IBITSExtensionSetup interface to enable and disable BITS upload for the given virtual directory.

Return Value

This method returns S_OK for success. Otherwise, the method failed.

Example Code

See the example for the IBITSExtensionSetupFactory interface.

Requirements

Client

Requires Windows Vista.

Server

Requires Windows Server 2008 or Windows Server 2003.

Redistributable

Requires BITS 1.5 on Windows XP and Windows 2000.

Header

Declared in Bitscfg.h.

IDL

Declared in Bitscfg.idl.

DLL

Requires BitsMgr.dll.

IID

IID_IBITSExtensionSetupFactory is defined as D5D2D542-5503-4E64-8B48-72EF91A32EE1.

BITS Structures and Unions

The Background Intelligent Transfer Service (BITS) interfaces use the following structures.

Structure

Description

BG_AUTH_CREDENTIALS

Identifies the target (server or proxy), authentication scheme, and user's credentials to use for a user authentication request.

BG_BASIC_CREDENTIALS

Contains the user's credentials.

BG_FILE_INFO

Identifies the local and remote names of the file to transfer.

BG_FILE_PROGRESS

Provides file-related progress information, such as the number of bytes transferred.

BG_FILE_RANGE

Provides the offset and length of a range to download.

BG_JOB_PROGRESS

Provides job-related progress information, such as the number of bytes and files transferred.

BG_JOB_TIMES

Provides job-related time stamps.

The BITS interfaces use the following union.

Union

Description

BG_AUTH_CREDENTIALS_UNION

Contains the credentials required by the chosen authentication scheme.

BITS Upload Protocol

This section describes the network protocol for BITS upload and upload-reply job types. The BITS upload protocol is layered on top of HTTP 1.1 and uses many of the existing HTTP headers and defines new headers. The BITS upload protocol supports a single upload file per session.

BITS uses packets to describe client requests and server responses. The BITS-Packet-Type header specifies the type of packet being sent. Each packet contains specific headers. BITS uses the BITS_POST verb to identify BITS upload packets. Response packets always use the Ack packet type which stands for acknowledge. The Ack packet is sent in the context of the previous request; there can be only one outstanding request at one time.

For upload-reply jobs, BITS uses this protocol to upload the file but does not use this protocol to send the reply to the client. Instead, the BITS server sends the location of the reply file to the client and the client creates a BITS download job to download the reply file.

Use the upload protocol to replace the BITS client or server software with your own implementation. For a list of request packets sent by the BITS client, see BITS Request Packets. For a list of response packets sent by the BITS server, see BITS Response Packets.

The client determines how it responds to errors or unexpected packets from the BITS server. If the server receives a packet that it does not expect, the server should send an Ack packet with a 400 (Bad Request) return code.

BITS Request Packets

Request packets describe client requests. There can be only one outstanding request at any given time; you must receive an Ack for the current request from the server before sending another request.

The following table lists the request packets sent to the BITS server for upload and upload-reply jobs. The table lists the packets in the typical sequence they are sent to the server.

Request packet

Purpose

Ping

Establishes a connection and negotiates security with the server.

Create-Session

Requests an upload session with the BITS server.

Fragment

Sends a fragment of the file to the BITS server. The number of fragment requests sent depends on the fragment size you choose and the size of the upload file.

Close-Session

Ends the file upload session with the BITS server.

Cancel-Session

Ends the file upload session with the BITS server. Typically, you send the Cancel-Session packet if the user canceled the job.

The Ping packet is optional. Instead of sending a Ping packet, you can use the Create-Session packet to establish a connection and negotiate security. However, it is more efficient to use the Ping packet for this purpose.

BITS Response Packets

The following table lists the response packets sent to the BITS client for upload and upload-reply jobs. The table lists the packets in the typical sequence they are sent to the client.

Response packet

Purpose

Ack for Ping

Acknowledges the Ping request.

Ack for Create-Session

Acknowledges the Create-Session request and returns a session identifier that the BITS client uses on all subsequent requests to identify this file transfer session.

Ack for Fragment

Acknowledges the Fragment request and writes the fragment to the upload file on the server.

Ack for Close-Session

Acknowledges the Close-Session request and releases all resources associated with the session.

Ack for Cancel-Session

Acknowledges the Cancel-Session request and releases all resources associated with the session.

Queue Manager

[Queue Manager (QMGR) is available for use in the operating systems listed in a topic's Requirements section. It may be altered or unavailable in subsequent versions. Use the Background Intelligent Transfer Service (BITS) instead.]

The Queue Manager (QMGR) reference section contains information about the following API elements:

Enumeration

Description

GROUPPROP

Defines the constant values for retrieving and setting group property values.

GROUPPROP Enumeration

[Queue Manager (QMGR) is available for use in the operating systems listed in the Requirements section. It may be altered or unavailable in subsequent versions. Use the Background Intelligent Transfer Service (BITS) instead.]

The GROUPPROP enumeration defines the constant values for retrieving and setting group property values.

typedef enum {

GROUP_PRIORITY = 0,

GROUP_REMOTEUSERID = 1,

GROUP_REMOTEUSERPWD = 2,

GROUP_LOCALUSERID = 3,

GROUP_LOCALUSERPWD = 4,

GROUP_PROTOCOLFLAGS = 5,

GROUP_NOTIFYFLAGS = 6,

GROUP_NOTIFYCLSID = 7,

GROUP_PROGRESSSIZE = 8,

GROUP_PROGRESSPERCENT = 9,

GROUP_PROGRESSTIME = 10,

GROUP_DISPLAYNAME = 11,

GROUP_DESCRIPTION = 12

} GROUPPROP;

Constants

GROUP_PRIORITY

Determines when the QMGR processes the group relative to other groups in the queue.

There is only one priority. You must specify a value of 1 when setting this property. The property always returns a value of 1.

Variant data type can be VT_I4, VT_I2, VT_UI4, VT_UI2, VT_INT, or VT_UINT.

GROUP_REMOTEUSERID

Not supported.

GROUP_REMOTEUSERPWD

Not supported.

GROUP_LOCALUSERID

Not supported.

GROUP_LOCALUSERPWD

Not supported.

GROUP_PROTOCOLFLAGS

Specifies the protocol to use for the download.

You must specify QM_PROTOCOL_HTTP when setting this property.

Variant data type can be VT_I4, VT_I2, VT_UI4, VT_UI2, VT_INT, or VT_UINT.

GROUP_NOTIFYFLAGS

Specifies the type of event notification to receive for the group. See Remarks.

Variant data type can be VT_I4, VT_I2, VT_UI4, VT_UI2, VT_INT, or VT_UINT.

GROUP_NOTIFYCLSID

The CLSID to activate when an event specified by GROUP_NOTIFYFLAGS occurs. For more details on CLSID activation, see IBackgroundCopyCallback1.

Variant data type is VT_BSTR.

GROUP_PROGRESSSIZE

Not supported.

GROUP_PROGRESSPERCENT

Not supported.

GROUP_PROGRESSTIME

Not supported.

GROUP_DISPLAYNAME

Specifies a display name that can be used to identify the group in a user interface. The length of the string is limited to 256 characters, not including the null terminator.

Variant data type is VT_BSTR.

GROUP_DESCRIPTION

Specifies a description to associate with the group. The length of the string is limited to 1,024 characters, not including the null terminator.

Variant data type is VT_BSTR.

Remarks

The GROUP_NOTIFYFLAGS group property can contain one or more of the following notification flags.

Flag

Meaning

QM_NOTIFY_FILE_DONE

Not supported.

QM_NOTIFY_JOB_DONE

Not supported.

QM_NOTIFY_GROUP_DONE

Notifies the application through IBackgroundCopyCallback1::OnStatus that the group is complete.

QM_NOTIFY_DISABLE_NOTIFY

Disables all notifications.

QM_NOTIFY_USE_PROGRESSEX

Not supported.

Note  By default, QMGR calls your IBackgroundCopyCallback1::OnStatus method when an error occurs.

Requirements

Client

Requires Windows Vista, Windows XP, or Windows 2000 Professional.

Server

Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server.

Header

Declared in Qmgr.h.

IDL

Declared in Qmgr.idl.

MSDN

MSDN HomeMSDN LibraryMSDN LearnMSDN DownloadsMSDN SupportMSDN Community

MSDN Library

Development Tools and LanguagesMobile and Embedded Development.NET DevelopmentOffice DevelopmentServers and Enterprise DevelopmentWeb DevelopmentWin32 and COM DevelopmentMSDN Library Archive

Win32 and COM Development

Administration and ManagementComponent DevelopmentData Access and StorageDevelopment GuidesDiagnosticsGraphics and MultimediaMessaging and CollaborationMobile PCNetworkingSecuritySystem ServicesToolsUser InterfaceWindows SearchWindows Driver KitWindows Logo KitWindows VersionsXMLTechnical Articles

Networking

Network AuthenticationNetwork CommunicationNetwork Firewall and RoutingNetwork ManagementNetwork ProtocolsWireless Networking

Network Communication

Background Intelligent Transfer Ser...Fax ServiceMessage Queuing (MSMQ)Network List ManagerPeer-to-PeerTelephony Application Programming I...

Background Intelligent Transfer Ser...

What's NewAbout BITSUsing BITSBITS Reference

BITS Reference

BITS EnumerationsBITS InterfacesBITS Return ValuesBITS Samples and ToolsBITS Server Settings for Upload Job...BITS Structures and UnionsBITS Upload ProtocolQueue Manager

Queue Manager

QMGR EnumerationsQMGR InterfacesQMGR Structures

QMGR Interfaces

IBackgroundCopyCallback1IBackgroundCopyGroupIBackgroundCopyJob1IBackgroundCopyQMgrIEnumBackgroundCopyGroupsIEnumBackgroundCopyJobs1

QMGR Interfaces

[Queue Manager (QMGR) interfaces are available for use in the operating systems listed in a topic's Requirements section. They may be altered or unavailable in subsequent versions. Use the BITS interfaces instead.]

Use the following Queue Manager (QMGR) interfaces to download files and monitor jobs within the download queue.

Interface

Description

IBackgroundCopyCallback1

Implement to receive notification when events occur.

IBackgroundCopyGroup

Use to manage the group. For example, add a job to the group, set the properties of the group, and start and stop the group in the download queue.

IBackgroundCopyJob1

Use to add files to the job and retrieve the job's status.

IBackgroundCopyQMgr

Use to create a new group, retrieve an existing group, or enumerate all groups in the queue.

IEnumBackgroundCopyGroups

Use to retrieve a list of groups in the download queue.

IEnumBackgroundCopyJobs1

Use to retrieve a list of jobs in the group.

QMGR Structures

[Queue Manager (QMGR) is available for use in the operating systems listed in a topic's Requirements section. It may be altered or unavailable in subsequent versions. Use the Background Intelligent Transfer Service (BITS) instead.]

The Queue Manager (QMGR) interfaces use the following structures.

Structure

Purpose

FILESETINFO

Identifies the remote and local names of the file to download.

BACKGROUND_COPY_TIMES

Not supported.

FILESETINFO Structure

[Queue Manager (QMGR) is available for use in the operating systems listed in the Requirements section. It may be altered or unavailable in subsequent versions. Use the Background Intelligent Transfer Service (BITS) instead.]

The FILESETINFO structure identifies the remote and local names of the file to download.

typedef struct {
BSTR bstrRemoteFile;
BSTR bstrLocalFile;
DWORD dwSizeHint;

} FILESETINFO;

Members

bstrRemoteFile

Null-terminated string that contains the name of the file on the server (for example, http://<server>/<path>/file.ext). The format of the name must conform to the transfer protocol you use. You cannot use wildcards in the path or file name. The URL must only contain legal URL characters; no escape processing is performed. The URL is limited to 2,200 characters, not including the null terminator.

bstrLocalFile

Null-terminated string that contains the name of the file on the client. The file name must include the full path, for example, d:\myapp\updates\file.ext. You cannot use wildcards in the path or file name, and directories in the path must exist. The path is limited to MAX_PATH, not including the null terminator. The user must have permission to write to the local directory for downloads and uploads that request reply. BITS does not support NTFS streams. Instead of using network drives, which are session specific, use UNC paths (for example, \\server\share\path\file).

dwSizeHint

Not supported.

Requirements

Client

Requires Windows Vista, Windows XP, or Windows 2000 Professional.

Server

Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server.

Header

Declared in Qmgr.h.

IDL

Declared in Qmgr.idl.

Configure BITS Server Extensions

Updated: January 21, 2005


 

To configure BITS Server Extensions

1.

Click Start, click Administrative Tools, and then click Internet Information Services (IIS) Manager.

2.

Click to expand the nodes under the server where BITS Server Extensions is installed, and then click to expand Web Sites.

3.

Right-click the virtual directory for which you want to configure BITS Server Extensions, and then select Properties.

4.

In the Properties dialog box, select the BITS Server Extensions tab.

The following sections explain the settings on the BITS Server Extensions tab.

Allow clients to transfer data to this virtual directory

Enables uploads from BITS clients into the virtual directory. If this check box is not checked, BITS clients attempting an upload are denied access.

Use default settings

Precludes configuring BITS Server Extensions for the virtual directory. The remaining settings cannot be configured unless you select Customize settings.

Note

Configuration settings can be inherited. If the directory is a subdirectory of another virtual directory and the parent virtual directory defines a custom configuration, the configuration of the parent virtual directory is used instead of the default settings.

Customize settings

Allows you to configure this property page according to the settings specified in Custom settings.

Top of page

Custom settings

Permits selection of maximum file size and allows you to specify a time limit after which incomplete jobs can be deleted.

Maximum file size

Defines the maximum size of a file that can be uploaded in a single BITS job. If this setting is not enabled, clients can upload files of any size.

Delete incomplete jobs after

If enabled, permits incomplete upload files to be deleted by the cleanup process if no progress has been made within the specified time period. Deletions are performed only when the cleanup process is scheduled to run, or when you manually run a cleanup. See Schedule Cleanup for information about scheduling the cleanup process. See Run Cleanup Now for information about manually running a cleanup.

Top of page

Enable server farm support

If enabled, instructs the client to try to reconnect to the server of choice instead of the original upload URL used by the client. Server farms can be configured two ways: by using a shared volume for the upload virtual directory, or by using server local storage for the uploaded files. If you want to use local storage, this option enables the client computer to reconnect to the same server computer in the server farm. Uploading to server farms and using local storage are not recommended without enabling and configuring Enable server farm support.

Reconnect to IP address

Specifies the public IP address to use for reconnecting to this server. A server usually has two IP addresses. One points outward and is reachable by client systems. The other belongs to the inner (protected) network. You should specify the outward-pointing IP address here.

Notes

You can specify a DNS name here only if each computer in your Web farm has an independent DNS name that can be resolved by client computers.

Enable server farm support must be checked in order to configure this setting.

Use original IP address after

Specifies the amount of time during which a client computer must reconnect to the server specified in Reconnect to IP address. If the client computer does not connect to the server during this time, the client computer must attempt to connect to the original DNS name specified in the upload URL.

Top of page

Allow notifications

Enables notifications for this virtual directory. Both Notification type and Notification URL settings are required if this setting is enabled. For additional information about the notification settings on the BITS Server Extensions tab on the Properties page for the virtual directory, see Using BITS notifications in Related Topics.

Notification type

You can send either the file name or the data. If Send the file name is selected, the server passes the path for the completed upload file to the URL specified by the Notification URL setting. The server returns a file to the client computer as a response. If Send the data is selected, the server passes the entire upload file to the URL specified by the Notification URL as a POST. The response is sent to the client computer.

Notification URL

Specifies the URL to pass the completed upload file to via a POST request if the Notification type is either Send the file contents or Send the file name. The URL can be absolute or self-relative. If the URL is self-relative, the original request URL is used as the base.

Top of page

Schedule Cleanup

Configures the frequency with which BITS Server Extensions scans the virtual directory for incomplete upload files. If an incomplete file is found, it is checked against the time-out value set in Delete incomplete jobs after. If the time-out period has elapsed since progress was made on this file, the upload is cancelled and any partial file contents are deleted. This setting is not affected by IIS property inheritance and applies only to the virtual directory.

Top of page

Run Cleanup Now

Immediately starts a cleanup by scanning the virtual directory for incomplete upload files. If an incomplete file is found, it is checked against the time-out value set in Delete incomplete jobs after. If the time-out period has elapsed since progress was made on this file, the upload is cancelled and any partial file contents are deleted. To remove all incomplete files from this virtual directory, set the time-out value to 0 before running the cleanup.

Notes

To install BITS Server Extensions, you must be a member of the Administrators group on the local computer, or you must have been delegated the appropriate credentials. If the computer is joined to a domain, members of the Domain Admins group might be able to perform this procedure. As a security best practice, consider using the runas command to perform this procedure. For Windows 2000 Server family products, see the online Help documentation or go to Windows 2000 Product Documentation and select Help for the appropriate product.

After you configure settings on the BITS Server Extensions tab and click Apply or OK, a security message appears, indicating that BITS will shut down all Run script and Execute permissions for this virtual directory. When you click OK, the Run Cleanup Now button becomes enabled. For more information about this security message, see Setting permissions on virtual directories in Related Topics.

BITS Server Extensions must be in the Allowed state in order to function. To determine the state, expand Web Service Extension in the IIS console tree. Locate the extension state in the right panel. Click Allowed if the extension is in the Prohibited state.

For information about virtual directories, see Help for Internet Information Services.


 

1 comment:

Unknown said...

1.How do i create a BITS job for posting a file on to server asp page?

2.What happens when the user machine get disconnected during BITS upload? Does the post to asp will be still valid?