DownloadDataTaskAsync() public method

public DownloadDataTaskAsync ( System address ) : System.Threading.Tasks.Task
address System
return System.Threading.Tasks.Task
Ejemplo n.º 1
0
        public static async Task BeginDownloadMinecraft(this MainWindow window)
        {
            window.LoadingBox.Visibility = Visibility.Visible;
            window.LoadingText.Content = "Updating Minecraft...";
            window.LoadingProgress.IsIndeterminate = true;
            if (!Directory.Exists(Globals.LauncherDataPath + @"\Minecraft")) Directory.CreateDirectory(Globals.LauncherDataPath + @"\Minecraft");
            if (!Directory.Exists(Globals.LauncherDataPath + @"\Minecraft\bin")) Directory.CreateDirectory(Globals.LauncherDataPath + @"\Minecraft\bin");
            if (!Directory.Exists(Globals.LauncherDataPath + @"\Minecraft\bin\natives")) Directory.CreateDirectory(Globals.LauncherDataPath + @"\Minecraft\bin\natives");
            WebClient c = new WebClient();
            try
            {
                
                if ((long)Settings.Default["CachedLWJGLTimestamp"] == null || LauncherInformation.Current.LWJGLTimestamp > (long)Settings.Default["CachedLWJGLTimestamp"])
                {
                    window.LoadingText.Content = "Downloading updated LWJGL...";
                    byte[] d = await c.DownloadDataTaskAsync(LauncherInformation.Current.LWJGLLocation);
                    
                    ZipFile f = ZipFile.Read(new MemoryStream(d));
                    f.ExtractAll(Globals.LauncherDataPath + @"\Minecraft\bin", ExtractExistingFileAction.OverwriteSilently);

                    Settings.Default["CachedLWJGLTimestamp"] = LauncherInformation.Current.LWJGLTimestamp;
                    Settings.Default.Save();
                }
                if((long)Settings.Default["CachedMinecraftTimestamp"] == null || LauncherInformation.Current.MinecraftTimestamp > (long)Settings.Default["CachedMinecraftTimestamp"])
                {
                    MessageBoxResult r = MessageBox.Show("Do you want to update Minecraft? (Latest version: " + LauncherInformation.Current.MinecraftVersion + ")", "MCLauncher", MessageBoxButton.YesNo, MessageBoxImage.Question);

                    if (r == MessageBoxResult.Yes)
                    {
                        window.LoadingText.Content = "Downloading Minecraft " + LauncherInformation.Current.MinecraftVersion + "...";
                        byte[] mc = await c.DownloadDataTaskAsync(LauncherInformation.Current.MinecraftLocation);

                        File.WriteAllBytes(Globals.LauncherDataPath + @"\Minecraft\bin\minecraft.jar", mc);
                        Settings.Default["CachedMinecraftTimestamp"] = LauncherInformation.Current.MinecraftTimestamp;
                        Settings.Default.Save();
                    }
                }
            }
            catch (WebException ex)
            {
                MessageBox.Show("Failed to update Minecraft. Is your internet down? Exception information: " + ex.ToString(), "An error has occured.", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                c.Dispose();
            }
            
        }
Ejemplo n.º 2
0
        private async Task <MemoryStream> InvokeCreation(Models.GenerationRequest data)
        {
            MemoryStream ms;
            var          path   = data.Template.Url;
            var          client = new System.Net.WebClient();

            var src = await client.DownloadDataTaskAsync(path);

            Scryber.Components.Document doc = null;

            using (ms = new MemoryStream(src))
            {
                doc = Scryber.Components.Document.ParseDocument(ms, path, ParseSourceType.RemoteFile);
            }

            if (data.Params != null)
            {
                foreach (var p in data.Params)
                {
                    doc.Params[p.Key] = p.Value;
                }
            }



            ms = new MemoryStream();

            doc.SaveAsPDF(ms, true);


            return(ms);
        }
Ejemplo n.º 3
0
        private static async void RunFetchLoopAsync(IActorRef publisher, string url, string source)
        {
            await Task.Yield();
            try
            {
                var c = new WebClient();
                while (true)
                {
                    var data = await c.DownloadDataTaskAsync(new Uri(url));
                    var str = Encoding.UTF8.GetString(data);
                    dynamic res = JsonConvert.DeserializeObject(str);
                    //   Console.WriteLine("Downloaded {0}",url);

                    foreach (var bus in res)
                    {
                        string id = bus.ID;
                        double lat = bus.Latitude;
                        double lon = bus.Longitude;

                        publisher.Tell(new Presenter.Position(lon, lat, id, source));
                    }

                    //how long should we wait before polling again?
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }
            catch
            {
                Console.WriteLine("Missing Route {0}", url);
            }
        }
Ejemplo n.º 4
0
		[Category("AndroidNotWorking")] // Attempts to access the test dll which won't work on Android
		public void DownloadData ()
		{
			WebClient wc;
			bool progress_changed = false;
			bool completed = false;
			bool progress_changed_error = false;
			bool completed_error = false;

			int thread_id = Thread.CurrentThread.ManagedThreadId;

			wc = new WebClient ();

			wc.DownloadProgressChanged += delegate {
				progress_changed = true;
				if (Thread.CurrentThread.ManagedThreadId != thread_id)
					progress_changed_error = true;
			};
			wc.DownloadDataCompleted += delegate {
				completed = true;
				if (Thread.CurrentThread.ManagedThreadId != thread_id)
					completed_error = true;
			};

			MessagePumpSyncContext.Run (async () => {
				var url = Assembly.GetExecutingAssembly ().CodeBase;
				await wc.DownloadDataTaskAsync (url);
				Assert.AreEqual (Thread.CurrentThread.ManagedThreadId, thread_id);
			}, () => progress_changed && completed, 10000);

			Assert.IsTrue (progress_changed, "#1");
			Assert.IsFalse (progress_changed_error, "#2");
			Assert.IsTrue (completed, "#3");
			Assert.IsFalse (completed_error, "#4");
		}
Ejemplo n.º 5
0
 private static IObservable<byte[]> CreateObservableTimePoller()
 {
     return Observable.Create<byte[]>(observer =>
     {
         var scheduler = Scheduler.Default;
         return scheduler.ScheduleAsync(async (schedulerController, cancelletionToken) =>
         {
             while (!cancelletionToken.IsCancellationRequested)
             {
                 var client = new WebClient();
                 client.Headers.Add("user-agent",
                     @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)");
                 try
                 {
                     var result = await client.DownloadDataTaskAsync("http://www.timeapi.org/utc/now");
                     observer.OnNext(result);
                 }
                 catch (Exception ex)
                 {
                     Console.WriteLine(ex);
                     observer.OnError(ex);
                 }
                 await schedulerController.Sleep(TimeSpan.FromMilliseconds(500), cancelletionToken);
             }
         });
     });
 }
Ejemplo n.º 6
0
 private async Task<byte[]> downloadImage(string path)
 {
     using (var wb = new WebClient())
     {
         return await wb.DownloadDataTaskAsync(path);
     }
 }
Ejemplo n.º 7
0
 public static async Task<string> DownloadPageAsync(string path)
 {
     using (var webClient = new WebClient())
     {
         return Encoding.UTF8.GetString(await webClient.DownloadDataTaskAsync(path));
     }
 }
Ejemplo n.º 8
0
        private static async Task<byte[]> DownloadProfilePhoto(string profileUrlString, byte[] emptyPhotoBytes)
        {
            var webClient = new WebClient();
            webClient.UseDefaultCredentials = true;

            byte[] blobBytes = new byte[emptyPhotoBytes.Length];
            try
            {
                blobBytes = await webClient.DownloadDataTaskAsync(profileUrlString);
            }
            catch (WebException webException)
            {
                if (webException.Status == WebExceptionStatus.ProtocolError)
                {
                    if (((HttpWebResponse)webException.Response).StatusCode == HttpStatusCode.NotFound)
                    {
                        emptyPhotoBytes.CopyTo(blobBytes, 0);
                    }
                }
                else if (webException.Status == WebExceptionStatus.NameResolutionFailure)
                {
                    emptyPhotoBytes.CopyTo(blobBytes, 0);
                }
                else
                {
                    throw webException;
                }
            }

            return blobBytes;
        }
        public async Task DownloadAndRunAsync()
        {
            if (string.IsNullOrWhiteSpace(SupportUrl))
            {
                throw Log.ErrorAndCreateException<InvalidOperationException>("Please initialize the service by setting the SupportUrl property");
            }

            Log.Info("Downloading support app from '{0}'", SupportUrl);

            var webClient = new WebClient();

            webClient.DownloadProgressChanged += OnWebClientOnDownloadProgressChanged;
            webClient.DownloadDataCompleted += OnWebClientOnDownloadDataCompleted;

            var data = await webClient.DownloadDataTaskAsync(SupportUrl);

            Log.Info("Support app is downloaded, storing file in temporary folder");

            var tempDirectory = Path.Combine(Path.GetTempPath(), "Orc_AutomaticSupport", DateTime.Now.ToString("yyyyMMddHHmmss"));
            if (!Directory.Exists(tempDirectory))
            {
                Directory.CreateDirectory(tempDirectory);
            }

            var tempFile = Path.Combine(tempDirectory, "SupportApp.exe");

            File.WriteAllBytes(tempFile, data);

            Log.Info("Running support app");

            _processService.StartProcess(tempFile, CommandLineParameters, exitCode =>
            {
                _dispatcherService.BeginInvoke(() => SupportAppClosed.SafeInvoke(this));
            });
        }
Ejemplo n.º 10
0
        public async Task<long> GetPageSize(CancellationToken cToken)
        {
            WebClient wc = new WebClient();
            Stopwatch sw = Stopwatch.StartNew();

            byte[] apressData = await wc.DownloadDataTaskAsync(TargetUrl);
            Debug.WriteLine("Elapsed ms: {0}", sw.ElapsedMilliseconds);
            return apressData.LongLength;

            //List<long> results = new List<long>();

            //for (int i = 0; i < 10; i++)
            //{
            //    if (!cToken.IsCancellationRequested)
            //    {
            //        Debug.WriteLine("Making Request: {0}", i);
            //        byte[] apressData = await wc.DownloadDataTaskAsync(TargetUrl);
            //        results.Add(apressData.LongLength);
            //    }
            //    else
            //    {
            //        Debug.WriteLine("Cancelled");
            //        return 0;
            //    }
            //}
            ////byte[] apressData = await wc.DownloadDataTaskAsync(TargetUrl);
            //Debug.WriteLine("Elapsed ms: {0}", sw.ElapsedMilliseconds);
            ////return apressData.LongLength;
            //return (long)results.Average();
        }
Ejemplo n.º 11
0
        public void DownloadDataTaskAsyncWhenCancellationTokenAndUriIsNullTest()
        {
            var webClient = new WebClient();
            var exception = Assert.Throws<ArgumentNullException>(() => webClient.DownloadDataTaskAsync(null, new CancellationToken()));

            Assert.AreEqual("uri", exception.ParamName);
        }
Ejemplo n.º 12
0
        private async void DownloadImageAsync()
        {
            try
            {
                var webClient = new WebClient();
                var data = await webClient.DownloadDataTaskAsync("http://www.dot42.com/dot42/img/logo.png").ConfigureAwait(this);

                var textView = FindViewById<TextView>(R.Ids.MyText);

                var bitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length);
                if (bitmap == null)
                {
                    textView.SetText("BitmapFactory cannot convert bytes into Bitmap");
                }
                else
                {
                    textView.SetText("Ready:");
                    var imageView = FindViewById<ImageView>(R.Ids.MyImage);
                    imageView.SetImageBitmap(bitmap);
                }
            }
            catch (Exception ex)
            {
                var textView = FindViewById<TextView>(R.Ids.MyText);
                textView.SetText("Exception: " + ex.Message);
            }
        }
Ejemplo n.º 13
0
        private async Task <Stream> GetStream(Uri imageUri)
        {
            // BitmapImage can download on its own from URIs, but in order
            // to support downloading on a worker thread, we need to download the image
            // data and put into a memorystream. Then have the BitmapImage decode the
            // image from the memorystream.
            byte[]       imageData = null;
            MemoryStream ms        = null;

            using (var wc = new System.Net.WebClient())
            {
                try
                {
                    imageData = await wc.DownloadDataTaskAsync(imageUri);

                    ms = new MemoryStream(imageData, writable: false);
                }
                catch (WebException webex)
                {
                    if (BadNetworkErrors.Any(c => webex.Status == c))
                    {
                        ErrorFloodGate.ReportBadNetworkError();
                        BitmapStatus = IconBitmapStatus.DefaultIconDueToWebExceptionBadNetwork;
                    }
                    else
                    {
                        BitmapStatus = IconBitmapStatus.DefaultIconDueToWebExceptionOther;
                    }
                }
            }

            return(ms);
        }
Ejemplo n.º 14
0
 public Task<byte[]> GetAsByteArrayAsync()
 {
     using (var webClient = new WebClient())
     {
         return webClient.DownloadDataTaskAsync(_url);
     }
 }
 public async Task ResetAsync(string CalculatorId)
 {
     using (var client = new WebClient())
     {
         await client.DownloadDataTaskAsync(new Uri(this.url + "reset?id=" + CalculatorId));
     }
 }
Ejemplo n.º 16
0
 private async Task<Dictionary<string, SongInfo[]>> GetSongIdMap(bool remote)
 {
     try
     {
         if (remote)
         {
             using (var client = new WebClient())
             {
                 var data = await client.DownloadDataTaskAsync(new Uri($"https://apiv2.deresute.info/data/live"));
                 using (var stream = new MemoryStream(data))
                 {
                     Directory.CreateDirectory("data/patterns");
                     File.WriteAllBytes($"data/patterns/index", data);
                     return ParseSongIdMap(stream);
                 }
             }
         }
         else
         {
             using (var fs = File.OpenRead($"data/patterns/index"))
             {
                 return ParseSongIdMap(fs);
             }
         }
     }
     catch
     {
         return null;
     }
 }
Ejemplo n.º 17
0
	public static void Main(string[] args)
	{
		var urls = Console.In.ReadToEnd().Split(new string[]{Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);

		var dir = args[0];

		Func<string, Task> download = async (url) => {
			var wc = new WebClient();
			var uri = new Uri(url);
			var fileName = Path.Combine(dir, Path.GetFileName(url));

			try {
				byte[] buf = await wc.DownloadDataTaskAsync(uri);

				using (var fs = new FileStream(fileName, FileMode.Create))
				{
					await fs.WriteAsync(buf, 0, buf.Length);
				}

				Console.WriteLine("download: {0} => {1}", url, fileName);
			} catch (Exception ex) {
				Console.WriteLine("failed: {0}, {1}", url, ex.Message);
			}
		};

		Task.WaitAll((from url in urls select download(url)).ToArray());
	}
Ejemplo n.º 18
0
 private static async Task<string> DownloadRawData(string url)
 {
     string cookieHeader = GetAllCookies_FireFox(StravaDomain);
     WebClient webClient = new WebClient();
     webClient.Headers.Add(HttpRequestHeader.Cookie, cookieHeader);
     var res = await webClient.DownloadDataTaskAsync(new Uri(url));
     return Encoding.UTF8.GetString(res);
 }
Ejemplo n.º 19
0
 public static async Task <byte[]> DownloadDataAsync(string url)
 {
     using (var wc = new System.Net.WebClient()) {
         wc.Headers[HttpRequestHeader.UserAgent] = WII_USER_AGENT;
         wc.DownloadProgressChanged += DownloadProgressChanged;
         return(await wc.DownloadDataTaskAsync(new Uri(url)));
     }
 }
 public async Task<AddResponse> AddAsync(AddRequest request)
 {
     using (var client = new WebClient())
     {
         await client.DownloadDataTaskAsync(new Uri(this.url + "add?id=" + request.CalculatorId + "&value=" + request.Value));
     }
     return new AddResponse();
 }
Ejemplo n.º 21
0
 public async Task<string> Load()
 {
     using (var client = new WebClient())
     {
         var raw= await client.DownloadDataTaskAsync(m_url);
         return Encoding.UTF8.GetString(raw);
     }
 }
Ejemplo n.º 22
0
        public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data,
                                    NameValueCollection values)
        {
            System.Net.WebClient webclient = new System.Net.WebClient();

            // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file"
            //webclient.Download * (...); // Any method starting with "Download"
            webclient.DownloadData(address);                            // Noncompliant
            webclient.DownloadDataAsync(uriAddress, new object());      // Noncompliant
            webclient.DownloadDataTaskAsync(uriAddress);                // Noncompliant
            webclient.DownloadFile(address, "filename");                // Noncompliant
            webclient.DownloadFileAsync(uriAddress, "filename");        // Noncompliant
            webclient.DownloadFileTaskAsync(address, "filename");       // Noncompliant
            webclient.DownloadString(uriAddress);                       // Noncompliant
            webclient.DownloadStringAsync(uriAddress, new object());    // Noncompliant
            webclient.DownloadStringTaskAsync(address);                 // Noncompliant

            // Should not raise for events
            webclient.DownloadDataCompleted   += Webclient_DownloadDataCompleted;
            webclient.DownloadFileCompleted   += Webclient_DownloadFileCompleted;
            webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged;
            webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted;


            //webclient.Open * (...); // Any method starting with "Open"
            webclient.OpenRead(address);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^   {{Make sure that this http request is sent safely.}}
            webclient.OpenReadAsync(uriAddress, new object());              // Noncompliant
            webclient.OpenReadTaskAsync(address);                           // Noncompliant
            webclient.OpenWrite(address);                                   // Noncompliant
            webclient.OpenWriteAsync(uriAddress, "STOR", new object());     // Noncompliant
            webclient.OpenWriteTaskAsync(address, "POST");                  // Noncompliant

            webclient.OpenReadCompleted  += Webclient_OpenReadCompleted;
            webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted;

            //webclient.Upload * (...); // Any method starting with "Upload"
            webclient.UploadData(address, data);                           // Noncompliant
            webclient.UploadDataAsync(uriAddress, "STOR", data);           // Noncompliant
            webclient.UploadDataTaskAsync(address, "POST", data);          // Noncompliant
            webclient.UploadFile(address, "filename");                     // Noncompliant
            webclient.UploadFileAsync(uriAddress, "filename");             // Noncompliant
            webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant
            webclient.UploadString(uriAddress, "data");                    // Noncompliant
            webclient.UploadStringAsync(uriAddress, "data");               // Noncompliant
            webclient.UploadStringTaskAsync(uriAddress, "data");           // Noncompliant
            webclient.UploadValues(address, values);                       // Noncompliant
            webclient.UploadValuesAsync(uriAddress, values);               // Noncompliant
            webclient.UploadValuesTaskAsync(address, "POST", values);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            // Should not raise for events
            webclient.UploadDataCompleted   += Webclient_UploadDataCompleted;
            webclient.UploadFileCompleted   += Webclient_UploadFileCompleted;
            webclient.UploadProgressChanged -= Webclient_UploadProgressChanged;
            webclient.UploadStringCompleted -= Webclient_UploadStringCompleted;
            webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted;
        }
Ejemplo n.º 23
0
        public Task<byte[]> LoadAsync(Uri uri)
        {
            using (var client = new WebClient())
            {
                Task<byte[]> task = client.DownloadDataTaskAsync(uri);

                return task;
            }
        }
		async void downloadAsync(object sender, System.EventArgs ea)
		{
			webClient = new WebClient ();
			//An large image url
			var url = new Uri ("http://photojournal.jpl.nasa.gov/jpeg/PIA15416.jpg");
			byte[] bytes = null;


			webClient.DownloadProgressChanged += HandleDownloadProgressChanged;

			this.downloadButton.SetTitle ("Cancel",UIControlState.Normal);
			this.downloadButton.TouchUpInside -= downloadAsync;
			this.downloadButton.TouchUpInside += cancelDownload;
			infoLabel.Text = "Downloading...";

			//Start download data using DownloadDataTaskAsync
			try{
				bytes = await webClient.DownloadDataTaskAsync(url);
			}
			catch(TaskCanceledException){
				Console.WriteLine ("Task Canceled!");
				return;
			}
			catch(Exception e) {
				Console.WriteLine (e.ToString());
				return;
			}
			string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);	
			string localFilename = "downloaded.png";
 			string localPath = Path.Combine (documentsPath, localFilename);
			infoLabel.Text = "Download Complete";

			//Save the image using writeAsync
			FileStream fs = new FileStream (localPath, FileMode.OpenOrCreate);
			await fs.WriteAsync (bytes, 0, bytes.Length);

			Console.WriteLine("localPath:"+localPath);


			//Resizing image is time costing, using async to avoid blocking the UI thread
			UIImage image = null;
			SizeF imageViewSize = imageView.Frame.Size;
	
			infoLabel.Text = "Resizing Image...";
			await Task.Run( () => { image = UIImage.FromFile(localPath).Scale(imageViewSize); } );
			Console.WriteLine ("Loaded!");

			imageView.Image = image;

			infoLabel.Text = "Click Dowload button to download the image";


			this.downloadButton.TouchUpInside -= cancelDownload;
			this.downloadButton.TouchUpInside += downloadAsync;
			this.downloadButton.SetTitle ("Download", UIControlState.Normal);
			this.downloadProgress.Progress = 0.0f;
		}
