private static async Task RetryErrorQueueAsync(string virtualHost, string queueName) { var stringErrorLength = ("_error").Length; var liveQueue = queueName.Remove(queueName.Length - stringErrorLength); var amqpurl = $"amqp://{userName}@/{virtualHost}"; // Use the shovel plugin to move messages between queues var shovelApiUrl = $"{ rabbitUrl }api/parameters/shovel/{virtualHost}/retry{queueName}"; var value = new ShovelData { SrcUri = amqpurl, SrcQueue = queueName, DestUri = amqpurl, DestQueue = liveQueue, DeleteAfter = "queue-length" }; var jsonShovel = JsonConvert.SerializeObject(new Shovel { ShovelData = value }); client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); var response = await client.UploadStringTaskAsync(new Uri(shovelApiUrl), "PUT", jsonShovel); Console.WriteLine("Successful response: " + response); }
private async Task UpdateItemsAsync() { m_timer.Stop(); var webClient = new WebClient(); RPCRequest request = new RPCRequest(); request.jsonrpc = "2.0"; request.id = 1; request.method = "listgroups"; request.parms = new object[] { 0, }; try { string queueItemsJson = await webClient.UploadStringTaskAsync(new Uri("http://127.0.0.1:6789/jsonrpc/listgroups"), JsonConvert.SerializeObject(request)); request.method = "history"; request.parms = new object[] { false, }; string historyItemsJson = await webClient.UploadStringTaskAsync(new Uri("http://127.0.0.1:6789/jsonrpc/listgroups"), JsonConvert.SerializeObject(request)); List <DownloadItem> downloadItems = ParseQueueItems(queueItemsJson); downloadItems.AddRange(ParseHistoryItems(historyItemsJson)); m_downloadItems = downloadItems; } catch { m_downloadItems = null; } m_timer.Start(); }
public async Task <bool> SendMoneyToWallet(string phone, string amount, string comment = null) { amount = amount.Replace(',', '.'); var request = new MoneyTransfer { Id = (1000 * DateTimeOffset.Now.ToUnixTimeSeconds()).ToString(), Sum = new Sum { Amount = amount, Currency = "643" }, Source = "account_643", PaymentMethod = new PaymentMethod { Type = "Account", AccountId = "643" }, Comment = comment, Fields = new Fields { Account = "+" + phone } }; _webClient.Headers["Authorization"] = $"Bearer {_token}"; _webClient.Headers["Content-Type"] = "application/json"; var url = BuildUrl("sinap/terms/99/payments"); try { var response = await _webClient.UploadStringTaskAsync(url, JsonConvert.SerializeObject(request, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() })); return(response.Contains("Accepted")); } catch { return(false); } }
public async Task <string> CallServer(string path, ServerPostData postData, bool callSync) { await EnsureNodeProcessIsRunning(callSync); string url = $"{BASE_URL}:{BasePort}/{path.ToLowerInvariant()}"; string json = JsonConvert.SerializeObject(postData); try { using (WebClient client = new WebClient()) { if (callSync) { Task <string> task = Task.Run(async() => await client.UploadStringTaskAsync(url, json)); bool completed = task.Wait(5000); if (!completed) { throw new Exception("TsLint call on build timed out. Timeout is 5 seconds."); } return(completed ? task.Result : null); } else { return(await client.UploadStringTaskAsync(url, json)); } } } catch (WebException ex) { Debug.WriteLine(ex.Message); Down(); return(string.Empty); } }
public async Task InsertListItemAsync(string listName, object item) { string formDigestValue = await GetFormDigestValueAsync(); _webClient.Headers.Add(SharePointWebHeaderCreator.GetInsertHeaders(formDigestValue)); Uri endPointUri = GetListItemsEndPoint(listName); string serializedObject = JsonConvert.SerializeObject(item); await _webClient.UploadStringTaskAsync(endPointUri, "POST", serializedObject); }
internal async Task <List <TraktActivity> > getCheckinHistory() { try { var myFeedClientScrobble = new WebClient(); String myFeedJsonString = await myFeedClientScrobble.UploadStringTaskAsync(new Uri("https://api.trakt.tv/activity/user.json/9294cac7c27a4b97d3819690800aa2fedf0959fa/" + AppUser.Instance.UserName + "/all/scrobble"), AppUser.createJsonStringForAuthentication()); var myFeedClientCheckin = new WebClient(); String myFeedJsonStringCheckin = await myFeedClientScrobble.UploadStringTaskAsync(new Uri("https://api.trakt.tv/activity/user.json/9294cac7c27a4b97d3819690800aa2fedf0959fa/" + AppUser.Instance.UserName + "/all/checkin"), AppUser.createJsonStringForAuthentication()); var myFeedClientSeen = new WebClient(); String myFeedJsonStringSeen = await myFeedClientSeen.UploadStringTaskAsync(new Uri("https://api.trakt.tv/activity/user.json/9294cac7c27a4b97d3819690800aa2fedf0959fa/" + AppUser.Instance.UserName + "/all/seen"), AppUser.createJsonStringForAuthentication()); List <TraktActivity> activity = new List <TraktActivity>(); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(myFeedJsonString))) { var ser = new DataContractJsonSerializer(typeof(TraktFriendsActivity)); TraktFriendsActivity myActivity = (TraktFriendsActivity)ser.ReadObject(ms); activity.AddRange(myActivity.Activity); ms.Close(); } using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(myFeedJsonStringCheckin))) { var ser = new DataContractJsonSerializer(typeof(TraktFriendsActivity)); TraktFriendsActivity myActivity = (TraktFriendsActivity)ser.ReadObject(ms); activity.AddRange(myActivity.Activity); ms.Close(); } using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(myFeedJsonStringSeen))) { var ser = new DataContractJsonSerializer(typeof(TraktFriendsActivity)); TraktFriendsActivity myActivity = (TraktFriendsActivity)ser.ReadObject(ms); activity.AddRange(myActivity.Activity); ms.Close(); } return(activity); } catch (WebException) { Debug.WriteLine("WebException in getNewsFeed()."); } catch (TargetInvocationException) { Debug.WriteLine("TargetInvocationException in getNewsFeed()."); } return(new List <TraktActivity>()); }
private async Task <T> HitPost <T, TReq>(string api, TReq requestData, bool strictTypeNames = false) where T : APIResponse { try { if (api == null) { return(null); } api = ChatServer.ServerUrl?.TrimEnd('/') + "/" + api; using (var wc = new WebClient()) { wc.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{ChatServer.APIKey}:{ChatServer.APISecret}")); T resp = default(T); if (strictTypeNames) { resp = BsonSerializer.Deserialize <T>(await wc.UploadStringTaskAsync(api, requestData.ToJson())); } else { wc.Headers[HttpRequestHeader.ContentType] = "application/json"; wc.Headers[HttpRequestHeader.Accept] = "application/json"; resp = JsonConvert.DeserializeObject <T>(await wc.UploadStringTaskAsync(api, JsonConvert.SerializeObject(requestData))); } resp.Status = true; return(resp); } } catch (WebException ex) { using (var resp = new StreamReader(ex.Response.GetResponseStream())) { T respParsed = Activator.CreateInstance <T>(); if (strictTypeNames) { respParsed.Message = await resp.ReadToEndAsync(); } else { respParsed = JsonConvert.DeserializeObject <T>(await resp.ReadToEndAsync()); } respParsed.Status = false; return(respParsed); } } catch (Exception ex) { T respParsed = Activator.CreateInstance <T>(); respParsed.Status = false; respParsed.Message = ex.Message; return(respParsed); } }
public async Task <EvalResponse> VisualizeAsync(string declarations, string valueExpression) { var req = new EvalRequest { Declarations = declarations, ValueExpression = valueExpression }; var reqStr = JsonConvert.SerializeObject(req); var respStr = await client.UploadStringTaskAsync(visualizeUrl, reqStr); return(JsonConvert.DeserializeObject <EvalResponse> (respStr)); }
public async Task <EvalResponse> VisualizeAsync(string code) { var req = new EvalRequest { Code = code }; var reqStr = JsonConvert.SerializeObject(req); var respStr = await client.UploadStringTaskAsync(visualizeUrl, reqStr); return(JsonConvert.DeserializeObject <EvalResponse> (respStr)); }
/// <summary> /// Hits the post API where the system will run enabled services. /// </summary> public async Task <bool> HitPostApi() { Log.TraceStart(); try { if (IsEnabled == 1) { using (var client = new WebClient()) { client.Headers.Add("Content-Type:application/json"); client.Headers.Add("Accept:application/json"); // client.Headers.Add(String.Format("{0}:{1}", API_Key_Header, API_Key)); if (IsChatAppEnabled == 1) { //Runs chat app charging service var chatAppChargingUri = new Uri(Chat_App_Url); var response = await client.UploadStringTaskAsync(chatAppChargingUri, JsonConvert.SerializeObject(null)); Log.TraceExecute(response); } if (IsCoupleChatAppEnabled == 1) { //Runs couple chat app charging service var coupleChatAppChargingUri = new Uri(Couple_Chat_App_Url); var response = await client.UploadStringTaskAsync(coupleChatAppChargingUri, JsonConvert.SerializeObject(null)); Log.TraceExecute(response); } return(true); } } else { Log.TraceExecute("Schedules are disabled."); return(false); } } catch (Exception ex) { Log.Error(ex.Message); Console.WriteLine(ex.Message); return(false); } finally { Log.TraceEnd(); } }
public static void UploadString_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadString((string)null, null); }); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadString((string)null, null, null); }); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null); }); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null, null); }); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null); }); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null); }); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null, null); }); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null); }); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null, null); }); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null); }); Assert.Throws <ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null, null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null, null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null, null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null, null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null, null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null); }); Assert.Throws <ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null, null); }); }
public static async Task <bool> RegisterUser(string email, string password) { var body = JsonConvert.SerializeObject(new TempUser(email, password), GetJsonSerializerSettings()); try { client.Headers[HttpRequestHeader.ContentType] = "application/json"; string response = await client.UploadStringTaskAsync(GetUri(Constants.BaseAddress + Constants.RegisterPath), "POST", body); } catch (Exception ex) { return(false); } return(true); }
public async void AuthenticateWithWNS() { IsRefreshInProgress = true; var urlEncodedSid = HttpUtility.UrlEncode(WNS_PACKAGE_SECURITY_IDENTIFIER); var urlEncodedSecret = HttpUtility.UrlEncode(WNS_SECRET_KEY); var body = string.Format(PayloadFormat, urlEncodedSid, urlEncodedSecret, AccessScope); string response = null; Exception exception = null; using (var client = new WebClient()) { client.Headers.Add("Content-Type", UrlEncoded); try { response = await client.UploadStringTaskAsync(new Uri(AccessTokenUrl), body); } catch (Exception e) { exception = e; Debug.WriteLine(string.Format("Failed WNS authentication. Error: {0}", e.Message)); } } if (exception == null && response != null) { oAuthToken = GetOAuthTokenFromJson(response); ScheduleTokenRefreshing(); } IsRefreshInProgress = false; OnAuthenticated?.Invoke(); }
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 static async Task <JObject> PostRequestAsync(string url, string data) { WebClient thisClient = new WebClient { Headers = new WebHeaderCollection { "User-Agent:okhttp/3.10.0", "Content-Type:application/json; charset=utf-8", "Accept-Encoding:gzip" } }; try { string res = await thisClient.UploadStringTaskAsync(url, data); JObject tmp = JObject.Parse(res); return(tmp); } catch (WebException ex) { using (HttpWebResponse hr = (HttpWebResponse)ex.Response) { int statusCode = (int)hr.StatusCode; StringBuilder sb = new StringBuilder(); StreamReader sr = new StreamReader(hr.GetResponseStream(), Encoding.UTF8); sb.Append(sr.ReadToEnd()); JObject tmp = new JObject(JObject.Parse(sb.ToString())); throw new Exception(tmp["errors"]["system"]["message"].ToString()); } } }
private async Task <bool> IsStoreExisting(string sCnpj) { try { var oRequest = new CheckExistingStoreRequest { Cnpj = sCnpj }; using (_oWebClient = new WebClient()) { var oResponseResult = await _oWebClient.UploadStringTaskAsync(AppConfigUtility.sGetExistingStoreRequestUrl, "POST", oRequest.ToJSON(true)); if (string.IsNullOrEmpty(oResponseResult)) { throw new Exception(""); } var oResponse = oResponseResult.FromJSON <CheckExistingStoreResponse>(); return(oResponse.Result); } } catch (Exception) { throw new WebRequestException(AppConfigUtility.sMessageWebRequestError); } }
internal async Task <TraktProfile> GetUserProfile() { try { var userClient = new WebClient(); TraktProfile profile = null; String jsonString = await userClient.UploadStringTaskAsync(new Uri("https://api.trakt.tv/user/profile.json/9294cac7c27a4b97d3819690800aa2fedf0959fa/" + AppUser.Instance.UserName), AppUser.createJsonStringForAuthentication()); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { if (jsonString.Contains("watching\":[]")) { var ser = new DataContractJsonSerializer(typeof(TraktProfile)); profile = (TraktProfile)ser.ReadObject(ms); } else { var ser = new DataContractJsonSerializer(typeof(TraktProfileWithWatching)); profile = (TraktProfileWithWatching)ser.ReadObject(ms); } } return(profile); } catch (WebException) { Debug.WriteLine("WebException in GetUserProfile()."); } catch (TargetInvocationException) { Debug.WriteLine("TargetInvocationException in GetUserProfile()."); } return(null); }
internal async Task <TraktProfile[]> getFollowers() { try { var userClient = new WebClient(); TraktProfile[] profiles = null; String jsonString = await userClient.UploadStringTaskAsync(new Uri("https://api.trakt.tv/user/network/followers.json/9294cac7c27a4b97d3819690800aa2fedf0959fa/" + AppUser.Instance.UserName), AppUser.createJsonStringForAuthentication()); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { var ser = new DataContractJsonSerializer(typeof(TraktProfile[])); profiles = (TraktProfile[])ser.ReadObject(ms); } return(profiles); } catch (WebException) { Debug.WriteLine("WebException in getFollowers()."); } catch (TargetInvocationException) { Debug.WriteLine("TargetInvocationException in getFollowers()."); } return(null); }
internal async Task <List <TraktActivity> > getNewsFeed(String id) { try { var myFeedClient = new WebClient(); String myFeedJsonString = await myFeedClient.UploadStringTaskAsync(new Uri("https://api.trakt.tv/activity/user.json/9294cac7c27a4b97d3819690800aa2fedf0959fa/" + id), AppUser.createJsonStringForAuthentication()); List <TraktActivity> activity = new List <TraktActivity>(); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(myFeedJsonString))) { var ser = new DataContractJsonSerializer(typeof(TraktFriendsActivity)); TraktFriendsActivity myActivity = (TraktFriendsActivity)ser.ReadObject(ms); if (myActivity != null) { activity.AddRange(myActivity.Activity); } ms.Close(); } return(activity); } catch (Exception) { } return(new List <TraktActivity>()); }
internal async Task <TraktLastActivity> FetchLastActivity() { try { var userClient = new WebClient(); String jsonString = await userClient.UploadStringTaskAsync(new Uri("http://api.trakt.tv/user/lastactivity.json/9294cac7c27a4b97d3819690800aa2fedf0959fa/" + AppUser.Instance.UserName), AppUser.createJsonStringForAuthentication()); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { var ser = new DataContractJsonSerializer(typeof(TraktLastActivity)); TraktLastActivity activity = (TraktLastActivity)ser.ReadObject(ms); Debug.WriteLine("Fetched last activity from Trakt."); return(activity); } } catch (WebException) { Debug.WriteLine("WebException in FetchLastActivity()."); } catch (TargetInvocationException) { Debug.WriteLine("TargetInvocationException in FetchLastActivity()."); } return(null); }
public static async Task <bool> IsRecoding() { if (!_updated) { _updated = await DoUpdate(); if (!_updated) { return(false); } } using (var client = new WebClient()) { try { client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; var response = await client.UploadStringTaskAsync( new Uri(IsRecordingUrl), "userName="******"&force=false"); return(response.Contains("NowRecording", StringComparison.OrdinalIgnoreCase)); } catch { return(false); } } }
public static async Task <bool> DoUpdate() { if (SummonerId == 0) { UpdateSummonerId(); if (SummonerId == 0) { return(false); } } using (var client = new WebClient()) { try { client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; await client.UploadStringTaskAsync(new Uri(IsRecordingUrl), "summonerId=" + SummonerId); return(true); } catch { return(false); } } }
public bool IsApproved(AntiFraudClearSale data) { try { using (var webClient = new WebClient()) { var statusAntiFraud = string.Empty; webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json"); webClient.Encoding = Encoding.UTF8; var uri = new Uri("https://sandbox.clearsale.com.br/api/order/send"); var response = webClient.UploadStringTaskAsync(uri, WebRequestMethods.Http.Post, JsonConvert.SerializeObject(data)); //Cenário para testes. //Somente pedidos com endereço de entrega para o pais do comprador são validados. if (data.Orders.All(s => s.ShippingData.Address.Country == data.AnalysisLocation)) { statusAntiFraud = "APA"; } else { statusAntiFraud = "RPP"; } return(statusAntiFraud.Equals("APA")); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Proxy to <see cref="WebClient.UploadStringTaskAsync(string, string)"/>. Use one instance of <see cref="WebClient"/> per call because <see cref="WebClient"/> cannot be used cross thread. /// </summary> /// <param name="url">The URL.</param> /// <param name="data">The data.</param> /// <returns></returns> /// <exception cref="ArgumentNullException">If <c>url</c> or <c>data</c> parameter is null.</exception> public Task <string> UploadStringTaskAsync(string url, string data) { using (var wc = new WebClient()) { return(wc.UploadStringTaskAsync(url, data)); } }
public async Task <string> SendCommandAsync(string cmd) { try { string myParameters = string.Format("{0}&{1}", cmd, ID_CMD); string HtmlResult = "Something went wrong..."; using (WebClient wc = new WebClient()) { wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; HtmlResult = await wc.UploadStringTaskAsync(URI, myParameters); } return(HtmlResult); } catch (SocketException ex) { return("SocketException : " + ex.Message); } catch (Exception ex) { return("Exception : " + ex.Message); } finally { m_clientSocket.Close(); } }
public static async Task <JObject> PostRequestAsync(string url, string data) { WebClient thisClient = new WebClient { Headers = new WebHeaderCollection { "User-Agent:Mozilla/5.0 BSGameSDK", "Content-Type:application/x-www-form-urlencoded" } }; data += "&sign=" + GetSign(data); try { string res = await thisClient.UploadStringTaskAsync(url, data); JObject tmp = JObject.Parse(res); return(tmp); } catch (WebException ex) { using (HttpWebResponse hr = (HttpWebResponse)ex.Response) { int statusCode = (int)hr.StatusCode; StringBuilder sb = new StringBuilder(); StreamReader sr = new StreamReader(hr.GetResponseStream(), Encoding.UTF8); sb.Append(sr.ReadToEnd()); JObject tmp = new JObject(JObject.Parse(sb.ToString())); throw new Exception(tmp["errors"]["system"]["message"].ToString()); } } }
private async void UpdateRestServerContractSalesItem(ContractSalesItem contractSalesItem) { // Upload the item to the server via REST: string data = contractSalesItem.DataToString(); var webClient = new WebClient(); webClient.Headers[HttpRequestHeader.ContentType] = "application/json"; webClient.Encoding = Encoding.UTF8; string response = null; try { response = await webClient.UploadStringTaskAsync(BaseUrl + "/api/ContractSalesItem/" + contractSalesItem.Id.ToString(), "PUT", data); } catch (Exception e) { MessageBox.Show("Failed to upload item via REST. Exception message: " + e.Message); } // Send message via SignalR to update the other clients: if (response != null) { MakeCallToUpdateOtherClients(); } }
private async Task SendNotification(string channelUri, string payload, NotificationType type = NotificationType.Raw) { if (WNSAuthentication.Instance.oAuthToken.AccessToken != null && !WNSAuthentication.Instance.IsRefreshInProgress) { using (var client = new WebClient()) { SetHeaders(type, client); try { await client.UploadStringTaskAsync(new Uri(channelUri), payload); } catch (WebException webException) { if (webException.Response != null) { HandleError(((HttpWebResponse)webException.Response).StatusCode, channelUri, payload); } Debug.WriteLine($"Failed WNS authentication. Error: {webException.Message}"); } catch (Exception) { HandleError(HttpStatusCode.Unauthorized, channelUri, payload); } } } else { StoreNotificationForSending(channelUri, payload); } }
/// <summary> /// Send a request asynchronously to Trafikverket API /// A successful request will have the data delivered through the OnResponseEvent handler /// Errors will be delivered through OnFailureEvent /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <bool> RequestAsync(Request request) { SetLogin(ref request); try { var response = await _webClient.UploadStringTaskAsync(_address, "POST", request.Build()); var data = JsonConvert.DeserializeObject <QueryResponse>(response); Success(data.Response, request); return(true); } catch (WebException e) { Failure(Utils.GetErrorResponse(e), request, e); } catch (Exception e) { Failure(null, request, e); } return(false); }
public static async Task <object> UnSubscribe(string route, string fCMServerKey, params string[] deviceToken) { try { var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }; string url = string.Format("https://iid.googleapis.com/iid/v1:batchRemove"); using (var client = new WebClient()) { UnSubscribeTopic data = new UnSubscribeTopic(); data.to = route; data.registration_tokens = deviceToken; client.Headers.Add("Authorization", "key=" + fCMServerKey); var res = await client.UploadStringTaskAsync(url, JsonConvert.SerializeObject(data, jsonSerializerSettings)); return(res); } } catch (WebException e) { throw e; } }
public static void UploadString_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null, null); }); }
protected override Task<string> UploadStringAsync(WebClient wc, string address, string data) => wc.UploadStringTaskAsync(address, data);
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; }); }