コード例 #1
0
        private async Task <string> TranslateText(string Text, string Lang2, string Lang1 = null)
        {
            try
            {
                if (string.IsNullOrEmpty(Text))
                {
                    Text = "ReaLTaiizor";
                }

                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
                using (WebClient Client = new WebClient())
                {
                    NameValueCollection Post = new NameValueCollection()
                    {
                        { "", "" }
                    };
                    string JSON;
                    if (!string.IsNullOrEmpty(Lang1))
                    {
                        JSON = Encoding.UTF8.GetString(await Client.UploadValuesTaskAsync(URL + APIKey + "&text=" + Text + "&lang=" + Lang1 + "-" + Lang2, Post));
                    }
                    else
                    {
                        JSON = Encoding.UTF8.GetString(await Client.UploadValuesTaskAsync(URL + APIKey + "&text=" + Text + "&lang=" + Lang2, Post));
                    }

                    dynamic DJSON = JsonConvert.DeserializeObject(JSON);
                    int     i     = 0;
                    foreach (dynamic FJSON in DJSON)
                    {
                        foreach (dynamic CJSON in FJSON)
                        {
                            if (i == 2)
                            {
                                string Result = CJSON.ToString();
                                return(Result.Substring(6, Result.Length - 10).Replace(" \\n", Environment.NewLine).Replace("\\n", Environment.NewLine).Replace(" \\r", "").Replace("\\r", ""));
                            }
                            else
                            {
                                i++;
                            }
                        }
                    }
                    return("null");
                }
            }
            catch (Exception Ex)
            {
                return(Ex.Message);
            }
        }
コード例 #2
0
ファイル: WebClientTest.cs プロジェクト: must/dotnet-corefx
        public static void UploadValues_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();

            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValues((string)null, null); });
            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValues((string)null, null, null); });
            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValues((Uri)null, null); });
            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValues((Uri)null, null, null); });

            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null); });
            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null, null); });
            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null, null, null); });

            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((string)null, null); });
            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((string)null, null, null); });
            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((Uri)null, null); });
            Assert.Throws <ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((Uri)null, null, null); });

            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValues("http://localhost", null); });
            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValues("http://localhost", null, null); });
            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValues(new Uri("http://localhost"), null); });
            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValues(new Uri("http://localhost"), null, null); });

            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null); });
            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null, null); });
            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null, null, null); });

            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync("http://localhost", null); });
            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync("http://localhost", null, null); });
            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync(new Uri("http://localhost"), null); });
            Assert.Throws <ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync(new Uri("http://localhost"), null, null); });
        }
コード例 #3
0
        /// <summary>
        /// Performs a POST request over HTTP or HTTPS
        /// </summary>
        /// <param name="method"></param>
        /// <param name="data"></param>
        /// <param name="useHttps"></param>
        /// <returns></returns>
        private static async Task <string> PerformPostRequest(string method, NameValueCollection data, bool useHttps)
        {
            string prefix = "http";

            if (useHttps)
            {
                prefix = "https";
            }

            string result = string.Empty;

            try
            {
                string url = Uri.EscapeUriString(string.Format("{0}://ws.audioscrobbler.com/2.0/?method={1}", prefix, method));

                using (var client = new WebClient())
                {
                    byte[] responseBytes = await client.UploadValuesTaskAsync(url, "POST", data);

                    result = Encoding.UTF8.GetString(responseBytes);
                }
            }
            catch (Exception)
            {
                // Swallow: check for !string.IsNullOrEmpty(result)
            }

            return(result);
        }
