public DownloadStringTaskAsync ( System address ) : System.Threading.Tasks.Task |
||
address | System | |
return | System.Threading.Tasks.Task |
public async Task<Queue> DownloadQueue() { using (WebClient w = new WebClient()) { return this.ConvertApiResultToQueue(await w.DownloadStringTaskAsync("http://localhost:8080/sabnzbd/api?mode=queue&output=xml")); } }
public async override Task<IEnumerable<string>> GetVersion(string packageName) { if (string.IsNullOrEmpty(packageName)) return Enumerable.Empty<string>(); string url = $"http://registry.npmjs.org/{packageName}"; string json = "{}"; using (var client = new WebClient()) { json = await client.DownloadStringTaskAsync(url); } var array = JObject.Parse(json); var time = array["time"]; if (time == null) return Enumerable.Empty<string>(); var props = time.Children<JProperty>(); return from version in props where char.IsNumber(version.Name[0]) orderby version.Name descending select version.Name; }
/// <summary> /// Validates oauth 2 access_token against a google provider. /// </summary> /// <param name="param name="access_token""> /// An access token to validate. /// </param> /// <returns> /// Profile info. /// </returns> public async Task<UserAuthorization> Get(string access_token) { using(var client = new WebClient()) { client.Headers["Content-Type"] = "application/json"; client.QueryString["access_token"] = access_token; client.QueryString["input_token"] = access_token; var info = JsonConvert.DeserializeObject<TokenInfo>( await client.DownloadStringTaskAsync(validateUrl)); client.QueryString.Remove("input_token"); var profile = JsonConvert.DeserializeObject<Profile>( await client.DownloadStringTaskAsync(profileUrl)); return new UserAuthorization { Provider = Provider, AccessToken = access_token, ExpiresAt = new DateTime(1970, 1, 1).AddSeconds(info.data.expires_at), ClientId = info.data.app_id, Scopes = info.data.scopes ?? new string[0], Profile = new UserProfile { Provider = Provider, UserId = info.data.user_id, Name = profile.name, Locale = profile.locale, Gender = profile.gender, Picture = pictureUrl.Replace(":user-id", info.data.user_id) } }; } }
public async Task<SteamGame> Get(int appId) { using (var webClient = new WebClient()) { var urlString = "http://store.steampowered.com/api/appdetails?appids={0}"; var gameUri = new Uri(String.Format(urlString, appId)); var jsonGameString = await webClient.DownloadStringTaskAsync(gameUri); jsonGameString = jsonGameString.Replace("[]", "{}"); jsonGameString = jsonGameString.Replace("\"package_groups\":{}", "\"package_groups\":[]"); var jsonSteamGame = JsonConvert.DeserializeObject<JsonSteamGame>(jsonGameString); var dlcAppIds = String.Join(",", jsonSteamGame[appId].data.dlc); var dlcUri = new Uri(String.Format(urlString, dlcAppIds)); var jsonDlcString = await webClient.DownloadStringTaskAsync(dlcUri); jsonDlcString = jsonDlcString.Replace("[]", "{}"); jsonDlcString = jsonDlcString.Replace("\"package_groups\":{}", "\"package_groups\":[]"); var jsonDlcList = JsonConvert.DeserializeObject<JsonSteamGame>(jsonDlcString); var gameInformation = jsonSteamGame.First().Value; var steamGame = new SteamGame(gameInformation.data); foreach (var downloadableContent in jsonDlcList) { steamGame.DownloadableContent.Add(new SteamGame(downloadableContent.Value.data)); } return steamGame; } }
private async Task<IEnumerable<ISearchResult>> EasySearch(string query, uint maxResults) { using (var webClient = new WebClient { Proxy = null }) { var result = JsonConvert.DeserializeObject<SearchResult>( await webClient.DownloadStringTaskAsync( $"https://www.googleapis.com/youtube/v3/search?order=relevance&type=video®ionCode={CultureInfo.CurrentCulture.TwoLetterISOLanguageName}&part=snippet&videoDuration=any&maxResults={maxResults}&key={YouTubeApiKey}&q={Uri.EscapeDataString(query)}")); var result2 = JsonConvert.DeserializeObject<ContentDetailsResult>( await webClient.DownloadStringTaskAsync( $"https://www.googleapis.com/youtube/v3/videos?id={string.Join(",", result.items.Select(x => x.id.videoId))}&part=contentDetails&key={YouTubeApiKey}")); return result.items.Select( x => new YouTubeSearchResult(x.snippet.title, GetArtist(x.snippet.title, x.snippet.channelTitle), x.snippet.channelTitle, x.id.videoId, XmlConvert.ToTimeSpan( result2.items.First(y => y.id == x.id.videoId).contentDetails.duration), [email protected])); } }
public static Task<string> Get(string url, string authToken) { var client = new WebClient { Encoding = Encoding.UTF8 }; if (authToken == null) return client.DownloadStringTaskAsync(new Uri(url + "&api_key=" + ApiKey)); client.Headers.Add(AuthHeader(authToken)); return client.DownloadStringTaskAsync(url); }
public async void AccessUrlForNet5Async() { var client = new WebClient(); GetUrlLength(await client.DownloadStringTaskAsync(new Uri("http://msdn.microsoft.com/zh-tw"))); GetUrlLength(await client.DownloadStringTaskAsync(new Uri("http://www.microsoft.com/zh-tw"))); GetUrlLength(await client.DownloadStringTaskAsync(new Uri("http://channel9.msdn.com/"))); GetUrlLength(await client.DownloadStringTaskAsync(new Uri("http://technet.microsoft.com/zh-TW/"))); }
private async static Task<string> FetchJson(int comicNumber) { string json = ""; var client = new WebClient(); if(comicNumber == 0) { json = await client.DownloadStringTaskAsync(new Uri(xkcd + info)); } else { json = await client.DownloadStringTaskAsync(new Uri(xkcd + "/" + comicNumber.ToString() + info)); } return json; }
public async void DownloadSamples() { var wc = new WebClient(); var samples = await wc.DownloadStringTaskAsync("http://myvar.org/estd/get/all"); foreach (var item in samples.Split('\r')) { await wc.DownloadStringTaskAsync(item); } }
private Task[] CreateFetchTasks(int taskCount) { var tasks = new List<Task>(); for (int i = 0; i < taskCount; i++) { var fetchTask = Task.Factory.StartNew(async t => { var token = (CancellationToken)t; var client = new WebClient(); while (!token.IsCancellationRequested) { int id = _index++; try { var content = await client.DownloadStringTaskAsync(_url + id); _htmls.Add(Tuple.Create(id, content)); } catch (WebException) { Console.WriteLine("Not found {0}", id); } } }, _fetchTokenSource.Token); tasks.Add(fetchTask); } return tasks.ToArray(); }
public async Task<List<Song>> GetSongs() { var client = new WebClient (); const string smallFile = "http://docs.xamarin.com/xamu-wcf/songs-small.json"; var data = await client.DownloadStringTaskAsync (smallFile); return await Task.Run(() => Newtonsoft.Json.JsonConvert.DeserializeObject<List<Song>>(data)); }
private async Task<SoundCloudWebTrackResult> GetSoundCloudTrack(string url) { using (var web = new WebClient { Proxy = null }) { try { var result = JsonConvert.DeserializeObject<ApiResult>(await web.DownloadStringTaskAsync(string.Format("http://api.soundcloud.com/resolve.json?url={0}&client_id={1}", url, SensitiveInformation.SoundCloudKey))); return new SoundCloudWebTrackResult { Duration = TimeSpan.FromMilliseconds(result.duration), Year = result.release_year != null ? uint.Parse(result.release_year.ToString()) : (uint)DateTime.Parse(result.created_at).Year, Title = result.title, Uploader = result.user.username, Result = result, Views = (uint)result.playback_count, ImageUrl = result.artwork_url, Url = result.permalink_url, Genres = new List<Genre> { PlayableBase.StringToGenre(result.genre) }, Description = result.description }; } catch (Exception) { return null; } } }
public async Task <string> UrlAsync(string url) { using (System.Net.WebClient wc = new System.Net.WebClient()) { return(await wc.DownloadStringTaskAsync(url)); } }
private async void MainWindow_Loaded_1(object sender, EventArgs e) { Globals.Windows.MainWindow = this; LauncherSettings.Load(); /*foreach (SavedUser u in LauncherSettings.Default.SecuredLoginInfo) { }*/ WebClient w = new WebClient(); StringReader r = new StringReader(await w.DownloadStringTaskAsync("https://dl.dropbox.com/u/37049399/MCLauncher/LauncherMessage.xaml")); Announcements.Document = (FlowDocument)XamlReader.Load(XmlReader.Create(r)); ImageBrush b = new ImageBrush(); b.ImageSource = new BitmapImage(new Uri("pack://application:,,,/Images/dirt.png")); b.Viewport = new Rect(0.1, 0.1, 0.07, 0.1); b.TileMode = TileMode.Tile; this.Background = b; AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; LoadingText.Content = "Please wait..."; LoadingProgress.IsIndeterminate = true; ComputerInfo i = new ComputerInfo(); SystemInfo.Content = "An error occured getting your system's RAM information. This is not a good sign! D:"; SystemInfo.Content = String.Format("{0} MB ({1} GB) Free/{2} MB ({3} GB) Total", i.AvailablePhysicalMemory / 1024 / 1024, i.AvailablePhysicalMemory / 1024 / 1024 / 1024, i.TotalPhysicalMemory / 1024 / 1024, i.TotalPhysicalMemory / 1024 / 1024 / 1024); await this.GetLatestLauncherInformation(); await this.ApplyLatestBackground(); }
async Task<string> fnDownloadString(string strUri) { var webclient = new WebClient(); string strResultData; try { strResultData = await webclient.DownloadStringTaskAsync(new Uri(strUri)); Console.WriteLine(strResultData); } catch { strResultData = "Exception"; /* RunOnUiThread(() => Toast.MakeText(this, "Unable to connect to server!!!", ToastLength.Short).Show());*/ } finally { if (webclient != null) { webclient.Dispose(); webclient = null; } } return strResultData; }
private async void btnDownload_Click (object sender, EventArgs args) { Uri uri; try { uri = new Uri (txtAddress.Text); } catch (Exception e) { ReportError (e.ToString ()); return; } btnDownload.Enabled = false; var wc = new WebClient (); try { txtResult.Text = await wc.DownloadStringTaskAsync (uri); } catch (Exception e) { ReportError (e.ToString ()); throw; } btnDownload.Enabled = true; }
public async Task ProcessRequest(string uri, MultilineTextBox output = null) { if (output != null) output.AddLine($"Accessing '{uri}'..."); try { WebClient client = new WebClient(); string response = await client.DownloadStringTaskAsync(uri); var parsedResponse = JsonConvert.DeserializeObject<Dictionary<string, string>>(response); if (output != null) { output.AddLine("Status: " + parsedResponse["status"]); if (parsedResponse.ContainsKey("response")) output.AddLine("Response: " + parsedResponse["response"]); else { output.AddLine("Error: " + parsedResponse["error"]); Resolved = true; _canceller.Cancel(); } } Resolved = true; } catch (Exception ex) { if (output != null) output.AddLine($"ERROR: Exception thrown during access: {ex.Message}"); Resolved = true; _canceller.Cancel(); } }
private async Task SetLatestRelease() { string Url = $"https://gitlab.com/api/v4/projects/{Properties.Settings.Default.ProjectID}/releases"; string Link = ""; string TargetCommit = ""; string Tag = ""; using (var client = new System.Net.WebClient()) //WebClient { client.BaseAddress = Url; client.Headers.Add("Content-Type:application/json"); //Content-Type client.Headers.Add("Accept:application/json"); client.Headers["Private-Token"] = Properties.Resources.AccessToken; // Getting releases list dynamic res = JsonConvert.DeserializeObject(await client.DownloadStringTaskAsync(Url)); // Getting the latest release (it will always be the first item in the retrieved collection) dynamic latest = JsonConvert.DeserializeObject(res[0].ToString()); dynamic latestCommit = JsonConvert.DeserializeObject(latest.commit.ToString()); TargetCommit = latestCommit.id.ToString(); Tag = latest.tag_name.ToString(); //Getting the direct link to the .zip asset of the release dynamic latestZip = JsonConvert.DeserializeObject(latest.assets.sources[0].ToString()); Link = latestZip.url.ToString(); string results = latest.ToString(); } this.Link = Link; this.TargetCommit = TargetCommit; this.Tag = Tag; }
private async Task <string> GetJsonAsync(string pageTitle) { // dont just return task as WebClient would be disposed to early // https://stackoverflow.com/a/19103343/1200847 using (var wc = new System.Net.WebClient()) return(await wc.DownloadStringTaskAsync(_apiUrlBase + WebUtility.UrlEncode(pageTitle)).ConfigureAwait(false)); }
public async Task<IEnumerable<Entry>> GetEntries() { List<Entry> entries = new List<Entry>(); HtmlDocument doc = new HtmlDocument(); WebClient wc = new WebClient(); string s = null; try { s = await wc.DownloadStringTaskAsync(HOMEPAGE_URL); } catch (WebException e) { //because async debugging on windows phone sucks, having this here at least gives us a hint at what happened throw; } doc.LoadHtml(s); foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[@class='daily']")) { string name = HttpUtility.HtmlDecode(node.SelectSingleNode(".//a[@href]").InnerHtml).ToLowerInvariant(); string definition = HtmlRemoval.StripTags(HttpUtility.HtmlDecode(node.SelectSingleNode("div[@class='definition']").InnerHtml.Trim().Replace("<br>", " "))); string example = HtmlRemoval.StripTags(HttpUtility.HtmlDecode(node.SelectSingleNode("div[@class='example']").InnerHtml.Trim().Replace("<br><br>", "\n").Replace("<br>",""))); entries.Add(new Entry(name, definition, example)); } return entries; }
public static async void Run(Version current) { Logger.WriteLine("Checking for updates...", "TwitchPlugin"); const string versionXmlUrl = @"https://raw.githubusercontent.com/Epix37/HDT-Data/master/Plugins/twitchplugin-version"; try { Logger.WriteLine("Current version: " + current, "TwitchPlugin"); string xml; using(var wc = new WebClient()) xml = await wc.DownloadStringTaskAsync(versionXmlUrl); var newVersion = new Version(XmlManager<SerializableVersion>.LoadFromString(xml).ToString()); Logger.WriteLine("Latest version: " + newVersion, "TwitchPlugin"); if(newVersion > current) { await Task.Delay(5000); var result = await Hearthstone_Deck_Tracker.API.Core.MainWindow.ShowMessageAsync("TwitchPlugin update available!", "(Plugins can not be updated automatically)", MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings {AffirmativeButtonText = "download", NegativeButtonText = "not now"}); if(result == MessageDialogResult.Affirmative) Process.Start(@"https://github.com/Epix37/HDT-TwitchPlugin/releases"); } } catch(Exception e) { Logger.WriteLine("Error checking for new version.\n\n" + e, "TwitchPlugin"); } }
public async Task<FullCustomer> GetASync(int id) { var webClient = new WebClient(); var customerString = await webClient.DownloadStringTaskAsync(BuildUrl(id)); var customer = JsonConvert.DeserializeObject<Customer>(customerString); var fullCustomer = new FullCustomer(customer); var orders = new List<Order>(); foreach (var orderId in customer.OrderIds) { var orderString = await webClient.DownloadStringTaskAsync(BuildUrl(id, orderId)); var order = JsonConvert.DeserializeObject<Order>(orderString); orders.Add(order); } fullCustomer.Orders = orders; return fullCustomer; }
protected async Task <string> GetFileDataFromWebClient(string absoluteUrl) { SslTruster.TrustSslIfAppSettingConfigured(); try { if (absoluteUrl == null || absoluteUrl == "#") { return(null); } string downloadedSource; using (var client = new System.Net.WebClient()) { client.Encoding = DefaultEncoder; downloadedSource = await client.DownloadStringTaskAsync(absoluteUrl); } return(downloadedSource); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine("error while publishing to file " + ex.Message); //throw; } return(null); }
public static async Task<long?> GetPrimePlatSellOrders(string primeName) { CacheEntry<long?> cacheItem; if (_marketCache.TryGetValue(primeName, out cacheItem)) { if (!cacheItem.IsExpired(_expirationTimespan)) { return cacheItem.Value; } } var textInfo = new CultureInfo("en-US", false).TextInfo; var partName = textInfo.ToTitleCase(primeName.ToLower()); if (_removeBPSuffixPhrases.Any(suffix => partName.EndsWith(suffix + " Blueprint"))) { partName = partName.Replace(" Blueprint", ""); } // Since Warframe.Market is still using the term Helmet instead of the new one, TODO: this might change partName = partName.Replace("Neuroptics", "Helmet"); if (_fixedQueryStrings.ContainsKey(partName)) { //Some of Warframe.Market's query strings are mangled (extra spaces, misspellings, words missing) fix them manually... partName = _fixedQueryStrings[partName]; } string jsonData; using (var client = new WebClient()) { var uri = new Uri(_baseUrl + Uri.EscapeDataString(partName)); try { jsonData = await client.DownloadStringTaskAsync(uri); dynamic result = JsonConvert.DeserializeObject(jsonData); // when the server responds anything that is not 200 (HTTP OK) don't bother doing something else if (result.code != 200) { Debug.WriteLine($"Error with {partName}, Status Code: {result.code.Value}"); _marketCache[primeName] = new CacheEntry<long?>(null); return null; } IEnumerable<dynamic> sellOrders = result.response.sell; long? smallestPrice = sellOrders.Where(order => order.online_status).Min(order => order.price); _marketCache[primeName] = new CacheEntry<long?>(smallestPrice); return smallestPrice; } catch { return null; } } }
private async Task<string> NewDownloadStringAsync() { using (var client = new WebClient()) { return await client.DownloadStringTaskAsync(_url); } }
public async Task AsyncMethod() { var webClient = new WebClient(); var html = await webClient.DownloadStringTaskAsync(new Uri("http://www.google.com")); Debug.WriteLine(1); throw new Exception(); }
private async void button1_Click(object sender, EventArgs e) { WebClient wc = new WebClient(); richTextBox1.Text = await wc.DownloadStringTaskAsync("http://tclhost.com/tv1madj.gif"); MessageBox.Show("Done"); }
private static async Task<Deck> ImportIcyVeins(string url) { try { string json; using(var wc = new WebClient()) json = await wc.DownloadStringTaskAsync(url + ".json"); var wrapper = JsonConvert.DeserializeObject<IcyVeinsWrapper>(json); var deck = new Deck {Name = wrapper.deck_name}; foreach(var cardObj in wrapper.deck_cards) { var cardName = cardObj.name; if(cardName.EndsWith(" Naxx")) cardName = cardName.Replace(" Naxx", ""); if(cardName.EndsWith(" GvG")) cardName = cardName.Replace(" GvG", ""); if(cardName.EndsWith(" BrM")) cardName = cardName.Replace(" BrM", ""); var card = Database.GetCardFromName(cardName); card.Count = cardObj.quantity; deck.Cards.Add(card); if(string.IsNullOrEmpty(deck.Class) && card.PlayerClass != "Neutral") deck.Class = card.PlayerClass; } return deck; } catch(Exception e) { Logger.WriteLine(e.ToString(), "DeckImporter"); return null; } }
public async Task<List<WebTrackResultBase>> Search(string searchText, string email, string password) { await CheckAccessToken(email, password); using (var wc = new WebClient { Proxy = null }) { var str = await wc.DownloadStringTaskAsync( new Uri( string.Format( "https://api.vk.com/method/audio.search?q={0}&auto_complete={1}&sort={2}&lyrics={3}&count={4}&offset={5}&access_token={6}", searchText.ToEscapedUrl(), "true", 2, "false", 50, 0, _accessToken))); var count = uint.Parse(Regex.Match(str, @"\[(?<count>(\d+))(?:,|\])").Groups["count"].Value); if (count == 0) return new List<WebTrackResultBase>(); var cutText = str.Replace(count + ",", null); var result = JsonConvert.DeserializeObject<SearchResult>(cutText); if (result == null || result.response.Count == 0) return new List<WebTrackResultBase>(); return result.response.Select(x => new VkontakteWebTrackResult { Duration = TimeSpan.FromSeconds(x.duration), Uploader = x.artist, Url = x.url, Title = x.title.Replace("\n", " "), SearchResult = x }).Cast<WebTrackResultBase>().ToList(); } }
/// <summary> /// Akteingeselschaft mit aktuellen Kursinformationen /// </summary> /// <param name="symbol">Liste von Aktiensymbolen die geladen werden sollen</param> /// <returns>Aktiengesellschaft mit aktuellen Kursinformationen.</returns> public async Task<Aktie> GetAktieBySymbol(string symbol) { if (string.IsNullOrEmpty(symbol)) { throw new ArgumentException("Es wurde kein Aktiensymbol angegeben!", "symbol"); } Uri quoteUri = GenerateAktiengesellschaftRequestUri(new string[] { symbol }); // CSV downloaden var client = new WebClient(); string aktienCsv = await client.DownloadStringTaskAsync(quoteUri); // CSV parsen var result = await Task.Run<List<Aktie>>(() => ParseAktienCsv(aktienCsv)); if (result != null && result.Count == 1) { Aktie aktie = result[0]; aktie.Symbol = symbol; return aktie; } // Ergebnis zurückliefern return null; }
/// <summary> /// Lädt eine Liste von Akteingeselschaften /// </summary> /// <param name="symbole">Liste von Aktiensymbolen die geladen werden sollen</param> /// <returns>Liste von Aktiengesellschaften mit aktuellen Kursinformationen.</returns> public async Task<List<Aktie>> GetAktienBySymbole(params string[] symbole) { if (symbole == null || symbole.Length == 0) { throw new ArgumentException ("Es wurden keine Aktiensymbole angegeben!", "symbole"); } Uri quoteUri = GenerateAktiengesellschaftRequestUri(symbole); // CSV downloaden var client = new WebClient(); string aktiengesellschaftenCsv = await client.DownloadStringTaskAsync(quoteUri); // CSV parsen var result = await Task.Run<List<Aktie>>(() => ParseAktienCsv(aktiengesellschaftenCsv)); for (int i = 0; i < symbole.Length; i++) { result[i].Symbol = symbole[i]; } // Ergebnis zurückliefern return result; }
/// <summary> /// Creates and adds a few ItemViewModel objects into the Items collection. /// </summary> public async void LoadData() { var url = "http://freshart-static.cloudapp.net/recommended.xml"; var client = new WebClient(); try { string response = await client.DownloadStringTaskAsync(new Uri(url)); var doc = XDocument.Parse(response); var list = from query in doc.Descendants("exhibition") select new ItemViewModel { Title = (string)query.Element("title"), ImageUrl = (string)query.Element("preview-image"), Venue = (string)query.Element("venue"), Address = (string)query.Element("address") }; list.ToList().ForEach(this.Items.Add); this.IsDataLoaded = true; } catch { MessageBox.Show(messageBoxText: "Cannot retrieve exhibition list", caption: "Error", button: MessageBoxButton.OK); } }
public async Task<string> DownloadStringContent(string url) { using (var client = new WebClient()) { return await client.DownloadStringTaskAsync(new Uri(url)).ConfigureAwait(false); } }
public static async Task<WeatherData> GetWeatherfromService(string city) { string url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=cb881b3004e248e78c4a7585bb577eb9"; string response; string tmp; WeatherData wd = new WeatherData(); if (string.IsNullOrWhiteSpace(city)) { return null; } using (WebClient client = new WebClient()) { response = await client.DownloadStringTaskAsync(url); } JsonReader reader = new JsonTextReader(new StringReader(response)); JObject rss = JObject.Parse(response); tmp = (string)rss["main"]["temp"]; double ctmp = Convert.ToDouble(tmp)- 273.15; wd.temp = String.Format("{0:f1}",ctmp); wd.weathermain = (string)rss["weather"][0]["main"]; wd.weatherdescription= (string)rss["weather"][0]["description"]; wd.city = (string)rss["name"]; return wd; }
private static async Task DoIt() { System.Net.WebClient wc = new System.Net.WebClient(); var task1 = wc.DownloadStringTaskAsync("https://www.google.com.au"); Console.WriteLine(await task1); Console.WriteLine("done!"); }
public static async Task <string> Get(string url) { System.Net.WebClient wc = new System.Net.WebClient(); wc.Encoding = Encoding.UTF8; var result = await wc.DownloadStringTaskAsync(url); return(result); }
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; }
async Task CheckBlockLoop() { while (!bExit) { var gstr = MakeRpcUrl(rpc_getblockcount); try { var cstr = await wc.DownloadStringTaskAsync(gstr); var json = MyJson.Parse(cstr).AsDict(); bool bError = json.ContainsKey("error"); if (!bError) { try { int height = json["result"].AsInt(); remoteBlockHeight = height - 1; await SyncBlockTo(height - 1); } catch (Exception err) { Console.WriteLine(err.ToString()); } await Task.Delay(5000); } if (bError) {//出错了 await Task.Delay(5000); continue; } } catch (Exception ex) { await Task.Delay(5000); continue; } } SaveState(); FullExit = true; return; }
public async Task HttpGetAsync(string url, Encoding encoding = null) { int nbFait = rnd.Next(1, 150); var wc = new System.Net.WebClient { Proxy = _webproxy, Encoding = encoding ?? Encoding.UTF8 }; fait = await wc.DownloadStringTaskAsync(url + "/" + nbFait); }
private static async Task <string[]> TestDistributedLock() { IList <Task <string> > tasks = new List <Task <string> >(); for (int i = 0; i < 30; i++) { System.Net.WebClient client = InitializeWebClient(); string uri = "http://localhost:64888/mydiary/v2/Containers('articles" + (i + 1) + "')"; tasks.Add(client.DownloadStringTaskAsync(new Uri(uri))); } return(await System.Threading.Tasks.Task.WhenAll(tasks)); }
public static async Task <string> TinyUrlAsync(string url, string apiKey, string provider = "0_mk") { //string yourUrl = "http://your-site.com/your-url-for-minification"; //string apikey = "YOUR-API-KEY-GOES-HERE"; //string provider = "0_mk"; // see provider strings list in API docs var uriString = string.Format( "http://tiny-url.info/api/v1/create?url={0}&apikey={1}&provider={2}&format=text", url, apiKey, provider); var address = new Uri(uriString); var client = new System.Net.WebClient(); return(await client.DownloadStringTaskAsync(address)); }
public static async Task <string> DownloadFile(string _URL) { using (var wc = new System.Net.WebClient()) { try { return(await wc.DownloadStringTaskAsync(_URL)); } catch (WebException) { Console.WriteLine("Website not found"); return(""); } } }
// Private web GET request; returns downloaded string value private async static Task <string> get(string url, bool utf8 = false) { Common.other("QUERY: " + url); try { System.Net.WebClient wc = new System.Net.WebClient(); if (utf8) { wc.Encoding = Encoding.UTF8; } return(await wc.DownloadStringTaskAsync(url)); } catch (Exception) { return(""); } }
public async Task Verify() { string swaggerResult; using (var client = new System.Net.WebClient()) { swaggerResult = await client.DownloadStringTaskAsync("http://localhost:63300" + TargetUrl); } swaggerResult.Should().NotBeNull(); var obj = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(swaggerResult); var paths = obj["paths"]; Assert.True(paths.Children().Count() > 1); }
private async static Task <TextReader> LoadFile(string file) { if (file.StartsWith("http://") || file.StartsWith("https://")) { try { using (var client = new System.Net.WebClient()) { var response = await client.DownloadStringTaskAsync(new Uri(file)); return(new StringReader(response)); } } catch (WebException ex) { Helpers.ErrorDialog(ex, Resources.Error_Download); return(null); } } else { return(File.OpenText(file)); } }
/// <summary> /// 下载指定的资源 /// </summary> /// <param name="value">要执行的实例</param> /// <param name="address">要下载的地址</param> /// <param name="timeout">超时,毫秒</param> /// <returns>请求的资源</returns> public static string DownloadString(this WebClient value, Uri address, int timeout) => value.Execute(timeout, () => value.DownloadStringTaskAsync(address));
public Task <string> DownloadStringTaskAsync(Uri address) { return(_webClient.DownloadStringTaskAsync(address)); }
public static async Task <bool> DownloadLatestReleaseFromGithub(string url, Func <string, bool> assetSelector, string path, Func <string, string> extractFromArchive = null, bool redownloadIfAlreadyExists = false, TimeSpan?redownloadIfOlderThan = null) { try { if (File.Exists(path)) { if (!redownloadIfAlreadyExists) { return(true); } if (redownloadIfOlderThan.HasValue && (DateTime.Now - File.GetCreationTime(path)) <= redownloadIfOlderThan.Value) { return(true); } File.Delete(path); } using (var wc = new System.Net.WebClient()) { wc.Headers.Add(HttpRequestHeader.UserAgent, "arkbot"); var data = await wc.DownloadStringTaskAsync(url); var json = JsonConvert.DeserializeAnonymousType(data, new { tag_name = "", assets = new[] { new { name = "", browser_download_url = "" } } }); var downloadUrl = json?.assets?.FirstOrDefault(x => assetSelector(x.browser_download_url))?.browser_download_url; if (downloadUrl == null || !await DownloadFile(downloadUrl, path, redownloadIfAlreadyExists, redownloadIfOlderThan)) { return(false); } if (extractFromArchive != null) { using (var archive = ZipFile.OpenRead(path)) { foreach (var entry in archive.Entries) { string zpath = null; if ((zpath = extractFromArchive(entry.FullName)) == null) { continue; } entry.ExtractToFile(zpath, true); } } } } } catch (System.Net.WebException ex) { File.Delete(path); return(false); } catch (OperationCanceledException) { File.Delete(path); return(false); } return(true); }
public async Task <EsiModel> GetAsync(WebHeaderCollection headers, string address, int cacheSeconds = 0) { System.Net.WebClient client = new System.Net.WebClient { Headers = { ["UserAgent"] = _userAgent } }; if (headers != null) { client.Headers = headers; client.Headers["UserAgent"] = _userAgent; } CacheModel cachedItem = _cache.Get <CacheModel>(address); EsiModel esiModel = new EsiModel(); try { if (cacheSeconds == 0) { esiModel.Model = await client.DownloadStringTaskAsync(address); esiModel = BuildHeaders(client.ResponseHeaders, esiModel); return(esiModel); } if (cachedItem != null) { if (DateTime.Compare(cachedItem.Expires, DateTime.UtcNow) >= 0) { esiModel.Model = cachedItem.Item; esiModel.Etag = cachedItem.Etag; esiModel.MaxPages = cachedItem.Page; return(esiModel); } if (!string.IsNullOrEmpty(cachedItem.Etag)) { client.Headers["If-None-Match"] = cachedItem.Etag; } string esiResponse = await client.DownloadStringTaskAsync(address); esiModel = BuildHeaders(client.ResponseHeaders, esiModel); cachedItem = new CacheModel(esiResponse, esiModel.Etag, cacheSeconds, esiModel.MaxPages); _cache.Remove(address); _cache.Add(address, cachedItem); } else { string esiResponse = await client.DownloadStringTaskAsync(address); esiModel = BuildHeaders(client.ResponseHeaders, esiModel); cachedItem = new CacheModel(esiResponse, esiModel.Etag, cacheSeconds, esiModel.MaxPages); _cache.Add(address, cachedItem); } esiModel.Model = cachedItem.Item; return(esiModel); } catch (WebException e) { EsiModel returned = BuildException(e, cachedItem, esiModel, address, string.Empty); if (returned != null) { return(returned); } throw; } }