Ejemplo n.º 25
0
		public 	async void DownloadHistory ( ImageView imageView,string url,ProgressBar Pbar =null)
		{

			if (string.IsNullOrEmpty(url))
				return;


			try {	

				int index = url.LastIndexOf ("/");
				string localFilename = url.Substring (index + 1);
				var webClient = new WebClient ();
				var uri = new Uri (url);
				webClient.DownloadProgressChanged +=   (sender, e) => {if(Pbar!=null)  Pbar.Progress=e.ProgressPercentage; };


				documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);	

				localPath = System.IO.Path.Combine (documentsPath, localFilename);
				var localImage = new Java.IO.File (localPath);

				if (localImage.Exists ()) {

					var imgUri=Android.Net.Uri.Parse("file:"+localPath);
					imageView.SetImageURI(imgUri);

				} else {

					byte[] bytes = null;		
					bytes = await webClient.DownloadDataTaskAsync (uri);

					FileStream fs = new FileStream (localPath, FileMode.Create);
					await fs.WriteAsync (bytes, 0, bytes.Length);
					fs.Close ();	

					var imgUri=Android.Net.Uri.Parse("file:"+localPath);
					imageView.SetImageURI(imgUri);

//					teamBitmap = await BitmapFactory.DecodeByteArrayAsync (bytes, 0, bytes.Length);
//					imageView.SetImageBitmap (teamBitmap);

				}

			



			} catch (TaskCanceledException) {

				return;
			} catch (Exception) {
				return;
			}



		}
