Background​Uploader Background​Uploader Background​Uploader Class

Definition

Used to configure upload prior to the actual creation of the upload operation using CreateUpload. For an overview of Background Transfer capabilities, see Transferring data in the background. Download the Background Transfer sample for examples in JavaScript, C#, and C++.

Note

Background Transfer is primarily designed for long-term transfer operations for resources like video, music, and large images. For short-term operations involving transfers of smaller resources (i.e. a couple KB), use the Windows.Web.Http namespace.

public sealed class BackgroundUploader : IBackgroundTransferBase, IBackgroundUploader, IBackgroundUploader2, IBackgroundUploader3public sealed class BackgroundUploader : IBackgroundTransferBase, IBackgroundUploader, IBackgroundUploader2, IBackgroundUploader3Public NotInheritable Class BackgroundUploader Implements IBackgroundTransferBase, IBackgroundUploader, IBackgroundUploader2, IBackgroundUploader3
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
internetClientServer privateNetworkClientServer internetClient

Remarks

After app termination, an app should enumerate all existing UploadOperation instances at next start-up using GetCurrentUploadsAsync. When a Windows Store app using Background Transfer is terminated, incomplete uploads will persist in the background. If the app is restarted after termination and operations from the previous session are not enumerated and re-attached to the current session, they will remain incomplete and continue to occupy resources. Once enumerated, PUT upload operations are automatically restarted, and POST upload operations are terminated.

Note

When an app is uninstalled any current or persisted Background Transfer operations associated with it are cleaned up.

When implementing a library for Background Transfer operations, and this same library is used by other apps or components, specify a uniquegroup name string (e.g. a GUID) when creating uploads. An upload with a group name string can only be enumerated by providing the matching string to GetCurrentDownloadsAsync(String), and will not appear in GetCurrentDownloadsAsync calls without. This will ensure that other apps implementing that same library for uploads will not see your uploads

Upload operations via FTP are not supported.

Security concerns can exist when upload operations require a username and password for authentication. If the authentication model to be used is supported by WinINet, use the ServerCredential or ProxyCredential properties. These values will be securely saved in WinVault. For information on supported authentication methods, see Handling Authentication.

If the authentication model is not supported by WinINet, use HttpClient to implement custom authentication and obtain an upload-specific secure token (cookie). Set the appropriate header to have the secure token value used for background transfer. The service should limit the validity of the secure token only to the file that is being uploaded.

Note

The secure token will be stored in clear text within the application’s folder.

Upload services that require the username and password be set in clear text in a custom header for each upload file are insecure. Background transfer will cache the headers in clear text for the duration of the operation within the app’s folder.

Toast notifications

The BackgroundUploader class in Windows 8.1 and Windows Server 2012 R2 supports options for the user to receive tile and toast notifications when a transfer is completed successfully or fails to complete.

An app that uses Windows.Networking.BackgroundTransfer to communicate through a toast notification must declare that it is Toast capable in the app manifest file. The Toast capable setting is located under the Notifications section of Application tab. Set the Toast capable option to "Yes" so the app can receive toast notifications.

If Toast capable is not enabled in the app manifest, then any toast settings in the Windows.Networking.BackgroundTransfer namespace will be silently ignored and no toasts notifications will be received by the app.

Note

A user can manually disable or enable toast notifications for your app at any time.

For more information on toast notifications, see Sending toast notifications and How to opt in for toast notifications.

Handling Exceptions

A number of errors can cause exceptions to occur during an upload operation. You should write code to handle exceptions when you call methods on this class. Exceptions can result from parameter validation errors, name resolution failures, and network errors. Exceptions from network errors (loss of connectivity, connection failures, and other HTTP errors, for example) can happen at any time. These errors result in exceptions being thrown. If not handled by your app, an exception can cause your entire app to be terminated by the runtime.

