public static string DELETE(string uri, IDictionary<string, string> args) { try { WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; client.Headers["Connection"] = "Keep-Alive"; StringBuilder formattedParams = new StringBuilder(); IDictionary<string, string> parameters = new Dictionary<string, string>(); foreach (var arg in args) { parameters.Add(arg.Key, arg.Value); formattedParams.AppendFormat("{0}={{{1}}}", arg.Key, arg.Key); } //Formatted URI Uri baseUri = new Uri(uri); client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompletedDelete); client.UploadStringAsync(baseUri, "DELETE", string.Empty); allDone.Reset(); allDone.WaitOne(); return requestResult; } catch (WebException ex) { return ReadResponse(ex.Response.GetResponseStream()); } }
public void MakeRequest(string type, string platform, string reqjsondata) { System.Text.UTF8Encoding en = new System.Text.UTF8Encoding(); string secret = Configs.Secret; string uri = "http://api.bf3stats.com/" + platform + "/" + type + "/"; WebClient wc = new WebClient(); wc.Headers["Content-Type"] = "application/x-www-form-urlencoded"; if (type == "setupkey") { wc.UploadStringCompleted += new UploadStringCompletedEventHandler(completed_register); } else { wc.UploadStringCompleted += new UploadStringCompletedEventHandler(completed_update); secret = Configs.GetAPIkey(); } System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(en.GetBytes(secret)); Byte[] bytes = en.GetBytes(reqjsondata); string encodedRequest = Convert.ToBase64String(bytes).Replace('+', '-').Replace('/', '_').Replace("=", ""); byte[] hashVal = hmac.ComputeHash(en.GetBytes(encodedRequest)); string signature = Convert.ToBase64String(hashVal).Replace('+', '-').Replace('/', '_').Replace("=", ""); string query = "data=" + encodedRequest + "&sig=" + signature; wc.UploadStringAsync(new Uri(uri), "POST", query); }
/// <summary> /// Change Pin webservice /// </summary> private void ChangePinWebService() { string apiUrl = RxConstants.changePin; newPinHashed = Utilities.GetSHA256(objSettingsConfirmChangePinVM.Pin); oldPinHashed = Utilities.GetSHA256(App.PIN); try { ChangePinRequest objInputParam = new ChangePinRequest { mail = App.LoginEmailId, pin = oldPinHashed, newpin = newPinHashed, system_version = "android", app_version = "1.6", branding_version = "MLP" }; WebClient changepinswebservicecall = new WebClient(); var uri = new Uri(apiUrl, UriKind.RelativeOrAbsolute); var json = JsonHelper.Serialize(objInputParam); changepinswebservicecall.Headers["Content-type"] = "application/json"; changepinswebservicecall.UploadStringCompleted += ChangePinWebServiceCall_UploadStringCompleted; changepinswebservicecall.UploadStringAsync(uri, "POST", json); } catch (Exception) { MessageBox.Show("Sorry, Unable to process your request."); } }
/// <summary> /// Method to call the web service /// </summary> private void GetDynamicSplash() { CheckResponseTime(); string apiUrl = RxConstants.getPharmacyInformations; GetPharmacyInformationRequest objInputParameters = new GetPharmacyInformationRequest { Pharmacyid = App.LoginPharId.ToUpper(), Deviceid = string.Empty, Model = string.Empty, Os = string.Empty, Branding_hash = string.Empty, Advert_hash = string.Empty, Drugs_hash = string.Empty, system_version = "android", app_version = "1.6", branding_version = "MLP" }; WebClient pharmacyinfodynamicsplashwebservicecall = new WebClient(); var uri = new Uri(apiUrl, UriKind.RelativeOrAbsolute); var json = JsonHelper.Serialize(objInputParameters); pharmacyinfodynamicsplashwebservicecall.Headers["Content-type"] = "application/json"; pharmacyinfodynamicsplashwebservicecall.UploadStringCompleted += pharmacyinfodynamicsplashwebservicecall_UploadStringCompleted; pharmacyinfodynamicsplashwebservicecall.UploadStringAsync(uri, "POST", json); }
private void btn_Login(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPassword.Password )) { MessageBox.Show("Kullanıcı adı ve şifre alanları boş geçilemez."); return; } Progress.IsIndeterminate = true; txtUserName.IsEnabled = false; txtPassword.IsEnabled = false; LoginObject log = new LoginObject(); log.e = txtUserName.Text; log.p = txtPassword.Password; WebClient web = new WebClient(); web.Headers["Content-Type"] = "application/json"; web.Headers["User-Agent"] = "NeroIOS4/1.0.1 CFNetwork/609 Darwin/13.0.0"; web.UploadStringCompleted += web_UploadStringCompleted; string PostData = JsonConvert.SerializeObject(log); ((ApplicationBarIconButton)sender).IsEnabled = false; web.UploadStringAsync(new Uri("http://api.nero.mekanist.net/v2/user/login", UriKind.Absolute), "POST", PostData, sender); }
/// <summary> /// Prepares a hue bridge to allow the application to interact with it - needs to be run once per bridge. /// </summary> /// <param name="bridgeip">IP address of the bidge to connect to.</param> /// <param name="uname">Username for the paplication to use.</param> /// <returns>Boolean value depending on whether registration was a success.</returns> public bool hueconfigure(string bridgeip, string uname) { var client = new WebClient(); Tools.Log log = new Tools.Log(); //our uri to perform registration var uri = new Uri(string.Format("http://{0}/api", bridgeip)); //create our registration object, along with username and description var reg = new { username = uname, devicetype = Properties.Resources.APPLICATION_TITLE }; var jsonObj = JsonConvert.SerializeObject(reg); //decide what to do with the response we get back from the bridge client.UploadStringCompleted += (o, args) => { try { log.Write(Properties.Resources.LOG_HUE_BRIDGE_RESPONSE + " " + args.Result); } catch (Exception ex) { log.Write(Properties.Resources.LOG_HUE_BRIDGE_EXCEPTION + " " + ex.Message); } }; //Invoke a POST to the bridge client.UploadStringAsync(uri, jsonObj); //WriteLog("Connection request sent (hope you pressed the button!"); return true; }
private void btnLogin_Click(object sender, RoutedEventArgs e) { if (Validation() == true) { // show Loader myIndeterminateProbar.Visibility = Visibility.Visible; //==================================================================================================================== // Login Check //==================================================================================================================== // Parameters LoginRequest obj = new LoginRequest(); obj.email = txtUserName.Text.Trim(); // "djhs16"; obj.password = txtPassWord.Password.Trim(); //"qaz"; String data = "email=" + obj.email + "&password="******"Content-Type"] = "application/x-www-form-urlencoded"; webClient.Headers[HttpRequestHeader.AcceptLanguage] = "en_US"; webClient.UploadStringAsync(new Uri(Utilities.GetURL("auth/signIn/")), "POST", data); //Assign Event Handler webClient.UploadStringCompleted += wc_UploadStringCompleted; } }
void Print(object sender, RoutedEventArgs e) { WebClientInfo wci = Application.Current.Resources["dbclient"] as WebClientInfo; WebClient client = new WebClient(); client.UploadStringCompleted += wc_UploadStringCompleted; client.UploadStringAsync(new Uri(wci.BaseAddress), String.Format("[{{\"operator\":\"sql\",\"data\":\"update t_fapiaoinfos set f_fapiaostatue='已用' where f_invoicenum={0}\"}}]", fapiaoNum1.Text)); }
/// <summary> /// To get the user details while login and display it when "continue" is clciked /// </summary> private void GetUserDetailsWebService() { string apiUrl = RxConstants.getUserDetails; try { LoginParameters objLoginparameters = new LoginParameters { Mail = App.LoginEmailId, Pharmacyid = App.LoginPharId.ToUpper(), Pin = App.HashPIN, system_version = "android", app_version = "1.6", branding_version = "MLP" }; WebClient userdetailswebservicecall = new WebClient(); var uri = new Uri(apiUrl, UriKind.RelativeOrAbsolute); var json = JsonHelper.Serialize(objLoginparameters); userdetailswebservicecall.Headers["Content-type"] = "application/json"; userdetailswebservicecall.UploadStringCompleted += userdetailswebservicecall_UploadStringCompleted; userdetailswebservicecall.UploadStringAsync(uri, "POST", json); } catch (Exception) { MessageBox.Show("Sorry, Unable to process your request."); } }
private void LoadUrl(String us, String pwd) { StringBuilder parameter = new StringBuilder(); parameter.AppendFormat("{0}={1}&", "username", HttpUtility.UrlEncode(us)); parameter.AppendFormat("{0}={1}&", "password", HttpUtility.UrlEncode(pwd)); parameter.AppendFormat("{0}={1}&", "tag", HttpUtility.UrlEncode(us)); Navigation.Tag = parameter.AppendFormat("{0}={1}&", "tag", HttpUtility.UrlEncode(us)).ToString(); if (us.Equals("") || pwd.Equals("")) { Result = "Kosong"; MessageBox.Show("Username or Password should not be empty!"); } else { try { WebClient clientLogin = new WebClient(); clientLogin.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; clientLogin.Headers[HttpRequestHeader.ContentLength] = parameter.Length.ToString(); clientLogin.UploadStringCompleted += new UploadStringCompletedEventHandler(uploadLoginComplete); clientLogin.UploadStringAsync(new Uri(URL.BASE3 + "APIv2/landing/login.php"), "POST", parameter.ToString()); } catch { Result = "false"; } } }
private void apBarChangePassword_Click(object sender, EventArgs e) { string password = textBoxPwd.Password; string cpassword = textBoxCpwd.Password; StringBuilder parameter = new StringBuilder(); parameter.AppendFormat("{0}={1}&", "password", HttpUtility.UrlEncode(password.ToString())); if (password.Equals("") || cpassword.Equals("")) { MessageBox.Show("Please complete all field below."); } else { try { WebClient clientLogin = new WebClient(); clientLogin.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; clientLogin.Headers[HttpRequestHeader.ContentLength] = parameter.Length.ToString(); clientLogin.UploadStringCompleted += new UploadStringCompletedEventHandler(uploadRegisterComplete); clientLogin.UploadStringAsync(new Uri(URL.BASE3 + "api/setting/changepwd.php?id_donatur=" + Navigation.navIdLogin), "POST", parameter.ToString()); } catch { MessageBox.Show("An error occurred on the connection!"); } } }
public string DoOCR(string strRequestBody) { try { System.ComponentModel.AsyncOperationManager.SynchronizationContext = new System.Threading.SynchronizationContext(); m_bFinsh = false; m_strResponse = ""; using (System.Net.WebClient client = new System.Net.WebClient()) { client.Headers.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36"); client.UploadStringCompleted += new UploadStringCompletedEventHandler(UploadStringCallback); Uri objUrl = new Uri("http://127.0.0.1:18622/dwt/dwt_trial_13300115/OCRPro"); client.UploadStringAsync(objUrl, strRequestBody); while (1 > 0) { if (m_bFinsh == true) { break; } System.Threading.Thread.Sleep(1000); } return(m_strResponse); } } catch (Exception ex) { string _ex = ex.Message; return(_ex); } }
public void ClientePost() { try { List<Cliente> listCliente = ClienteDB.GetAll(); for (int x = 0; listCliente.Count() > x; x++) { WebClient webClient = new WebClient(); webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded"; webClient.Encoding = Encoding.UTF8; webClient.UploadStringAsync(new Uri("http://apiatenda.azurewebsites.net/api/cliente/"), "POST", "&Nome=" + listCliente[x].Nome + "&Telefone=" + listCliente[x].Telefone + "&Endereco=" + listCliente[x].Endereco + "&Bairro=" + listCliente[x].Bairro + "&Cidade=" + listCliente[x].Cidade + "&Estado=" + listCliente[x].Estado + "&CPF_CNPJ=" + listCliente[x].CPF_CNPJ); } } catch (ArgumentNullException ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Method to call Reset Pin Webservice /// </summary> private void ResetPinWebService() { string apiUrl = RxConstants.resetPin; var pinHashed = Utilities.GetSHA256(objResetPinLoginViewModel.DisplaySignUpPin); try { ResetPinRequest objInputParam = new ResetPinRequest { mail = objResetPinLoginViewModel.LoginEmail, code = objResetPinLoginViewModel.AuthCode, pin = pinHashed, system_version = "android", app_version = "1.6", branding_version = "MLP" }; WebClient resetpinswebservicecall = new WebClient(); var uri = new Uri(apiUrl, UriKind.RelativeOrAbsolute); var json = JsonHelper.Serialize(objInputParam); resetpinswebservicecall.Headers["Content-type"] = "application/json"; resetpinswebservicecall.UploadStringCompleted += resetpinswebservicecall_UploadStringCompleted; resetpinswebservicecall.UploadStringAsync(uri, "POST", json); } catch (Exception) { MessageBox.Show("Sorry, Unable to process your request."); } }
public void AgendaPost() { try { List<Agenda> listAgenda = AgendaDB.GetAll(); for (int x = 0; listAgenda.Count() > x; x++) { WebClient webClient = new WebClient(); webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded"; webClient.Encoding = Encoding.UTF8; webClient.UploadStringAsync(new Uri("http://apiatenda.azurewebsites.net/api/agenda/"), "POST", "&IdTecnico=" + listAgenda[x].IdTecnico + "&IdCliente=" + listAgenda[x].IdCliente + "&Hora=" + listAgenda[x].Hora + "&Data=" + listAgenda[x].Data + "&Local=" + listAgenda[x].Local + "&Servicos=" + listAgenda[x].Servicos + "&Observacoes=" + listAgenda[x].Observacoes + "&Status=" + listAgenda[x].Status); } } catch (ArgumentNullException ex) { MessageBox.Show(ex.Message); } }
public void SendKey(String key, String data) { WebClient client = new WebClient(); // XBMC媒体中心服务器 String JSON_RPC = "http://" + userSettings["host"] + "/jsonrpc?SendRemoteKey"; // WebClient 加载完成后的事件 // application/json; charset=UTF-8 client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; switch (key) { case "VolumeUp": client.UploadStringCompleted += new UploadStringCompletedEventHandler(user_VolumeUpCallback); break; case "VolumeDown": client.UploadStringCompleted += new UploadStringCompletedEventHandler(user_VolumeDownCallback); break; default: client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted); break; } try { // String data = "{\"jsonrpc\": \"2.0\", \"method\": \"Input.Up\", \"id\": 1}"; client.Headers[HttpRequestHeader.ContentLength] = data.Length.ToString(); client.UploadStringAsync(new Uri(JSON_RPC), "POST", data); } catch { } }
/// <summary> /// 批量 /// </summary> /// <param name="cmd"></param> private void BatchAction(String cmd) { WebClient wc = new WebClient(); Indicator.IsBusy = true; wc.UploadStringCompleted += wc_UploadStringCompleted; wc.UploadStringAsync(new Uri(list.WebClientInfo.BaseAddress), cmd); }
private void WatcherOnPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) { if (DateTime.Now.TimeOfDay.Subtract(_lastTimeSend) >= _minSendTime) { _geozoneRequest.Lat = e.Position.Location.Latitude; _geozoneRequest.Lon = e.Position.Location.Longitude; WebClient webClient = new WebClient(); webClient.UploadStringCompleted += (o, args) => { if (args.Error == null) { JObject jRoot = JObject.Parse(args.Result); if (JsonHelpers.GetStatusCode(jRoot) == 200) { double dist = jRoot["response"].Value<double>("distance"); if (dist > 0) _watcher.MovementThreshold = dist/2; } } }; string request = string.Format("{{\"request\":{0}}}", JsonConvert.SerializeObject(_geozoneRequest)); webClient.UploadStringAsync(Constants.GeozoneUrl, request); _lastTimeSend = DateTime.Now.TimeOfDay; } }
private void button2_Click(object sender, RoutedEventArgs e) { if (textBox4.Text == "") { textBlock11.Text = "Please provide solution"; return; } var solution = new ViewSolution { Id = Convert.ToInt32(selectedId), Solution = textBox4.Text, SolutionBy = userId }; DataContractJsonSerializer jsonData = new DataContractJsonSerializer(typeof(ViewSolution)); MemoryStream memStream = new MemoryStream(); //S2 : Write data into Memory Stream jsonData.WriteObject(memStream, solution); //S3 : Read the bytes from Stream do that it can then beconverted to JSON String byte[] jsonDataToPost = memStream.ToArray(); memStream.Close(); //S4: Ehencode the stream into string format var data = Encoding.UTF8.GetString(jsonDataToPost, 0, jsonDataToPost.Length); var api = "http://knowledgeshare.azurewebsites.net/api/solution"; WebClient webClient, webClientSolution; webClientSolution = new WebClient(); webClientSolution.UploadStringCompleted += new UploadStringCompletedEventHandler(webClientSolution_OpenWriteCompleted); webClientSolution.Headers["content-type"] = "application/json"; webClientSolution.UploadStringAsync(new Uri(api), "POST", data); }
/// <summary> /// コメント投稿をサーバに送信するメソッド /// </summary> /// <param name="name">ユーザ名</param> /// <param name="message">コメント内容</param> /// <param name="needAction">ユーザへのアクションが必要か</param> public static void PostComment(string name, string message, bool needAction) { // 送信用コンテンツ文字列の作成 string content = GetHTMLString(name, message); // サーバにPOST送信するオブジェクトを作成 WebClient webClient = new WebClient(); // サーバ処理完了後のハンドラ登録 webClient.UploadStringCompleted += (sender, e) => { if (needAction) { if (e.Error == null) { // 正常に完了 MessageBox.Show("ありがとうございます。送信完了しました。"); } else { // エラー MessageBox.Show("送信に失敗しました。" + Environment.NewLine + e.Result); } } }; // ファイルパスの設定 // (セキュリティの関係上、サクラサーバは同フォルダからのPOSTのみ受け付ける) const string filePath = SERVER_FOLDER_SAKURA + POST_FILE; // サーバにPOSTメソッドを送信する webClient.UploadStringAsync(new Uri(filePath), "POST", "content=" + content); }
private void button1_Click(object sender, RoutedEventArgs e) { string serviceUri = SalesForceServiceURL.SVC_AUTHORIZATION_URL;//string.Format(SalesForceServiceURL.SVC_AUTHORIZATION_URL, SalesForceServiceURL.SVC_AUTHORIZATION_USERNAME, SalesForceServiceURL.SVC_AUTHORIZATION_PASSWORD); WebClient wbClient = new WebClient(); wbClient.UploadStringCompleted += new UploadStringCompletedEventHandler(wbClient_UploadStringCompleted); wbClient.UploadStringAsync(new Uri(serviceUri), "POST", string.Empty); }
public SignUpSecondPage() { InitializeComponent(); //Show Loader myIndeterminateProbar.Visibility = Visibility.Visible; //==================================================================================================================== // Registration state dropdown //==================================================================================================================== // Parameters StateRequest obj = new StateRequest(); obj.country_id = _countryId; String data = "country_id=" + obj.country_id; //Initialize WebClient WebClient webClient = new WebClient(); //Set Header webClient.Headers[HttpRequestHeader.Authorization] = Utilities.GetAuthorization(); webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded"; webClient.Headers[HttpRequestHeader.AcceptLanguage] = "en_US"; webClient.UploadStringAsync(new Uri(Utilities.GetURL("location/getState/")), "POST", data); //Assign Event Handler webClient.UploadStringCompleted += wc_UploadStateCompleted; }
public void SaveConfigurationStoreXmlAsync(string xml, object userState = null) { Uri uri = CreateRestRequest("ConfigurationStore/Save"); WebClient webClient = new WebClient(); webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(onSaveConfigurationStoreCompleted); webClient.UploadStringAsync(uri, "POST", xml, userState); }
private void Btn_Alta_Click(object sender, RoutedEventArgs e) { try { objCliente = new WebClient(); objBuilder = new StringBuilder(); objUri = new Uri(vUrl, UriKind.Absolute); objBuilder.AppendFormat("{0}={1},{2},{3},{4}", "vCadena", HttpUtility.UrlEncode(txBox_Nombre.Text), HttpUtility.UrlEncode("1"), HttpUtility.UrlEncode(txBox_Telefono.Text), HttpUtility.UrlEncode(txBox_Correo.Text)); objCliente.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; objCliente.Headers[HttpRequestHeader.ContentLength] = objBuilder.Length.ToString(); objCliente.UploadStringAsync(objUri, "POST", objBuilder.ToString()); objCliente.UploadStringCompleted += objCliente_UploadStringCompleted; } catch (Exception ex) { } }
public static void httpPost(Uri resource, string postString, UploadStringCompletedEventHandler e) { WebClient client = new WebClient(); client.Headers["Content-Type"] = "application/x-www-form-urlencoded"; client.UploadStringCompleted += e; client.UploadStringAsync(resource, "POST", postString); }
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { WebClient client = sender as WebClient; client.DownloadStringCompleted -= client_DownloadStringCompleted; // 没有出错 if (e.Error == null) { try { String retid = e.Result as String; if (!"noid".Equals(retid) && userid != null) { //产生要发送后台的JSON串 WebClientInfo wci1 = Application.Current.Resources["server"] as WebClientInfo; string uri1 = wci1.BaseAddress + "/iesgas/gascz/comand"; WebClient client1 = new WebClient(); client1.UploadStringCompleted += client1_UploadStringCompleted; client1.UploadStringAsync(new Uri(uri1), ("[{customer_code:\"" + userid + "\",id:\"" + retid + "\"}]")); } } catch (Exception ex) { } } busy.IsBusy = false; }
/// <summary> /// VerifyBySmsWebService Method /// </summary> private void ResendBySmsWebService() { string apiUrl = RxConstants.resendConfirmationCodes; try { ResendConfirmationCodesRequest objInputParam = new ResendConfirmationCodesRequest { mail = App.YourDetailsLoginEmail, pin = App.HashPIN, pharmacyid = App.SignUpPharId.ToUpper(), system_version = "android", app_version = "1.6", branding_version = "MLP" }; WebClient resetpinswebservicecall = new WebClient(); var uri = new Uri(apiUrl, UriKind.RelativeOrAbsolute); var json = JsonHelper.Serialize(objInputParam); resetpinswebservicecall.Headers["Content-type"] = "application/json"; resetpinswebservicecall.UploadStringCompleted += resetpinswebservicecall_UploadStringCompleted; resetpinswebservicecall.UploadStringAsync(uri, "POST", json); } catch (Exception) { MessageBox.Show("Sorry, Unable to process your request."); } }
private void btnRegistrar_Click(object sender, RoutedEventArgs e) { if (txtEmail.Text == String.Empty || txtClave.Password == String.Empty) { MessageBox.Show("Por favor complete todos los campos"); } else { try { Usuario usuario = new Usuario(); usuario.email = txtEmail.Text; usuario.nombres = txtNombres.Text; usuario.apellidos = txtNombres.Text; usuario.clave = txtClave.Password; string jsonData = JsonConvert.SerializeObject(usuario); WebClient webClient = new WebClient(); Uri uri = new Uri(Constantes.urlServicioBase + "usuario/registrar", UriKind.Absolute); webClient.Headers[HttpRequestHeader.ContentType] = "application/json"; webClient.UploadStringCompleted += loginCompletado; webClient.UploadStringAsync(uri, "POST", jsonData); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
/// <summary> /// Tracks the screen view. /// </summary> /// <param name="viewName">View name.</param> /// <param name="clientId">Client ID.</param> public static void TrackScreenView(string viewName, string clientId) { StringBuilder address = new StringBuilder(Resource); address.Replace("{project_id}", ProjectId); address.Replace("{event_collection}", "appviews"); address.Replace("{write_key}", WriteKey); StringBuilder data = new StringBuilder(PayloadFormat); data.Replace("{app_name}", Application.ProductName); data.Replace("{app_version}", Application.ProductVersion); data.Replace("{user_id}", clientId); data.Replace("{view_name}", viewName); data.Replace("'", "\""); using (WebClient client = new WebClient()) { client.Headers["Content-Type"] = "application/json"; try { client.UploadStringAsync( address: new Uri(address.ToString()), method: "POST", data: data.ToString()); } catch { // Swallow all exceptions. } } }
private void LoadUrl(string email_donatur) { StringBuilder parameter = new StringBuilder(); parameter.AppendFormat("{0}={1}&", "email_donatur", HttpUtility.UrlEncode(email_donatur)); if (email_donatur.Equals("")) { MessageBox.Show("Input your email!"); } else { try { WebClient clientLogin = new WebClient(); clientLogin.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; clientLogin.Headers[HttpRequestHeader.ContentLength] = parameter.Length.ToString(); clientLogin.UploadStringCompleted += new UploadStringCompletedEventHandler(uploadResetComplete); clientLogin.UploadStringAsync(new Uri(URL.BASE3 + "api/forgot/forgot.php"), "POST", parameter.ToString()); } catch { MessageBox.Show("An error occured!"); } } }
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; }
public static void RegisterUserWithHue() { try { var client = new WebClient(); //our uri to perform registration var uri = new Uri(string.Format("http://{0}/api", HueLightIp)); //create our registration object, along with username and description var reg = new { username = HueLightUser, devicetype = "Coding4Fun Hue Kinect Light Project" }; var jsonObj = JsonConvert.SerializeObject(reg); client.UploadStringCompleted += client_UploadStringCompleted; //Invoke a POST to the bridge client.UploadStringAsync(uri, jsonObj); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }