Exemplo n.º 1
0
        /// <summary>
        /// This method creates a BackgroundTransferRequest object based on the information
        /// of the ITransferable object passed as a parameter. The BackgroundTransferRequest
        /// is then addedd to the BackgroundTransferService queue.
        /// </summary>
        /// <param name="Item">The ITransferable item.</param>
        /// <returns>True, if the BackgroundTransferRequest has been created and added successfully to the BackgroundTransferService.</returns>
        private bool AddTransferRequest(ITransferable Item)
        {
            //TODO: Improve validation of Item.TransferUri and Item.TransferLocationUri -> If URI is not valid then the object will not be removable

            // First, validate the TransferURI
            Uri TransferUri;
            if (!Uri.TryCreate(Item.TransferUrl, UriKind.Absolute, out TransferUri) || String.IsNullOrEmpty(Item.TransferUrl) || String.IsNullOrWhiteSpace(Item.TransferUrl))
            {
            #if DEBUG
                // In debug mode show MessageBox with exception details.
                MessageBox.Show("I'm unable to add the background transfer request due to a malformed remote URI (" + Item.TransferUrl + ").", "Unable to start transfer", MessageBoxButton.OK);
            #endif
                return false;
            }

            // Second, validate the TransferLocation
            Uri TransferLocation;
            if (!Uri.TryCreate(Item.FilenameWithPath, UriKind.Relative, out TransferLocation) || String.IsNullOrEmpty(Item.FilenameWithPath) || String.IsNullOrWhiteSpace(Item.FilenameWithPath))
            {
            #if DEBUG
                // In debug mode show MessageBox with exception details.
                MessageBox.Show("I'm unable to add the background transfer request due to a malformed local URI (" + Item.TransferLocationUri + ").", "Unable to start transfer", MessageBoxButton.OK);
            #endif
                return false;
            }

            // A new BackgroundTransferRequest is created by passing the TransferUri of the ITransferable object.
            BackgroundTransferRequest TransferRequest = new BackgroundTransferRequest(Item.TransferUri);

            // Set the transfer properties according to the TransferSettings of the ITransferable object
            #region Set transfer properties
            try
            {
                TransferRequest.Method = Item.Method; // GET or POST
                if (TransferRequest.Method == "GET")
                { // The temporary transfer location for download
                    TransferRequest.DownloadLocation = Item.TransferLocationUri;
                }
                else
                {// The temporary transfer location for upload
                    TransferRequest.UploadLocation = Item.TransferLocationUri;
                }
            }
            catch (ArgumentException)
            {
            #if DEBUG
                // In debug mode show MessageBox with exception details.
                MessageBox.Show("I'm unable to add the background transfer request due to a malformed local URI (" + Item.TransferLocationUri + ").", "Unable to start transfer", MessageBoxButton.OK);
            #endif
                return false;
            }

            TransferRequest.Tag = Item.UID.ToString(); // The TransferId
            //TransferRequest.Headers.Add(Item.Headers); // Additional headers
            TransferRequest.TransferPreferences = TransferSettings.I.TransferPreferences; // Transfer preferences such as None, AllowCellular, AllowBattery, AllowCellularAndBattery.
            #endregion

            // We register the event handlers for the progress change
            TransferRequest.TransferProgressChanged += Item.TransferProgressChanged;

            // The BackgroundTransferRequest is ready to be addedd to the BackgroundTransferService queue.
            // Before adding, we call the ITransferable BeforeAdding() method to perform additional
            // operations (e.g. placing the file in the right folder).
            Item.OnBeforeAdd();

            // Now the BackgroundTrabsferRequest is ready to be added to the BackgroundTransferService queue
            // A try/catch block is necessary to handle the possible exceptions
            TransferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(TransferRequest_TransferStatusChanged); // Transfer manager handler for status change

            try
            {
                BackgroundTransferService.Add(TransferRequest);

                // If add was successful we can retrieve the RequestId value and store it in the ITransferable object
                // The RequestId is generated right after the instantiation of the BackgroundTransferRequest, but to
                // avoid overwriting a previous value on the ITransferable object, we store it only after "Add" is
                // successful (which means that the same object is not currently transferring).
                Item.RequestId = TransferRequest.RequestId;

                lock (this)
                {
                    // We increment the internal counter
                    _ActiveBackgroundTransfers++;
                }

                var BackgroundTransfers = BackgroundTransferService.Requests;

                // The BackgroundTransferRequest was successfully added to the BackgroundTransferService queue.
                return true;
            }
            catch (BackgroundTransferInternalException ex)
            {   //BackgroundTransferInternalException is thrown when:
                // - The total request limit across all applications has been reached.
                // - The HTTP network provider returned an error.
                // - The HTTP network provider returned an error related to content-range request or response.
                // - The HTTP network provider returned a network-related error.
                // - The HTTP network provider returned a slow transfer error.
                // - The isolated storage provider returned an error.

            #if DEBUG
                // In debug mode show MessageBox with exception details.
                MessageBox.Show("I'm unable to add the background transfer request (BackgroundTransferInternalException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK);
            #endif
            }
            catch (InvalidOperationException ex)
            {   // InvalidOperationException is thrown when:
                // - The request has already been submitted.
                // - The maximum number of requests per application has been reached.
                // - A request with the same DownloadLocation URI has already been submitted.
                // - The user has disabled background tasks in the device’s Settings.

            #if DEBUG
                // In debug mode show MessageBox with exception details.
                MessageBox.Show("I'm unable to add the background transfer request (InvalidOperationException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK);
            #endif
            }
            catch (SystemException ex)
            {   //SystemException is thrown when:
                // - The maximum number of requests on the device has been reached.
                // - The underlying transport layer returned an error.
                // - The underlying transport layer returned an error related to the content-range request or response.
                // - There is not enough space on the disk.

                if (ex.Message == "There is not enough space on the disk.")
                {
                    MessageBox.Show("There is not enough space on the device to start the transfer. Please free up some space and then retry.", "Unable to start transfer", MessageBoxButton.OK);
                }

            #if DEBUG
                // In debug mode show MessageBox with exception details.
                MessageBox.Show("I'm unable to add the background transfer request (SystemException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK);
            #endif

            }
            catch (Exception ex)
            {
            #if DEBUG
                // In debug mode show MessageBox with exception details.
                MessageBox.Show("I'm unable to add the background transfer request (Exception). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK);
            #endif
            }

            return false;
        }
        /// <summary>
        /// This method creates a BackgroundTransferRequest object based on the information
        /// of the ITransferable object passed as a parameter. The BackgroundTransferRequest
        /// is then addedd to the BackgroundTransferService queue.
        /// </summary>
        /// <param name="Item">The ITransferable item.</param>
        /// <returns>True, if the BackgroundTransferRequest has been created and added successfully to the BackgroundTransferService.</returns>
        private bool AddTransferRequest(ITransferable Item)
        {
            // A new BackgroundTransferRequest is created by passing the TransferUri of the ITransferable object.
            BackgroundTransferRequest TransferRequest = new BackgroundTransferRequest(Item.TransferUri);

            // Set the transfer properties according to the TransferSettings of the ITransferable object
            #region Set transfer properties
            TransferRequest.Method = Item.Method; // GET or POST
            if (TransferRequest.Method == "GET")
            { // The temporary transfer location for download
                TransferRequest.DownloadLocation = Item.TransferLocationUri;
            }
            else
            {// The temporary transfer location for upload
                TransferRequest.UploadLocation = Item.TransferLocationUri;
            }
            TransferRequest.Tag = Item.UID.ToString(); // The TransferId
            //TransferRequest.Headers.Add(Item.Headers); // Additional headers
            TransferRequest.TransferPreferences = TransferSettings.I.TransferPreferences; // Transfer preferences such as None, AllowCellular, AllowBattery, AllowCellularAndBattery.
            #endregion

            // We register the event handlers for the progress change
            TransferRequest.TransferProgressChanged += Item.TransferProgressChanged;

            // The BackgroundTransferRequest is ready to be addedd to the BackgroundTransferService queue.
            // Before adding, we call the ITransferable BeforeAdding() method to perform additional
            // operations (e.g. placing the file in the right folder).
            Item.OnBeforeAdd();

            // Now the BackgroundTrabsferRequest is ready to be added to the BackgroundTransferService queue
            // A try/catch block is necessary to handle the possible exceptions
            TransferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(TransferRequest_TransferStatusChanged); // Transfer manager handler for status change

            try
            {
                BackgroundTransferService.Add(TransferRequest);

                // If add was successful we can retrieve the RequestId value and store it in the ITransferable object
                // The RequestId is generated right after the instantiation of the BackgroundTransferRequest, but to
                // avoid overwriting a previous value on the ITransferable object, we store it only after "Add" is
                // successful (which means that the same object is not currently transferring).
                Item.RequestId = TransferRequest.RequestId;

                // The BackgroundTransferRequest was successfully added to the BackgroundTransferService queue.
                return true;
            }
            catch (BackgroundTransferInternalException ex)
            {   //BackgroundTransferInternalException is thrown when:
                // - The total request limit across all applications has been reached.
                // - The HTTP network provider returned an error.
                // - The HTTP network provider returned an error related to content-range request or response.
                // - The HTTP network provider returned a network-related error.
                // - The HTTP network provider returned a slow transfer error.
                // - The isolated storage provider returned an error.

                // In debug mode show MessageBox with exception details.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    MessageBox.Show("I'm unable to add the background transfer request (BackgroundTransferInternalException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK);
                }
            }
            catch (InvalidOperationException ex)
            {   // InvalidOperationException is thrown when:
                // - The request has already been submitted.
                // - The maximum number of requests per application has been reached.
                // - A request with the same DownloadLocation URI has already been submitted.
                // - The user has disabled background tasks in the device’s Settings.

                // In debug mode show MessageBox with exception details.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    MessageBox.Show("I'm unable to add the background transfer request (InvalidOperationException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK);
                }
            }
            catch (SystemException ex)
            {   //SystemException is thrown when:
                // - The maximum number of requests on the device has been reached.
                // - The underlying transport layer returned an error.
                // - The underlying transport layer returned an error related to the content-range request or response.

                // In debug mode show MessageBox with exception details.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    MessageBox.Show("I'm unable to add the background transfer request (SystemException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                // In debug mode show MessageBox with exception details.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    MessageBox.Show("I'm unable to add the background transfer request (Exception). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK);
                }
            }

            return false;
        }