Inheritance: IBackgroundDownloader, IBackgroundTransferBase
Esempio n. 1
0
        private async void getInfo()
        {
            StorageFile myDB;
            try
            {
                string address = @"http://artmordent.ru/cheataxi/multiplylines.cr";
                StorageFile tempFile2 = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("info", CreationCollisionOption.ReplaceExisting);
                BackgroundDownloader manager2 = new BackgroundDownloader();
                var operation = manager2.CreateDownload(new Uri(address), tempFile2);
                IProgress<DownloadOperation> progressH = new Progress<DownloadOperation>((p) => { });
                await operation.StartAsync().AsTask(progressH);                
                myDB = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("info");
                
                // Read the data
                var alldata = await Windows.Storage.FileIO.ReadLinesAsync(myDB);
                string[] datalines = new string[alldata.Count];
                Int32 ko = 0;
                foreach (var line in alldata)
                {
                    datalines[ko] = line.ToString();
                    ko++;
                    infoBlockMain.Text += line.ToString() + "\r\n";
                }
                
                await myDB.DeleteAsync();


            }
            catch (Exception ex)
            {
                MessageDialog dialog = new MessageDialog("Ошибка загрузки информации. Проверьте ваше соединение или попробуйте позже.", "Ошибка загрузки");
            }
        }
        public static async Task<Episode> DownloadPodcastEpisodeAsync(Episode episode, Action<DownloadOperation> callback, Action errorCallback = null)
        {
            var appFolder = await KnownFolders.MusicLibrary.CreateFolderAsync("PodcastR", CreationCollisionOption.OpenIfExists);
            var podcastFolder = await appFolder.CreateFolderAsync(episode.Podcast.Name, CreationCollisionOption.OpenIfExists);
            try
            {
                var uri = new Uri(episode.WebPath);
                var extension = uri.AbsolutePath.GetExtension();
                var fileName = (episode.Name + extension).RemoveIllegalPathChars().Replace(":", "");
                var episodeFile = await podcastFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                var backgroundDownloader = new BackgroundDownloader();
                var downloadOperation = backgroundDownloader.CreateDownload(uri, episodeFile);
                var progress = new Progress<DownloadOperation>(callback);
                downloads.Add(episode, downloadOperation);
                var cts = new CancellationTokenSource();
                cancellationTokenSources.Add(episode, cts);

                await downloadOperation.StartAsync().AsTask(cts.Token, progress);

                downloads.Remove(episode);
                cancellationTokenSources.Remove(episode);
                episode.IsLocal = true;
                episode.WebPath = episodeFile.Path;
                return episode;
            }
            catch
            {
                if (errorCallback != null)
                    errorCallback();
                return episode;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// download a file 
        /// </summary>
        /// <param name="fileUrl">fileUrl</param>
        /// <param name="destinationFile">file's destination</param>
        /// <param name="downloadProgress">a action that can show the download progress</param>
        /// <param name="priority">background transfer priority </param>
        /// <param name="requestUnconstrainedDownload"></param>
        /// <returns></returns>
        public static async Task DownLoadSingleFileAsync(string fileUrl, IStorageFile destinationFile, Action<DownloadOperation> downloadProgress =null
        , BackgroundTransferPriority priority = BackgroundTransferPriority.Default, bool requestUnconstrainedDownload = false)
        {
            Uri source;
            if (!Uri.TryCreate(fileUrl, UriKind.Absolute, out source))
            {
                // Logger.Info("File Url:" + fileUrl + "is not valid URIs");
                Debug.WriteLine("File Url:" + fileUrl + "is not valid URIs");
                return;
            }
            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation download = downloader.CreateDownload(source, destinationFile);
            download.Priority = priority;

            Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}",
                source.AbsoluteUri, destinationFile.Name, priority, download.Guid));

            if (!requestUnconstrainedDownload)
            {
                // Attach progress and completion handlers.
                await HandleDownloadAsync(download, true, downloadProgress);
                return;

            }
        }
Esempio n. 4
0
		public static async Task<bool> Download(Revista rev, Func<IStorageFile, Task> onSucess, Action<string> callBack, Action<double> progressHandler)
		{
			if(!HaveInternetConnection())
			{
				callBack("Sem conexão à Internet");
				return false; 
			}

			BackgroundDownloader bg = new BackgroundDownloader();

			var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(RevistaControllerWrapper.FolderName, CreationCollisionOption.OpenIfExists);
			var file = await folder.CreateFileAsync(RevistaControllerWrapper.GetPdfName(rev), CreationCollisionOption.ReplaceExisting);

			DownloadHelper down = new DownloadHelper(); ;
			try
			{
				var d = bg.CreateDownload(RevistaController.Instance.GetDownloadFile(rev), file);

				await down.HandleDownloadAsync(d, true, onSucess, callBack, progressHandler);
			}
			catch
			{
				return false;
			}
			return true ;
		}
