public IActionResult ConfirmVenuePick(string venueId) { WeatherApi weather = new WeatherApi(); var start = (DateTime)TempData["startDate"]; var eveId = (string)TempData["eveId"]; EventVenueViewModel vm = new EventVenueViewModel(); var ven = _context.Venues.Where(x => x.Id == venueId).FirstOrDefault(); var eve = _context.Events.Where(x => x.Id == eveId).FirstOrDefault(); vm.currentVenue = ven; vm.currentEvent = eve; bool withinRange = weather.CheckDateRange(start); if (withinRange == true) { string location = weather.SetRequestString(ven.City, ven.State); var forecast = weather.GetForecast(location); TimeSpan day = start - DateTime.Today; var startForecast = forecast[day.Days]; vm.Forecast = forecast[0].text; int code = forecast[0].code; if (code < 20 || (code > 36 && code < 44) || (code > 44 && code < 48)) { string warning = "Warning, the weather forecast for this venue is poor"; vm.Warning = warning; } } return(View(vm)); }
public void updatePanelWeather() { var city = CityList.SelectedItem as City; // получаем прогноз погоды if (city == null) { return; } WeatherApi.GetCityWithWeather(city); panelWeather.Controls.Clear(); foreach (var weatherForecast in city.WeatherForecasts.Where(t => t.Date.Date == dateTimePicker.Value.Date).Reverse()) { WeatherTab weather = new WeatherTab( weatherForecast.PartOfDay, weatherForecast.Sky, weatherForecast.Temperature, weatherForecast.Pressure, (int)weatherForecast.Speed, weatherForecast.Wind, weatherForecast.Humidity); panelWeather.Controls.Add(weather); } }
/// <summary> /// Gets the WeatherResponse object from the WeatherApi wrapper and returns a view /// </summary> /// <returns>View to display weather</returns> public ActionResult Index() { var weatherApi = new WeatherApi(); var weather = weatherApi.getWeather("30.4704", "-87.2329"); return(View(weather)); }
private List <string> Weather() { List <string> returnStrings = new List <string>(); string bodyResp = ApiCall(Config.wetherUrl.concat()); WeatherApi weatherResponse = JsonConvert.DeserializeObject <WeatherApi>(bodyResp); returnStrings.Add(weatherResponse.weather.First().description.ToUpper()); returnStrings.Add(weatherResponse.main.temp.ToString() + "°"); string imagesFolder = @"~/images/Weather/"; string pathLogo = imagesFolder + weatherResponse.weather.First().description + ".png"; if (System.IO.File.Exists(pathLogo)) { returnStrings.Add(pathLogo); } else if (returnStrings.First().Contains("PLUIE")) { returnStrings.Add(@"/images/Weather/pluie.png"); } else { returnStrings.Add(@"/images/Weather/couvert.png"); } return(returnStrings); }
public async Task CheckCurrentWeather(string location) { if (configManager.OptionalSettings.Contains("WeatherApiKey")) { return; } WeatherApi apiResult = weatherApiHandler.GetWeatherApiResult(Program.BotConfiguration.WeatherApiKey, location); if (apiResult.StatusCode != 200) { await Context.Message.Channel.SendMessageAsync("Warn: can't process request"); return; } EmbedBuilder weatherEmbed = new EmbedBuilder() .WithTitle("Weather Info") .WithDescription("Current Weather Informations") .AddField(location, $"{apiResult.Weather.Temperature} °C") .AddField("Max. Temp today", $"{apiResult.Weather.MaxTemperature} °C") .AddField("Min. Temp for today", $"{apiResult.Weather.MinTemperature} °C") .AddField("Weather Condition", apiResult.WeatherCondition.First().ShortDescription) .WithColor(new Color((uint)Convert.ToInt32(CommandHandlerService.MessageAuthor.EmbedColor, 16))) .WithTimestamp(DateTime.Now) .WithFooter(NET.DataAccess.File.FileAccess.GENERIC_FOOTER, NET.DataAccess.File.FileAccess.GENERIC_THUMBNAIL_URL); await Context.Message.Channel.SendMessageAsync(embed : weatherEmbed.Build()).ConfigureAwait(false); }
private static async void CheckWeather_Elapsed(object sender, ElapsedEventArgs e) { foreach (User user in DatabaseAccess.Instance.Users) { if (user.NotifierTime == null || user.WeatherLocation == null) { continue; } if (!(DateTime.Now.Hour == user.NotifierTime.Value.Hours && DateTime.Now.Minute == user.NotifierTime.Value.Minutes)) { continue; } SocketUser disUser = client.GetUser(user.Id); if (disUser == null) { continue; } WeatherApi apiResult = await weatherApiHandler.Request2WeatherApiAsync(credentials.WeatherApiKey, user.WeatherLocation); EmbedBuilder weatherEmbed = new EmbedBuilder() .WithTitle("Weather Info") .WithDescription("Weather Notification for today") .AddField(user.WeatherLocation, $"{apiResult.Weather.Temperature} °C") .AddField("Max. Temp today", $"{apiResult.Weather.MaxTemperature} °C") .AddField("Min. Temp for today", $"{apiResult.Weather.MinTemperature} °C") .AddField("Weather Condition", apiResult.WeatherCondition.First().ShortDescription) .WithColor(Color.Blue) .WithTimestamp(DateTime.Now) .WithFooter(FileAccess.GENERIC_FOOTER, FileAccess.GENERIC_THUMBNAIL_URL); await disUser.SendMessageAsync(embed : weatherEmbed.Build()).ConfigureAwait(false); } }
static async void GetWeather(string area) { var data = await WeatherApi.GetTodayRestAsync(area); if (!data.State) { Console.WriteLine(data.Msg); return; } var properties = data.Data.GetType().GetProperties(); var sb = new StringBuilder(); foreach (var item in properties) { var attr = item.GetCustomAttributes(typeof(DisplayAttribute), true).FirstOrDefault(); if (attr != null) { var nameText = ((DisplayAttribute)attr).Name; sb.AppendLine(string.Format("{0} = {1}", nameText, item.GetValue(data.Data, null))); } } Console.WriteLine("{0} 天气情况如下:", area); Console.WriteLine(sb.ToString()); Console.WriteLine("请输要查询的地区(帮助请输 -h):"); }
public WeatherApi Weather() { using (WebClient webclient = new WebClient()) { string json = webclient.DownloadString("http://api.openweathermap.org/data/2.5/weather?q=vejle&mode=json&units=metric&appid=e9b3b99c257810d4beaf8dc7be2a0c44"); return(WeatherApi.FromJson(json)); } }
public async Task OnLoadWeatherForecast() { WeatherForecast = await WeatherApi.GetWeatherForecast(Name); WeatherNow = await WeatherApi.GetWeatherNow(Name); OnCalculateWeatherByDays(); }
public void HttpOperationException_TestMethod_2() { //Arrange WeatherApi client = new WeatherApi("c5976f0996947c1488798209b0bc3f77", "756135", 15); //Assert Assert.ThrowsException <HttpOperationException>(() => client.GetFourDaysForecastData("AA")); }
public static async Task <IAgroManager> AgroManager(string ObjectIdAAD, bool isBatch) { var email = new Email("*****@*****.**", "Aresa2019"); var uploadImage = new UploadImage(Environment.GetEnvironmentVariable("StorageConnectionStrings", EnvironmentVariableTarget.Process)); var weatherApi = new WeatherApi(Environment.GetEnvironmentVariable("KeyWeatherApi", EnvironmentVariableTarget.Process)); var searchServiceInstance = new AgroSearch(Environment.GetEnvironmentVariable("SearchServiceName", EnvironmentVariableTarget.Process), Environment.GetEnvironmentVariable("SearchServiceKey", EnvironmentVariableTarget.Process)); return(new AgroManager(ConfigManager.GetDbArguments, email, uploadImage, weatherApi, searchServiceInstance, ObjectIdAAD, isBatch)); }
public async Task <WeatherApi> GetWeatherDataAsync() { string link = $"https://api.openweathermap.org/data/2.5/weather?q=stockholm&appid=891eafc578fbdbf0762bcad68c8bd4da&units=metric&lang=sv"; Task <string> weatherforecast = client.GetStringAsync(link); string weatherString = await weatherforecast; weatherStockholm = JsonSerializer.Deserialize <WeatherApi>(weatherString); return(weatherStockholm); }
public static async Task <IAgroManager <GeographyPoint> > AgroManager(string ObjectIdAAD) { var email = new Email("*****@*****.**", "Aresa2019"); var uploadImage = new UploadImage(Environment.GetEnvironmentVariable("StorageConnectionStrings", EnvironmentVariableTarget.Process)); var weatherApi = new WeatherApi(Environment.GetEnvironmentVariable("KeyWeatherApi", EnvironmentVariableTarget.Process)); var searchServiceInstance = new AgroSearch <GeographyPoint>(Environment.GetEnvironmentVariable("SearchServiceName", EnvironmentVariableTarget.Process), Environment.GetEnvironmentVariable("SearchServiceKey", EnvironmentVariableTarget.Process), new ImplementsSearch(), new HashEntityAgroSearch()); return(new AgroManager <GeographyPoint>(new DbConnect(ConfigManager.GetDbArguments), email, uploadImage, weatherApi, searchServiceInstance, ObjectIdAAD)); }
public void GetWeatherByLocation_InvalidZip_Null() { Weather testWeather = new Weather(); string zipCheck = "94"; WeatherApi testWeatherApi = new WeatherApi(); testWeather = testWeatherApi.GetWeatherByLocation(zipCheck); Assert.IsNull(testWeather); }
public Frm_Wall() { InitializeComponent(); weather = new WeatherApi(); background = new BackgroundController(); // Start with the right weather background.DefineBackgroundWeather(weather); tmr_atualizador.Enabled = true; }
public void GetWeatherByLocation_ValidZip_NotNull() { //checks if a weather object returned from the GetWeatherByLocation is null Weather testWeather = new Weather(); string zipCheck = "94121"; //San Francisco, CA WeatherApi testWeatherApi = new WeatherApi(); testWeather = testWeatherApi.GetWeatherByLocation(zipCheck); Assert.IsNotNull(testWeather); }
/// <summary> /// Gets WeatherApiResponse object and returns it as a json object /// </summary> /// <returns>Json object in HttpResponseMessage</returns> public HttpResponseMessage Get() { var weather = new WeatherApi(); var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(weather.getWeather("30.4704", "-87.2329")); return(new HttpResponseMessage() { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") }); }
public MainWindow() { ShowWindow(GetConsoleWindow(), SW_HIDE); InitializeComponent(); ReadAllCities(); ReadFavorites(); CurrentCityCoords = WeatherApi.GetGeolocation().GetAwaiter().GetResult(); CurrentCityId = 524901; // presenter should set city id or coordinates, and call start thread DataContext = this; StartThread(true); }
private async Task <DialogTurnResult> WeatherResultStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var Intent = stepContext.Result.ToString(); var weather = await WeatherApi.GetWeather(Intent); var weatherOk = weather.ToString(); await stepContext.Context.SendActivityAsync(weatherOk); return(await stepContext.EndDialogAsync(null, cancellationToken)); }
private void butUpdate_Click(object sender, EventArgs e) { try { dataCities.Cities = WeatherApi.GetCities(); updateCitiesList(); } catch (Exception ex) { MessageBox.Show("Не удалось обновить данные"); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var blankStationUI = new Form1(); var weatherApi = new WeatherApi(); var weatherStation = WeatherStationUIController.InitUIWith(blankStationUI, weatherApi); Application.Run(weatherStation); }
async void GetWeather(object sender, EventArgs e) { if (!String.IsNullOrEmpty(cityIdEntry.Text)) { Weather weather = await WeatherApi.GetWeather(cityIdEntry.Text); if (weather != null) { this.BindingContext = weather; getWeatherBtn.Text = "Search Again"; } } }
public async Task weatherApiGetsData() { // ARRANGE var mockOptions = new Mock <IOptions <WeatherApiConfig> >(); mockOptions.Setup(m => m.Value) .Returns(new WeatherApiConfig() { weatherApiUrl = "http://testapi.com/", weatherApiKey = "123456789" }); var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); handlerMock .Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ) .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(new FakeWeatherData())) }) .Verifiable(); var httpClient = new HttpClient(handlerMock.Object); var weatherApi = new WeatherApi(mockOptions.Object, httpClient); //ACT WeatherData result = await weatherApi.getData("Vilnius"); // ASSERT Assert.IsNotNull(result); Assert.AreEqual("Vilnius", result.name); Assert.AreEqual(200, result.cod); var expectedUri = new Uri("http://testapi.com/?appid=123456789&q=Vilnius&units=metric"); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.Is <HttpRequestMessage>(req => req.Method == HttpMethod.Get && req.RequestUri == expectedUri ), ItExpr.IsAny <CancellationToken>()); }
public WeatherViewModel() { UpdateData = new Command( execute: () => { IsExecuting = true; var req = WeatherApi.Get(); req.Wait(); var response = req.Result; if (response.Successful) { var WeatherInfo = JsonConvert.DeserializeObject <WeatherInfo>(response.Content); Console.WriteLine("asdasda"); WeatherName = WeatherInfo.weather[0].main; Temperature = WeatherInfo.main.temp; MaxTemperature = WeatherInfo.main.temp_max; MinTemperature = WeatherInfo.main.temp_min; Pressure = WeatherInfo.main.pressure; Humidity = WeatherInfo.main.humidity; } IsExecuting = false; }, canExecute: () => { if (!IsExecuting) { return(true); } else { return(false); } }); // initial execute //UpdateData.Execute(new object()); }
private static async Task checkWeather() { WeatherApi apiResult = await weatherApiHandler.Request2WeatherApiAsync(credentials.WeatherApiKey, credentials.WeatherPlace); //main.temp 70%, pointsSum = calculateWeatherPoints(15f, 20f, 0.7f, apiResult.Weather.Temperature); //main.humidity 5%, pointsSum += calculateWeatherPoints(10f, 50f, 0.05f, apiResult.Weather.Humidity); //wind.speed 5%, pointsSum += calculateWeatherPoints(10f, 4f, 0.05f, apiResult.Wind.Speed); //clouds.all 10%, pointsSum += calculateWeatherPoints(50f, 10f, 0.1f, apiResult.Clouds.Density); //rain.1h 0.2 10%, pointsSum += calculateWeatherPoints(2.5f, 0f, 0.1f, 0f); }
/// <summary> /// Default constructor /// </summary> /// <param name="apiKey">UWaterloo API Key</param> public UWaterlooApi(string apiKey) { // Initializing endpoints FoodServices = new FoodServicesApi(apiKey); Courses = new CoursesApi(apiKey); Events = new EventsApi(apiKey); News = new NewsApi(apiKey); Weather = new WeatherApi(apiKey); Terms = new TermsApi(apiKey); Resources = new ResourcesApi(apiKey); DefinitionsAndCodes = new DefinitionsAndCodesApi(apiKey); Buildings = new BuildingsApi(apiKey); Api = new ApiApi(apiKey); Server = new ServerApi(apiKey); }
// Start is called before the first frame update void Start() { lightGameObject = new GameObject("Light"); lightComp = lightGameObject.AddComponent <Light>(); locationService = lightGameObject.AddComponent <LocationService>(); weatherApi = lightGameObject.AddComponent <WeatherApi>(); //Make a instance of the plugin for reading ambient light sensor value #if UNITY_ANDROID plugin = new AndroidJavaClass("jp.kshoji.unity.sensor.UnitySensorPlugin").CallStatic <AndroidJavaObject>("getInstance"); if (plugin != null) { plugin.Call("startSensorListening", "light"); } #endif }
public MainPageViewModel() { Now = DateTime.Now; _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromSeconds(1); _timer.Tick += _timer_Tick; _timer.Start(); _weatherTimer = new DispatcherTimer(); _weatherTimer.Interval = TimeSpan.FromHours(1); _weatherTimer.Tick += _weatherTimer_Tick; _weatherApi = new WeatherApi(); _calendarApi = new GoogleCalendarApi(); _calendarTimer = new DispatcherTimer(); _calendarTimer.Interval = TimeSpan.FromHours(1); _calendarTimer.Tick += _calendarTimer_Tick; _calendarEvents = new ObservableCollection <CalendarEventViewModel>(); }
public override void OnFrameworkInitializationCompleted() { const string?API_VAR = "WEATHER_API_KEY"; if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { string?apiKey = Environment.GetEnvironmentVariable(API_VAR); var api = new WeatherApi(apiKey); desktop.MainWindow = new MainWindow { DataContext = new MainWindowViewModel(api) }; } base.OnFrameworkInitializationCompleted(); }
private async void button1_Click(object sender, EventArgs e) { var btn = (Button)sender; btn.Enabled = false; if (string.IsNullOrEmpty(this.textBox1.Text)) { MessageBox.Show("请输入地区名."); return; } var data = await WeatherApi.GetDailyRestAsync(this.textBox1.Text); if (!data.State) { btn.Enabled = true; return; } var i = 0; foreach (var item in data.Data.results.FirstOrDefault().daily) { var tabPage = new TabPage(item.date); tabPage.BackColor = Color.White; if (this.tabControl1.TabPages.Count <= i) { this.tabControl1.TabPages.Add(tabPage); tabPage.Controls.Add(new SeniverseControl(item)); } else { tabPage = this.tabControl1.TabPages[i]; tabPage.Name = item.date; var uCtrl = tabPage.Controls.Cast <Control>().First() as SeniverseControl; uCtrl.Refresh(item); } i++; } var resultFirst = data.Data.results.FirstOrDefault(); this.lbUpdateTime.Text = resultFirst.last_update.ToString("yyyy-MM-dd HH:mm:ss"); var path = resultFirst.location.path.Split(','); this.lbCity.Text = string.Join(" ", path.Where((item, n) => n > 0).Reverse()); btn.Enabled = true; }