コード例 #4
0
        //Button used to change the customers password, using his old one and comparing it to the new
        private async void changePasswordBtn_ClickedAsync(object sender, EventArgs e)
        {
            oldPassword       = oldPasswordTxt.Text;
            newPassword       = newPasswordTxt.Text;
            newPasswordRepeat = newPasswordRepeatTxt.Text;
            email             = App.DB.GetCustomerEmail(id);

            if (!oldPassword.Equals(newPassword) && newPassword.Equals(newPasswordRepeat))
            {
                //Calling the REST service to update the password
                Uri                 uri        = new Uri("https://nsterdt.000webhostapp.com/UpdatePassword.php");
                WebClient           client     = new WebClient();
                NameValueCollection parameters = new NameValueCollection();

                parameters.Add("NewPassword", newPassword);
                parameters.Add("Email", email);

                try
                {
                    await client.UploadValuesTaskAsync(uri, parameters);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            else
            {
                await DisplayAlert("Try Again.", "The specified passwords don't match, or are not new.", "OK");
            }
        }
コード例 #5
0
        //Button used to change the customers email address, comparing his old one and the entered new one.
        private async void changeEmailBtn_ClickedAsync(object sender, EventArgs e)
        {
            oldEmail = oldEmailTxt.Text;
            newEmail = newEmailTxt.Text;

            if (!oldEmail.Equals(newEmail))
            {
                //Calling the REST service to update the email adress
                Uri                 uri        = new Uri("https://nsterdt.000webhostapp.com/UpdateEmail.php");
                WebClient           client     = new WebClient();
                NameValueCollection parameters = new NameValueCollection();

                parameters.Add("OldEmail", oldEmail);
                parameters.Add("NewEmail", newEmail);


                try
                {
                    await client.UploadValuesTaskAsync(uri, parameters);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            else
            {
                await DisplayAlert("Try Again.", "The specified emails are the same.", "OK");
            }
        }
コード例 #6
0
ファイル: AlLogistic.cs プロジェクト: Erusalim12/Calc
        private async Task <AlLogisticModel> GetCityIdAsync(string name)
        {
            string url = "http://allogistik.ru/ajax/cities.php";

            using (var webClient = new WebClient())
            {
                // Создаём коллекцию параметров
                var pars = new NameValueCollection
                {
                    // Добавляем необходимые параметры в виде пар ключ, значение
                    { "search", name }
                };

                // Посылаем параметры на сервер
                var response = await webClient.UploadValuesTaskAsync(url, pars);

                //Конвертируем данные из байтов в строку, а строку в JSON и отправляем серверу
                try
                {
                    var data = JsonConvert.DeserializeObject <AlLogisticModel[]>(Encoding.GetEncoding("UTF-8")
                                                                                 .GetString(response, 0, response.Length));
                    return(data.FirstOrDefault());
                }
                catch (Exception)
                {
                    return(null);
                }
            }
        }
コード例 #7
0
        public async Task Upload(string filePath)
        {
            using (var webClient = new WebClient()) {
                try {
                    webClient.Headers.Add("Authorization", string.Format("Client-ID {0}", _clientId));
                    var data =
                        await
                        webClient.UploadValuesTaskAsync(new Uri(_uploadPath),
                                                        new NameValueCollection { { "image", Convert.ToBase64String(File.ReadAllBytes(filePath)) } });

                    using (var ms = new MemoryStream(data)) {
                        var doc = XDocument.Load(ms);
                        if (doc.Root != null)
                        {
                            var xElement = doc.Root.Element("link");
                            if (xElement != null)
                            {
                                var link = xElement.Value;
                                OnImageUploadSuccess(new UploaderEventArgs {
                                    ImageUrl = link
                                });
                            }
                        }
                    }
                } catch (Exception ex) {
                    OnImageUploadFailed(new UploaderEventArgs {
                        Exception = ex
                    });
                }
            }
        }
コード例 #8
0
ファイル: WebClientTest.cs プロジェクト: Foxtrek64/runtime
 public static async Task ConcurrentOperations_Throw()
 {
     await LoopbackServer.CreateServerAsync((server, url) =>
     {
         var wc       = new WebClient();
         Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
         Assert.Throws <NotSupportedException>(() => { wc.DownloadData(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadDataAsync(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadString(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadStringAsync(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadString(url, "42"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadFile(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
         return(Task.CompletedTask);
     });
 }
            public async void send(string body, string userKey)
            {
                if (string.IsNullOrEmpty(_token))
                {
                    _log.Error("Unable to send push notification because 'pushover.token' is not specified.");
                    return;
                }

                if (string.IsNullOrEmpty(body) || body.Length > 1024)
                {
                    _log.Error("Unable to send push notification because body is null or longer than 1024 characters.");
                    return;
                }

                try
                {
                    using (var client = new WebClient())
                    {
                        var data = new NameValueCollection();
                        data["token"]   = _token;
                        data["user"]    = userKey;
                        data["message"] = body;
                        await client.UploadValuesTaskAsync("https://api.pushover.net/1/messages.json", data);
                    }
                }
                catch (Exception e)
                {
                    _log.Error(e.Message, e);
                }
            }
コード例 #10
0
        internal static async Task <string> RegisterUser(string locale, string version)
        {
            if (DoNotSend)
            {
                return(string.Empty);
            }
            NameValueCollection values = new NameValueCollection();

            if (OverrideUID != null)
            {
                values.Add("uid", OverrideUID);
            }
            values.Add("locale", locale);
            values.Add("version", version);

            WebClient wc = new WebClient();

            byte[] resp = await wc.UploadValuesTaskAsync(baseUrl + "registerUser", values);

            string uid = Encoding.UTF8.GetString(resp);

            // Save UID for future calls
            Properties.Settings.Default.AppTelemetryUID = uid;
            Properties.Settings.Default.Save();
            return(uid);
        }
コード例 #11
0
        /// <summary>
        /// Get set of data elements async for the session's username, password and uniq.
        /// The set of data elements depends of "i" param.
        /// </summary>
        /// <param name="sessionId">The Session ID returned from the JavaScript data collector.</param>
        /// <param name="username">The username of the user.</param>
        /// <param name="password">Customer identifier.</param>
        /// <param name="uniq">The password of the user.</param>
        /// <param name="dse">The requested set of data elements expected in response.</param>
        /// <returns>Set of data elements</returns>
        public async Task <Info> GetInfoAsync(string sessionId, string username, string password, string uniq, DataSetElements dse)
        {
            int i = dse.Build();

            ValidateGetInfo(sessionId, username, password, uniq, i);

            using (WebClient client = new WebClient())
            {
                PrepareWebClient((WebClient)client, true);

                NameValueCollection reqparm = GetRequestedParams(sessionId, username, password, uniq, i);
                this.LogRequest(InfoEndpoint, username: username, password: password, session: sessionId, uniq: uniq, i: i);

                try
                {
                    byte[] responsebytes = await client.UploadValuesTaskAsync(InfoEndpoint, "POST", reqparm);

                    string responsebody = Encoding.UTF8.GetString(responsebytes);
                    Info   info         = JsonConvert.DeserializeObject <Info>(responsebody);

                    return(info);
                }
                catch (WebException ex)
                {
                    HandleWebException(ex);
                }
                return(null);
            }
        }
コード例 #12
0
        /// <summary>
        /// Gets the velocity data async for the session's username and password.
        /// </summary>
        /// <param name="sessionId">The Session ID returned from the JavaScript data collector.</param>
        /// <param name="username">The username of the user.</param>
        /// <param name="password">The password of the user.</param>
        /// <returns>Velocity data</returns>
        public async Task <VelocityInfo> GetVelocityAsync(string sessionId, string username, string password)
        {
            ValidateSession(sessionId);

            using (WebClient client = new WebClient())
            {
                PrepareWebClient(client, true);

                NameValueCollection reqparm = GetRequestedParams(sessionId, username, password);
                this.LogRequest(VelocityEndpoint, username: username, password: password, session: sessionId);

                try
                {
                    byte[] responsebytes = await client.UploadValuesTaskAsync(VelocityEndpoint, "POST", reqparm);

                    string responsebody = Encoding.UTF8.GetString(responsebytes);
                    return(await Task.Factory.StartNew(() => JsonConvert.DeserializeObject <VelocityInfo>(responsebody)));
                }
                catch (WebException ex)
                {
                    HandleWebException(ex);
                }
                return(null);
            }
        }
コード例 #13
0
        public async Task <bool> CheckRoboRioImage()
        {
            using (WebClient wc = new WebClient())
            {
                byte[] result = await wc.UploadValuesTaskAsync($"http://{m_connectionValues.ConnectionIp}/nisysapi/server", "POST",
                                                               new NameValueCollection
                {
                    { "Function", "GetPropertiesOfItem" },
                    { "Plugins", "nisyscfg" },
                    { "Items", "system" }
                });

                var sstring = Encoding.Unicode.GetString(result);

                var doc = new XmlDocument();
                doc.LoadXml(sstring);

                var vals = doc.GetElementsByTagName("Property");

                string str = null;

                foreach (XmlElement val in vals.Cast <XmlElement>().Where(val => val.InnerText.Contains("FRC_roboRIO")))
                {
                    str = val.InnerText;
                }

                return(DeployProperties.RoboRioAllowedImages.Any(rio => str != null && str.Contains(rio.ToString())));
            }
        }
コード例 #14
0
        private Task MakeRequestAsync(ClientId clientId, string method)
        {
            if (clientId == null || clientId.Value == null)
            {
                throw new ArgumentNullException("clientId");
            }

            Parameters.Add(clientId);

            ValidateRequestParams();

            var requestParams = new NameValueCollection();

            using (var webClient = new WebClient())
            {
                webClient.Proxy = Proxy;

                requestParams.Add(Parameters.GenerateNameValueCollection());

                if (method == "POST")
                {
                    return(webClient.UploadValuesTaskAsync(_uri, method, requestParams));
                }
                else
                {
                    webClient.QueryString = requestParams;
                    return(webClient.DownloadStringTaskAsync(_uri));
                }
            }
        }
コード例 #15
0
        /// <summary>
        /// Returns the refresh code given the <paramref name="credentials"/> and the <paramref name="accessCode"/>.
        /// </summary>
        /// <param name="credentials">The oauth credentials.</param>
        /// <param name="accessCode">The access code returned from the login flow.</param>
        public static async Task <string> EndOAuthFlow(OAuthCredentials credentials, string redirectUrl, string accessCode)
        {
            var client = new WebClient();
            var form   = new NameValueCollection
            {
                { CodeValue, accessCode },
                { ClientIdKey, credentials.ClientId },
                { ClientSecretKey, credentials.ClientSecret },
                { RedirectUriKey, redirectUrl },
                { GrantTypeKey, AuthorizationCodeValue },
            };

            try
            {
                var response = await client.UploadValuesTaskAsync(OAuthApiUrl, form);

                var decoded = Encoding.UTF8.GetString(response);
                var model   = JsonConvert.DeserializeObject <IDictionary <string, string> >(decoded);
                return(model[RefreshTokenKey]);
            }
            catch (WebException ex)
            {
                Debug.WriteLine($"Failed to finalize oauth flow: {ex.Message}");
                throw new OAuthException(ex.Message, ex);
            }
            catch (JsonException ex)
            {
                Debug.WriteLine($"Failed to parse result: {ex.Message}");
                throw new OAuthException(ex.Message, ex);
            }
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: daniukoi/Google_Form
        public async Task <string> SubmitAsync()
        {
            if (!_field.Any() && !_checkbox.Any())
            {
                throw new InvalidOperationException("No data has been set to submit");
            }

            NameValueCollection nameValue = new NameValueCollection();


            foreach (var temp in _field)
            {
                nameValue.Add(temp.Key, temp.Value);
            }

            foreach (var temp in _checkbox)
            {
                for (int i = 0; i < temp.Value.Length; i++)
                {
                    _baseUrl += temp.Key + "=" + temp.Value[i] + "&";
                }
                _baseUrl.TrimEnd();
            }

            _uri = new Uri(_baseUrl);
            byte[] response = await _client.UploadValuesTaskAsync(_uri, "POST", nameValue);

            string result = Encoding.UTF8.GetString(response);

            return(result);
        }
コード例 #17
0
        static void Main(string[] args)
        {
            var wc  = new WebClient();
            var nvc = new NameValueCollection()
            {
                { "gfe_rd", "cr" }, { "q", "anna+malina" }
            };
            Task <byte[]> tsk = wc.UploadValuesTaskAsync(new Uri("http://www.google.pl"), "GET", nvc);

            try
            {
                Console.Write(tsk.Result);
            }
            catch (AggregateException e)
            {
                foreach (Exception exchild in e.InnerExceptions)
                {
                    Console.WriteLine(exchild.Message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }
コード例 #18
0
        private static async Task <string> GetToken()
        {
            using (var webClient = new WebClient())
            {
                //var test = _configuration.GetValue<string>("AzureAd:ClientId");
                var clientId          = _appSettings.Value.ClientId;
                var contentType       = _appSettings.Value.ContentType;
                var accept            = _appSettings.Value.Accept;
                var clientCredentials = _appSettings.Value.ClientCredentials;
                var clientSecret      = _appSettings.Value.ClientSecret;
                var resource          = _appSettings.Value.Resource;
                var tenantId          = _appSettings.Value.TenantId;



                var requestParameters = new NameValueCollection();
                requestParameters.Add("resource", resource);
                requestParameters.Add("client_id", clientId);
                requestParameters.Add("grant_type", clientCredentials);
                requestParameters.Add("client_secret", clientSecret);
                requestParameters.Add("Content-Type", contentType);
                requestParameters.Add("Accept", accept);

                var url           = $"https://login.microsoftonline.com/{tenantId}/oauth2/token";
                var responsebytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);

                var responsebody = Encoding.UTF8.GetString(responsebytes);
                var obj          = JsonConvert.DeserializeObject <JObject>(responsebody);
                var token        = obj["access_token"].Value <string>();

                return(token);
            }
        }
コード例 #19
0
 /// <summary>
 /// Poll a request until the specified string is found in the response
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="sender"></param>
 /// <param name="ri"></param>
 /// <param name="untilexists"></param>
 /// <param name="cancellationToken"></param>
 /// <param name="pollintervalsecs"></param>
 /// <returns></returns>
 protected async Task PollAsync <T>(T sender, RequestInfo ri, string untilexists, CancellationToken cancellationToken, int pollintervalsecs = 30) where T : IRequest
 {
     string URI = ri.ENDPOINT + ri.Script;
     var    c   = new WebClient();
     await Task.Run(async() =>
     {
         string httpresult = "";
         do
         {
             cancellationToken.ThrowIfCancellationRequested();
             if (ri.Method == HTTPMETHOD.GET)
             {
                 var append        = String.Join("&", ri.Values.Select(kv => kv.Key + "=" + kv.Value));
                 string requesturi = String.Concat(URI, "?", append);
                 var result        = await c.DownloadStringTaskAsync(requesturi);
                 httpresult        = (result);
             }
             else
             {
                 //POST
                 var result = await c.UploadValuesTaskAsync(new Uri(URI), ri.Method.ToString(), ri.Values.ToNameValueCollection());
                 httpresult = (Encoding.UTF8.GetString(result));
             }
             await Task.Delay(new TimeSpan(0, 0, pollintervalsecs));
         } while (!httpresult.Contains(untilexists));//Poll until specified text is found in the resulting page
         sender.SetResponse(httpresult);
     }, cancellationToken);
 }
コード例 #20
0
        public async Task TestMethod3()
        {
            //  Constants
            var tenant     = "vitalsigyn.onmicrosoft.com";
            var serviceUri = "https://vitalsigyn.com/WebApplicationAAD";
            var clientID   = "a1d51587-bf4c-4915-b588-8df1d9fd7ac9";
            var userName   = "******";
            var password   = "******";

            using (var webClient = new WebClient())
            {
                var requestParameters = new NameValueCollection();

                requestParameters.Add("resource", serviceUri);
                requestParameters.Add("client_id", clientID);
                requestParameters.Add("grant_type", "password");
                requestParameters.Add("username", userName);
                requestParameters.Add("password", password);
                requestParameters.Add("scope", "openid");

                var url           = $"https://login.microsoftonline.com/" + tenant + "/oauth2/token";
                var responsebytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);

                var responsebody = Encoding.UTF8.GetString(responsebytes);
            }
        }
コード例 #21
0
ファイル: Imgur.cs プロジェクト: yh200212121212/ScreenToGif
        public async Task <UploadedFile> UploadFileAsync(string path, CancellationToken cancellationToken, IProgress <double> progressCallback = null)
        {
            using (var w = new WebClient())
            {
                w.Headers.Add("Authorization", "Client-ID " + Secret.ImgurId);
                var values = new NameValueCollection {
                    { "image", Convert.ToBase64String(File.ReadAllBytes(path)) }
                };
                var response = await w.UploadValuesTaskAsync("https://api.imgur.com/3/upload.xml", values);

                var x = XDocument.Load(new MemoryStream(response));

                var node     = x.Descendants().FirstOrDefault(n => n.Name == "link");
                var nodeHash = x.Descendants().FirstOrDefault(n => n.Name == "deletehash");

                if (node == null)
                {
                    throw new UploadingException("No link was provided by Imgur", new Exception(x.Document?.ToString() ?? "The document was null. :/"));
                }

                return(new UploadedFile()
                {
                    Link = node.Value, DeleteLink = "https://imgur.com/delete/" + nodeHash?.Value
                });
            }
        }
コード例 #22
0
        private static async Task <string> HttpAppAuthenticationAsync()
        {
            //  Constants
            var resource = "https://graph.microsoft.com/";

            //var tenant = "dovahkiin.onmicrosoft.com";
            //var clientID = "b4ac67df-89f2-4ae0-a64d-87386f081570";
            //var secret = "v9CEUUj0PL8942ln3S1mhi2JTDDc5j5m20BNdyomgaE=";

            using (var webClient = new WebClient())
            {
                var requestParameters = new NameValueCollection();

                requestParameters.Add("resource", resource);
                requestParameters.Add("client_id", clientID);
                requestParameters.Add("grant_type", "client_credentials");
                requestParameters.Add("client_secret", secret);

                var url           = $"https://login.microsoftonline.com/{tenant}/oauth2/token";
                var responsebytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);

                var responsebody = Encoding.UTF8.GetString(responsebytes);
                var obj          = JsonConvert.DeserializeObject <JObject>(responsebody);
                var token        = obj["access_token"].Value <string>();

                return(token);
            }
        }
コード例 #23
0
        static async Task <T> UploadValuesAsync <T>(WebClient WebClient, string Url, NameValueCollection Values)
        {
            // Task.Run done to prevent UI thread from freezing when upload fails.
            var response = await Task.Run(async() => await WebClient.UploadValuesTaskAsync(Url, Values));

            return(JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(response)));
        }
            public async void send(string body)
            {
                if (string.IsNullOrEmpty(_token))
                {
                    _log.Error("Unable to send push notification because 'pushalot.token' is not specified.");
                    return;
                }

                if (string.IsNullOrEmpty(body) || body.Length > 32768)
                {
                    _log.Error("Unable to send push notification because body is null or longer than 32768 characters.");
                    return;
                }

                try
                {
                    using (var client = new WebClient())
                    {
                        var data = new NameValueCollection();
                        data["AuthorizationToken"] = _token;
                        data["Body"] = body;
                        await client.UploadValuesTaskAsync("https://pushalot.com/api/sendmessage", data);
                    }
                }
                catch (Exception e)
                {
                    _log.Error(e.Message, e);
                }
            }
コード例 #25
0
        private async void HandleYesClicked(object sender, EventArgs e)
        {
            btnYes.Enabled = false;
            btnNo.Enabled  = false;
            UpdateStatus(Color.Blue, "Submitting...");
            using (var client = new WebClient())
            {
                try
                {
                    byte[] response = await client.UploadValuesTaskAsync("http://martijn.tikkie.net/reportbug.php", "POST", _collectedData);

                    string responseStr = Encoding.ASCII.GetString(response);
                    if (responseStr.Equals("ok"))
                    {
                        UpdateStatus(Color.Green, "Submitted, thank you!");
                    }
                    else
                    {
                        UpdateStatus(Color.Red, "Server error: " + responseStr);
                    }
                }
                catch (Exception uploadex)
                {
                    UpdateStatus(Color.Red, "Failed to submit: " + uploadex.Message);
                }
            }
        }
コード例 #26
0
        public static async Task UploadImage(Bitmap bmp)
        {
            List <byte> imageBytes = new List <byte>();

            {
                using (var stream = new MemoryStream())
                {
                    bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] buffer = new byte[1024];
                    for (int len; (len = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0;)
                    {
                        for (int i = 0; i < len; i++)
                        {
                            imageBytes.Add(buffer[i]);
                        }
                    }
                }
            }
            using (var w = new WebClient())
            {
                var values = new NameValueCollection
                {
                    { "key", "433a1bf4743dd8d7845629b95b5ca1b4" },
                    { "image", Convert.ToBase64String(imageBytes.ToArray()) }
                };
                byte[] response = await w.UploadValuesTaskAsync("https://api.imgur.com/3/image", values);

                Console.WriteLine(XDocument.Load(new MemoryStream(response)));
            }
        }
コード例 #27
0
        public async Task <TokenInfo> ValidateToken(string token)
        {
            using (var wb = new WebClient())
            {
                //set headers to token based authentication
                var data = new NameValueCollection();
                data["token"] = token;

                try
                {
                    var response = await wb.UploadValuesTaskAsync(new Uri(_endPoint + "validate"), "POST", data);

                    var responseString = System.Text.Encoding.UTF8.GetString(response);
                    var tokenInfo      = JsonConvert.DeserializeObject <TokenInfo>(responseString);

                    //check headers if needed
                    // WebHeaderCollection myWebHeaderCollection = wb.ResponseHeaders;

                    return(tokenInfo);
                }
                catch (WebException ex)
                {
                    //returning null if not authenticated
                    return(null);
                }
            }
            //return Task.Run(() => 1);
        }
コード例 #28
0
        public async Task <TokenInfo> Authenticate(string email, string password)
        {
            using (var wb = new WebClient())
            {
                var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(email + ":" + password);
                var base64         = System.Convert.ToBase64String(plainTextBytes);

                var data = new NameValueCollection();

                //set header to basic authorization
                data["Authorization"] = "Basic " + base64;
                //data["password"] = "******";
                wb.Headers.Add(data);

                try
                {
                    var response = await wb.UploadValuesTaskAsync(new Uri(_endPoint + "generate"), "POST", new NameValueCollection());

                    var responseString = System.Text.Encoding.UTF8.GetString(response);
                    var tokenInfo      = JsonConvert.DeserializeObject <TokenInfo>(responseString);

                    //check headers if needed
                    // WebHeaderCollection myWebHeaderCollection = wb.ResponseHeaders;

                    return(tokenInfo);
                }
                catch (WebException ex)
                {
                    //var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
                    //returning null if not authenticated
                    return(null);
                }
            }
            //return Task.Run(() => 1);
        }
コード例 #29
0
        public async Task <string> GetTokenAsync()
        {
            string token;
            string postURL  = config.APIMPostURL;
            string clientID = config.APIMClientID;
            string secret   = config.APIMClientSecret;
            string resource = config.APIMResource;

            //string apimTenantId = config.APIMTenantId;

            using (var webClient = new WebClient())
            {
                var requestParameters = new NameValueCollection();
                requestParameters.Add("grant_type", "client_credentials");
                requestParameters.Add("client_id", clientID);
                requestParameters.Add("client_secret", secret);
                requestParameters.Add("resource", resource);

                var url = "https://login.microsoftonline.com/" + APIMTenantId + "/oauth2/token";
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                var responseBytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);

                var responseBody = Encoding.UTF8.GetString(responseBytes);

                var jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(responseBody);
                token = jsonObject.Value <string>("access_token");
            }

            return(token);
        }
コード例 #30
0
        private async Task <string> GetPriceFromSite(string inCity, string outCity, string car)
        {
            string url = @"https://www.eastlines.ru";

            using (var client = new WebClient())
            {
                // Создаём коллекцию параметров
                var pars = new NameValueCollection
                {
                    // Добавляем необходимые параметры в виде пар ключ, значение
                    { "action", "getCalcInfo" },
                    { "module", "calc" },
                    { "city1", inCity },
                    { "city2", outCity },
                    { "car", car }
                };

                // Посылаем параметры на сервер
                var response = await client.UploadValuesTaskAsync(url, pars);

                //Конвертируем данные из байтов в строку, а строку в JSON и отправляем серверу
                var deserealizedResult = JsonConvert.DeserializeObject <Dictionary <string, string> >(Encoding.GetEncoding("UTF-8")
                                                                                                      .GetString(response, 0, response.Length));
                string value = "Цена устанавливается через менеджера";
                deserealizedResult.TryGetValue("price", out value);
                return(value.Replace(" ", ""));
            }
        }
コード例 #31
0
ファイル: WebClientTest.cs プロジェクト: Corillian/corefx
 protected override Task<byte[]> UploadValuesAsync(WebClient wc, string address, NameValueCollection data) => wc.UploadValuesTaskAsync(address, data);
コード例 #32
0
ファイル: WebClientTest.cs プロジェクト: Corillian/corefx
 public static async Task ConcurrentOperations_Throw()
 {
     await LoopbackServer.CreateServerAsync((server, url) =>
     {
         var wc = new WebClient();
         Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
         Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
         return Task.CompletedTask;
     });
 }
コード例 #33
0
ファイル: WebClientTest.cs プロジェクト: Corillian/corefx
        public static void UploadValues_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();
            
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((string)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((Uri)null, null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null, null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((string)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((Uri)null, null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues("http://localhost", null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues("http://localhost", null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues(new Uri("http://localhost"), null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null, null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync("http://localhost", null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync("http://localhost", null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync(new Uri("http://localhost"), null, null); });
        }