Esempio n. 5
0
        //string imagerySet = MapType.Aerial.ToString();

        public async Task<WriteableBitmap> RequestImage(Geopoint point)
        {
            
            if (geo == null)
            {
                geo = new Geolocator();
            }
            Geoposition pos = await geo.GetGeopositionAsync();
            //Geopoint point = pos.Coordinate.Point;

            myMap.Center = new Location(point.Position.Latitude, point.Position.Longitude);
            myMap.ZoomLevel = 2;
            myMap.Width = 100;
            this.myMap.Height = 100;
            string url = String.Format("http://dev.virtualearth.net/REST/v1/Imagery/Map/{0}/{1},{2}/{3}" +
                                  "?mapSize={4},{5}&key={6}",
                               //imagerySet,
                               this.myMap.Center.Latitude,
                               this.myMap.Center.Longitude,
                               Math.Floor(this.myMap.ZoomLevel),
                               this.myMap.Width,
                               this.myMap.Height,
                               apiKey);


            var backgroundDownloader = new BackgroundDownloader();
            var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("tempmapimage.jpg",
                CreationCollisionOption.ReplaceExisting);
            var downloadOperation = backgroundDownloader.CreateDownload(new Uri(url), file);

            await downloadOperation.StartAsync();
            return await BitmapFactory.New(1, 1).FromStream(await file.OpenReadAsync(),
                Windows.Graphics.Imaging.BitmapPixelFormat.Unknown);
        }
Esempio n. 6
0
		private async void Button_Click(object sender, RoutedEventArgs e)
		{
			var source = new Uri("http://download.thinkbroadband.com/5MB.zip", UriKind.Absolute);
			var destination = await KnownFolders
				.PicturesLibrary
				.CreateFileAsync("5MB.zip", CreationCollisionOption.GenerateUniqueName);

			var downloader = new BackgroundDownloader();

			// Toast notification para sucesso
			var successToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
			successToastXml.GetElementsByTagName("text").Item(0).InnerText =
				"Download Concluído.";
			var successToast = new ToastNotification(successToastXml);
			downloader.SuccessToastNotification = successToast;

			// Toast notification para falha
			var failureToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
			failureToastXml.GetElementsByTagName("text").Item(0).InnerText =
				"Falha no download.";
			var failureToast = new ToastNotification(failureToastXml);
			downloader.FailureToastNotification = failureToast;

			var downloadOperation = downloader.CreateDownload(source, destination);
			downloadOperation.Priority = BackgroundTransferPriority.High;

			var progressCallback = new Progress<DownloadOperation>(DownloadProgress);
			await downloadOperation.StartAsync().AsTask(new CancellationToken(), progressCallback);
			;
		}
Esempio n. 7
0
        private static async Task<StorageFile> SaveFileFromUriAsync(Uri fileUri, string localFileName, string localPath = "Images", NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting)
        {
            if (localFileName.StartsWith("/"))
                localFileName = localFileName.Substring(1);

            localFileName = Path.GetFileName(localFileName);
            
            var destinationFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync(localPath, CreationCollisionOption.OpenIfExists);

            var outFile = await destinationFolder.CreateFileAsync(localFileName, CreationCollisionOption.OpenIfExists);
            if((await outFile.GetBasicPropertiesAsync()).Size == 0)
            {
                BackgroundDownloader backgroundDownloader = new BackgroundDownloader();
                var download = backgroundDownloader.CreateDownload(fileUri, outFile);
                try
                {
                    download.CostPolicy = BackgroundTransferCostPolicy.Always;
                    var downloadTask = download.StartAsync();
                    await downloadTask;
                }
                catch
                {
                }

            }
            return outFile;
        }
Esempio n. 8
0
 public static async Task<DownloadItem> Create(BackgroundDownloader b, string url)
 {
     DownloadItem item = new DownloadItem();
     item.Downloader = b;
     item.Url = url;
     await item.Construct();   
     return item;
 }
