UploadDataTaskAsync() public méthode

public UploadDataTaskAsync ( System address, byte data ) : System.Threading.Tasks.Task
address System
data byte
Résultat System.Threading.Tasks.Task
        public async Task Reduce(FileInfo input, FileInfo output)
        {
            if (input == null)
            {
                throw new ArgumentException("Missing parameter input", "input");
            }

            if (output == null)
            {
                throw new ArgumentException("Missing parameter outputDirectory", "outputDirectory");
            }

            var fileName = input.Name;
            var endpoint = new Uri("https://api.accusoft.com/v1/imageReducers/" + fileName);
            
            using (var client = new WebClient())
            {
                client.Headers.Add("acs-api-key", _apiKey);
                client.Headers.Add("Content-Type", input.Extension == "png" ? "image/png" : "image/jpg");

                using (var reader = new BinaryReader(input.OpenRead()))
                {
                    var data = reader.ReadBytes((int)reader.BaseStream.Length);
                    var result = await client.UploadDataTaskAsync(endpoint, "POST", data);

                    using (var writeStream = output.Create())
                    {
                        await writeStream.WriteAsync(result, 0, result.Length);
                    }
                }
            }
        }
 public static async Task<string> GetHttpResponseAsync(string url, string data)
 {
     var client = new WebClient();
     client.Headers.Add("user-agent", "User-Agent: Mozilla/5.0");
     client.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
     byte[] rawData = await client.UploadDataTaskAsync(url, Encoding.UTF8.GetBytes(data));
     return Encoding.UTF8.GetString(rawData);
 }
Exemple #3
0
        public static async Task <string> Post(string url, byte[] data)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.Encoding = Encoding.UTF8;
            var resultbts = await wc.UploadDataTaskAsync(url, data);

            return(System.Text.Encoding.UTF8.GetString(resultbts));
        }
Exemple #4
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;
        }