An app can use the HRESULT from the exception to determine the error that caused the exception. An app can then decide how to handle the exception based on the error code. The BackgroundTransferError.GetStatus method can convert most HRESULT values returned to a WebErrorStatus enumeration value. Most of the WebErrorStatus enumeration values correspond to an error returned by the native HTTP or FTP client operation. An app can filter on specific WebErrorStatus enumeration values to modify app behavior depending on the cause of the exception.

Some HRESULT values cannot be converted to a WebErrorStatus enumeration value. When a background POST operation is canceled, an exception is thrown. The operation is not restarted. For more information, see UploadOperation.StartAsync

For information on network exceptions, see Handling exceptions in network apps.

Debugging Guidance

Stopping a debugging session in Microsoft Visual Studio is comparable to closing your app; PUT uploads are paused and POST uploads are terminated. Even while debugging, your app should enumerate and then restart or cancel any persisted uploads. For example, you can have your app cancel enumerated persisted upload operations at app startup if there is no interest in previous operations for that debug session.

While enumerating downloads/uploads on app startup during a debug session, you can have your app cancel them if there is no interest in previous operations for that debug session. Note that if there are Microsoft Visual Studio project updates, like changes to the app manifest, and the app is uninstalled and re-deployed, GetCurrentUploadsAsync cannot enumerate operations created using the previous app deployment.

See Debugging and testing Windows Store apps for more information.

When using Background Transfer during development, you may get into a situation where the internal caches of active and completed transfer operations can get out of sync. This may result in the inability to start new transfer operations or interact with existing operations and BackgroundTransferGroup objects. In some cases, attempting to interact with existing operations may trigger a crash. This result can occur if the TransferBehavior property is set to Parallel. This issue occurs only in certain scenarios during development and is not applicable to end users of your app.

Four scenarios using Microsoft Visual Studio can cause this issue.

  • You create a new project with the same app name as an existing project, but a different language (from C++ to C#, for example).
  • You change the target architecture (from x86 to x64, for example) in an existing project.
  • You change the culture (from neutral to en-US, for example) in an existing project.
  • You add or remove a capability in the package manifest (adding Enterprise Authentication, for example) in an existing project. Regular app servicing, including manifest updates which add or remove capabilities, do not trigger this issue on end user deployments of your app.

To work around this issue, completely uninstall all versions of the app and re-deploy with the new language, architecture, culture, or capability. This can be done via the Start screen or using PowerShell and the Remove-AppxPackage cmdlet.

Examples

The following example demonstrates how to configure and begin a basic upload operation, and is based on the Background Transfer sample offered in the Windows Sample Gallery.

        var upload = null;
        var promise = null;

        function UploadFile (uriString, file) {
            try {

                var uri = Windows.Foundation.Uri(uriString);
                var uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader();

                // Set a header, so the server can save the file (this is specific to the sample server).
                uploader.setRequestHeader("Filename", file.name);

                // Create a new upload operation.
                upload = uploader.createUpload(uri, file);

                // Start the upload and persist the promise to be able to cancel the upload.
                promise = upload.startAsync().then(complete, error, progress);
            } catch (err) {
                displayError(err);
            }
        };

        using Windows.Foundation; 
        using Windows.Networking.BackgroundTransfer;
        using Windows.Storage.Pickers;
        using Windows.Storage;

        private async void StartUpload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Uri uri = new Uri(serverAddressField.Text.Trim());
                FileOpenPicker picker = new FileOpenPicker();
                picker.FileTypeFilter.Add("*");
                StorageFile file = await picker.PickSingleFileAsync();

                BackgroundUploader uploader = new BackgroundUploader();
                uploader.SetRequestHeader("Filename", file.Name);

                UploadOperation upload = uploader.CreateUpload(uri, file);

                // Attach progress and completion handlers.
                HandleUploadAsync(upload, true);
            }
            catch (Exception ex)
            {
                LogException("Upload Error", ex);
            }
        }

Constructors

BackgroundUploader() BackgroundUploader() BackgroundUploader()

Instantiates a new BackgroundUploader object.

public BackgroundUploader()public BackgroundUploader()Public Sub New()
Attributes