Ejemplo n.º 26
0
 public static byte[] DownloadData(string url)
 {
     using (var wc = new System.Net.WebClient()) {
         wc.Headers[HttpRequestHeader.UserAgent] = WII_USER_AGENT;
         wc.DownloadProgressChanged += DownloadProgressChanged;
         var task = wc.DownloadDataTaskAsync(new Uri(url));
         return(task.Result);
     }
 }
 public async Task<byte[]> Retrieve(string storageKey)
 {
     var uri = _uriFormatter.FormatUri(storageKey);
     _logger.Debug("Reading blob {0} from {1}", storageKey, uri);
     using (var webClient = new WebClient())
     {
         var result = await webClient.DownloadDataTaskAsync(uri);
         return result;
     }
 }
 public async Task<byte[]> DownloadAsync(string url, IDictionary<string, string> headers, string method)
 {
     var client = new WebClient();
     if (headers != null)
     {
         foreach (var header in headers)
             client.Headers[header.Key] = header.Value;
     }
     return await client.DownloadDataTaskAsync(url);
 }
Ejemplo n.º 29
0
        public void DownloadDataTaskAsyncTest()
        {
            var uri = new Uri("https://www.google.com");
            var timout = new TimeSpan(0, 0, 30);
            var webClient = new WebClient();
            var result = webClient.DownloadDataTaskAsync(uri, timout).Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(typeof(byte[]), result.GetType());
        }
