// GET: ApiTest public ActionResult Index() { api = new ApiFetcher(_context); //Dictionary<Tag, int> test = new Dictionary<Tag, int>(); //test.Add(new Tag() //{ // RawGTagId = 36, // Slug = "open-world", // TagName = "Open World" //}, 4); //test.Add(new Tag() //{ // RawGTagId = 7, // Slug = "multiplayer", // TagName = "Multiplayer" //}, 1); //test.Add(new Tag() //{ // RawGTagId = 24, // Slug = "rpg", // TagName = "RPG" //}, 3); //test.Add(new Tag() //{ // RawGTagId = 32, // Slug = "sci-fi", // TagName = "Sci-Fi" //}, 1); //test.OrderBy(e => e.Value); //Game rawr = api.GetGameFromApi(test); return(View()); }
public ActionResult BusInfo(PostcodeSelection selection) { // Add some properties to the BusInfo view model with the data you want to render on the page. // Write code here to populate the view model with info from the APIs. // Then modify the view (in Views/Home/BusInfo.cshtml) to render upcoming buses. var postcode = new BusInfo(selection.Postcode); try { var coordinates = ApiFetcher.GetCoordinates(postcode.PostCode); var stopPoints = ApiFetcher.GetStopPoints(coordinates.result); var busStops = new List <BusStop>(); foreach (var stopPoint in stopPoints) { var buses = ApiFetcher.GetBuses(stopPoint); foreach (var bus in buses) { bus.timeToStation = bus.timeToStation / 60; } var busStop = new BusStop(buses, stopPoint.commonName); busStops.Add(busStop); } return(View(busStops)); } catch { return(View()); } }
public ActionResult <Game> GetResult(int[] answerIds) { var scores = ( from tag in _context.Tags.AsEnumerable() join tagpoints in ( from tagpoint in _context.TagPoints where answerIds.Contains(tagpoint.AnswerId) select tagpoint ) on tag.Id equals tagpoints.TagId into grouping where grouping.Sum(tp => tp.Point) > 0 select new { tag, points = grouping.Sum(tp => tp.Point) } ).Take(5).OrderByDescending(t => t.points).ToList(); var apiFetcher = new ApiFetcher(_context); // ugly hack but we're running out of time (as if everything else is pretty) for (int amount = scores.Count; amount > 0; amount--) { try { var subset = scores.Take(amount).ToDictionary(score => score.tag, score => score.points); return(apiFetcher.GetGameFromApi(subset)); } catch { } } return(null); }
public ProductsService(UnitOfWork unitOfWork, Scraper scraper, ILogger <ProductsService> logger, ParametersService parametersService, ApiFetcher apiFetcher) { this.unitOfWork = unitOfWork; this.scraper = scraper; this.logger = logger; this.parametersService = parametersService; this.apiFetcher = apiFetcher; }
public async Task RequestFoxFact() { string fact = await ApiFetcher.RequestStringFromApi("https://some-random-api.ml/facts/fox", "fact"); if (!string.IsNullOrEmpty(fact)) { await Context.Channel.SendMessageAsync(fact); } else { await Context.Channel.SendMessageAsync("The foxfact command is currently unavailable."); } }
public async Task RequestCatFact() { string fact = await ApiFetcher.RequestStringFromApi("https://catfact.ninja/fact", "fact"); if (!string.IsNullOrEmpty(fact)) { await Context.Channel.SendMessageAsync(fact); } else { await Context.Channel.SendMessageAsync("The catfact command is currently unavailable."); } }
public async Task RequestDog() { string fileUrl = await ApiFetcher.RequestEmbeddableUrlFromApi("https://random.dog/woof.json", "url"); if (!string.IsNullOrEmpty(fileUrl) && Uri.IsWellFormedUriString(fileUrl, UriKind.Absolute)) { await SendAnimalEmbed(":dog:", fileUrl); } else { await Context.Channel.SendMessageAsync("The dog command is currently unavailable."); } }
public async Task RequestFox() { string fileUrl = await ApiFetcher.RequestEmbeddableUrlFromApi("https://wohlsoft.ru/images/foxybot/randomfox.php", "file"); if (!string.IsNullOrEmpty(fileUrl) && Uri.IsWellFormedUriString(fileUrl, UriKind.Absolute)) { await SendAnimalEmbed(":fox:", fileUrl); } else { await Context.Channel.SendMessageAsync("The fox command is currently unavailable."); } }
public async Task RequestCat() { string fileUrl = await ApiFetcher.RequestEmbeddableUrlFromApi("https://aws.random.cat/meow", "file"); if (!string.IsNullOrEmpty(fileUrl) && Uri.IsWellFormedUriString(fileUrl, UriKind.Absolute)) { await SendAnimalEmbed(":cat:", fileUrl); } else { await Context.Channel.SendMessageAsync("The cat command is currently unavailable."); } }
static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); new Thread((new ThreadStart(MonitorMatchesOfInterest))).Start(); while (true) { foreach (var matchOfInterest in matchesOfInterest) { try { var result = ApiFetcher.GetMatch(matchOfInterest.id).FirstOrDefault(); if (result != null) { result.id = Guid.NewGuid().ToString(); var previousResult = DataStore.GetLastStore(); DataStore.StoreNew(result); if (previousResult == null) { continue; } var messages = MessageHandler.MessageHandler.GetMessages(previousResult, result, matchOfInterest.id); foreach (var message in messages) { var score = string.Format("{0} {1}/{2}", result.BattingTeam, result.BattingTeamOuts, result.BattingTeamRuns); var messageSender = new MessageSender(); messageSender.Send(message, score); Console.WriteLine(DateTime.Now + ": " + message + " --- Score: " + score); } } } catch (Exception e) { Console.WriteLine("Exception caught: " + e.Message); Log.Logger.Error(e, "An exception was caught by the main thread"); } } Thread.Sleep(30000); } }
public void getDataTest() { Console.WriteLine("test"); RiotSharp.FeaturedGamesEndpoint.FeaturedGames testgame = ApiFetcher.api.GetFeaturedGames(Region.euw); string sname = testgame.GameList[0].Participants[0].SummonerName; ApiFetcher.CURRENT_SUMMONER = ApiFetcher.api.GetSummoner(Region.euw, sname).Id; //ApiFetcher.CURRENT_SUMMONER = 60077041; int result = ApiFetcher.getData(); ApiFetcher.getData(1, 1); Assert.IsTrue(true); // TODO: Assertionen zu Methode ApiFetcherTest.getDataTest() hinzufügen }
public async Task RequestBirb() { string fileUrl = await ApiFetcher.RequestEmbeddableUrlFromApi("https://random.birb.pw/tweet.json", "file"); if (!string.IsNullOrEmpty(fileUrl) && Uri.IsWellFormedUriString(fileUrl, UriKind.Absolute)) { fileUrl = "https://random.birb.pw/img/" + fileUrl; await SendAnimalEmbed(":bird:", fileUrl); } else { await Context.Channel.SendMessageAsync("The birb command is currently unavailable."); } }
public async Task XKCD([Summary("Comic ID")] string comicId = "") { int parsedComicId; if ((!int.TryParse(comicId, out parsedComicId) || parsedComicId <= 0) && !String.IsNullOrEmpty(comicId)) { await Context.Channel.SendMessageAsync("Comic ID must be a positive integer less than or equal to " + Int32.MaxValue + "."); return; } string json; if (parsedComicId == 0) { json = await ApiFetcher.RequestSiteContentAsString("https://xkcd.com/info.0.json"); } else { json = await ApiFetcher.RequestSiteContentAsString($"https://xkcd.com/{comicId}/info.0.json"); } if (string.IsNullOrEmpty(json)) { await Context.Channel.SendMessageAsync("404 Not Found"); return; } string imgLink; string imgHoverText; string comicTitle; using (JsonDocument parsedJson = JsonDocument.Parse(json)) { imgLink = parsedJson.RootElement.GetProperty("img").ToString(); imgHoverText = parsedJson.RootElement.GetProperty("alt").ToString(); comicTitle = parsedJson.RootElement.GetProperty("safe_title").ToString(); } EmbedBuilder builder = new EmbedBuilder(); builder.Title = comicTitle; builder.WithImageUrl(imgLink); builder.WithFooter(imgHoverText); builder.Color = EMBED_COLOR; await SendEmbed(builder.Build()); }
static void Main(string[] args) { var postcode = UserInterface.GetPostcode(); var coordinates = ApiFetcher.GetCoordinates(postcode); var stopPoints = ApiFetcher.GetStopPoints(coordinates.result); foreach (var stopPoint in stopPoints) { var buses = ApiFetcher.GetBuses(stopPoint); UserInterface.ShowInformation(buses, stopPoint.commonName); } Console.ReadLine(); }
static void MonitorMatchesOfInterest() { while (true) { var availableMatches = ApiFetcher.GetMatches(); matchesOfInterest = availableMatches.Where(m => m.HasTeamPlaying(followingTeams)).ToList(); if (!matchesOfInterest.Any()) { Console.WriteLine("No matches of interest"); } else { Console.WriteLine($"Found {matchesOfInterest.Count()} matches of interest"); } Thread.Sleep(160000); } }
static async Task Main(string[] args) { /* * Check if arguments are provided and try to parse them as the longitude and latitude to look for. * First argument should be Longitude. (North is positive, South is negative.) * Second argument should be Latitude. (East is positive, West is negative.) */ if (args.Length > 0) { bool validLongitude = decimal.TryParse(args[0], out decimal longitude); bool validLatitude = decimal.TryParse(args[1], out decimal latitude); // Try to parse and return an error message if this fails. if (!validLongitude || !validLatitude) { Console.WriteLine("Failed to parse the command-line arguments.\n" + "Please make sure that the arguments are valid.\n" + "First argument should be Longitude. (North is positive, South is negative.)\n" + "Second argument should be Latitude. (East is positive, West is negative.)"); } Console.WriteLine($"Looking for States near the {longitude} - {latitude}"); var apiFetcher = new ApiFetcher(); var distanceCalculation = new DistanceCalculation(); StatesResponse response = await apiFetcher.GetStatesNearCoordinates(longitude, latitude); var shortestDistance = double.MaxValue; State foundState = null; // Calculate the distances for every state and return the shortest. foreach (var state in response.ConvertedStates) { var distance = distanceCalculation.CalculateGeodesicDistance(longitude, latitude, state.Longitude, state.Latitude); // Overwrite the new shortest before checking other States. if (distance < shortestDistance) { shortestDistance = distance; foundState = state; } } Console.WriteLine($"Closest State to the given coordinates ({longitude}, {latitude}):\n" + $"Geodesic distance: {shortestDistance}\n" + $"Callsign: {foundState.CallSign}\n" + $"Longitude: {foundState.Longitude}\n" + $"Latitude: {foundState.Latitude}\n" + $"Geometric Altitude: {foundState.GeoAltitude}\n" + $"Country of Origin: {foundState.OriginCountry}\n" + $"ICAO24 ID: {foundState.ICAO24}"); } // Otherwise test it out with the two given challenge inputs. else { var apiFetcher = new ApiFetcher(); var distanceCalculation = new DistanceCalculation(); /* * Eiffel Tower * Longitude: 48.8584 N * Latitude: 2.2945 E */ Console.WriteLine("Looking for States near the Eiffel Tower..."); var longitude = 48.8584M; var latitude = 2.2945M; StatesResponse response = await apiFetcher.GetStatesNearCoordinates(longitude, latitude); var shortestDistance = double.MaxValue; State foundState = null; // Calculate the distances for every state and return the shortest. foreach (var state in response.ConvertedStates) { var distance = distanceCalculation.CalculateGeodesicDistance(longitude, latitude, state.Longitude, state.Latitude); // Overwrite the new shortest before checking other States. if (distance < shortestDistance) { shortestDistance = distance; foundState = state; } } Console.WriteLine($"Closest State to the Eiffel Tower:\n" + $"Geodesic distance: {shortestDistance}\n" + $"Callsign: {foundState.CallSign}\n" + $"Longitude: {foundState.Longitude}\n" + $"Latitude: {foundState.Latitude}\n" + $"Geometric Altitude: {foundState.GeoAltitude}\n" + $"Country of Origin: {foundState.OriginCountry}\n" + $"ICAO24 ID: {foundState.ICAO24}"); /* * John F. Kennedy Airport * Longitude: 40.6413 N * Latitude: 73.7781 W */ Console.WriteLine("Looking for States near the John F. Kennedy Airport..."); longitude = 40.6413M; latitude = -73.7781M; response = await apiFetcher.GetStatesNearCoordinates(longitude, latitude); shortestDistance = double.MaxValue; foundState = null; // Calculate the distances for every state and return the shortest. foreach (var state in response.ConvertedStates) { var distance = distanceCalculation.CalculateGeodesicDistance(longitude, latitude, state.Longitude, state.Latitude); // Overwrite the new shortest before checking other States. if (distance < shortestDistance) { shortestDistance = distance; foundState = state; } } Console.WriteLine($"Closest State to the John F. Kennedy Airport:\n" + $"Geodesic distance: {shortestDistance}\n" + $"Callsign: {foundState.CallSign}\n" + $"Longitude: {foundState.Longitude}\n" + $"Latitude: {foundState.Latitude}\n" + $"Geometric Altitude: {foundState.GeoAltitude}\n" + $"Country of Origin: {foundState.OriginCountry}\n" + $"ICAO24 ID: {foundState.ICAO24}"); } }
public static List <string> GetMessages(CricinfoMatchDetails previousResult, CricinfoMatchDetails currentResult, int id) { var result = new List <string>(); // If the game has just started, that's the only information we can get if (previousResult == null && currentResult != null) { var sydneyTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "Sydney"); if (sydneyTime.Hour < 12) { result.Add("Morning, everyone"); } else { result.Add("Afternoon, everyone"); } result.Add("We start a new game for Australia"); } // If the team has changed, that's the only information we can get from it if (previousResult.BattingTeam != currentResult.BattingTeam) { var message = string.Format("{0} comes into bat", currentResult.BattingTeam); result.Add(message); return(result); } // Has there been a wicket? if (previousResult.BattingTeamOuts < currentResult.BattingTeamOuts) { // who was it? var batter = IsBatterOut(previousResult.CurrentBatter, currentResult) ? previousResult.CurrentBatter : previousResult.OtherBatter; var score = IsBatterOut(previousResult.CurrentBatter, currentResult) ? previousResult.CurrentBatterScore : previousResult.OtherBatterScore; // Get the out string var out_string = ApiFetcher.GetLastWicketInfo(id); var message = string.Format("OUT! {0} on {1}, {2}", batter, score, out_string); result.Add(message); } // Has a batter for a four or a six? foreach (var batter in currentResult.Batters) { /*if (IsBatterFour(batter, previousResult, currentResult)) * { * result.Add($"And that's a *four* for {batter}"); * }*/ if (IsBatterSix(batter, previousResult, currentResult)) { result.Add($"And that's a *six* for {batter}"); } } // Has there been a batter milestone for the current batter? for (int milestone = 50; milestone < 300; milestone += 50) { foreach (var batter in currentResult.Batters) { if (IsBatterMilestone(batter, milestone, previousResult, currentResult)) { var message = string.Format("{0} for {1}!", milestone, batter); result.Add(message); } } } // Has there been a milestone for the team? for (int milestone = 50; milestone < 700; milestone += 50) { if (IsTeamMilestone(milestone, previousResult, currentResult)) { var message = string.Format("{0} has made it to {1}", currentResult.BattingTeam, milestone); result.Add(message); } } // Has the team declared? if (IsTeamJustDeclared(previousResult, currentResult)) { var message = string.Format("{0} has declared", currentResult.BattingTeam); result.Add(message); } // Has the state changed if (HasStateJustChanged(previousResult, currentResult)) { var state = currentResult.State; if (!string.IsNullOrWhiteSpace(state)) { var message = string.Format("State has changed to {0}", state); switch (state) { case STATE_MATCH_OVER: message = "And that's it folks, the *match is over*"; break; case STATE_TEA: message = "The boys have gone off for *tea*, and they will be back shortly."; break; case STATE_RAIN_DELAY: message = "Unfortunately there's a bit of a *rain delay* going on, we will hopefully be back shortly."; break; case STATE_INNINGS_BREAK: message = "That's the *end of the innings*!"; break; case STATE_LUNCH: message = "We're just off to grab some *lunch*, we'll be back in a bit"; break; case STATE_DRINKS: message = "Just a quick couple of minutes for *drinks*"; break; case STATE_STUMPS: message = "That's it for the day!"; break; } if (state == STATE_PLAY) { switch (previousResult.State) { case STATE_TEA: message = "We're back from the Tea break"; break; case STATE_RAIN_DELAY: message = "Fortunately we've been able to get back from the rain delay"; break; case STATE_INNINGS_BREAK: message = $"And we're into a marvelous *new* innings as {currentResult.BattingTeam} come into bat!"; break; default: message = "And we're back into play"; break; } } result.Add(message); } } return(result); }