BackgroundUploader(BackgroundTransferCompletionGroup) BackgroundUploader(BackgroundTransferCompletionGroup) BackgroundUploader(BackgroundTransferCompletionGroup)

Instantiates a new BackgroundUploader object as a member of a completion group.

public BackgroundUploader(BackgroundTransferCompletionGroup completionGroup)public BackgroundUploader(BackgroundTransferCompletionGroup completionGroup)Public Sub New(completionGroup As BackgroundTransferCompletionGroup)
Parameters
completionGroup
BackgroundTransferCompletionGroup BackgroundTransferCompletionGroup BackgroundTransferCompletionGroup

The completion group that the created BackgroundUploader instance is to be a member of.

Attributes

Properties

CompletionGroup CompletionGroup CompletionGroup

Gets the BackgroundTransferCompletionGroup associated with the BackgroundUploader.

public BackgroundTransferCompletionGroup CompletionGroup { get; }public BackgroundTransferCompletionGroup CompletionGroup { get; }Public ReadOnly Property CompletionGroup As BackgroundTransferCompletionGroup
Attributes

CostPolicy CostPolicy CostPolicy

Gets or sets the cost policy for the background upload operation.

public BackgroundTransferCostPolicy CostPolicy { get; set; }public BackgroundTransferCostPolicy CostPolicy { get; set; }Public ReadWrite Property CostPolicy As BackgroundTransferCostPolicy
Value
BackgroundTransferCostPolicy BackgroundTransferCostPolicy BackgroundTransferCostPolicy

Indicates whether transfers can occur on costed networks.

Attributes

FailureTileNotification FailureTileNotification FailureTileNotification

Gets and sets the TileNotification used to define the visuals, identification tag, and expiration time of a tile notification used to update the app tile when indicating failure of an upload to the user.

public TileNotification FailureTileNotification { get; set; }public TileNotification FailureTileNotification { get; set; }Public ReadWrite Property FailureTileNotification As TileNotification
Value
TileNotification TileNotification TileNotification

The TileNotification used to indicate upload failure.

Attributes

FailureToastNotification FailureToastNotification FailureToastNotification

Gets or sets the ToastNotification that defines the content, associated metadata, and events used in a toast notification to indicate failure of an upload to the user.

public ToastNotification FailureToastNotification { get; set; }public ToastNotification FailureToastNotification { get; set; }Public ReadWrite Property FailureToastNotification As ToastNotification
Value
ToastNotification ToastNotification ToastNotification

The ToastNotification used to indicate upload failure.

Attributes

Remarks

An app that uses Windows.Networking.BackgroundTransfer to communicate through a toast notification must declare that it is Toast capable in the app manifest file. The Toast capable setting is located under the Notifications section of Application tab. Set the Toast capable option to "Yes" so the app can receive toast notifications.

If Toast capable is not enabled in the app manifest, then any toast settings in the Windows.Networking.BackgroundTransfer namespace will be silently ignored and no toasts notifications will be received by the app.

Note

A user can manually disable or enable toast notifications for your app at any time.

For more information on toast notifications, see Sending toast notifications and How to opt in for toast notifications.

See Also

Group Group Group

Note

Group may be altered or unavailable for releases after Windows 8.1. Instead, use TransferGroup.

Gets or sets a string value (e.g. a GUID) indicating the group the upload will belong to. An upload operation with a group ID will only appear in operation enumerations using GetCurrentDownloadsAsync(String) with the specific group string value.

public PlatForm::String Group { get; set; }public string Group { get; set; }Public ReadWrite Property Group As string
Value
string string string

The group name.

Attributes

Method Method Method

Gets or sets the HTTP method used for the upload. The default method used for upload operations is POST.

public PlatForm::String Method { get; set; }public string Method { get; set; }Public ReadWrite Property Method As string
Value
string string string

The method to use for the background upload. Setting this property will override the default method used for the operation.

Attributes

ProxyCredential ProxyCredential ProxyCredential

Gets or sets the proxy credentials for the upload.