Exemple #5
0
        public static async Task <string> Post(string url, byte[] data)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.Encoding = Encoding.UTF8;
            wc.Headers["content-type"] = "text/plain;charset=UTF-8";
            var resultbts = await wc.UploadDataTaskAsync(url, "POST", data);

            return(System.Text.Encoding.UTF8.GetString(resultbts));
        }
 public async Task UploadAsync(string url, IDictionary<string, string> headers, string method, byte[] data)
 {
     var client = new WebClient();
     if (headers != null)
     {
         foreach (var header in headers)
             client.Headers[header.Key] = header.Value;
     }
     await client.UploadDataTaskAsync(url, "PUT", data);
 }
 public async Task UploadAsync(string url, IDictionary<string, string> headers, string method, byte[] data)
 {
     using (var client = new WebClient())
     {
         SubscribeToUploadEvents(client);
         if (headers != null)
         {
             foreach (var header in headers)
                 client.Headers[header.Key] = header.Value;
         }
         await client.UploadDataTaskAsync(url, "PUT", data);
         UnsubscribeFromUploadEvents(client);
     }
 }
        public async Task<SpeechToTextResult> ConvertToTextAsync(byte[] voice)
        {
            var wc = new WebClient();
            //wc.Headers["Content-Type"] = "audio/x-flac; rate=16000";
            wc.Headers["Content-Type"] = "audio/x-flac; rate=8000";

            //var contents = File.ReadAllBytes("i_like_pickles.flac");
            var url = "https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=en-US";
            var result = await wc.UploadDataTaskAsync(url, voice);
            var txt = Encoding.UTF8.GetString(result);
            var obj = JsonConvert.DeserializeObject<SpeechToTextResult>(txt);
            obj.Raw = txt;
            return obj;
            //return resultObj.Hypotheses["utterance"];
            //return resultObj.Hypotheses.First().Utterance;
        }
        private Task<AnomalyRecord[]> GetAlertsFromRRS(string timeSeriesData)
        {
            var rrs = _detectorUrl;
            var apikey = _detectorAuthKey;

            using (var wb = new WebClient())
            {
                wb.Headers[HttpRequestHeader.ContentType] = "application/json";
                wb.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + apikey);

                var featureVector = string.Format("\"data\": \"{0}\",\"params\": \"{1}\"", timeSeriesData, _spikeDetectorParams);
                string jsonData = "{\"Id\":\"scoring0001\", \"Instance\": {\"FeatureVector\": {" + featureVector + "}, \"GlobalParameters\":{\"level_mhist\": 300, \"level_shist\": 100, \"trend_mhist\": 300, \"trend_shist\": 100 }}}";
                var jsonBytes = Encoding.Default.GetBytes(jsonData);

                return wb.UploadDataTaskAsync(rrs, "POST", jsonBytes)
                    
                    .ContinueWith(
                    resp =>
                    {
                        var response = Encoding.Default.GetString(resp.Result);
#if DEBUG_LOG
                        Trace.TraceInformation("AzureML response: {0}...", response.Substring(0, Math.Min(100, response.Length)));
#endif

                        JavaScriptSerializer ser = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
                        var results = ser.Deserialize<List<string[]>>(response);

                        var presults = results.Select(AnomalyRecord.Parse);
                        return filterAnomaly(presults);
                    }
                    );
            }
        }
        /// <summary>
        /// Uploads the specified file to   the cloud.
        /// </summary>
        /// <param name="file">The full path to the desired .zip file.</param>
        private async Task<UploadResult> Upload(DS4Session session, CancellationToken ct)
        {
            string file = session.CompressedScanFile;
            string contentType = "application/x/7z-compressed";

            WebClient proxy;

            string result = string.Empty;

            // Step1: Get s3 signed URL
            proxy = new WebClient();

            // Gather data
            string fileName = Path.GetFileName(file);
            
            Dictionary<string, string> postDict = new Dictionary<string, string> {
                {"filename", fileName},
                {"file_type", contentType},
            };

            String postData = JSONHelper.Instance.Serialize(postDict);
            // Prepare request
            proxy.Headers["Content-Type"] = "application/json";
            proxy.Headers["Authorization"] = _authHeader;

            // Perform request            
            try
            {
                result = await proxy.UploadStringTaskAsync(this.BuildUri("s3/sign"), "POST", postData);
            }
            catch (WebException ex)
            {
                return new UploadResult { Success = false, Exception = ex };
            }

            ct.ThrowIfCancellationRequested();

            // Step 2: Upload to s3 signed PUT URL
            _s3Proxy = proxy = new WebClient();
            proxy.UploadProgressChanged += new UploadProgressChangedEventHandler(this.Progress);
            proxy.UploadDataCompleted += (s , e) => { if(ct.IsCancellationRequested) _canceled = true; };

            // Gather data
            Dictionary<string, string> response = JSONHelper.Instance.CreateDictionary(result);
            string url = response["signedUrl"];
            string key = response["key"];

            byte[] binaryData = File.ReadAllBytes(file);

            // Prepare headers
            proxy.Headers["Content-Type"] = contentType;

            // Prepare request
            Uri uri = new Uri(url, UriKind.Absolute);
            // Perform request
            try
            {
                byte[] uploadResponse = await proxy.UploadDataTaskAsync(uri, "PUT", binaryData);
            }
            catch (WebException ex)
            {
                
                Console.WriteLine(Uploader.GetErrorMsgFromWebException(ex));
                return new UploadResult { Success = false, Exception = ex, Canceled = _canceled };
            }

            ct.ThrowIfCancellationRequested();

            // Step 3: PostUpload and get returned BodyId
            proxy = new WebClient();

            //Assemble payload
            List<Dictionary<string, string> > artifacts = new List<Dictionary<string, string> >();
            artifacts.Add(new Dictionary<string, string> { 
                {"artifactsType","DS4Measurements"}
            });

            artifacts.Add(new Dictionary<string, string> { 
                {"artifactsType","DS4Alignment"}
            });

            DS4BodyRequest bodyRequest = new DS4BodyRequest("ds4_scan", key, artifacts);

            postData = JSONHelper.Instance.Serialize(bodyRequest);

            // Prepare request
            proxy.Headers["Content-Type"] = "application/json";
            proxy.Headers["Authorization"] = _authHeader;

            // Perform request
            try
            {
                result = await proxy.UploadStringTaskAsync(this.BuildUri("bodies/from_scan"), "POST", postData);
            }
            catch (WebException ex)
            {
                Console.WriteLine(Uploader.GetErrorMsgFromWebException(ex));
                return new UploadResult { Success = false, Exception = ex };
            }

            DS4PostUploadResponse ds4PostUploadResponse;
            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(result)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DS4PostUploadResponse));
                ds4PostUploadResponse = (DS4PostUploadResponse)serializer.ReadObject(ms);
                ms.Close();
            }

            string bodyId = ds4PostUploadResponse.BodyId;

            return new UploadResult { Success = true, BodyId = bodyId, Artifacts = ds4PostUploadResponse.Artifacts };
        }
 public async Task<PortCheckResult> RunAsync()
 {
   var client = new WebClient();
   var data   = new JObject();
   data["instanceId"] = InstanceId.ToString("N");
   data["ports"] = new JArray(Ports);
   var succeeded = false;
   var stopwatch = new System.Diagnostics.Stopwatch();
   string response_body = null;
   try {
     stopwatch.Start();
     var body = System.Text.Encoding.UTF8.GetBytes(data.ToString());
     response_body = System.Text.Encoding.UTF8.GetString(
       await client.UploadDataTaskAsync(Target, body)
     );
     stopwatch.Stop();
     succeeded = true;
     var response = JToken.Parse(response_body);
     var response_ports = response["ports"].Select(token => (int)token);
     return new PortCheckResult(
         succeeded,
         response_ports.ToArray(),
         stopwatch.Elapsed);
   }
   catch (WebException) {
     succeeded = false;
     return new PortCheckResult(
         succeeded,
         null,
         stopwatch.Elapsed);
   }
   catch (Newtonsoft.Json.JsonReaderException) {
     succeeded = false;
     return new PortCheckResult(
         succeeded,
         null,
         stopwatch.Elapsed);
   }
 }
        public static async void probando4()
        {
            using (var client = new WebClient())
            {

                byte[] archivo = System.IO.File.ReadAllBytes(@"C:\tesisData\dataset\rock\rock.00007.au");
                Uri address = new Uri("http://developer.echonest.com/api/v4/track/upload?api_key=ERYL0FA7VZ24XQMOO&filetype=au");


                Task<byte[]> task = client.UploadDataTaskAsync(address, "POST", archivo);
                byte[] a = await task;
                var responseString = Encoding.Default.GetString(a);

            }

        }