Ejemplo n.º 30
0
 public async Task<bool> FileExistsAsync(GitHubRepoSearchItem repo, string filePath) {
     var wc = new WebClient();
     var url = $"https://raw.githubusercontent.com/{repo.FullName}/master/{filePath}";
     try {
         var json = await wc.DownloadDataTaskAsync(url);
         return true;
     } catch (WebException) {
         return false;
     }
 }
Ejemplo n.º 31
0
 public async Task LoadChangelog()
 {
     var downloader = new WebClient();
     string version = await downloader.DownloadStringTaskAsync("http://battlelogium.github.io/Battlelogium/releaseinfo/releaseversion");
     MemoryStream changenotes = new MemoryStream(await downloader.DownloadDataTaskAsync("http://battlelogium.github.io/Battlelogium/releaseinfo/releasenotes.rtf"));
     this.Dispatcher.Invoke(() =>
     {
         new TextRange(changeLogBox.Document.ContentStart, changeLogBox.Document.ContentEnd).Load(changenotes, DataFormats.Rtf);
         this.versionLabel.Content = "Version " + version;
     });
 }
Ejemplo n.º 32
0
		public async Task<Bitmap> downloadAsync (string uri)
		{
		 
			if (uri == null)
				return null;

			int index = uri.LastIndexOf ("/");
			string localFilename = uri.Substring (index + 1);
			webClient = new WebClient ();
			var url = new Uri (uri);
			byte[] bytes = null;


			try {

				bytes = await webClient.DownloadDataTaskAsync (url);
			} catch (TaskCanceledException Ex) {
				Log.Error ("downloadAsync:", Ex.Message);
				return null;
			} catch (Exception Ex) {
			
				Log.Error ("downloadAsync:", Ex.Message);

				return null;
			}

			string documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);	

			string localPath = System.IO.Path.Combine (documentsPath, localFilename);
		

			//Sive the Image using writeAsync
			FileStream fs = new FileStream (localPath, FileMode.OpenOrCreate);
			await fs.WriteAsync (bytes, 0, bytes.Length);

			//Console.WriteLine("localPath:"+localPath);
			fs.Close ();


			BitmapFactory.Options options = new BitmapFactory.Options ();
			options.InJustDecodeBounds = true;
			await BitmapFactory.DecodeFileAsync (localPath, options);

			//	options.InSampleSize = options.OutWidth > options.OutHeight ? options.OutHeight / imageview.Height : options.OutWidth / imageview.Width;
			options.InJustDecodeBounds = false;

			Bitmap bitmap = await BitmapFactory.DecodeFileAsync (localPath, options);



			return (bitmap);

		
		}