public PasswordCredential ProxyCredential { get; set; }public PasswordCredential ProxyCredential { get; set; }Public ReadWrite Property ProxyCredential As PasswordCredential
Value
PasswordCredential PasswordCredential PasswordCredential

The credentials used to authenticate with an HTTP proxy.

Attributes

ServerCredential ServerCredential ServerCredential

Gets or sets the credentials to use to authenticate with the origin server.

public PasswordCredential ServerCredential { get; set; }public PasswordCredential ServerCredential { get; set; }Public ReadWrite Property ServerCredential As PasswordCredential
Value
PasswordCredential PasswordCredential PasswordCredential

The credential to use for authentication.

Attributes

SuccessTileNotification SuccessTileNotification SuccessTileNotification

Gets and sets the TileNotification used to define the visuals, identification tag, and expiration time of a tile notification used to update the app tile when indicating success of an upload to the user.

public TileNotification SuccessTileNotification { get; set; }public TileNotification SuccessTileNotification { get; set; }Public ReadWrite Property SuccessTileNotification As TileNotification
Value
TileNotification TileNotification TileNotification

The TileNotification used to indicate upload success.

Attributes

SuccessToastNotification SuccessToastNotification SuccessToastNotification

Gets or sets the ToastNotification that defines the content, associated metadata, and events used in a toast notification to indicate success of an upload to the user.

public ToastNotification SuccessToastNotification { get; set; }public ToastNotification SuccessToastNotification { get; set; }Public ReadWrite Property SuccessToastNotification As ToastNotification
Value
ToastNotification ToastNotification ToastNotification

The ToastNotification used to indicate upload success.

Attributes

Remarks

An app that uses Windows.Networking.BackgroundTransfer to communicate through a toast notification must declare that it is Toast capable in the app manifest file. The Toast capable setting is located under the Notifications section of Application tab. Set the Toast capable option to "Yes" so the app can receive toast notifications.

If Toast capable is not enabled in the app manifest, then any toast settings in the Windows.Networking.BackgroundTransfer namespace will be silently ignored and no toasts notifications will be received by the app.

Note

A user can manually disable or enable toast notifications for your app at any time.

For more information on toast notifications, see Sending toast notifications and How to opt in for toast notifications.

See Also

TransferGroup TransferGroup TransferGroup

Gets or sets the group that an upload operation will belong to.

public BackgroundTransferGroup TransferGroup { get; set; }public BackgroundTransferGroup TransferGroup { get; set; }Public ReadWrite Property TransferGroup As BackgroundTransferGroup
Value
BackgroundTransferGroup BackgroundTransferGroup BackgroundTransferGroup

The group to associate with the upload.

Attributes

Methods

CreateUpload(Uri, IStorageFile) CreateUpload(Uri, IStorageFile) CreateUpload(Uri, IStorageFile)

Initializes an UploadOperation that indicates the location for and file for upload.

public UploadOperation CreateUpload(Uri uri, IStorageFile sourceFile)public UploadOperation CreateUpload(Uri uri, IStorageFile sourceFile)Public Function CreateUpload(uri As Uri, sourceFile As IStorageFile) As UploadOperation
Parameters
uri
Uri Uri Uri

The location for the upload.

sourceFile
IStorageFile IStorageFile IStorageFile

The file for upload.

Returns

The resultant upload operation.

Attributes

Remarks

Important

Creating a large number of transfers on the main UI thread with CreateUpload can result in degraded performance of your app's UI. If you are queuing up a large number of transfers, it is recommended that you call CreateUpload on a background worker thread as in the following example.

operation = await Task.Run(() => { return myDownloader.CreateUpload(uri, file); });

CreateUploadAsync(Uri, IIterable<BackgroundTransferContentPart>) CreateUploadAsync(Uri, IIterable<BackgroundTransferContentPart>) CreateUploadAsync(Uri, IIterable<BackgroundTransferContentPart>)

Returns an asynchronous operation that, on completion, returns an UploadOperation with the specified URI and one or more BackgroundTransferContentPart objects.