Esempio n. 9
0
        private async void StartDownload(BackgroundTransferPriority priority,bool requestUnconstrainedDownload,string downloadLink,string destination) {
            // Validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
            // the "Home or Work Networking" capability.
            Uri source;
            if(!Uri.TryCreate(downloadLink,UriKind.Absolute,out source)) {
                Debug.WriteLine("Invalid URI.");
                return;
            }

            if(string.IsNullOrWhiteSpace(destination)) {
                Debug.WriteLine("A local file name is required.");
                return;
            }

            StorageFile destinationFile;
            try {
                destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                    destination,
                    CreationCollisionOption.GenerateUniqueName);
            }
            catch(FileNotFoundException ex) {
                Debug.WriteLine("Error while creating file: " + ex.Message );
                return;
            }

            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation download = downloader.CreateDownload(source,destinationFile);

            Debug.WriteLine(String.Format(CultureInfo.CurrentCulture,"Downloading {0} to {1} with {2} priority, {3}",
                source.AbsoluteUri,destinationFile.Name,priority,download.Guid));

            download.Priority = priority;

            if(!requestUnconstrainedDownload) {
                // Attach progress and completion handlers.
                await HandleDownloadAsync(download,true);
                return;
            }

            List<DownloadOperation> requestOperations = new List<DownloadOperation>();
            requestOperations.Add(download);

            // If the app isn't actively being used, at some point the system may slow down or pause long running
            // downloads. The purpose of this behavior is to increase the device's battery life.
            // By requesting unconstrained downloads, the app can request the system to not suspend any of the
            // downloads in the list for power saving reasons.
            // Use this API with caution since it not only may reduce battery life, but it may show a prompt to
            // the user.
            UnconstrainedTransferRequestResult result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations);

            Debug.WriteLine(String.Format(CultureInfo.CurrentCulture,"Request for unconstrained downloads has been {0}",
                (result.IsUnconstrained ? "granted" : "denied")));

            await HandleDownloadAsync(download,true);
        }
Esempio n. 10
0
        /// <summary>
        /// Overrides the base execute logic to use the background downloader to download the file.
        /// </summary>
        protected async override void OnExecute()
        {
            BT.BackgroundDownloader downloader;
            if (this.Url.OriginalString.StartsWith(this.LiveClient.ApiEndpoint, StringComparison.OrdinalIgnoreCase))
            {
                if (base.RefreshTokenIfNeeded())
                {
                    return;
                }

                downloader = new BT.BackgroundDownloader();
                if (this.LiveClient.Session != null)
                {
                    downloader.SetRequestHeader(
                        ApiOperation.AuthorizationHeader,
                        AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken);
                }
                downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());
            }
            else
            {
                downloader = new BT.BackgroundDownloader();
            }

            downloader.Group = LiveConnectClient.LiveSDKDownloadGroup;
            this.cts         = new CancellationTokenSource();
            this.downloadOp  = downloader.CreateDownload(this.Url, this.OutputFile);
            var progressHandler = new Progress <BT.DownloadOperation>(this.OnDownloadProgress);

            LiveDownloadOperationResult result = null;
            Exception webError = null;

            try
            {
                this.downloadOp = await this.downloadOp.StartAsync().AsTask(this.cts.Token, progressHandler);

                result = this.OutputFile != null ?
                         new LiveDownloadOperationResult(this.OutputFile) :
                         new LiveDownloadOperationResult(this.downloadOp.GetResultStreamAt(0));
            }
            catch (TaskCanceledException)
            {
                result = new LiveDownloadOperationResult(null, true);
            }
            catch (Exception error)
            {
                webError = error;
            }

            if (webError != null)
            {
                result = await this.ProcessDownloadErrorResponse(webError);
            }

            this.OnOperationCompleted(result);
        }
Esempio n. 11
0
        public async void download(String url, Folder folder)
        {

            var uri = new Uri(url);
            var downloader = new BackgroundDownloader();
            StorageFile file = await folder.CreateFileAsync("100MB.zip",
                CreationCollisionOption.ReplaceExisting);
            DownloadOperation download = downloader.CreateDownload(uri, file);
            download.StartAsync();
        }
Esempio n. 12
0
 private async void DownloadClick(object sender, RoutedEventArgs e)
 {
     const string fileLocation
      = "http://www.vulcanlab.net/download/Release.rar";
     var uri = new Uri(fileLocation);
     var downloader = new BackgroundDownloader();
     StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("100MB.zip",
         CreationCollisionOption.ReplaceExisting);
     DownloadOperation download = downloader.CreateDownload(uri, file);
     await StartDownloadAsync(download);
 }
        public async Task<StorageFile> DownloadFileAsync(
            string appFolderName,
            string folderName,
            string fileName,
            string fileUrl,
            Action<DownloadOperation> callback,
            Action<Exception> errorCallback = null)
        {
            var appFolder = await KnownFolders.MusicLibrary.CreateFolderAsync(appFolderName, CreationCollisionOption.OpenIfExists);
            var podcastFolder = await appFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);
            var uri = new Uri(fileUrl);
            var extension = uri.AbsolutePath.GetExtension();
            var filename = (fileName + extension).RemoveIllegalPathChars();

            try
            {
                var file = await podcastFolder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists);
                var backgroundDownloader = new BackgroundDownloader();
                var downloadOperation = backgroundDownloader.CreateDownload(uri, file);

                var progress = new Progress<DownloadOperation>(callback);
                downloads.Add(fileUrl, downloadOperation);

                var cts = new CancellationTokenSource();
                cancellationTokenSources.Add(fileUrl, cts);

                await downloadOperation.StartAsync().AsTask(cts.Token, progress);

                downloads.Remove(fileUrl);
                cancellationTokenSources.Remove(fileUrl);
                return file;
            }
            catch (NullReferenceException ex)
            {
                if (errorCallback != null)
                    errorCallback(ex);
                return null;
            }
            catch (Exception)
            {
                try
                {
                    var file = await podcastFolder.GetFileAsync(filename);
                    return file;
                }
                catch (Exception ex)
                {
                    if (errorCallback != null)
                        errorCallback(ex);
                    return null;
                }
            }

        }
Esempio n. 14
0
        private async void StartDownload(BackgroundTransferPriority priority,bool requestUnconstrainedDownload,string url,string fileNameField) {
            Uri source;
            if(!Uri.TryCreate(url.Trim(),UriKind.Absolute,out source)) {
                //rootPage.NotifyUser("Invalid URI.",NotifyType.ErrorMessage);
                return;
            }

            string destination = fileNameField.Trim() + ".zip";

            if(string.IsNullOrWhiteSpace(destination)) {
                destination = fileNameField.Trim();
            }

            StorageFile destinationFile;
            try {
                destinationFile = await KnownFolders.VideosLibrary.CreateFileAsync(
                    destination,
                    CreationCollisionOption.GenerateUniqueName);
            }
            catch {
                return;
            }

            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation download = downloader.CreateDownload(source,destinationFile);

            //Log(String.Format(CultureInfo.CurrentCulture,"Downloading {0} to {1} with {2} priority, {3}",
            //    source.AbsoluteUri,destinationFile.Name,priority,download.Guid));

            download.Priority = priority;

            if(!requestUnconstrainedDownload) {
                // Attach progress and completion handlers.
                await HandleDownloadAsync(download,true);
                return;
            }

            List<DownloadOperation> requestOperations = new List<DownloadOperation>();
            requestOperations.Add(download);

            // If the app isn't actively being used, at some point the system may slow down or pause long running
            // downloads. The purpose of this behavior is to increase the device's battery life.
            // By requesting unconstrained downloads, the app can request the system to not suspend any of the
            // downloads in the list for power saving reasons.
            // Use this API with caution since it not only may reduce battery life, but it may show a prompt to
            // the user.
            UnconstrainedTransferRequestResult result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations);

            //Log(String.Format(CultureInfo.CurrentCulture,"Request for unconstrained downloads has been {0}",
            //(result.IsUnconstrained ? "granted" : "denied")));

            await HandleDownloadAsync(download,true);
        }
Esempio n. 15
0
        public async Task<string> GetAsync(string request)
        {
            var backgroundDownloader = new BackgroundDownloader();
            var temporaryFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(Utils.TemporaryFile, CreationCollisionOption.OpenIfExists);
            var downloader = backgroundDownloader.CreateDownload(
                new Uri(request),
                temporaryFile);
            await downloader.StartAsync();

            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(Utils.TemporaryFile, CreationCollisionOption.OpenIfExists);
            return await FileIO.ReadTextAsync(file);
        }
 /// <summary>
 /// 要下载调用这个方法
 /// </summary>
 /// <param name="url">下载的文件网址的来源</param>
 /// <returns></returns>
 public static async Task Start(string filename,string url,DownloadType type,StorageFolder folder=null)
 {
     try
     {
         Uri uri = new Uri(Uri.EscapeUriString(url), UriKind.RelativeOrAbsolute);
         BackgroundDownloader downloader = new BackgroundDownloader();
         if (folder==null)
         {
             folder = await KnownFolders.MusicLibrary.CreateFolderAsync("kgdownload", CreationCollisionOption.OpenIfExists);
             switch (type)
             {
                 case DownloadType.song:
                     folder = await folder.CreateFolderAsync("song", CreationCollisionOption.OpenIfExists);
                     downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("song");
                     break;
                 case DownloadType.mv:
                     folder = await folder.CreateFolderAsync("mv", CreationCollisionOption.OpenIfExists);
                     downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("mv");
                     break;
                 case DownloadType.other:
                     folder = await folder.CreateFolderAsync("other", CreationCollisionOption.OpenIfExists);
                     downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
                     break;
                 default:
                     break;
             }
         }else
         {
             downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
         }
         //string name = uri.ToString().Substring(uri.ToString().LastIndexOf("/"), uri.ToString().Length);
         string name = filename;
         StorageFile file = await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName);
         downloader.FailureToastNotification = DownloadedToast.Done(filename, DownloadedToast.DownResult.Fa);
         downloader.SuccessToastNotification = DownloadedToast.Done(filename, DownloadedToast.DownResult.Su);
         var download = downloader.CreateDownload(new Uri(url), file);
         TransferModel transfer = new TransferModel();
         transfer.DownloadOperation = download;
         transfer.Source = download.RequestedUri.ToString();
         transfer.Destination = download.ResultFile.Path;
         transfer.BytesReceived = download.Progress.BytesReceived;
         transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive;
         transfer.Progress = 0;
         transfers.Add(transfer);
         Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
         download.StartAsync().AsTask(cancelToken.Token, progressCallback);
     }
     catch
     {
         await new MessageDialog("链接已失效!").ShowAsync();
     }
 }
        public static BackgroundDownloader CreateBackgroundDownloader()
        {
            BackgroundTransferCompletionGroup completionGroup = new BackgroundTransferCompletionGroup();

            BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
            builder.TaskEntryPoint = "Tasks.CompletionGroupTask";
            builder.SetTrigger(completionGroup.Trigger);

            BackgroundTaskRegistration taskRegistration = builder.Register();

            BackgroundDownloader downloader = new BackgroundDownloader(completionGroup);

            return downloader;
        }
Esempio n. 18
0
        // 非同期ダウンロードする
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            // ダウンロードしたファイルの保存先を指定する
            var uri = new Uri("http://download.thinkbroadband.com/100MB.zip");
//            var uri = new Uri("{バックグランドでダウンロードするファイルのURL}");

            var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("example.zip", 
                Windows.Storage.CreationCollisionOption.ReplaceExisting);

            // バックグランドで非同期ダウンロードする
            var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
            DownloadOperation downloadOperation = downloader.CreateDownload(uri, file);
            var progress = new Progress<DownloadOperation>(NotificationProgress);
            await downloadOperation.StartAsync().AsTask(progress);
        }
Esempio n. 19
0
        private async static Task<StorageFile> SaveAsync(
              Uri fileUri,
              StorageFolder folder,
              string fileName)
        {
            var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
            var downloader = new BackgroundDownloader();
            var download = downloader.CreateDownload(
                fileUri,
                file);

            var res = await download.StartAsync();

            return file;
        }
Esempio n. 20
0
        public async static Task SaveAsync(
           Uri fileUri,
           StorageFolder folder,
           string fileName)
        {
            // Hitting System.UnauthorizedAccessException when the file already exists.
            // If they already have it, keep what is there.
            var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);
            var downloader = new BackgroundDownloader();
            var download = downloader.CreateDownload(
                fileUri,
                file);

            await download.StartAsync();
        }
