public static async Task <int> SaveTour(Tour tour) { try { Task <float> tmp = WebRequester.ReturnDistance(tour.Source, tour.Destination); await tmp; tour.Distance = tmp.Result; int rCode = Database.InsertTour(tour); if (rCode == 0) { FetchImage(tour.Name, tour.Source, tour.Destination); } else { return(-1); } } catch (Exception e) { Console.WriteLine("Exception Encountered:{0}", e.Message); } return(1); }
public async Task AggregateIntegrationTest() { var store = new JsonStore( new HardDrive(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\StackoverflowRecentQuestions")); var web = new WebRequester(); var getter = new RecentQuestionsGetter(store, web); QuestionsWhenUnrestricted = await HandleStackexchangeThrottle(async() => await getter.GetSince(0), store); QuestionsWhenUnrestrictedPage2 = await HandleStackexchangeThrottle(async() => await getter.GetSince(0, 2), store); QuestionsWithEitherJavaOrCSharpSince2017 = await HandleStackexchangeThrottle( async() => await getter.GetSince(Year2017, 1, "stackoverflow", new[] { "c#", "java" }), store); TestsPassed = true; var methods = GetType().GetMethods(); foreach (var method in methods) { if (method.Name.IndexOf("Test") == 0) { await AggregateResult(method.Name.Substring(4), web); } } if (!TestsPassed) { Assert.Fail(TestsFailedString); } }
public void SendPicture(byte[] picture, WebRequester.RequestDone callback) { WebRequester.GetResponse(apiBaseUrl + "image", "multipart/form-data", "POST", callback, new Dictionary <string, dynamic>() { { "picture", picture } }); }
private static Task RemoveEntities <TEntity>(string entityName, RawRabbitConfiguration config) where TEntity : IRabbtMqEntity { var tasks = new List <Task>(); foreach (var hostname in config.Hostnames) { var credentials = new NetworkCredential(config.Username, config.Password); var queuesTask = new WebRequester() .WithUrl($"http://{hostname}:15672/api/{entityName}") .WithMethod(HttpMethod.Get) .WithCredentials(credentials) .PerformAsync <List <TEntity> >() .ContinueWith(entitiesTask => { var removeTask = new List <Task>(); foreach (var entity in entitiesTask.Result) { if (string.IsNullOrEmpty(entity.Name) || entity.Name.StartsWith("amq.")) { continue; } var removeEntityTask = new WebRequester() .WithUrl($"http://{hostname}:15672/api/{entityName}/{Uri.EscapeDataString(entity.Vhost)}/{Uri.EscapeUriString(entity.Name)}") .WithMethod(HttpMethod.Delete) .WithCredentials(credentials) .GetResponseAsync(); removeTask.Add(removeEntityTask); } return(Task.WhenAll(removeTask)); }); tasks.Add(queuesTask); } return(Task.WhenAll(tasks)); }
public async Task GetResponseAsync_WithTemplate_ShouldBuildCorrectUrl() { // Arrange var httpClient = A.Fake <IHttpClient>(); var template = "test/{item}/{id}"; var parameters = new NameValueCollection { { "item", "itemName" }, { "id", "123" } }; var expectedUrl = "/test/itemName/123"; A.CallTo( () => httpClient.SendAsync( A <HttpRequestMessage> .Ignored)) .Returns(_basicResponse); A.CallTo( () => httpClient.Client) .Returns(_basicClient); var requester = new WebRequester(httpClient); // Act await requester.GetResponseAsync(template, parameters); // Assert A.CallTo( () => httpClient.SendAsync( A <HttpRequestMessage> .That.Matches(req => req.RequestUri.ToString().Equals(expectedUrl))) ).MustHaveHappened(); }
public void SyncChainFromPeerInfo(AboutInfo peerChainInfo) { try { var thisChainDiff = this.Chain.CalcCumulativeDifficulty(); var peerChainDiff = peerChainInfo.CumulativeDifficulty; if (peerChainDiff > thisChainDiff) { Console.WriteLine("@Chain sync started.Peer: {0}." + " Expected chain length = {1}, expected cummulative difficulty = {2}.", peerChainInfo.NodeUrl, peerChainInfo.BlocksCount, peerChainDiff); var blocks = JsonConvert.DeserializeObject <List <Block> >(WebRequester.Get(peerChainInfo.NodeUrl + "/api/Node/blocks")); var chainIncreased = this.Chain.ProcessLongerChain(blocks); if (chainIncreased) { this.NotifyPeersAboutNewBlock(); } } } catch (Exception ex) { Console.WriteLine("Error loading the chain: " + ex.Message); } }
public void NotifyPeersAboutNewBlock() { var notification = new { blocksCount = this.Chain.Blocks.Count, cumulativeDifficulty = this.Chain.CalcCumulativeDifficulty(), nodeUrl = this.SelfUrl }; foreach (var nodeId in this.Peers) { var peerUrl = this.Peers[nodeId.Key]; Console.WriteLine("Notifying peer {0} about the new block", peerUrl); try { var result = WebRequester .Post(peerUrl + "/api/Node/peers/notify-new-block", notification); } catch (Exception ex) { Console .WriteLine("Notifying peer {0} failed, due to {1}", peerUrl, ex.Message); } } }
public async Task Send_WithUrlAndDefaultParameters_ShouldBuildCorrectUrl() { // Arrange var httpClient = A.Fake <IHttpClient>(); var url = "test/itemName/123"; var defaultParams = new NameValueCollection { { "APIKey", "keyvalue" } }; var expectedUrl = "/test/itemName/123?APIKey=keyvalue"; A.CallTo( () => httpClient.SendAsync( A <HttpRequestMessage> .Ignored)) .Returns(_basicResponse); A.CallTo( () => httpClient.Client) .Returns(_basicClient); var requester = new WebRequester(httpClient, defaultParams); // Act var request = new HttpRequestMessage(HttpMethod.Get, url); await requester.SendMessageAsync(request); // Assert A.CallTo( () => httpClient.SendAsync( A <HttpRequestMessage> .That.Matches(req => req.RequestUri.ToString().Equals(expectedUrl))) ).MustHaveHappened(); }
public Song(string file) { if (StringNetworkTools.IsURL(file)) { //Setup MP3 IDv1 TAG Reader //First we get our MP3TAG from remote file byte[] id3data = WebRequester.Request(file, null, null, 128); this._ID3 = new ID3(id3data); if (_ID3.hasTag) { this.mp3tag = _ID3; this.Name = $"{mp3tag.Artist} - {mp3tag.Title}"; } else { string href = StringNetworkTools.FileFromURL(file); this.Name = href.Split('.')[0]; } this.URL = file; } else { this.Name = file.Split('.')[0]; this.URL = file; this.mp3tag = null; } }
public async Task GetResponseAsync_WithQueryParameterAndDefaultParameters_ShouldAppendDefaultParameters() { // Arrange var httpClient = A.Fake <IHttpClient>(); var url = "test/itemName/123?parameter=value"; var defaultParams = new NameValueCollection { { "APIKey", "keyvalue" } }; var expectedUrl = "/test/itemName/123?parameter=value&APIKey=keyvalue"; A.CallTo( () => httpClient.SendAsync( A <HttpRequestMessage> .Ignored)) .Returns(_basicResponse); A.CallTo( () => httpClient.Client) .Returns(_basicClient); var requester = new WebRequester(httpClient, TimeSpan.FromMilliseconds(1), defaultParams); // Act await requester.GetResponseAsync(url); // Assert A.CallTo( () => httpClient.SendAsync( A <HttpRequestMessage> .That.Matches(req => req.RequestUri.ToString().Equals(expectedUrl))) ).MustHaveHappened(); }
public async Task GetResponseAsync_WithTemplateAndDefaultParameters_ShouldBuildCorrectUrl() { // Arrange var httpClient = A.Fake <IHttpClient>(); var template = "test/{item}/{id}"; var defaultParams = new NameValueCollection { { "APIKey", "keyvalue" } }; var parameters = new NameValueCollection { { "item", "itemName" }, { "id", "123" }, { "isEnabled", "true" } }; var expectedUrl = "/test/itemName/123?isEnabled=true&APIKey=keyvalue"; A.CallTo( () => httpClient.SendAsync( A <HttpRequestMessage> .Ignored)) .Returns(_basicResponse); A.CallTo( () => httpClient.Client) .Returns(_basicClient); var requester = new WebRequester(httpClient, TimeSpan.FromMilliseconds(1), defaultParams); // Act await requester.GetResponseAsync(template, parameters); // Assert A.CallTo( () => httpClient.SendAsync( A <HttpRequestMessage> .That.Matches(req => req.RequestUri.ToString().Equals(expectedUrl))) ).MustHaveHappened(); }
public async Task GetResponseAsStringAsync_WithQueryParameter_ShouldIncludeQueryParameterInRequest() { // Arrange var httpClient = A.Fake <IHttpClient>(); var fakeResponse = new HttpResponseMessage { Content = new StringContent("All good") }; var url = "test/path?APIKey=value"; A.CallTo( () => httpClient.SendAsync( A <HttpRequestMessage> .Ignored)) .Returns(fakeResponse); var requester = new WebRequester(httpClient); // Act await requester.GetResponseAsStringAsync(url); // Assert A.CallTo( () => httpClient.SendAsync(A <HttpRequestMessage> .That.Matches(req => req.RequestUri.ToString().Equals("/" + url))) ).MustHaveHappened(); }
public IGeoCodeResult GetCoordinates(string search) { GeoCodeResult gResult = new GeoCodeResult(); gResult.Library = this.GetType().ToString(); if (!String.IsNullOrEmpty(Config.Key)) { try { string url = BuildSearchQuery(search); //135+pilkington+avenue,+birmingham string json = new WebRequester(url).GetData(); if (!String.IsNullOrEmpty(json)) { JObject result = (JObject)JsonConvert.DeserializeObject(json); if (result["results"][0]["locations"].Count() > 0) { foreach (var loc in result["results"][0]["locations"]) { try { Location l = new Location(); var latLng = loc["latLng"]; if (latLng != null) { l.Latitude = latLng["lat"].GetDoubleValue(); l.Longitude = latLng["lng"].GetDoubleValue(); } l.Accuracy = loc["geocodeQuality"].GetStringValue(); String[] AddressTemp = new string[] { loc["street"].GetStringValue(), loc["adminArea5"].GetStringValue(), loc["adminArea4"].GetStringValue(), loc["postalCode"].GetStringValue(), loc["adminArea1"].GetStringValue() }; l.Type = loc["type"].GetStringValue(); l.Address = String.Join(",", AddressTemp.Where(s => !String.IsNullOrEmpty(s))); l.Name = l.Address; gResult.Locations.Add(l); } catch { } } } //gResult.Count = 1; } } catch { } } return(gResult); }
public HttpClient(Configuration config) { BaseUrl = config.BaseUrl; config.Advanced.Serializers = config.Advanced.Serializers.Concat(ContentSerializers.Defaults).ToList(); _webRequester = new WebRequester(config); _responseTransformer = new ResponseTransformer(config.Advanced.Serializers); }
public Processor(ILogger <Processor> logger, WebRequester requester, IRepository <User> userRepository, IOptions <EnvironmentSettings> options) { Logger = logger; Requester = requester; UserRepository = userRepository; Options = options; }
public static async Task <string[]> GetTypeList() { string[] result = await WebRequester.HttpGet <string[]>( serviceBaseUrl, "/types"); return(result); }
public static async Task <Beleg.StatusEnum[]> GetStatusList() { Beleg.StatusEnum[] result = await WebRequester.HttpGet <Beleg.StatusEnum[]>( serviceBaseUrl, "/status"); return(result); }
public void Database_GetImage() { Byte[] result = null; Task <Byte[]> tmp = WebRequester.GetPicture("Illmitz", "Neusiedl am See"); tmp.Wait(); result = tmp.Result; Mainlogic.SaveImage(result, "test"); Assert.IsNotNull(result); }
public async void PostRawAsync_MockSearchEndpoint_ReturnsJsonString() { string sampleJson = File.ReadAllText("Data/BigMacSearch.json"); var mockClient = new HttpClient(Util.MockHttpMessageHandlerFactory("https://api.nal.usda.gov/fdc/v1/search?api_key=DEMO_KEY", sampleJson)); IRequester webRequester = new WebRequester(mockClient); string returnedString = await webRequester.PostRawAsync("https://api.nal.usda.gov/fdc/v1/search?api_key=DEMO_KEY", "{\"generalSearchInput\": \"big mac\"}"); Assert.Equal(sampleJson, returnedString); }
public async void GetRawAsync_MockFoodEndpoint_ReturnsJsonString() { string sampleJson = File.ReadAllText("Data/BigMacFood.json"); var mockClient = new HttpClient(Util.MockHttpMessageHandlerFactory("https://api.nal.usda.gov/fdc/v1/170720?api_key=DEMO_KEY", sampleJson)); IRequester webRequester = new WebRequester(mockClient); string returnedString = await webRequester.GetRawAsync("https://api.nal.usda.gov/fdc/v1/170720?api_key=DEMO_KEY"); Assert.Equal(sampleJson, returnedString); }
public IGeoCodeResult GetCoordinates(string search) { GeoCodeResult gResult = new GeoCodeResult(); gResult.Library = this.GetType().ToString(); try { string url = BuildSearchQuery(search); //1600+Amphitheatre+Parkway,+Mountain+View,+CA string json = new WebRequester(url).GetData(); if (!String.IsNullOrEmpty(json)) { JObject result = (JObject)JsonConvert.DeserializeObject(json); if (result["status"].GetStringValue() == GoogleResultStatus.OK.ToString() && result["results"].Count() > 0) { foreach (var loc in result["results"]) { Location Location = new Location(); Location.Address = loc["formatted_address"].GetStringValue(); var geometry = loc["geometry"]; if (geometry != null) { var location = geometry["location"]; if (location != null) { Location.Latitude = location["lat"].GetDoubleValue(); Location.Longitude = location["lng"].GetDoubleValue(); } Location.Type = location["location_type"].GetStringValue(); } var addresscomponents = loc["address_components"]; if (addresscomponents != null && addresscomponents.Count() > 0) { Location.Name = loc["address_components"][0]["long_names"].GetStringValue(); //!String.IsNullOrEmpty(loc["address_components"][0]["long_name"].Value<String>()) ? loc["address_components"][0]["long_name"].Value<String>() : string.Empty; } gResult.Locations.Add(Location); } } else { gResult.Error = result["status"].ToString(); } } } catch (Exception e) { gResult.Error = e.Message; } return(gResult); }
public IGeoCodeResult GetCoordinates(string search) { GeoCodeResult gResult = new GeoCodeResult(); gResult.Library = this.GetType().ToString(); try { string url = BuildSearchQuery(search); //1600+Amphitheatre+Parkway,+Mountain+View,+CA string json = new WebRequester(url).GetData(); if (!String.IsNullOrEmpty(json)) { JObject result = (JObject)JsonConvert.DeserializeObject(json); if (result["found"].Value <int>() > 0) { foreach (var loc in result["features"]) { Location Location = new Location(); var properties = loc["properties"]; if (properties != null) { Location.Name = properties["name"].GetStringValue(); Location.Address = Location.Name; Location.Type = properties["place"].GetStringValue(); } var centroid = loc["centroid"]; if (centroid != null) { var coordinates = centroid["coordinates"]; if (coordinates != null && coordinates.Count() > 1) { Location.Latitude = coordinates[0].GetDoubleValue(); Location.Longitude = coordinates[1].GetDoubleValue(); } } gResult.Locations.Add(Location); } } else { gResult.Error = "No results"; } } } catch (Exception e) { gResult.Error = e.Message; } return(gResult); }
public async Task GetResponseAsStringAsync_NoParameters_ShouldThrowArgumentNullException() { // Arrange var httpClient = A.Fake <IHttpClient>(); var requester = new WebRequester(httpClient); // Act var ex = await Record.ExceptionAsync(async() => { await requester.GetResponseAsStringAsync("/test", null, 0); }); // Assert ex.ShouldBeOfType <ArgumentNullException>(); }
public async void PostAsync_MockSearchEndpoint_ReturnsSearchResultObject() { string sampleJson = File.ReadAllText("Data/BigMacSearch.json"); var mockClient = new HttpClient(Util.MockHttpMessageHandlerFactory("https://api.nal.usda.gov/fdc/v1/search?api_key=DEMO_KEY", sampleJson)); IRequester webRequester = new WebRequester(mockClient); var returnedObject = await webRequester.PostAsync <SearchResult>("https://api.nal.usda.gov/fdc/v1/search?api_key=DEMO_KEY", "{\"generalSearchInput\": \"big mac\"}"); string searchInput = returnedObject.FoodSearchCriteria.GeneralSearchInput; Assert.Equal("big mac", searchInput); }
public async void GetAsync_MockFoodEndpoint_ReturnsFoodObject() { string sampleJson = File.ReadAllText("Data/BigMacFood.json"); var mockClient = new HttpClient(Util.MockHttpMessageHandlerFactory("https://api.nal.usda.gov/fdc/v1/170720?api_key=DEMO_KEY", sampleJson)); IRequester webRequester = new WebRequester(mockClient); var returnedObject = await webRequester.GetAsync <Food>("https://api.nal.usda.gov/fdc/v1/170720?api_key=DEMO_KEY"); string description = returnedObject.Description; Assert.Equal("McDONALD'S, BIG MAC", description); }
public async Task GetResponseAsync_ShouldTimeoutOnSlowResponse() { // Arrange var httpClient = WebRequestHttpClientFactory.Configure(new Uri(Url)).WithTimeout(TimeSpan.FromMilliseconds(100)).Create(); var webRequester = new WebRequester(httpClient); // Act var exception = await Record.ExceptionAsync(async() => await webRequester.GetResponseAsync("/delay/250")); // Assert exception.ShouldBeOfType(typeof(TaskCanceledException)); }
static void Main(string[] args) { byte[] test = WebRequester.Request("http://tv2.partizan.si/YoutubeVideoPlayer/api/audio/song2.mp3", null, null, 128); ID3 tag = new ID3(test); Console.WriteLine("Tag is available: " + tag.hasTag); Console.WriteLine("Artist: " + tag.Artist); Console.WriteLine("Title: " + tag.Title); Console.ReadLine(); }
public static async Task DeleteBeleg(string user, int belegnummer) { // Parameter prüfen if (string.IsNullOrWhiteSpace(user)) { throw new ArgumentNullException(nameof(user)); } await WebRequester.HttpDelete( serviceBaseUrl, string.Format("/{0}/{1}", user, belegnummer)); }
public IGeoCodeResult GetCoordinates(string search) { GeoCodeResult gResult = new GeoCodeResult(); gResult.Library = this.GetType().ToString(); if (!String.IsNullOrEmpty(Config.Key)) { try { string url = BuildSearchQuery(search); //135+pilkington+avenue,+birmingham string json = new WebRequester(url).GetData(); if (!String.IsNullOrEmpty(json)) { JObject result = (JObject)JsonConvert.DeserializeObject(json); if (result["resourceSets"][0]["resources"].Count() > 0) { foreach (var loc in result["resourceSets"][0]["resources"]) { Location l = new Location(); String AddressTemp = String.Empty; l.Name = loc["name"].GetStringValue(); var point = loc["point"]; if (point != null && point.Count() > 1) { l.Latitude = point["coordinates"][0].GetDoubleValue(); l.Longitude = point["coordinates"][1].GetDoubleValue(); } l.Accuracy = loc["confidence"].GetStringValue(); if (loc["address"].HasValues) { AddressTemp = String.Join(",", loc["address"].Values().Where(add => !string.IsNullOrEmpty(add.Value <string>()))); } l.Address = AddressTemp; gResult.Locations.Add(l); } //gResult.Count = 1; // for now we are only dealing with the first result } else { gResult.Error = "No Results"; } } } catch { } } return(gResult); }
public async void Search_FoodNameOnly_ReturnsSearchResultObject() { string sampleJson = File.ReadAllText("Data/BigMacSearch.json"); var mockClient = new HttpClient(Util.MockHttpMessageHandlerFactory("https://api.nal.usda.gov/fdc/v1/search?api_key=DEMO_KEY", sampleJson)); IRequester webRequester = new WebRequester(mockClient); var api = new FoodDataCentralAPI("DEMO_KEY", webRequester); SearchResult searchResult = await api.Search("big mac"); string searchInput = searchResult.FoodSearchCriteria.GeneralSearchInput; Assert.Equal("big mac", searchInput); }
public BackupsController(IAppsService apps) { this.apps = apps; this.requester = new WebRequester(); }