Exemple #1
0
        /// <summary>
        /// Can chu y sua
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ApplicationBarIconButton_DownloadClick(object sender, EventArgs e)
        {
            foreach (var track in App.AlbumVM.TrackList)
            {
                if (track.IsSelected)
                {
                    string   link;
                    string[] links = await NhacCuaTui.GetSongDownloadLinkAsync(track.Song.Info);

                    if (links[1] != null)
                    {
                        link = links[1];
                    }
                    else if (links[0] != null)
                    {
                        link = links[0];
                    }
                    else
                    {
                        link = track.Location;
                    }

                    BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(new Uri(link, UriKind.RelativeOrAbsolute));
                    transferRequest.Method = "GET";

                    transferRequest.DownloadLocation = new Uri("shared/transfers/" + track.Title.Replace(' ', '-') + ".mp3", UriKind.RelativeOrAbsolute);
                    try
                    {
                        BackgroundTransferService.Add(transferRequest);
                    }
                    catch (Exception) { }
                }
            }
        }
Exemple #2
0
 public void Download(string url, AsyncCallback DownloadCallback)
 {
     url          = url.Replace("https", "http");
     BTR_Download = new BackgroundTransferRequest(new Uri(url));
     using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
     {
         if (!iso.DirectoryExists(TRANSFER_FOLDER))
         {
             iso.CreateDirectory(TRANSFER_FOLDER);
         }
     }
     BTR_Download.DownloadLocation         = new Uri(DOWNLOAD_LOCATION, UriKind.Relative);
     BTR_Download.TransferStatusChanged   += BTR_Download_TransferStatusChanged;
     BTR_Download.TransferProgressChanged += BTR_Download_TransferProgressChanged;
     if (!Downloading)
     {
         foreach (BackgroundTransferRequest req in BackgroundTransferService.Requests)
         {
             if (req.DownloadLocation == BTR_Download.DownloadLocation)
             {
                 BackgroundTransferService.Remove(req);
             }
         }
         BackgroundTransferService.Add(BTR_Download);
         Downloading = true;
         _downloadProgressChangeCallback = DownloadCallback;
     }
 }
Exemple #3
0
        public void Upload(AsyncCallback UploadCallback, AsyncCallback uploadProgressCallback)
        {
            string upload_uri = FILEPICKER_BASEURL + "/api/store/S3?key=" + FILEPICKER_APIKEY;

            BTR = new BackgroundTransferRequest(new Uri(upload_uri));
            BTR.TransferStatusChanged   += BTR_TransferStatusChanged;
            BTR.TransferProgressChanged += BTR_TransferProgressChanged;
            BTR.Method = "POST";

            using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!iso.DirectoryExists(TRANSFER_FOLDER))
                {
                    iso.CreateDirectory(TRANSFER_FOLDER);
                }
                iso.CopyFile("/cars.sdf", TRANSFER_FOLDER + "/cars.sdf", true);
            }
            BTR.DownloadLocation = new Uri(SAVE_RESPONSE_LOCATION, UriKind.Relative);
            BTR.UploadLocation   = new Uri(TRANSFER_FOLDER + "/cars.sdf", UriKind.Relative);
            if (!Uploading)
            {
                Uploading = true;
                foreach (BackgroundTransferRequest req in BackgroundTransferService.Requests)
                {
                    if (req.UploadLocation == BTR.UploadLocation)
                    {
                        BackgroundTransferService.Remove(req);
                    }
                }
                BackgroundTransferService.Add(BTR);
                _uploadCallback = UploadCallback;
                _uplaodProgressChangeCallback = uploadProgressCallback;
            }
        }
Exemple #4
0
        void OnBackgroundTransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            if (e.Request.TransferStatus == TransferStatus.Completed)
            {
                BackgroundTransferService.Remove(e.Request);

                if (_idMapping.ContainsKey(e.Request.RequestId))
                {
                    _idMapping[e.Request.RequestId].Invoke(e.Request);
                    _idMapping.Remove(e.Request.RequestId);
                }

                // Check if there are pending downloads, if there are then queue them up with background transfer service now.
                if (_requests.Count > 0)
                {
                    try
                    {
                        BackgroundTransferService.Add(_requests[0]);
                        _requests.RemoveAt(0);
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }
            }
        }
 public void RequestStart()
 {
     try
     {
         BackgroundTransferService.Add(_request);
     }
     catch (ArgumentNullException err)
     {
         Debug.WriteLine("The request argument cannot be null.");
         Debug.WriteLine(err);
         ErrorMessage = "Invalid request";
         State        = TransferRequestState.Failed;
         StatusText   = ControlResources.StatusFailed;
     }
     catch (InvalidOperationException err)
     {
         Debug.WriteLine("The request has already been submitted.");
         Debug.WriteLine(err);
         ErrorMessage = "The request has already been submitted.";
         State        = TransferRequestState.Failed;
     }
     catch (SystemException err)
     {
         Debug.WriteLine("The maximum number of requests on the device has been reached.");
         Debug.WriteLine(err);
         ErrorMessage = "The maximum number of requests on the device has been reached.";
         State        = TransferRequestState.Failed;
         StatusText   = ControlResources.StatusFailed;
     }
 }
        /// <summary>
        /// This function is for demo purposes. It adds three files to the background download queue and displays them in the multi-select list.
        /// </summary>
        private void OnAddButtonClick(object sender, EventArgs e)
        {
            Dictionary <string, Uri> urlPresets = new Dictionary <string, Uri>
            {
                { "21 MB File", new Uri("http://media.ch9.ms/ch9/ecbc/cfcb0ad7-fbdd-47b0-aabf-4da5e3e0ecbc/WP8JumpStart06.mp3", UriKind.Absolute) },
                { "34 MB File", new Uri("http://media.ch9.ms/ch9/7e13/ce6ea97c-e233-4e7c-a74d-ee1c81e37e13/WP8JumpStart04.mp3", UriKind.Absolute) },
                { "92 MB File", new Uri("http://media.ch9.ms/ch9/7e13/ce6ea97c-e233-4e7c-a74d-ee1c81e37e13/WP8JumpStart04.wmv", UriKind.Absolute) },
            };

            foreach (var preset in urlPresets)
            {
                Uri saveLocation = new Uri("/shared/transfers/" + preset.Key, UriKind.Relative);
                BackgroundTransferRequest request = new BackgroundTransferRequest(preset.Value, saveLocation)
                {
                    TransferPreferences = TransferPreferences.AllowBattery   // Note: this will not use cellular data to download
                };
                TransferMonitor monitor = new TransferMonitor(request, preset.Key);
                try
                {
                    BackgroundTransferService.Add(request);
                }
                catch (Exception err) // An exception is thrown if this transfer is already requested.
                {
                    Debug.WriteLine(err);
                    continue;
                }
                monitor.Failed += TransferCanceled;
                _list.Add(monitor);
            }
        }
        public void downloadFile(MyChatBubble chatBubble, string msisdn)
        {
            Uri downloadUriSource = new Uri(Uri.EscapeUriString(HikeConstants.FILE_TRANSFER_BASE_URL + "/" + chatBubble.FileAttachment.FileKey),
                                            UriKind.RelativeOrAbsolute);

            string relativeFilePath = "/" + msisdn + "/" + Convert.ToString(chatBubble.MessageId);
            string destinationPath  = "shared/transfers" + "/" + Convert.ToString(chatBubble.MessageId);
            Uri    destinationUri   = new Uri(destinationPath, UriKind.RelativeOrAbsolute);

            BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(downloadUriSource);

            // Set the transfer method. GET and POST are supported.
            transferRequest.Tag    = relativeFilePath;
            transferRequest.Method = "GET";
            transferRequest.TransferStatusChanged   += new EventHandler <BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
            transferRequest.TransferProgressChanged += new EventHandler <BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
            transferRequest.DownloadLocation         = destinationUri;
            try
            {
                transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
                BackgroundTransferService.Add(transferRequest);
                requestIdChatBubbleMap.Add(transferRequest.RequestId, chatBubble as ReceivedChatBubble);
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(AppResources.FileTransfer_ErrorMsgBoxText + ex.Message);
            }
            catch (Exception e)
            {
                MessageBox.Show(AppResources.FileTransfer_ErrorMsgBoxText);
            }
        }
Exemple #8
0
        private void Download_Click(object sender, EventArgs e)
        {
            try
            {
                // Sichergehen, dass der Download-Ordner existiert
                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!isoStore.DirectoryExists(TransfersFolder))
                    {
                        isoStore.CreateDirectory(TransfersFolder);
                    }
                }

                var request = new BackgroundTransferRequest(new Uri("http://ralfe-software.net/Wildlife.wmv", UriKind.Absolute))
                {
                    DownloadLocation    = new Uri(DownloadLocation, UriKind.Relative),
                    Method              = "GET",
                    TransferPreferences = TransferPreferences.AllowBattery
                };
                BackgroundTransferService.Add(request);

                DownloadButton.IsEnabled = false;
                DeleteButton.IsEnabled   = true;
                UpdateUI();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        void GlobalOfflineSync_Ready(object sender, FileDownloadEvntArgs e)
        {
            OfflineSyncExt sync = (OfflineSyncExt)sender;

            if (!GlobalOfflineSync.Cancelled)
            {
                BackgroundTransferService.Add(sync.BACKGROUND_REQUEST);
            }
        }
        private void GetSas(string result)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(string));

            result = "<root>" + result + "</root>";
            XDocument document = XDocument.Parse(result);

            sas = document.Root.Value;
            //  ECGName = "634708322772702206";

            string fileDownload = "https://echelperspace.blob.core.windows.net/" + Patientid + "/" + ECGName + "/" + sas;
            // Uri fileDownloadUri = new Uri("https://echelperspace.blob.core.windows.net/{patientuser}/{filename}+{sas}");

            Uri fileDownloadUri = new Uri(fileDownload);



            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!isoStore.DirectoryExists("shared/transfers"))
                {
                    isoStore.CreateDirectory("shared/transfers");
                }
            }
            //解析文件名,赋给SAVE_LOCATION
            //       SAVE_LOCATION = SAVE_LOCATION + filename;
            Uri saveLocationUri = new Uri(SAVE_LOCATION, UriKind.RelativeOrAbsolute);

            using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (userStore.FileExists(SAVE_LOCATION))
                {
                    userStore.DeleteFile(SAVE_LOCATION);
                }
            }


            _currentRequest        = new BackgroundTransferRequest(fileDownloadUri, saveLocationUri);
            _currentRequest.Method = "GET";
            _currentRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
            // try
            //{
            foreach (BackgroundTransferRequest request in BackgroundTransferService.Requests)
            {
                BackgroundTransferService.Remove(request);
            }

            BackgroundTransferService.Add(_currentRequest);

            InitializeTransferRequestEventHandlers();
            // }
            ////catch (InvalidOperationException)
            //{
            //    textBlock_Status.Text = "wocao";
            //}
            //sas = (string)serializer.Deserialize(document.CreateReader());
        }
Exemple #11
0
        private void HandleDownload(BackgroundTransferRequest transferRequest, DownloadInfo info, bool isAddQueue)
        {
            transferRequest.TransferStatusChanged += (o, e) =>
            {
                switch (e.Request.TransferStatus)
                {
                case TransferStatus.Completed:
                    if (e.Request.StatusCode == 200 || e.Request.StatusCode == 206)
                    {
                        DownloadCompleted(info);
                        BackgroundTransferService.Remove(e.Request);
                        e.Request.Dispose();
                    }
                    break;

                case TransferStatus.WaitingForWiFi:
                case TransferStatus.WaitingForNonVoiceBlockingNetwork:
                    info.DownloadState = DownloadState.WaitingForWiFi;
                    Utils.TileUtils.CreateBasicToast("需要在WiFi环境下才能下载");
                    break;

                case TransferStatus.WaitingForExternalPower:
                case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
                    info.DownloadState = DownloadState.WaitingForExternalPower;
                    Utils.TileUtils.CreateBasicToast("需要外接电源才能下载");
                    break;

                default:
                    break;
                }
            };
            transferRequest.TransferProgressChanged += (o, e) =>
            {
                DownloadProgress(e.Request, info);
            };

            if (isAddQueue)
            {
                transferRequest.Method = "GET";
                info.RequestId         = transferRequest.RequestId;

                try
                {
                    if (BackgroundTransferService.Find(info.RequestId) == null)
                    {
                        BackgroundTransferService.Add(transferRequest);
                    }
                }
                catch (Exception ex)
                {
                    _isDownloading = false;
                    DownloadFailture(info, ex.Message);
                }
            }
        }
Exemple #12
0
        public void startAsync(string options)
        {
            try
            {
                var optStings = JSON.JsonHelper.Deserialize <string[]>(options);

                var uriString = optStings[0];
                var filePath  = optStings[1];


                if (_activDownloads.ContainsKey(uriString))
                {
                    return;
                }

                _activDownloads.Add(uriString, new Download(uriString, filePath, optStings[2]));


                var requestUri = new Uri(uriString);

                BackgroundTransferRequest transfer = FindTransferByUri(requestUri);

                if (transfer == null)
                {
                    // "shared\transfers" is the only working location for BackgroundTransferService download
                    // we use temporary file name to download content and then move downloaded file to the requested location
                    var downloadLocation = new Uri(@"\shared\transfers\" + Guid.NewGuid(), UriKind.Relative);

                    transfer = new BackgroundTransferRequest(requestUri, downloadLocation);

                    // Tag is used to make sure we run single background transfer for this file
                    transfer.Tag = uriString;

                    BackgroundTransferService.Add(transfer);
                }

                if (transfer.TransferStatus == TransferStatus.Completed)
                {
                    // file was already downloaded while we were in background and we didn't report this
                    MoveFile(transfer);
                    BackgroundTransferService.Remove(transfer);
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
                }
                else
                {
                    transfer.TransferProgressChanged += ProgressChanged;
                    transfer.TransferStatusChanged   += TransferStatusChanged;
                }
            }
            catch (Exception ex)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ex.Message));
            }
        }
Exemple #13
0
        public void Start()
        {
            //Create a new background transfer request
            BackgroundTransferRequest request = new BackgroundTransferRequest(requestUri, downloadUri);

            request.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
            requestId = request.RequestId;

            //Subscribe to the events
            request.TransferStatusChanged   += request_TransferStatusChanged;
            request.TransferProgressChanged += request_TransferProgressChanged;

            //Add new request to the queue
            BackgroundTransferService.Add(request);
        }
Exemple #14
0
        public async Task DownloadRulesFileAsync()
        {
            await Task.Yield();

            Uri requestUri  = new Uri(this.RulesUri);
            Uri downloadUri = new Uri(this.localFileName, UriKind.RelativeOrAbsolute);
            BackgroundTransferRequest req = new BackgroundTransferRequest(requestUri, downloadUri)
            {
                TransferPreferences = TransferPreferences.AllowCellularAndBattery
            };

            BackgroundTransferService.Add(req);

            TransferMonitor monitor = new TransferMonitor(req);

            monitor.Complete += (sender, args) => BackgroundTransferService.Remove(args.Request);
        }
 private void SubmitTransfer(BackgroundTransferRequest transfer)
 {
     try {
         BackgroundTransferService.Add(transfer);
         // updates local cache
         //TransferRequests.Add(transfer);
     } catch (InvalidOperationException ioe) {
         TryToDispose(transfer);
         if (ioe.Message != "The request has already been submitted")
         {
             throw;
         }
     } catch (Exception) {
         TryToDispose(transfer);
         throw;
     }
 }
Exemple #16
0
        public void QueueDownload(string source, string destination, string tag, OnTransferCompleted callback)
        {
            Uri requestUri       = new Uri(source, UriKind.Absolute);
            Uri downloadLocation = new Uri(destination, UriKind.Relative);
            BackgroundTransferRequest request = new BackgroundTransferRequest(requestUri, downloadLocation);

            request.TransferPreferences = TransferPreferences.AllowCellularAndBattery;

            request.TransferStatusChanged += new EventHandler <BackgroundTransferEventArgs>(OnBackgroundTransferStatusChanged);
            request.Tag = tag;

            try
            {
                _idMapping.Add(request.RequestId, callback);
                BackgroundTransferService.Add(request);
            }
            catch (InvalidOperationException)
            {
                _requests.Add(request);
            }
        }