Esempio n. 21
0
        private async void getPlaceFromCoordinates(Windows.Foundation.Point pos)
        {
            // Get world coordinates
            myMap.TryPixelToLocation(pos, out location);
            myMap.SetView(location);
            // Form request
            string tmpSourseLoc = Convert.ToString(location.Latitude).Substring(0, Convert.ToString(location.Latitude).IndexOf(',')) + '.' + Convert.ToString(location.Latitude).Substring(Convert.ToString(location.Latitude).IndexOf(',') + 1, Convert.ToString(location.Latitude).Length - Convert.ToString(location.Latitude).IndexOf(',') - 1);
            tmpSourseLoc += "," + Convert.ToString(location.Longitude).Substring(0, Convert.ToString(location.Longitude).IndexOf(',')) + '.' + Convert.ToString(location.Longitude).Substring(Convert.ToString(location.Longitude).IndexOf(',') + 1, Convert.ToString(location.Longitude).Length - Convert.ToString(location.Longitude).IndexOf(',') - 1);
            string address = "http://geocode-maps.yandex.ru/1.x/?geocode=" + tmpSourseLoc + "&sco=latlong";
                //log1.Text += address;
            StorageFile myDB;
            try
            {
                // Send request
                StorageFile tempFile2 = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("multi", CreationCollisionOption.ReplaceExisting);
                BackgroundDownloader manager2 = new BackgroundDownloader();
                var operation = manager2.CreateDownload(new Uri(address), tempFile2);
                IProgress<DownloadOperation> progressH = new Progress<DownloadOperation>((p) =>
                { /* Debug.WriteLine("Transferred: {0}, Total: {1}", p.Progress.BytesReceived, p.Progress.TotalBytesToReceive); */ });
                await operation.StartAsync().AsTask(progressH);
                 //Debug.WriteLine("BacgroundTransfer created");

                // Write answer
                myDB = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("multi");
                var alldata = await Windows.Storage.FileIO.ReadLinesAsync(myDB);
                datalines = new string[alldata.Count];
                int ko = 0; int start;
                // Analise answer
                foreach (var line in alldata)
                {
                    datalines[ko] = line.ToString();
                    ko++;
                    if ((start = datalines[ko - 1].IndexOf("<text>")) != -1)
                    {
                        // Print adress
                        int nameLeng = datalines[ko - 1].Length;
                        if (!isSourseTapped) sourseLable.Text = datalines[ko - 1].Substring(start + 6, nameLeng - 6 - start - 7);
                        else aimLable.Text = datalines[ko - 1].Substring(start + 6, nameLeng - 6 - start - 7);
                        break;
                    }
                }
                await myDB.DeleteAsync();
            }
            catch
            {
                MessageDialog dialog = new MessageDialog("Мы не смогли обнаружить ничего рядом с данной меткой. Однако вы все равно можете попробовать построить маршрут, используя её.", "Ничего не найдено!");
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Downloads a file from the specified address and returns the file.
        /// </summary>
        /// <param name="fileUri">The URI of the file.</param>
        /// <param name="folder">The folder to save the file to.</param>
        /// <param name="fileName">The file name to save the file as.</param>
        /// <param name="option">
        /// A value that indicates what to do
        /// if the filename already exists in the current folder.
        /// </param>
        /// <remarks>
        /// If no file name is given - the method will try to find
        /// the suggested file name in the HTTP response
        /// based on the Content-Disposition HTTP header.
        /// </remarks>
        /// <returns></returns>
        public async static Task<StorageFile> SaveAsync(
            Uri fileUri,
            StorageFolder folder = null,
            string fileName = null,
            NameCollisionOption option = NameCollisionOption.GenerateUniqueName)
        {
            if (folder == null)
            {
                folder = ApplicationData.Current.LocalFolder;
            }

            var file = await folder.CreateTempFileAsync();
            var downloader = new BackgroundDownloader();
            var download = downloader.CreateDownload(
                fileUri,
                file);

            var res = await download.StartAsync();

            if (string.IsNullOrEmpty(fileName))
            {
                // Use temp file name by default
                fileName = file.Name;

                // Try to find a suggested file name in the http response headers
                // and rename the temp file before returning if the name is found.
                var info = res.GetResponseInformation();

                if (info.Headers.ContainsKey("Content-Disposition"))
                {
                    var cd = info.Headers["Content-Disposition"];
                    var regEx = new Regex("filename=\"(?<fileNameGroup>.+?)\"");
                    var match = regEx.Match(cd);

                    if (match.Success)
                    {
                        fileName = match.Groups["fileNameGroup"].Value;
                        await file.RenameAsync(fileName, option);
                        return file;
                    }
                }
            }

            await file.RenameAsync(fileName, option);
            return file;
        }
Esempio n. 23
0
 public static async Task<bool> AddDownload(string filename, string url, DownloadType type, StorageFolder folder = null)
 {
     try
     {
         var down = new BackgroundDownloader();
         down.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
         if (folder == null)
         {
             folder = await KnownFolders.MusicLibrary.GetFolderAsync("kgdownload");
             switch (type)
             {
                 case DownloadType.song:
                     folder = await folder.GetFolderAsync("song");
                     down.TransferGroup = BackgroundTransferGroup.CreateGroup("song");
                     break;
                 case DownloadType.mv:
                     folder = await folder.GetFolderAsync("mv");
                     down.TransferGroup = BackgroundTransferGroup.CreateGroup("mv");
                     break;
                 case DownloadType.other:
                     folder = await folder.GetFolderAsync("other");
                     down.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
                     break;
                 default:
                     break;
             }
         }
         var files= (await folder.GetFilesAsync()).ToList();
         foreach (var item in files)
         {
             await item.DeleteAsync();
         }
         var file = await folder.CreateFileAsync(filename);
         down.FailureToastNotification = DownloadToast(filename, DownloadResult.Failure);
         down.SuccessToastNotification = DownloadToast(filename, DownloadResult.Success);
         var opera= down.CreateDownload(new Uri(url), file);
         opera.CostPolicy = BackgroundTransferCostPolicy.Always;
         opera.StartAsync();
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
Esempio n. 24
0
        //private Boolean _toastOnce = false;
        //ErrorVisualizer errorVisualizier = new ErrorVisualizer();
        #endregion
        #region Constructors
        /// <summary>
        /// Constructor with encryption username and password
        /// </summary>
        /// <param name="sh_url">URL to Server</param>
        /// <param name="sh_path">Path to JSON</param>
        /// <param name="sh_port">Serverport</param>
        /// <param name="sh_username">Username</param>
        /// <param name="sh_password">Passwort</param>
        public ImageCacheManager(String sh_url, String sh_path, Int32 sh_port, String sh_username, String sh_password, Boolean isHTTPSOn)
        {
            this.sh_url = sh_url;
            this.sh_path = sh_path;
            this.sh_port = sh_port;
            this.sh_username = sh_username;
            this.sh_passwort = sh_password;
            //this.sh_uriBuilder = new UriBuilder("http", this.sh_url, this.sh_port, "/rest/sitemaps/");
            this.secured = isHTTPSOn;
            if (secured)
            {
                try
                {
                    uriToOpenHAB = new UriBuilder(sh_url);
                }
                catch (ArgumentNullException ex)
                {
                    //Happens when the HostName could not parsed
                }
                catch (FormatException ex)
                {
                    //Is equal to UriFormatException
                }
                filter = new HttpBaseProtocolFilter();
                /**
                 * Ignore some Certifcateerrors
                 * */
                filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
                filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired);
                filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidName);
                filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.IncompleteChain);
                filter.ServerCredential = new PasswordCredential("winHAB", this.sh_username, this.sh_passwort);
                /**
                 * Establish HttpClient
                 * */
                backgroundDownloader = new BackgroundDownloader();
                backgroundDownloader.ServerCredential = new PasswordCredential("winHAB", this.sh_username, this.sh_passwort);
            }
            else if (!secured)
            {

            }
        }
Esempio n. 25
0
        private static async void DoDownload()
        {
            try
            {
                Uri uri = new Uri("http://kiewic.com");

                IStorageFile resultFile = await KnownFolders.PicturesLibrary.CreateFileAsync("blah.html", CreationCollisionOption.GenerateUniqueName);

                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation download = downloader.CreateDownload(uri, resultFile);
                await download.StartAsync();

                Debug.WriteLine(download.Progress.Status);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
Esempio n. 26
0
        // Click on find-adress button
        // Forming omniBox
        private async void button5_Click(object sender, RoutedEventArgs e)
        {
            string address = "http://geocode-maps.yandex.ru/1.x/?geocode=" + textBox.Text;            
            StorageFile myDB;
            try
            {
                listBox.Visibility = Visibility.Visible;
                controlsBG2.Visibility = Visibility.Visible;
                controlsBG.Visibility = Visibility.Collapsed;
                listBox.Items.Clear();
                StorageFile tempFile2 = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("multi", CreationCollisionOption.ReplaceExisting);
                BackgroundDownloader manager2 = new BackgroundDownloader();
                var operation = manager2.CreateDownload(new Uri(address), tempFile2);
                IProgress<DownloadOperation> progressH = new Progress<DownloadOperation>((p) =>
                { /*Debug.WriteLine("Transferred: {0}, Total: {1}", p.Progress.BytesReceived, p.Progress.TotalBytesToReceive);*/ });
                await operation.StartAsync().AsTask(progressH);
                    //Debug.WriteLine("BacgroundTransfer created");
                
                // Read the data
                myDB = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("multi");
                var alldata = await Windows.Storage.FileIO.ReadLinesAsync(myDB);
                datalines = new string[alldata.Count];
                int ko = 0; // counter
                int start; // first no-hashtag sybol in string
                foreach (var line in alldata)
                {
                    datalines[ko] = line.ToString();
                    ko++;
                    if ((start = datalines[ko - 1].IndexOf("<text>")) != -1)
                    {
                        // forming omniBox
                        int nameLeng = datalines[ko - 1].Length;
                        listBox.Items.Add(datalines[ko - 1].Substring(start + 6, nameLeng - 6 - start - 7));
                    }
                }
                await myDB.DeleteAsync();

            }
            catch (Exception)
            {
                MessageDialog dialog = new MessageDialog("Ошибка при поиске Вашего запроса. Очистите карту и попробуйте построить маршрут снова.", "Ошибка поиска #007101");
            }
        }
Esempio n. 27
0
 private async void DownloadFile()
 {
     try
     {
         var source = new Uri(SelectedMusic.file, UriKind.Absolute);
         var destinationFile =
             await
                 KnownFolders.MusicLibrary.CreateFileAsync(SelectedMusic.title + ".mp3",
                     CreationCollisionOption.ReplaceExisting);
         var downloader = new BackgroundDownloader();
         var download = downloader.CreateDownload(source, destinationFile);
         await download.StartAsync().AsTask(new CancellationToken(), new Progress<DownloadOperation>());
     }
     catch (Exception e)
     {
         new MessageDialog(loader.GetString("ErrorDowload")).ShowAsync();
     }
     new MessageDialog(loader.GetString("DownloadOk")).ShowAsync();
 }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string serverAddressField = "http://distribution.bbb3d.renderfarming.net//video/png/00_00/0001.png";
            Uri source = new Uri(serverAddressField);

            string destination = "TEST.png";

            StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                destination, CreationCollisionOption.GenerateUniqueName);

            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation download = downloader.CreateDownload(source, destinationFile);

            Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);

           // await download.StartAsync();

            await download.StartAsync().AsTask(cts.Token,progressCallback);

        }