public IAsyncOperation<UploadOperation> CreateUploadAsync(Uri uri, IIterable<BackgroundTransferContentPart> parts)public IAsyncOperation<UploadOperation> CreateUploadAsync(Uri uri, IIterable<BackgroundTransferContentPart> parts)Public Function CreateUploadAsync(uri As Uri, parts As IIterable<BackgroundTransferContentPart>) As IAsyncOperation( Of UploadOperation )
Parameters
uri
Uri Uri Uri

The location for the upload.

parts

One or more BackgroundTransferContentPart objects.

Returns

The resultant asynchronous UploadOperation

Attributes

CreateUploadAsync(Uri, IIterable<BackgroundTransferContentPart>, String) CreateUploadAsync(Uri, IIterable<BackgroundTransferContentPart>, String) CreateUploadAsync(Uri, IIterable<BackgroundTransferContentPart>, String)

Returns an asynchronous operation that, on completion, returns an UploadOperation with the specified URI, one or more BackgroundTransferContentPart objects, and the multipart subtype.

public IAsyncOperation<UploadOperation> CreateUploadAsync(Uri uri, IIterable<BackgroundTransferContentPart> parts, String subType)public IAsyncOperation<UploadOperation> CreateUploadAsync(Uri uri, IIterable<BackgroundTransferContentPart> parts, String subType)Public Function CreateUploadAsync(uri As Uri, parts As IIterable<BackgroundTransferContentPart>, subType As String) As IAsyncOperation( Of UploadOperation )
Parameters
uri
Uri Uri Uri

The location for the upload.

parts

One or more BackgroundTransferContentPart objects.

subType
System.String System.String System.String

The multipart subtype. For example, "related" for content of type "multipart/related ".

Returns

The resultant asynchronous UploadOperation.

Attributes

CreateUploadAsync(Uri, IIterable<BackgroundTransferContentPart>, String, String) CreateUploadAsync(Uri, IIterable<BackgroundTransferContentPart>, String, String) CreateUploadAsync(Uri, IIterable<BackgroundTransferContentPart>, String, String)

Returns an asynchronous operation that, on completion, returns an UploadOperation with the specified URI, multipart subtype, one or more BackgroundTransferContentPart objects, and the delimiter boundary value used to separate each part.

public IAsyncOperation<UploadOperation> CreateUploadAsync(Uri uri, IIterable<BackgroundTransferContentPart> parts, String subType, String boundary)public IAsyncOperation<UploadOperation> CreateUploadAsync(Uri uri, IIterable<BackgroundTransferContentPart> parts, String subType, String boundary)Public Function CreateUploadAsync(uri As Uri, parts As IIterable<BackgroundTransferContentPart>, subType As String, boundary As String) As IAsyncOperation( Of UploadOperation )
Parameters
uri
Uri Uri Uri

The location for the upload.

parts

One or more BackgroundTransferContentPart objects.

subType
System.String System.String System.String

The multipart subtype. For example, "related" for content of type "multipart/related ".

boundary
System.String System.String System.String

A string that is used to identify the delimiter used to indicate separation between provided content parts.

Returns

The resultant asynchronous UploadOperation

Attributes

CreateUploadFromStreamAsync(Uri, IInputStream) CreateUploadFromStreamAsync(Uri, IInputStream) CreateUploadFromStreamAsync(Uri, IInputStream)

Returns an asynchronous operation that, on completion, returns an UploadOperation with the specified URI and the source stream.

public IAsyncOperation<UploadOperation> CreateUploadFromStreamAsync(Uri uri, IInputStream sourceStream)public IAsyncOperation<UploadOperation> CreateUploadFromStreamAsync(Uri uri, IInputStream sourceStream)Public Function CreateUploadFromStreamAsync(uri As Uri, sourceStream As IInputStream) As IAsyncOperation( Of UploadOperation )
Parameters
uri
Uri Uri Uri

The URI associated with the resource.

sourceStream
IInputStream IInputStream IInputStream