Exemple #17
0
        /*
         * Guid jkd
         * status mystatus
         * facebookaccesstoken
         * twitteraccesstoken
         * twittertokensecret
         * linkedinaccesstoken
         * starttime
         * endtime
         * selected
         */

        private void AddBackgroundTransfer()
        {
            //IsolatedStorageFileExtensions.SavePicture(Path.Combine(TransfersFiles, picture.FileName), picture.Data);

            var transferRequest = new BackgroundTransferRequest(new Uri(ServiceUploadLocationURL, UriKind.Absolute));

            //if (!_wifiOnly)
            //{
            //    transferRequest.TransferPreferences = TransferPreferences.AllowCellular;
            //}
            //if (!_externalPowerOnly)
            //{
            //    transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
            //}
            //if (!_wifiOnly && !_externalPowerOnly)
            //{
            //    transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
            //}
            transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
            transferRequest.Method                   = "POST";
            transferRequest.UploadLocation           = new Uri(TransfersFiles + @"\" + filename, UriKind.Relative);
            transferRequest.TransferStatusChanged   += OnTransferStatusChanged;
            transferRequest.TransferProgressChanged += OnTransferProgressChanged;

            try
            {
                BackgroundTransferService.Add(transferRequest);
                dispatcher.BeginInvoke(() => MessageBox.Show("Added Background Agent for request"));
                //PictureRepository.Instance.SetPictureStatus(picture, FileStatus.Active, transferRequest.RequestId);
                //UpdateRequestsList();
            }
            catch (InvalidOperationException ex)
            {
                dispatcher.BeginInvoke(() => MessageBox.Show("Unable to add background transfer request. " + ex.Message));
            }
            catch (Exception ex)
            {
                dispatcher.BeginInvoke(() => MessageBox.Show("Unable to add background transfer request." + ex.Message));
            }
        }
        public void DownloadFile(File file)
        {
            if (BackgroundTransferService.Requests.Count() >= 5)
            {
                _informerManagerLocator.InformerManager.AddMessage("Error", "The maximum number of background file transfer requests for this application has been exceeded");
            }
            //var toto = await _fileApi.DownloadFile(file, _user.Token);


            Uri transferUri = _fileApi.GetDownloadUrl(file);
            BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);

            // Set the transfer method. GET and POST are supported.
            transferRequest.Method = "GET";
            transferRequest.Headers["Authorization"] = _user.Token;
            Uri downloadUri = new Uri("shared/transfers/" + file.Name, UriKind.RelativeOrAbsolute);

            transferRequest.DownloadLocation = downloadUri;
            transferRequest.Tag = file.Size + "~" + file.ContentType.Split('/').First() + "~" + file.Name;
            transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
            try
            {
                BackgroundTransferService.Add(transferRequest);
            }
            catch (InvalidOperationException ex)
            {
                _informerManagerLocator.InformerManager.AddMessage("Unable to add background transfer request", ex.Message);
            }
            catch (Exception)
            {
                _informerManagerLocator.InformerManager.AddMessage("Error", "Unable to add background transfer request.");
            }
            if (transferRequest != null)
            {
                transferRequest.TransferProgressChanged += transfer_TransferProgressChanged;
                transferRequest.TransferStatusChanged   += transfer_TransferStatusChanged;
                //this.transferRequests.ToList().Add(transferRequest);
                UpdateRequestsList();
            }
        }
        internal bool Add(BackgroundTransferRequest request)
        {
            bool status = false;

            request.TransferProgressChanged += onTransferProgressChanged;
            request.TransferStatusChanged   += onTransferStatusChanged;
            request.TransferPreferences      = TransferPreferences.AllowCellularAndBattery;
            try
            {
                BackgroundTransferService.Add(request);
                status = true;
            }
            catch (InvalidOperationException ex)
            {
                Logger.Error("Unable to add background transfer request. Reason - " + ex.Message);
            }
            catch (Exception e)
            {
                Logger.Error("Unable to add background transfer request. Reason" + e.Message);
            }
            return(status);
        }
        public void StartDownload(DownloadItem item)
        {
            var request = new BackgroundTransferRequest(new Uri(item.Url, UriKind.Absolute))
            {
                Method           = "GET",
                DownloadLocation = new Uri("shared/transfers/" + item.Filename, UriKind.RelativeOrAbsolute)
            };

            request.TransferProgressChanged += (sender, args) => UpdateProgress(item, args.Request);
            request.TransferStatusChanged   += (sender, args) => UpdateTransferStatus(item, request);

            try {
                BackgroundTransferService.Add(request);
            } catch (Exception exception) {
                MessageBox.Show("Fehler beim Landen: " + exception.Message);
            }

            item.TotalBytes      = 100;
            item.DownloadedBytes = 0;

            item.Id = request.RequestId;
        }
        private void btnResourceDownload_Click(object sender, RoutedEventArgs e)
        {
            if (backgroundTransferRequest != null)
            {
                BackgroundTransferService.Remove(backgroundTransferRequest);
            }

            // backgroundTransferRequest = new BackgroundTransferRequest(videoDownloadUri, saveLocationUri);
            Button btnDownload      = sender as Button;
            string transferFileName = "http://www.usebackpack.com/resources/547/download?1383196424"; //btnDownload.Tag.ToString();
            Uri    transferUri      = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);
            // backgroundTransferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;

            BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);

            // Set the transfer method. GET and POST are supported.
            transferRequest.Method = "GET";


            string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
            Uri    downloadUri  = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);

            transferRequest.DownloadLocation    = downloadUri;
            transferRequest.TransferPreferences = TransferPreferences.AllowCellular;
            // Pass custom data with the Tag property. In this example, the friendly name
            // is passed.
            transferRequest.Tag = downloadFile;
            try
            {
                BackgroundTransferService.Add(transferRequest);
            }
            catch (Exception exc)
            {
            }

            ProcessTransfer(transferRequest);
        }
Exemple #22
0
        public static async Task InitiateBackgroundTransferAsync(string path)
        {
            try
            {
                string          filename = path.Substring(path.LastIndexOf("/") + 1);
                PrepareDownload download = await App.Context.Connection.Xbmc.Files.PrepareDownloadAsync(path);

                Uri sourceUri = App.Context.Connection.Xbmc.GetFileUri(download.Details.Path);

                const string targetDirectory = "/shared/transfers/";

                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!isoStore.DirectoryExists(targetDirectory))
                    {
                        isoStore.CreateDirectory(targetDirectory);
                    }
                }

                Uri downloadUri = new Uri(targetDirectory + filename, UriKind.RelativeOrAbsolute);

                var request = new BackgroundTransferRequest(sourceUri, downloadUri);
                request.Tag = filename;
                request.TransferProgressChanged += OnTransferProgressChanged;
                request.TransferStatusChanged   += OnTransferStatusChanged;

                BackgroundTransferService.Add(request);
                BackgroundTransferRequestStateChanged?.Raise(request, DownloadRequestState.Initialized);

                string message = string.Format(AppResources.Global_Downloads_Started_Format, filename);
                MessageBox.Show(message, AppResources.Global_Downloads, MessageBoxButton.OK);
            }
            catch (Exception ex)
            {
                App.TrackException(ex);
            }
        }
Exemple #23
0
        private ITransferRequest DownloadAsyncViaBackgroundTranfer(Uri serverUri, Uri phoneUri)
        {
            try
            {
                var request = new BackgroundTransferRequest(serverUri, phoneUri);
                request.Tag = serverUri.ToString();
                request.TransferPreferences = TransferPreferences.AllowCellularAndBattery;

                int count = 0;
                foreach (var r in BackgroundTransferService.Requests)
                {
                    count++;
                    if (r.RequestUri == serverUri)
                    {
                        return(new WindowsTransferRequest(r));
                    }
                    if (r.TransferStatus == TransferStatus.Completed)
                    {
                        BackgroundTransferService.Remove(r);
                        count--;
                    }
                    // Max 5 downloads
                    if (count >= 5)
                    {
                        return(null);
                    }
                }
                BackgroundTransferService.Add(request);
                PersistRequestToStorage(request);
                return(new WindowsTransferRequest(request));
            }
            catch (InvalidOperationException)
            {
                return(GetRequest(serverUri.ToString()));
            }
        }
        public void UploadFileByBackgroundTranfer()
        {
            if (BackgroundTransferService.Requests.Count() >= 5)
            {
                _informerManagerLocator.InformerManager.AddMessage("Error", "The maximum number of background file transfer requests for this application has been exceeded");
                return;
            }

            var boundary = Guid.NewGuid().ToString();
            var mimeType = "image/jpeg";

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isoStore.FileExists("shared/transfers/" + UploadTextBox))
                {
                    isoStore.DeleteFile("shared/transfers/" + UploadTextBox);
                }
                IsolatedStorageFileStream fileStream = isoStore.CreateFile("shared/transfers/" + UploadTextBox);

                // Define header of the multipart form data concerning the body of the request
                // We have to do it because it's possible to upload several files
                StringBuilder content = new StringBuilder();
                content.AppendLine(String.Format("--{0}", boundary));
                content.AppendLine(String.Format("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"", UploadTextBox));
                content.AppendLine(String.Format("Content-Type: {0}", mimeType));

                content.AppendLine();

                // Writing the header in the request
                byte[] contentAsBytes = Encoding.UTF8.GetBytes(content.ToString());
                fileStream.Write(contentAsBytes, 0, contentAsBytes.Length);

                content.Clear();

                EntityToUploadStream.Position = 0;

                byte[] buffer = new byte[16 * 1024];
                int    read;
                while ((read = EntityToUploadStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fileStream.Write(buffer, 0, read);
                }

                content.AppendLine();

                // Footer of body
                content.AppendLine(String.Format("--{0}--", boundary));

                contentAsBytes = Encoding.UTF8.GetBytes(content.ToString());
                fileStream.Write(contentAsBytes, 0, contentAsBytes.Length);

                fileStream.Close();
                EntityToUploadStream = null;
            }

            Uri transferUri = _fileApi.GetUploadUrl(_currentFolderId);
            BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);

            transferRequest.Method = "POST";
            transferRequest.Headers["Authorization"] = _user.Token;

            // Headet of the multi part request
            transferRequest.Headers["Content-Type"] = string.Format("multipart/form-data; boundary={0}", boundary);
            transferRequest.UploadLocation          = new Uri("shared/transfers/" + UploadTextBox, UriKind.Relative);
            transferRequest.Tag = UploadTextBox;
            transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
            try
            {
                BackgroundTransferService.Add(transferRequest);
            }
            catch (InvalidOperationException ex)
            {
                _informerManagerLocator.InformerManager.AddMessage("Unable to add background transfer request", ex.Message);
            }
            catch (Exception)
            {
                _informerManagerLocator.InformerManager.AddMessage("Error", "Unable to add background transfer request.");
            }
            if (transferRequest != null)
            {
                transferRequest.TransferProgressChanged += transfer_TransferProgressChanged;
                transferRequest.TransferStatusChanged   += transfer_TransferStatusChanged;
                UpdateRequestsList();
            }
        }
 public void Add(BackgroundTransferRequest request)
 {
     BackgroundTransferService.Add(request);
 }
