UploadFileTaskAsync() public method

public UploadFileTaskAsync ( System address, string fileName ) : System.Threading.Tasks.Task
address System
fileName string
return System.Threading.Tasks.Task
Example #1
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;
        }
Example #2
0
 private async static Task<byte[]> PostRequestFile(string url)
 {
     using (var client = new WebClient())
     {
         client.Headers.Add("user-agent", "my own code");
         client.Headers.Add("content-type", "x-www-form-urlencoded");
         client.UploadProgressChanged += client_UploadProgressChanged;
         return await client.UploadFileTaskAsync(url, "asdf");
     }
 }
Example #3
0
        private async void buttonShare_Click(object sender, RoutedEventArgs e)
        {
            var popup = new ToolTip();

            popup.BorderBrush     = new SolidColorBrush(Colors.LightGray);
            popup.BorderThickness = new Thickness(2);
            popup.Background      = new SolidColorBrush(Colors.Black);
            var stack = new StackPanel();

            stack.Margin = new Thickness(5);
            var text = new TextBlock()
            {
                Text = "Uploading image...", Foreground = new SolidColorBrush(Colors.White), FontSize = 20, Margin = new Thickness(0, 5, 0, 5)
            };
            var progress = new ProgressBar()
            {
                Foreground = Foreground = new SolidColorBrush(Colors.SteelBlue), Margin = new Thickness(0, 5, 0, 5), Height = 15
            };

            stack.Children.Add(text);
            stack.Children.Add(progress);
            popup.Content         = stack;
            popup.PlacementTarget = this;
            popup.Placement       = PlacementMode.Center;
            popup.IsOpen          = true;
            var savePath = Path.Combine(Path.GetTempPath(), "CleanShot_Image.png");

            EditedImage.Save(savePath, ImageFormat.Png);
            var client = new System.Net.WebClient();

            client.UploadProgressChanged += (send, arg) => {
                progress.Value = arg.ProgressPercentage;
            };
#if DEBUG
            var url = "https://localhost:44355/ImageShare";
#else
            var url = "https://lucency.co/ImageShare";
#endif
            byte[] response = new byte[0];
            try
            {
                response = await client.UploadFileTaskAsync(new Uri(url), savePath);
            }
            catch (System.Net.WebException)
            {
                popup.IsOpen = false;
                MessageBox.Show("There was a problem uploading the image.  Your internet connection may not be working, or the web service may be temporarily unavailable.", "Upload Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            var strResponse = Encoding.UTF8.GetString(response);
            popup.IsOpen = false;
            Process.Start(strResponse);
        }
Example #4
0
		[Category ("AndroidNotWorking")] // Test suite hangs if the tests runs as part of the entire BCL suite. Works when only this fixture is ran
		public void UploadFileAsyncContentType ()
		{
			var serverUri = "http://localhost:13370/";
			var filename = Path.GetTempFileName ();

			HttpListener listener = new HttpListener ();
			listener.Prefixes.Add (serverUri);
			listener.Start ();

			using (var client = new WebClient ())
			{
				client.UploadFileTaskAsync (new Uri (serverUri), filename);
				var request = listener.GetContext ().Request;

				var expected = "multipart/form-data; boundary=---------------------";
				Assert.AreEqual (expected.Length + 15, request.ContentType.Length);
				Assert.AreEqual (expected, request.ContentType.Substring (0, expected.Length));
			}
			listener.Close ();
		}
 private static async Task<string> UploadFile(string url, string fName)
 {
     WebClient wClient = new WebClient();
     wClient.UploadProgressChanged += wClient_UploadProgressChanged;   
     var ans = await wClient.UploadFileTaskAsync(url, "POST", fName);
     string res = System.Text.Encoding.Default.GetString(ans);
     return res;
 }
 private async Task<byte[]> UploadImage(string url, string filePath, NameValueCollection valueCollection = null)
 {
     using (var webClient = new WebClient())
     {
         try
         {
             webClient.UploadProgressChanged += WebClientUploadProgressChanged;
             webClient.UploadFileCompleted += WebClientUploadCompleted;
             if (valueCollection != null) webClient.Headers.Add(valueCollection);
             if (File.Exists(filePath))
             {
                 string fileType = Path.GetExtension(filePath).Remove(0, 1).ToLower();
                 if (fileType == "jpg") fileType = "jpeg";
                 webClient.Headers.Add(HttpRequestHeader.ContentType, "image/" + fileType);
                 return await webClient.UploadFileTaskAsync(new Uri(url), filePath);
             }
         }
         catch (Exception ex)
         {
             Log.Add(ex);
             MessageBox.Show(ex.Message, Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
         }
     }
     return null;
 }
Example #7
0
 //       public async Task<string> MyMainAsync(int i, string h, string u, string p, string f, CancellationToken cancel, IProgress<string> progress)
        public async Task<string> MyMainAsync(int i, FTPConfiguration ftpconfiguration, CancellationToken cancel, IProgress<string> progress)
        {
            using (WebClient client = new WebClient())
            {
                try
                {
                    //--- Record the start time---
                    startTime = DateTime.Now;
                    // First create a Stopwatch instance
                    stopwatch = new Stopwatch();
                    ctime1 = ctime2 = ctime3 = ctime4 = ctime5 = ptime1 = ptime2 = ptime3 = ptime4 = ptime5 = 0;    // zero out each run
                    // Begin the stopwatch
                    stopwatch.Start();
                    cancel.ThrowIfCancellationRequested();
                    if (cancel.IsCancellationRequested)
                    {
                        client.CancelAsync();
                    }
                    // Get the object used to communicate with the server.
                    //                WebClient client = new WebClient();
                    client.Proxy = null;
                    client.BaseAddress = "ftp://" + ftpconfiguration.Host;
// TODO: put back in /demo/ when doing hardwired for real
//                    client.BaseAddress = "ftp://" + ftpconfiguration.Host + "/demo/";     

                    CredentialCache cache = new CredentialCache();
                    NetworkCredential credential = new NetworkCredential(ftpconfiguration.Username, ftpconfiguration.Password);

                    client.Credentials = credential;

                    if (i == 0)
                    { client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged1); }
                    else if (i == 1)
                    { client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged2); }
                    else if (i == 2)
                    { client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged3); }
                    else if (i == 3)
                    { client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged4); }
                    else if (i == 4)
                    { client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged5); }

                    //client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged); 
                    //client.UploadFileCompleted += new UploadFileCompletedEventHandler(client_UploadFileCompleted);
                    Uri remoteFile;
                    Uri.TryCreate(ftpconfiguration.Filename, System.UriKind.Relative, out remoteFile);

                    FileInfo fi = new FileInfo(@demoDir + ftpconfiguration.Filename);
                    //fileSize = fi.Length;
                    //                await client.DownloadFileTaskAsync(remoteFile, "/temp/demo/RRVideo.mp4");

                    Task uploadTask = client.UploadFileTaskAsync(remoteFile, @demoDir + ftpconfiguration.Filename);
                    //string sNull = null;
                    //client.UploadFileAsync(remoteFile, sNull, @demoDir + f, i.ToString());
                    //client.UploadFile(remoteFile, @demoDir + f);

                    //if (i == 3)
                    //{
                    //   await MyDelayAsync(i);
                    //}
                    await uploadTask;
                    ////update the progress on UI
//                  label1.Invoke((Action)delegate { ReportProgress2(1, i, Convert.ToString(fi.Length) + " bytes sent", 0); });

                    if (i == 0)     // stop Elapsed timer when last Task done.
                    {
                        label1.Invoke((Action)delegate { timer1.Change(Timeout.Infinite, Timeout.Infinite); });
                    }


                    if (cancel.IsCancellationRequested)
                    {
                        client.CancelAsync();
                    }
                    //showTime();

                }
                catch (OperationCanceledException oce)
                {
                    client.CancelAsync();
                    //label1.Text = "Cancelled";
                }
                catch (Exception e)
                {
                    ReportError(e.Message, i);
                }
                return "end";
            }
        }