Esempio n. 29
0
        private async void doLoadBG()
        {
            try
            {
                System.Xml.Linq.XDocument xmlDoc = XDocument.Load("http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US");
                IEnumerable<string> strTest = from node in xmlDoc.Descendants("url") select node.Value;
                string strURL = "http://www.bing.com" + strTest.First();

                Uri source = new Uri(strURL);
                StorageFile destinationFile;
                try
                {
                    destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("raindropBG.jpg",
                        CreationCollisionOption.ReplaceExisting);
                }
                catch (FileNotFoundException ex)
                {
                    return;
                }
                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation download = downloader.CreateDownload(source, destinationFile);
                await download.StartAsync();
                ResponseInformation response = download.GetResponseInformation();

                Uri imageUri;
                BitmapImage image = null;

                if (Uri.TryCreate(destinationFile.Path, UriKind.RelativeOrAbsolute, out imageUri))
                {
                    image = new BitmapImage(imageUri);
                }

                imgBrush.ImageSource = image;

            }
            catch
            {
                //
            }

        }
        /// <summary>
        /// Overrides the base execute logic to use the background downloader to download the file.
        /// </summary>
        protected async override void OnExecute()
        {
            var loginResult = await this.LiveClient.Session.AuthClient.GetLoginStatusAsync();
            if (loginResult.Error != null)
            {
                this.taskCompletionSource.SetException(loginResult.Error);
                return;
            }
            else
            {
                var downloader = new BackgroundDownloader();
                downloader.SetRequestHeader(
                        ApiOperation.AuthorizationHeader,
                        AuthConstants.BearerTokenType + " " + loginResult.Session.AccessToken);
                downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());

                downloader.Group = LiveConnectClient.LiveSDKDownloadGroup;
                this.downloadOp = downloader.CreateDownload(this.Url, this.OutputFile);
                this.taskCompletionSource.SetResult(new LiveDownloadOperation(downloadOp));
            }
        }
Esempio n. 31
0
        private async void Save_Click(object sender, RoutedEventArgs e) {
            var image = ImagesList.SelectedItem as ImageResult;
            if (image == null) return;

            var uri = new Uri(image.MediaUrl);
            var filename = uri.Segments[uri.Segments.Length - 1];
            var extension = System.IO.Path.GetExtension(filename);

            var picker = new FileSavePicker();
            picker.SuggestedFileName = filename;
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeChoices.Add(extension.Trim('.').ToUpper(), new string[] { extension });

            var saveFile = await picker.PickSaveFileAsync();
            if (saveFile != null) {
                Status.Text = "Download Started";
                var download = new BackgroundDownloader().CreateDownload(uri, saveFile);
                await download.StartAsync();
                Status.Text = "Download Complete";
            }
        }