Exemple #26
0
        private IDownloadCancelHandle StartEnqueuedDownload(QueuedDownload download)
        {
            _downloadStartedEvent.OnNext(download);
            App.Engine.StatisticsManager.LogDownloadStart(download);

            Transport.PendingDownload pendingDownload = Transport.StartQueuedDownload(download);

            pendingDownload.Response
            .ObserveOnDispatcher()
            .Subscribe <Transport.RunningDownload>(
                activeDownload =>
            {
                if (activeDownload.Download.DownloadSize == long.MaxValue || activeDownload.Download.DownloadSize == 0)
                {
                    activeDownload.Download.DownloadSize = activeDownload.ContentLength;
                }
                BackgroundWorker worker = new BackgroundWorker()
                {
                    WorkerReportsProgress = true, WorkerSupportsCancellation = true
                };

                // change cancel handle
                startedDownloads[activeDownload.Download] = new ActiveDownloadCancelHandle(worker);

                worker.DoWork += (sender, e) =>
                {
                    Transport.RunningDownload dl = (Transport.RunningDownload)e.Argument;
                    BackgroundWorker bw          = (BackgroundWorker)sender;
                    long bytesRead = dl.Download.DownloadedBytes;

                    // limited number of progress bar updates
                    var uiUpdates       = new Subject <long>();
                    var cancelUiUpdates = uiUpdates
                                          .Take(1)
                                          .Merge(Observable.Empty <long>().Delay(TimeSpan.FromMilliseconds(KProgressUpdateInterval)))
                                          .Repeat()
                                          .Subscribe <long>(progress =>
                    {
                        if (bw.IsBusy)
                        {
                            bw.ReportProgress(0, progress);
                        }
                    });

                    if (dl is Transport.ActiveDownload)
                    {
                        string filePath = Utils.MediaFilePath(App.Engine.LoggedUser, dl.Download);
                        using (Stream writer = new IsolatedStorageFileStream(filePath, FileMode.Append, IsolatedStorageFile.GetUserStoreForApplication()))
                        {
                            using (Stream reader = ((Transport.ActiveDownload)dl).Stream)
                            {
                                byte[] buffer = new byte[16 * 1024];
                                int readCount;
                                while ((readCount = reader.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    bytesRead += readCount;
                                    writer.Write(buffer, 0, readCount);
                                    uiUpdates.OnNext(bytesRead);

                                    if (bw.CancellationPending)
                                    {
                                        pendingDownload.Cancel();
                                        e.Cancel = true;
                                        break;
                                    }
                                }
                                bw.ReportProgress(0, bytesRead);
                                e.Result = activeDownload.Download;
                            }
                        }
                        cancelUiUpdates.Dispose();
                    }
                    if (dl is Transport.BackgroundDownload)
                    {
                        BackgroundTransferRequest downloadRequest = ((Transport.BackgroundDownload)dl).Request;
                        IObservable <IEvent <BackgroundTransferEventArgs> > requestObserver = Observable.FromEvent <BackgroundTransferEventArgs>(downloadRequest, "TransferStatusChanged");
                        if (downloadRequest.TransferStatus != TransferStatus.Completed)
                        {
                            if (downloadRequest.TransferStatus == TransferStatus.None)
                            {
                                downloadRequest.DownloadLocation    = new Uri(Utils.BackgroundFilePath(App.Engine.LoggedUser, dl.Download), UriKind.RelativeOrAbsolute);
                                downloadRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
                                e.Result = activeDownload.Download;
                                BackgroundTransferService.Add(downloadRequest);
                            }
                            downloadRequest.TransferProgressChanged += (senderBackground, eventBackground) =>
                            {
                                if (activeDownload.Download.DownloadSize == long.MaxValue || activeDownload.Download.DownloadSize == 0)
                                {
                                    activeDownload.Download.DownloadSize =
                                        activeDownload.ContentLength == -1 ?
                                        0:
                                        activeDownload.ContentLength;
                                }
                                uiUpdates.OnNext(eventBackground.Request.BytesReceived);
                            };
                            IDisposable cancelOnStop = DownloadStopPendingEvent.Subscribe(stoppedDownload =>
                            {
                                if (dl.Download == stoppedDownload)
                                {
                                    BackgroundTransferService.Remove(downloadRequest);
                                    dl.Download.State           = QueuedDownload.DownloadState.Stopped;
                                    dl.Download.DownloadedBytes = 0;
                                }
                            });
                            bw.ReportProgress(0, requestObserver.First().EventArgs.Request);
                            cancelOnStop.Dispose();
                        }
                        e.Result = activeDownload.Download;
                    }
                };
                worker.ProgressChanged += (sender, e) =>
                {
                    if (e.UserState is BackgroundTransferRequest)
                    {
                        BackgroundTransferRequest request = e.UserState as BackgroundTransferRequest;
                        if (request.TransferStatus != TransferStatus.Completed || request.TransferError is InvalidOperationException)
                        {
                            activeDownload.Download.DownloadedBytes = 0;
                        }
                        else
                        {
                            activeDownload.Download.DownloadedBytes = ((BackgroundTransferRequest)e.UserState).BytesReceived;
                        }
                    }
                    else
                    {
                        activeDownload.Download.DownloadedBytes = (long)e.UserState;
                    }
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    if (activeDownload is Transport.ActiveDownload)
                    {
                        startedDownloads.Remove(activeDownload.Download);

                        if (!IsFileDownloadSuccessfulOrResumed(e, activeDownload.Download))
                        {
                            _downloadStoppedEvent.OnNext(activeDownload.Download);
                        }
                    }
                    else
                    {
                        if (!e.Cancelled && e.Error == null)
                        {
                            startedDownloads.Remove(activeDownload.Download);
                            QueuedDownload result = (QueuedDownload)e.Result;
                            if (IsBackgroundTransferSuccesfull(((Transport.BackgroundDownload)activeDownload).Request, result))
                            {
                                _downloadCompletedEvent.OnNext(activeDownload.Download);
                                App.Engine.StatisticsManager.LogDownloadCompleted(activeDownload.Download, "Completed");
                            }
                            else
                            {
                                _downloadStoppedEvent.OnNext(activeDownload.Download);
                            }
                        }
                        else if (e.Error != null)
                        {
                            startedDownloads.Remove(download);
                            _downloadErrorEvent.OnNext(download);
                        }
                        else
                        {
                            try
                            {
                                BackgroundTransferService.Remove((activeDownload as Transport.BackgroundDownload).Request);
                                _downloadStoppedEvent.OnNext(activeDownload.Download);
                                startedDownloads.Remove(download);
                            }
                            catch (InvalidOperationException)
                            {
                                startedDownloads.Remove(download);
                            }
                        }
                    }
                };
                worker.RunWorkerAsync(activeDownload);
            },
                error =>
            {
                startedDownloads.Remove(download);

                if (IsFileMissingFromServer(error))
                {
                    _downloadErrorEvent.OnNext(download);
                    App.Engine.StatisticsManager.LogDownloadCompleted(download, "Error");
                }
                else
                {
                    _downloadStoppedEvent.OnNext(download);
                }
            }
                );
            return(new PendingDownloadCancelHandle(pendingDownload));
        }
        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            // Check to see if the maximum number of requests per app has been exceeded.
            if (BackgroundTransferService.Requests.Count() >= 25)
            {
                // Note: Instead of showing a message to the user, you could store the
                // requested file URI in isolated storage and add it to the queue later.
                MessageBox.Show("The maximum number of background file transfer requests for this application has been exceeded. ");
                return;
            }

            // Get the URI of the file to be transferred from the Tag property
            // of the button that was clicked.

            string transferFileName = UrlTextBox.Text;

            if (!validURL(transferFileName))
            {
                MessageBox.Show("Invalid URL");
                return;
            }

            Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);



            // Create the new transfer request, passing in the URI of the file to
            // be transferred.
            BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);

            transferRequest.TransferStatusChanged   += new EventHandler <BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
            transferRequest.TransferProgressChanged += new EventHandler <BackgroundTransferEventArgs>(transfer_TransferProgressChanged);

            // Set the transfer method. GET and POST are supported.
            transferRequest.Method = "GET";

            // Get the file name from the end of the transfer URI and create a local URI
            // in the "transfers" directory in isolated storage.
            string downloadFile = createUniqueFilename(transferFileName);
            Uri    downloadUri  = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);

            transferRequest.DownloadLocation = downloadUri;

            // Pass custom data with the Tag property. In this example, the friendly name
            // is passed.
            transferRequest.Tag = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1) + "#" + downloadFile;

            transferRequest.TransferPreferences = TransferPreferences.AllowBattery;

            // If the Wi-Fi-only check box is not checked, then set the TransferPreferences
            // to allow transfers over a cellular connection.

            /*if (wifiOnlyCheckbox.IsChecked == false)
             * {
             *  transferRequest.TransferPreferences = TransferPreferences.AllowCellular;
             * }
             * if (externalPowerOnlyCheckbox.IsChecked == false)
             * {
             *  transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
             * }
             * if (wifiOnlyCheckbox.IsChecked == false && externalPowerOnlyCheckbox.IsChecked == false)
             * {
             *  transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
             * }
             */
            // Add the transfer request using the BackgroundTransferService. Do this in
            // a try block in case an exception is thrown.
            try
            {
                BackgroundTransferService.Add(transferRequest);
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show("Unable to add background transfer request. " + ex.Message);
            }
            catch (Exception)
            {
                MessageBox.Show("Unable to add background transfer request.");
            }



            UpdateUI();
        }
