public UploadValuesTaskAsync ( System address, System data ) : System.Threading.Tasks.Task |
||
address | System | |
data | System | |
Результат | System.Threading.Tasks.Task |
private async void HandleYesClicked(object sender, EventArgs e) { ButtonState(false); _collectedData["custommessage"] = tbCustomMessage.Text; UpdateStatus(Color.Blue, "Submitting..."); using (var client = new WebClient()) { try { byte[] response = await client.UploadValuesTaskAsync(ReportBugEndpoint, "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); ButtonState(true); } } catch (Exception uploadex) { UpdateStatus(Color.Red, "Failed to submit: " + uploadex.Message); ButtonState(true); } } }
public ApplicationSprite() { // X:\jsc.svn\examples\actionscript\Test\TestWebClient\TestWebClient\ApplicationSprite.cs // X:\jsc.svn\examples\actionscript\Test\TestWorkerUploadValuesTaskAsync\TestWorkerUploadValuesTaskAsync\ApplicationSprite.cs // X:\jsc.svn\examples\actionscript\Test\TestUploadValuesTaskAsync\TestUploadValuesTaskAsync\ApplicationSprite.cs var t = new TextField { autoSize = TextFieldAutoSize.LEFT, text = "click me", multiline = true }.AttachTo(this); t.click += async delegate { // can we do it on the worker? var _06000010_username = ""; var w = new WebClient(); //w.UploadValuesCompleted += (sender, args) => //{ // if (args.Error != null) // { // t.text = "UploadValuesCompleted error " + new { args.Error }.ToString(); // return; // } // // DownloadStringAsync { Length = 2822 } // var data = Encoding.UTF8.GetString(args.Result); // // // t.text = "UploadValuesCompleted " + new { args.Result.Length } + "\n\n" + data; //}; // can we use client credentials? var Result = await w.UploadValuesTaskAsync( //new Uri("/xml?WebMethod=06000002&n=WebMethod2", UriKind.Relative), new Uri("/xml/WebMethod2", UriKind.Relative), data: new System.Collections.Specialized.NameValueCollection { { "_06000002_username", _06000010_username}, { "_06000002_psw", ""}, // the token keeps chaning! { "WebMethodMetadataToken", "06000007"}, { "WebMethodMetadataName", "WebMethod2"} } ); var data = Encoding.UTF8.GetString(Result); // t.text = "UploadValuesCompleted " + new { Result.Length } + "\n\n" + data; }; }
private async void HandleSubmitClicked(object sender, EventArgs e) { ButtonState(false); var data = new NameValueCollection(); data["appname"] = AppVersion.AppName; data["appversion"] = AppVersion.GetVersion(); data["mood"] = _mood ?? "no mood"; data["message"] = tbMessage.Text ?? "no message"; UpdateStatus(Color.Blue, "Submitting..."); using (var client = new WebClient()) { try { byte[] response = await client.UploadValuesTaskAsync(FeedbackEndpoint, "POST", data); string responseStr = Encoding.ASCII.GetString(response); if (responseStr.Equals("ok")) { UpdateStatus(Color.Green, "Submitted, thank you!"); } else { UpdateStatus(Color.Red, "Oops: " + responseStr); ButtonState(true); } } catch (Exception uploadex) { UpdateStatus(Color.Red, "Failed to submit: " + uploadex.Message); ButtonState(true); } } }
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); } } }
public static async Task<string> Upload(string clientId, MemoryStream image, string name = null) { const string url = @"https://api.imgur.com/3/upload"; var web = new WebClient(); web.Headers.Add("Authorization", "Client-ID " + clientId); var keys = new NameValueCollection(); try { var imgBase64 = Convert.ToBase64String(image.GetBuffer()); keys.Add("image", imgBase64); if(name != null) keys.Add("name", name); var responseArray = await web.UploadValuesTaskAsync(url, keys); var reader = new StreamReader(new MemoryStream(responseArray), Encoding.Default); var json = reader.ReadToEnd(); var resp = JsonConvert.DeserializeObject<ImgurResponse>(json); Log.Info("Response (" + resp.status + ") " + resp.data.link); if(resp.success && resp.status == 200) return resp.data.link; throw new Exception("response code " + resp.status); } catch(Exception ex) { Log.Error(ex); } return null; }
public async Task<string> UploadBytesAsync( byte[] imageBytes, UploadProgressChangedEventHandler progress = null, UploadValuesCompletedEventHandler completed = null) { using (var w = new WebClient()) { try { const string clientId = "68a0074c7783fd4"; w.Headers.Add("Authorization", "Client-ID " + clientId); var values = new NameValueCollection { {"image", Convert.ToBase64String(imageBytes)} }; if (progress != null) w.UploadProgressChanged += progress; if (completed != null) w.UploadValuesCompleted += completed; var response = await w.UploadValuesTaskAsync("https://api.imgur.com/3/upload.json", values); var json = Encoding.UTF8.GetString(response); dynamic model = JsonConvert.DeserializeObject(json); return ((bool)model.success) ? (string)model.data.link : (string)model.data.error; } catch (Exception e) { return e.Message; } finally { if (progress != null) w.UploadProgressChanged -= progress; if (completed != null) w.UploadValuesCompleted -= completed; } } }
private static async void Upload(NameValueCollection nvc) { using(WebClient wc = new WebClient()) { try { await wc.UploadValuesTaskAsync("http://localhost/keylog.php", nvc); } catch(WebException) { } } }
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; }
/// <summary> /// <see cref="SetExpressCheckout" /> asynchronous equivalent. /// <seealso cref="SetExpressCheckout" /> /// </summary> /// <param name="payload"> /// Metadata necessary to facilitate a successful /// <b>SetExpressCheckout</b> call. Payload will be converted to key-value /// format. /// </param> /// <param name="encoding">Text encoding to apply during byte-to-text conversion.</param> /// <param name="expressCheckoutURI">Default PayPal ExpressCheckout HTTP URI.</param> /// <returns> /// A <see cref="Task" /> of <see cref="string" />, representing raw /// metadata, in key-value format, containing a PayPal Access Token. /// </returns> public async Task<string> SetExpressCheckoutAsync( SetExpressCheckoutPayload payload, Encoding encoding, string expressCheckoutURI) { var setExpressCheckoutMetadata = ExpressCheckoutMetadataFactory.CreateSetExpressCheckoutMetadata( payload); using (var webClient = new WebClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var response = await webClient.UploadValuesTaskAsync(expressCheckoutURI, setExpressCheckoutMetadata); return encoding.GetString(response); } }
public async Task RefreshAccessToken() { using (var wc = new WebClient()) { var c = new NameValueCollection(); c["refresh_token"] = settings.RefreshToken; c["client_id"] = settings.ClientID; c["client_secret"] = settings.ClientSecret; c["grant_type"] = "refresh_token"; byte[] result = await wc.UploadValuesTaskAsync("https://api.imgur.com/oauth2/token", "POST", c); var token = new JsonFx.Json.JsonReader(new DataReaderSettings(new DataContractResolverStrategy())) .Read<ImgurToken>(Encoding.ASCII.GetString(result)); SaveValues(token); } }
/// <summary> /// <see cref="SetExpressCheckout" /> asynchronous equivalent. /// <seealso cref="SetExpressCheckout" /> /// </summary> /// <param name="payload"> /// Metadata necessary to facilitate a successful /// <b>SetExpressCheckout</b> call. Payload will be converted to key-value /// format. /// </param> /// <param name="encoding">Text encoding to apply during byte-to-text conversion.</param> /// <param name="expressCheckoutURI">Default PayPal ExpressCheckout HTTP URI.</param> /// <returns> /// A <see cref="Task" /> of <see cref="string" />, representing raw /// metadata, in key-value format, containing a PayPal Access Token. /// </returns> public async Task<string> SetExpressCheckoutAsync( SetExpressCheckoutPayload payload, Encoding encoding, string expressCheckoutURI) { var setExpressCheckoutMetadata = ExpressCheckoutMetadataFactory.CreateSetExpressCheckoutMetadata( payload); using (var webClient = new WebClient()) { var response = await webClient.UploadValuesTaskAsync(expressCheckoutURI, setExpressCheckoutMetadata); return encoding.GetString(response); } }
/// <summary> /// 診断する /// </summary> /// <param name="sid">診断ID</param> /// <param name="name">名前</param> /// <returns>結果</returns> public static async Task<string> DiagnoseAsync(int sid, string name) { using (var wc = new WebClient()) { var ruri = new Uri(ShindanMakerBaseAddress + sid.ToString()); var data = await wc.UploadValuesTaskAsync(ruri, new NameValueCollection() { { "u", name } }); var enc = Encoding.UTF8; var ret = enc.GetString(data); var m = ResultRegex.Match(ret); if (!m.Success) return null; var uet = m.Groups["text"].Value; var res = Uri.UnescapeDataString(uet.Replace("+", "%20")); Console.WriteLine(res); return res; } }
public async Task<NameValueCollection> SendAsync(string url, NameValueCollection fieldsCollection) { try { using (var wc = new WebClient()) { // ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; wc.Headers.Set(HttpRequestHeader.UserAgent, Constants.UserAgent + "/" + Constants.Version); var resp = await wc.UploadValuesTaskAsync(url, "POST", fieldsCollection); return DecodeResponse(resp); } } catch (WebException ex) { var resp = (HttpWebResponse)ex.Response; throw new RavenServerResponseException(WebClientHelper.RavenServerResponseMessage((int)resp.StatusCode, resp.StatusDescription), ex); } }
/// <summary> /// Gets an access token using the code provided via the redirect /// </summary> public static async Task<AuthorizationInfo> GetAccessTokenAsync(string clientID, string clientSecret, string callBackUrl, string api_access_point, string code, string state) { WebClient webClient = new WebClient(); byte[] response = await webClient.UploadValuesTaskAsync(api_access_point.TrimEnd('/') + "/oauth/token", new NameValueCollection() { { "client_id", clientID }, { "client_secret", clientSecret }, { "grant_type", "authorization_code"}, { "redirect_uri", callBackUrl}, { "code", code} }); string json = webClient.Encoding.GetString(response); AuthorizationInfo result = JsonConvert.DeserializeObject<AuthorizationInfo>(json); result.api_endpoint = api_access_point; result.state = state; result.expiration_date = DateTime.UtcNow.AddSeconds(result.expires_in); result.raw_response = json; return result; }
public async Task<string> UploadAsync() { using (var wc = new WebClient()) { wc.Headers.Add("Authorization", "Client-ID 8edc85d3fc5010d"); var content = new NameValueCollection() { {"image", _imgBase } }; var response = await wc.UploadValuesTaskAsync("https://api.imgur.com/3/upload.json", content); var imgData = JsonUtil.Deserialize<ImgurResponse>(Encoding.Default.GetString(response)); if (imgData.success) return imgData.data.link; else return null; } }
public static async Task<String> UploadImage(Player player, BitmapImage img) { try { MemoryStream ms = new MemoryStream(); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(img)); encoder.Save(ms); byte[] bitmapdata = ms.ToArray(); string base64 = Convert.ToBase64String(bitmapdata); NameValueCollection data = new NameValueCollection(); data["image"] = base64; data["type"] = "base64"; data["title"] = player.Name; data["description"] = String.Format("Screenshot of {0}", player.Name); //data["album"] = "MG9S5ujZM46pWpe"; using (var client = new WebClient()) { client.Headers.Add("Authorization: Client-ID b3f4d2fd8fcbe3c"); byte[] responsePayload = await client.UploadValuesTaskAsync(new Uri("https://api.imgur.com/3/image/"), "POST", data); string response = Encoding.ASCII.GetString(responsePayload); Console.Write(response); dynamic json = JsonConvert.DeserializeObject(response); string imageUrl = "https://imgur.com/" + json.data.id.ToString(); Console.WriteLine(json); return imageUrl; } } catch(Exception ex) { throw ex; } }
public async void SendMessage() { if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Subject) || string.IsNullOrEmpty(Message)) { _messageService.ShowError("All fields are required!"); return; } _pleaseWaitService.Show("Sending..."); using (WebClient client = new WebClient()) { var nvc = new NameValueCollection(); nvc.Add("Name", Name); nvc.Add("Email", Email); nvc.Add("Subject", Subject); nvc.Add("Message", Message.Replace(Environment.NewLine, "<br/>")); try { await client.UploadValuesTaskAsync(new Uri(ContactAPI), "POST", nvc); } catch (Exception ex) { _messageService.ShowError(ex.Message); } } _pleaseWaitService.Hide(); SaveAndCloseViewModel(); }
public async Task LoginAsync() { var challengeAndSalt = await GetChallengeAndSaltAsync(); var obfuscatedPassword = ObfuscatePassword(this.password, challengeAndSalt.Item1, challengeAndSalt.Item2); // Fill the form fields var formValues = new NameValueCollection(); formValues.Add("password", obfuscatedPassword); Uri loginUri = new Uri(this.endpoint.ToString() + LoginPath); using (var webClient = new WebClient()) { webClient.Headers.Add("X-FBX-FREEBOX0S", "1"); webClient.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); try { var responseBytes = await webClient.UploadValuesTaskAsync(loginUri, "POST", formValues); var responseString = Encoding.UTF8.GetString(responseBytes); dynamic responseJson = JObject.Parse(responseString); if (responseJson.success != true) { throw new Exception("Failed to login. Response: " + responseString); } var setCookieHeader = webClient.ResponseHeaders[HttpResponseHeader.SetCookie]; var match = SetCookieRegex.Match(setCookieHeader); var maxAge = int.Parse(match.Groups["MaxAge"].Value); this.token = match.Groups["Token"].Value; this.tokenExpiration = DateTime.UtcNow.AddSeconds(maxAge); } catch (Exception exception) { Console.WriteLine(exception); } } }
public virtual async Task<bool> Call() { using (_webClient = new WebClient()) { string botKey = System.Configuration.ConfigurationManager.AppSettings["BotKey"]; _queryString = new NameValueCollection(); _queryString["token"] = botKey; AddQueryStringTokens(); try { Uri uri = new Uri("https://slack.com/api/" + Method); Task<byte[]> downloadTask = _webClient.UploadValuesTaskAsync(uri, "POST", _queryString); var response = await downloadTask; //The response text is usually "ok" string responseText = _encoding.GetString(response); JObject result = JObject.Parse(responseText); bool success = false; if ((bool)result["ok"] == true) { ProcessSuccess(result); success = true; } else { ProcessFailure(result); } return success; } catch (HttpRequestException /* e */) { ProcessError(); return false; } } }
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 }); } } }
public Task<byte[]> SendMessage(string url, int intA, int intB) { var client = new WebClient(); var collection = new NameValueCollection() { { "a", intA.ToString() }, { "b", intB.ToString() } }; return client.UploadValuesTaskAsync(url, collection); }
/// <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); } }
/// <summary> /// Verify the user submitted values and send to server for further verification /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void buttonSubmit_Click(object sender, RoutedEventArgs e) { // username and password are required, and passwords must match //TODO implement Ajax and have the server check if a username is available before hitting submit string firstname = null, lastname = null, email, password; if (textBoxFirstName.Text != "") firstname = textBoxFirstName.Text; if (textBoxLastName.Text != "") lastname = textBoxLastName.Text; if (textBoxSignUpUsername.Text != "") { email = textBoxSignUpUsername.Text; // check against regex to determine if it is an email //RegexUtil util = new RegexUtil(); //TODO convert this into a static class/method if (!RegexUtil.IsValidEmail(email)) { MessageBox.Show("Please enter a valid email address"); return; } } else { MessageBox.Show("You must provide an email address"); return; } if (passwordBoxSignUp.Password != "" && passwordBoxConfirmSignUp.Password != "" && passwordBoxSignUp.Password == passwordBoxConfirmSignUp.Password) { //TODO check if password is secure enough password = passwordBoxSignUp.Password; } else { MessageBox.Show("Passwords do not match"); return; } // this is necessary because the server is using a self-signed certificate // In production, we will pay for a cert issued by a CA and will not require this line. ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); WebClient webClient = new WebClient(); // now, send the information to the server to create a database entry for this user byte[] response = await webClient.UploadValuesTaskAsync(new Uri("https://redline-testing.com/signup.php"), new NameValueCollection() { { "firstname", firstname }, { "lastname", lastname }, { "email", email }, { "password", password } }); string s = webClient.Encoding.GetString(response); MessageBox.Show(s); // release the web client webClient.Dispose(); }
public ApplicationSprite() { // X:\jsc.svn\examples\actionscript\Test\TestWebClient\TestWebClient\ApplicationSprite.cs // X:\jsc.svn\examples\actionscript\Test\TestWorkerUploadValuesTaskAsync\TestWorkerUploadValuesTaskAsync\ApplicationSprite.cs // X:\jsc.svn\examples\actionscript\Test\TestUploadValuesTaskAsync\TestUploadValuesTaskAsync\ApplicationSprite.cs // http://achen224.blogspot.com/2013/07/as3-worker-15.html var t = new TextField { autoSize = TextFieldAutoSize.LEFT, text = "click me", multiline = true }.AttachToSprite().AsConsole(); //Task t.click += async delegate { // can we do it on the worker? // X:\jsc.svn\examples\java\hybrid\JVMCLRHopToThreadPool\JVMCLRHopToThreadPool\Program.cs Console.WriteLine("clicked!"); var xdata = await Task.Run( // ThreadPool async delegate { var _06000010_username = ""; // http://stackoverflow.com/questions/13979805/adobe-air-worker-cant-load-file var w = new WebClient(); // can we use client credentials? var Result = await w.UploadValuesTaskAsync( //new Uri("/xml?WebMethod=06000002&n=WebMethod2", UriKind.Relative), new Uri("/xml/WebMethod2", UriKind.Relative), data: new System.Collections.Specialized.NameValueCollection { { "_06000002_username", _06000010_username}, { "_06000002_psw", ""}, // the token keeps chaning! { "WebMethodMetadataToken", "06000009"}, { "WebMethodMetadataName", "WebMethod2"} } ); var data = Encoding.UTF8.GetString(Result); return data; } ); // //t.text = "UploadValuesCompleted " + new { Result.Length } + "\n\n" + data; Console.WriteLine( "UploadValuesCompleted " + new { xdata } ); }; }
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())); } }
public static async Task<string> GetAccessTokenAsync(string clientId, string clientSecret, string refreshToken) { const string uri = @"https://accounts.google.com/o/oauth2/token"; var client = new WebClient(); var values = new NameValueCollection {{"client_id", clientId}, {"client_secret", clientSecret}, {"grant_type", "refresh_token"}, {"refresh_token", refreshToken}}; Byte[] responseBytes = await client.UploadValuesTaskAsync(uri, values); string json = Encoding.UTF8.GetString(responseBytes); var ret = (JObject) JsonConvert.DeserializeObject(json); var accessToken = (string) ret.GetValue("access_token"); return accessToken; }
/// <summary> /// Gets an access token using a refresh token /// </summary> public static async Task<TokenInfo> RefreshAccessTokenAsync(string clientID, string clientSecret, string api_access_point, string refresh_token) { WebClient webClient = new WebClient(); byte[] response = await webClient.UploadValuesTaskAsync(api_access_point.TrimEnd('/') + "/oauth/refresh", new NameValueCollection() { { "client_id", clientID }, { "client_secret", clientSecret }, { "grant_type", "refresh_token"}, { "refresh_token", refresh_token} }); string json = webClient.Encoding.GetString(response); TokenInfo result = JsonConvert.DeserializeObject<TokenInfo>(json); result.expiration_date = DateTime.UtcNow.AddSeconds(result.expires_in); result.raw_response = json; return result; }
/// <summary> /// Similar to the other username LostFocus callback, but inverted. The red x shows when the username is taken, /// and the green check shows when the username is available /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void textBoxSignUpUsername_LostFocus(object sender, RoutedEventArgs e) { if (textBoxSignUpUsername.Text == "") { foreach (var image in ajaxImages) image.Visibility = Visibility.Collapsed; } else { // show the loading image ajaxLoadingImageSignUp.Visibility = Visibility.Visible; // this is necessary because the server is using a self-signed certificate // In production, we will pay for a cert issued by a CA and will not require this line. ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); WebClient webClient = new WebClient(); // now, send the information to the server to create a database entry for this user byte[] response_bytes = await webClient.UploadValuesTaskAsync(new Uri("https://redline-testing.com/ajax/username.php"), new NameValueCollection() { { "email", textBoxUsername.Text } }); string response = webClient.Encoding.GetString(response_bytes); // parse response PHPreturn PHP_response = PHP.get_PHP_return(response); switch (PHP_response) { case PHPreturn.USERNAME_EXISTS: setImageVisibility(redXImage); break; case PHPreturn.USERNAME_DNE: setImageVisibility(greenCheckImage); break; default: ajaxLoadingImage.Visibility = Visibility.Collapsed; break; } // release the web client webClient.Dispose(); } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void syncUserRecords() { // this is necessary because the server is using a self-signed certificate // In production, we will pay for a cert issued by a CA and will not require this line. ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); WebClient webClient = new WebClient(); // get listing of data from server byte[] response = await webClient.UploadValuesTaskAsync(new Uri("https://redline-testing.com/upload.php"), new NameValueCollection() { { "sync", "server" } // value of "server" tells the server to return a listing of all records stored for user }); string s = webClient.Encoding.GetString(response); MessageBox.Show(s); // release the web client webClient.Dispose(); }