Ejemplo n.º 33
0
 public async Task<IActionResult> Convert(ImageToConvert imageToConvert)
 {
     var result = string.Empty;
     if (!string.IsNullOrEmpty(imageToConvert.UrlOfTheImage))
     {
         WebClient webClient = new WebClient();
         var imageBytes = await webClient.DownloadDataTaskAsync(new Uri(imageToConvert.UrlOfTheImage));
         result = ConvertToText(imageBytes);
     }
     return Json(result);
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Downloads a file from the Internet (http, https).  If an exception occurs a
        /// null will be returned.
        /// </summary>
        /// <param name="remoteUrl"></param>
        public static async Task <byte[]> SafeDownloadFileAsync(string remoteUrl)
        {
            try
            {
                using var wc = new System.Net.WebClient();

                return(await wc.DownloadDataTaskAsync(remoteUrl));
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 35
0
        public async Task <WebResult> Download(Url url)
        {
            //TODO: проверять content type перед закачкой
            var result = new WebResult {
                Url = url
            };

            try
            {
                var rawdata = await _client.DownloadDataTaskAsync(url.ToString());

                result.Data = Encoding
                              .GetEncoding(GetCharset() ?? Encoding.UTF8.WebName)
                              .GetString(rawdata);
                result.ErrorCode = 200;
            }
            catch (WebException ex) when(ex.Response is HttpWebResponse && ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
            {
                result.ErrorCode = GetStatusCode(ex);
            }

            return(result);
        }
Ejemplo n.º 36
0
    /// <summary>
    /// Scarica un file in asincrono.
    /// </summary>
    /// <param name="Url">L'Url da dove prelevare il file</param>
    /// <param name="Destination">La destinazione locale dove salvarlo</param>
    /// <param name="WriteOnBuffer">Se deve scaricare i dati (alcune estensioni hanno problemi con downloadfile)</param>
    public static async UniTask <bool> DownloadFileAsync(string Url, string Destination, bool WriteOnBuffer = false)
    {
        try {
            if (WriteOnBuffer)
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                byte[] buffer = await webClient.DownloadDataTaskAsync(Url);

                File.WriteAllBytes(Destination, buffer);
                webClient.Dispose();
            }
            else
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                await webClient.DownloadFileTaskAsync(Url, Destination);

                webClient.Dispose();
            }
        } catch (Exception e) {
            LogE("Utilities", "Errore DownloadFile: [" + e + "]");
            return(false);
        }
        return(true);
    }
Ejemplo n.º 37
0
        public async static Task LoadGeneratedMonsters()
        {
            //Console.WriteLine("test");
            string url = "https://jsonplaceholder.typicode.com/photos";

            System.Net.WebClient wc = new System.Net.WebClient();
            byte[] raw = await(wc.DownloadDataTaskAsync(url));

            string webData = System.Text.Encoding.UTF8.GetString(raw);
            JArray photos  = JArray.Parse(webData);

            //Console.WriteLine("test");

            foreach (var item in photos)
            {
                var idToken    = item.SelectToken("id");
                var titleToken = item.SelectToken("title");
                //Console.WriteLine(e);
                int id = Int32.Parse(idToken.ToString());
                _randomMonsters.Add(new Monster(MonsterID.GENERATED, titleToken.ToString(), 10, 10, 10, 10, 10));
            }

            Console.WriteLine(_randomMonsters.Count);
        }
Ejemplo n.º 38
0
 public Task <byte[]> DownloadDataTaskAsync(string address)
 {
     return(_webClient.DownloadDataTaskAsync(address));
 }
Ejemplo n.º 39
-1
 public async Task<IActionResult> ProfileImage(string domain, string login)
 {
     using (var client = new WebClient())
     {
         var uri = string.Format(_appSettings.Options.SharePointImageUrl, domain, login);
         var data = await client.DownloadDataTaskAsync(uri);
         return File(data, "image/jpeg");
     }
 }
        public Task<byte[]> DownloadUrl(string url)
        {
            var wc = new WebClient();

            this.Log().Info("Downloading url: " + url);

            return this.WarnIfThrows(() => wc.DownloadDataTaskAsync(url),
                "Failed to download url: " + url);
        }