Exemple #28
0
        private void startNextEpisodeDownload(TransferPreferences useTransferPreferences = TransferPreferences.AllowCellularAndBattery)
        {
            if (BackgroundTransferService.Requests.Count() > 0)
            {
                // For some reason there are still old requests in the background transfer service.
                // Let's clean everything and start over.
                foreach (BackgroundTransferRequest t in BackgroundTransferService.Requests.AsEnumerable())
                {
                    BackgroundTransferService.Remove(t);
                }
            }

            if (m_episodeDownloadQueue.Count > 0)
            {
                m_currentEpisodeDownload = m_episodeDownloadQueue.Peek();
                Uri downloadUri;
                try
                {
                    downloadUri = new Uri(m_currentEpisodeDownload.EpisodeDownloadUri, UriKind.Absolute);
                }
                catch (Exception e)
                {
                    App.showErrorToast("Cannot download the episode.");
                    Debug.WriteLine("Cannot download the episode. URI exception: " + e.Message);
                    m_currentEpisodeDownload.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Idle;
                    m_episodeDownloadQueue.Dequeue();
                    saveEpisodeInfoToDB(m_currentEpisodeDownload);
                    startNextEpisodeDownload();
                    return;
                }

                m_currentEpisodeDownload.EpisodeFile = generateLocalEpisodeFileName(m_currentEpisodeDownload);
                if (string.IsNullOrEmpty(m_currentEpisodeDownload.EpisodeFile))
                {
                    App.showErrorToast("Cannot download the episode.");
                    Debug.WriteLine("Cannot download the episode. Episode file name is null or empty.");
                    m_currentEpisodeDownload.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Idle;
                    m_episodeDownloadQueue.Dequeue();
                    saveEpisodeInfoToDB(m_currentEpisodeDownload);
                    startNextEpisodeDownload();
                    return;
                }

                // Create a new background transfer request for the podcast episode download.
                m_currentBackgroundTransfer = new BackgroundTransferRequest(downloadUri,
                                                                            new Uri(m_currentEpisodeDownload.EpisodeFile, UriKind.Relative));
                if (useTransferPreferences == TransferPreferences.None)
                {
                    m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.None;
                }
                else if (canAllowCellularDownload(m_currentEpisodeDownload))
                {
                    bool settingsAllowCellular = false;
                    using (var db = new PodcastSqlModel())
                    {
                        settingsAllowCellular = db.settings().IsUseCellularData;
                    }

                    Debug.WriteLine("Settings: Allow cellular download: " + settingsAllowCellular);

                    if (settingsAllowCellular && canDownloadOverCellular())
                    {
                        m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
                    }
                    else
                    {
                        m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.AllowBattery;
                    }
                }
                else
                {
                    m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.None;
                }

                Debug.WriteLine("m_currentBackgroundTransfer.TransferPreferences = " + m_currentBackgroundTransfer.TransferPreferences.ToString());

                m_currentBackgroundTransfer.TransferStatusChanged += new EventHandler <BackgroundTransferEventArgs>(backgroundTransferStatusChanged);

                // Store request to the episode.
                m_currentEpisodeDownload.DownloadRequest = m_currentBackgroundTransfer;

                m_applicationSettings.Remove(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID);
                m_applicationSettings.Add(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID, m_currentEpisodeDownload.EpisodeId);
                m_applicationSettings.Save();

                try
                {
                    BackgroundTransferService.Add(m_currentBackgroundTransfer);
                }
                catch (InvalidOperationException)
                {
                    foreach (BackgroundTransferRequest r in BackgroundTransferService.Requests)
                    {
                        BackgroundTransferService.Remove(r);
                    }

                    BackgroundTransferService.Add(m_currentBackgroundTransfer);
                }
            }
        }
        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            Button nb = (Button)sender;

            // Check to see if the maximum number of requests per app has been exceeded.
            if (BackgroundTransferService.Requests.Count() >= 25)
            {
                // Note: Instead of showing a message to the user, you could store the
                // requested file URI in isolated storage and add it to the queue later.
                if (LnaguageClass.LanguageSelect == 1)
                {
                    MessageBox.Show("تجاوز عدد الايات الكلي عدد العناصر المسموح لتنزيلها معا وهي 25 عنصر لذالك قلل عدد السور ");
                }
                else
                {
                    MessageBox.Show("The maximum number of background file transfer requests for this application has been exceeded. ");
                }
                return;
            }

            // Get the URI of the file to be transferred from the Tag property
            // of the button that was clicked.
            // Get the Uri
            string transferFileName = "http://server" + managment.serverNumber(LnaguageClass.OtherFolderName) + ".mp3quran.net/" + LnaguageClass.OtherFolderName + "/" + ((Button)sender).Tag as string + ".mp3";

            //string transferFileName =
            Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);


            // Create the new transfer request, passing in the URI of the file to
            // be transferred.
            BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);

            // Set the transfer method. GET and POST are supported.
            transferRequest.Method = "GET";
            // Get the file name from the end of the transfer URI and create a local URI
            // in the "transfers" directory in isolated storage.
            string downloadFile = LnaguageClass.OtherFolderName + transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
            //  MessageBox.Show("/shared/transfers/" + LnaguageClass.OtherFolderName +  downloadFile);
            Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);

            transferRequest.DownloadLocation = downloadUri;

            // Pass custom data with the Tag property. In this example, the friendly name
            // is passed.
            transferRequest.Tag = downloadFile;
            // If the Wi-Fi-only check box is not checked, then set the TransferPreferences
            // to allow transfers over a cellular connection.
            if (wifiOnlyCheckbox.IsChecked == false)
            {
                transferRequest.TransferPreferences = TransferPreferences.AllowCellular;
            }
            if (externalPowerOnlyCheckbox.IsChecked == false)
            {
                transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
            }
            if (wifiOnlyCheckbox.IsChecked == false && externalPowerOnlyCheckbox.IsChecked == false)
            {
                transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
            }
            // Add the transfer request using the BackgroundTransferService. Do this in
            // a try block in case an exception is thrown.
            try
            {
                BackgroundTransferService.Add(transferRequest);
                nb.IsEnabled = false;
            }
            catch (InvalidOperationException ex)
            {
                if (LnaguageClass.LanguageSelect == 1)
                {
                    MessageBox.Show("هذه السورة تم اضافتها الى قائمة التحميل سابقا");
                }
                else
                {
                    MessageBox.Show("Unable to add background transfer request. " + ex.Message);
                }
            }
            catch (Exception)
            {
                if (LnaguageClass.LanguageSelect == 1)
                {
                    MessageBox.Show("  لا يمكن اضافةالاية الى عناصر قائمة التحميل");
                }
                else
                {
                    MessageBox.Show("Unable to add background transfer request.");
                }
            }
        }