Represents the source stream.

Returns

The resultant asynchronous upload operation.

Attributes

GetCurrentUploadsAsync() GetCurrentUploadsAsync() GetCurrentUploadsAsync()

Returns a collection of pending uploads that are not associated with a group.

public static IAsyncOperation<IVectorView<UploadOperation>> GetCurrentUploadsAsync()public static IAsyncOperation<IVectorView<UploadOperation>> GetCurrentUploadsAsync()Public Static Function GetCurrentUploadsAsync() As IAsyncOperation( Of IVectorViewUploadOperation )
Returns

A collection of pending uploads for the current application instance.

Attributes

GetCurrentUploadsAsync(String) GetCurrentUploadsAsync(String) GetCurrentUploadsAsync(String)

Note

GetCurrentUploadsAsync(group) may be altered or unavailable for releases after Windows 8.1. Instead, use GetCurrentUploadsForTransferGroupAsync.

Returns a collection of pending uploads for a specific Group.

public static IAsyncOperation<IVectorView<UploadOperation>> GetCurrentUploadsAsync(String group)public static IAsyncOperation<IVectorView<UploadOperation>> GetCurrentUploadsAsync(String group)Public Static Function GetCurrentUploadsAsync(group As String) As IAsyncOperation( Of IVectorViewUploadOperation )
Parameters
group
System.String System.String System.String

A string indicating a specific group of uploads.

Returns

A collection of pending uploads for the specific group.

Attributes

GetCurrentUploadsForTransferGroupAsync(BackgroundTransferGroup) GetCurrentUploadsForTransferGroupAsync(BackgroundTransferGroup) GetCurrentUploadsForTransferGroupAsync(BackgroundTransferGroup)

Gets all uploads associated with the provided BackgroundTransferGroup.

public static IAsyncOperation<IVectorView<UploadOperation>> GetCurrentUploadsForTransferGroupAsync(BackgroundTransferGroup group)public static IAsyncOperation<IVectorView<UploadOperation>> GetCurrentUploadsForTransferGroupAsync(BackgroundTransferGroup group)Public Static Function GetCurrentUploadsForTransferGroupAsync(group As BackgroundTransferGroup) As IAsyncOperation( Of IVectorViewUploadOperation )
Parameters
group
BackgroundTransferGroup BackgroundTransferGroup BackgroundTransferGroup

Contains information used to identify a group of uploads.

Returns

A list of uploads currently associated with the specified group.

Attributes

RequestUnconstrainedUploadsAsync(IIterable<UploadOperation>) RequestUnconstrainedUploadsAsync(IIterable<UploadOperation>) RequestUnconstrainedUploadsAsync(IIterable<UploadOperation>)

Used to request an unconstrained upload operation. When this method is called the user is provided with a UI prompt that they can use to indicate their consent for an unconstrained operation.An unconstrained transfer operation will run without the resource restrictions normally associated with background network operations while a device is running on battery.

public static IAsyncOperation<UnconstrainedTransferRequestResult> RequestUnconstrainedUploadsAsync(IIterable<UploadOperation> operations)public static IAsyncOperation<UnconstrainedTransferRequestResult> RequestUnconstrainedUploadsAsync(IIterable<UploadOperation> operations)Public Static Function RequestUnconstrainedUploadsAsync(operations As IIterable<UploadOperation>) As IAsyncOperation( Of UnconstrainedTransferRequestResult )
Parameters
operations

The upload operation to run unconstrained.

Returns

Indicates if the operations will run unconstrained.

Attributes

SetRequestHeader(String, String) SetRequestHeader(String, String) SetRequestHeader(String, String)

Used to set an HTTP request header.

public void SetRequestHeader(String headerName, String headerValue)public void SetRequestHeader(String headerName, String headerValue)Public Function SetRequestHeader(headerName As String, headerValue As String) As void
Parameters
headerName
System.String System.String System.String

The header name.

headerValue
System.String System.String System.String

The header value.

Attributes

See Also