Example #1
0
        public WeatherResponse GetWeather(WeatherRequest request)
        {
            var messageBytes = Encoding.UTF8.GetBytes(request.ToString());

            var props         = _channel.CreateBasicProperties();
            var correlationId = Guid.NewGuid().ToString();

            props.CorrelationId = correlationId;
            props.ReplyTo       = _replyQueueName;

            _channel.BasicPublish(exchange: "",
                                  routingKey: QNAME,
                                  basicProperties: props,
                                  body: messageBytes);

            _channel.BasicConsume(
                consumer: _consumer,
                queue: _replyQueueName,
                autoAck: true);

            string          response = _respQueue.Take();
            WeatherResponse output   = JsonConvert.DeserializeObject <WeatherResponse>(response);

            return(output);
        }
 public override async Task GetWeather(WeatherRequest request, IServerStreamWriter <WeatherResponse> responseStream, ServerCallContext context)
 {
     foreach (var item in getWeatherData())
     {
         await responseStream.WriteAsync(item);
     }
 }
Example #3
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine("Requesting current weather..");

            using var channel = GrpcChannel.ForAddress("https://localhost:5001");

            var client = new WeatherService.WeatherServiceClient(channel);

            var request = new WeatherRequest
            {
                Location = BragaCode
            };

            var weatherData = await client.RequestCurrentWeatherDataAsync(request);

            Console.WriteLine(JsonConvert.SerializeObject(weatherData));

            Console.WriteLine("Requesting historic data..");

            var historicData = await client.RequestHistoricDataAsync(request);

            Console.WriteLine(JsonConvert.SerializeObject(historicData));

            Console.ReadLine();
        }
Example #4
0
        public void Api_Submit_InvalidWeatherRequest_ReturnsNotFound(
            int woeId,
            ApiProxy apiProxy,
            IWeatherRequest weatherRequest,
            IWeatherResponse weatherResponse)
        {
            $"Given a woeId value of {woeId}"
            .x(() => weatherRequest = new WeatherRequest {
                WoeId = woeId
            });

            "And an ApiProxy"
            .x(() => apiProxy = new ApiProxy(_metaWeatherService));

            "When the weather request is submitted"
            .x(
                async() => weatherResponse =
                    await apiProxy.SubmitWeatherRequest(weatherRequest).ConfigureAwait(false));

            "Then the weather response should return StatusCode 404, and Forecasts should be empty"
            .x(
                () =>
            {
                using (new AssertionScope())
                {
                    weatherResponse.StatusCode.Should().Be(HttpStatusCode.NotFound);
                    weatherResponse.Forecasts.Should().BeNullOrEmpty();
                }
            });
        }
Example #5
0
 public static WeatherForecast  Get(WeatherRequest request)
 {
     lock (DataList)
     {
         return(DataList.Where(c => c.Location == request.Location).OrderByDescending(c => c.RecordDate).FirstOrDefault());
     }
 }
Example #6
0
        public void Api_Submit_ValidWeatherRequest_ReturnsForecasts(
            int woeId,
            int expectedCount,
            ApiProxy apiProxy,
            IWeatherRequest weatherRequest,
            IWeatherResponse weatherResponse)
        {
            $"Given a woeId value of {woeId}"
            .x(() => weatherRequest = new WeatherRequest {
                WoeId = woeId
            });

            "And an ApiProxy"
            .x(() => apiProxy = new ApiProxy(_metaWeatherService));

            "When the weather request is submitted"
            .x(
                async() => weatherResponse =
                    await apiProxy.SubmitWeatherRequest(weatherRequest).ConfigureAwait(false));

            $"Then the weather response should return StatusCode HttpStatusCode.OK), and contain {expectedCount} Forecasts"
            .x(
                () =>
            {
                using (new AssertionScope())
                {
                    weatherResponse.StatusCode.Should().Be(HttpStatusCode.OK);
                    weatherResponse.Forecasts.Should().HaveCount(expectedCount);
                }
            });
        }
Example #7
0
 public async override Task StreamWeather(WeatherRequest request, IServerStreamWriter <WeatherResponse> responseStream, ServerCallContext context)
 {
     for (var x = 0; x < 5; ++x)
     {
         await responseStream.WriteAsync(GenerateResult());
     }
 }
Example #8
0
        private async Task <string> OnWeatherRequestAsync(WeatherRequest request)
        {
            if (request == null || Helpers.IsNullOrEmpty(request.LocationPinCode) || Helpers.IsNullOrEmpty(request.CountryCode))
            {
                return("The request is in incorrect format.");
            }

            if (!int.TryParse(request.LocationPinCode, out int pinCode))
            {
                return("Could not parse the specified pin code.");
            }

            await ProcessingSemaphore.WaitAsync().ConfigureAwait(false);

            (bool status, WeatherData response) = Core.WeatherApi.GetWeatherInfo(Core.Config.OpenWeatherApiKey, pinCode, request.CountryCode);

            if (!status || response == null)
            {
                ProcessingSemaphore.Release();
                return("Internal error occured during the process.");
            }

            ProcessingSemaphore.Release();
            return(ObjectToString <WeatherData>(response));
        }
        public async Task <IActionResult> Get([FromQuery] WeatherRequest weatherViewModel)
        {
            var weather =
                await _weatherClient.GetWeatherAsync(weatherViewModel.City, weatherViewModel.Language, weatherViewModel.Unit);

            return(Ok(weather));
        }
Example #10
0
        public WeatherResponse GetWeather(WeatherRequest request)
        {
            Console.WriteLine($"Got a weather request for zip code:  {request.ZipCode}");
            WeatherResponse response = null;

            // build web request
            string url = $"{WEATHER_URL}&zip={request.ZipCode},us&appid={API_KEY}";

            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage res = client.GetAsync(url).Result)
                {
                    using (HttpContent content = res.Content)
                    {
                        string data = content.ReadAsStringAsync().Result;
                        if (data != null)
                        {
                            Console.WriteLine("API Response OK");
                            response = JsonConvert.DeserializeObject <WeatherResponse>(data);
                            Console.WriteLine("Parsed OK");
                        }
                    }
                }
            }

            return(response);
        }
Example #11
0
        private async Task GetWeatherAsync(WeatherRequest weatherRequest)
        {
            try
            {
                if (weatherRequest == null)
                {
                    return;
                }

                string city = weatherRequest.City.Name;

                if (string.IsNullOrWhiteSpace(city))
                {
                    throw new NullReferenceException("City name cannot be null or whitespace");
                }

                var weather = await _weatherService.GetWeatherAsync(city);

                SetWeather(city, weather);
            }
            catch (WebException ex)
            {
                await this._alertService.DisplayAsync("MCWeather", ex.Message, "Done");
            }
        }
Example #12
0
        // POST api/transfernumberapi
        public string Post([FromBody] string requestStr)
        {
            try
            {
                WeatherRequest requests = JsonConvert.DeserializeObject <WeatherRequest>(requestStr);
                string         output   = "";

                WeatherRepository repository = new WeatherRepository();
                WeatherResult     results    = repository.Check(requests);
                output = JsonConvert.SerializeObject(results);

                return(output);
            }
            catch (Exception ex)
            {
                //發生錯誤時,傳回HTTP 500及錯誤訊息
                var resp = new HttpResponseMessage()
                {
                    StatusCode   = HttpStatusCode.InternalServerError,
                    Content      = new StringContent(ex.Message),
                    ReasonPhrase = "Web API Error"
                };
                throw new HttpResponseException(resp);
            }
        }
Example #13
0
        public override async Task GetWeatherStream(WeatherRequest request, IServerStreamWriter <WeatherData> responseStream, ServerCallContext context)
        {
            var rng = new Random();
            var now = DateTimeOffset.UtcNow;

            var i = 0;

            while (!context.CancellationToken.IsCancellationRequested && i < 20)
            {
                var forecast = new WeatherData
                {
                    DateTimeStamp = now.AddDays(i++).ToUnixTimeSeconds(),
                    TemperatureC  = rng.Next(-20, 55),
                    Summary       = Summaries[rng.Next(Summaries.Length)]
                };

                await responseStream.WriteAsync(forecast);

                await Task.Delay(500); // Gotta look busy
            }

            if (context.CancellationToken.IsCancellationRequested)
            {
                _logger.LogInformation("The client cancelled their request");
            }
        }
Example #14
0
        public ActionResult UpdateWeatherAsync([FromBody] WeatherRequest request)
        {
            Console.WriteLine("\n\n---[WEATHER] ENDPOINT CALLED---");

            string userInput = string.Format(
                "\nwid: {0}" +
                "\nwmorning: {1}" +
                "\nwafternoon: {2}" +
                "\nwnight: {3}" +
                "\nwdate: {4}",
                request.wid, request.wmorning, request.wafternoon,
                request.wnight, request.wdate);

            Console.WriteLine(userInput);

            if (request.wmorning == "")
            {
                request.wmorning = "-";
            }
            else if (request.wafternoon == "")
            {
                request.wafternoon = "-";
            }
            else if (request.wnight == "")
            {
                request.wnight = "-";
            }
            //call weatherService to update the values into postgresql database
            weatherService.updateWeather(request.wid, request.wmorning, request.wafternoon,
                                         request.wnight, request.wdate);


            Console.WriteLine("\nExecution OK\n");
            return(Ok());
        }
Example #15
0
 public Task <WeatherResponse> GetWeatherForecast(string token, WeatherRequest request)
 {
     return(_configuration.BaseUrl
            .AppendPathSegment("weatherforecast") //TODO: Work out a way to remove these as "magic strings"
            .WithOAuthBearerToken(token)
            .GetJsonAsync <WeatherResponse>());
 }
Example #16
0
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    _initQueue(channel);

                    var consumer = new EventingBasicConsumer(channel);
                    channel.BasicConsume(queue: QNAME,
                                         autoAck: false,
                                         consumer: consumer);

                    Console.WriteLine("Awaiting RPC message...");

                    consumer.Received += (model, ea) =>
                    {
                        // get the properties for our reply
                        var replyProperties = channel.CreateBasicProperties();
                        replyProperties.CorrelationId = ea.BasicProperties.CorrelationId;
                        replyProperties.ReplyTo       = ea.BasicProperties.ReplyTo;

                        WeatherResponse response = null;
                        try
                        {
                            // get the weather
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body);

                            WeatherRequest req = JsonConvert.DeserializeObject <WeatherRequest>(message);
                            response = _worker.GetWeather(req);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Error: {ex.ToString()}");
                        }
                        finally
                        {
                            // respond to caller
                            var responseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response));
                            channel.BasicPublish(exchange: "",
                                                 routingKey: replyProperties.ReplyTo,
                                                 basicProperties: replyProperties,
                                                 body: responseBytes
                                                 );

                            channel.BasicAck(ea.DeliveryTag, false);
                        }
                    };

                    Console.ReadLine();
                }
            }
        }
Example #17
0
 public void Initialize()
 {
     _sut = new WeatherRequest(
         new CoordinateRequestLocationProvider(40.34F, -74.123f),
         new RequestElementsProvider {
         MaximumTemperature = true
     });
 }
Example #18
0
        public async Task <ActionResult> Post(WeatherRequest weatherRequest)
        {
            // Model state validation currently 'implicit' - would implement FluentValidation, to align
            // business rules
            // TODO: Add logic to validate and return correct StatusCode
            var results = await _apiProxy.SubmitWeatherRequest(weatherRequest).ConfigureAwait(false);

            return(Ok(results));
        }
        public override Task <WeatherReply> GetWeather(WeatherRequest request, ServerCallContext context)
        {
            Random rnd = new Random();

            return(Task.FromResult(new WeatherReply
            {
                Temperature = rnd.Next(0, 30)
            }));
        }
Example #20
0
        public WeatherRequestResult WeatherForLocation([FromUri] CoordinateViewModel viewModel)
        {
            var location = new CoordinateRequestLocationProvider(viewModel.Latitude, viewModel.Longitude);
            var request  = new WeatherRequest(location, RequestElementsProvider.AllElements);
            var data     = _weatherService.GetData(request);
            var result   = _weatherResultFactory.Build(data);

            //return data;
            return(result);
        }
Example #21
0
        public Result <WeatherForecast> Get(string location)
        {
            WeatherRequest request = new WeatherRequest();

            request.Location = location;
            WeatherRequestManagement weatherMan = new WeatherRequestManagement(_Worker);
            var result = weatherMan.GetWeatherInformation(request);

            return(result);
        }
        public Result <List <WeatherForecast> > Get()
        {
            WeatherRequestManagement weatherMan = new WeatherRequestManagement(_Worker);
            WeatherRequest           request    = new WeatherRequest();

            request.StartDate = DateTime.Now.AddHours(-24);
            var result = weatherMan.GetWeatherInformations(request);

            return(result);
        }
        public override async Task GetWeatherStream(WeatherRequest request,
                                                    IServerStreamWriter <WeatherResponse> responseStream,
                                                    ServerCallContext context)
        {
            for (var x = 0; x < 10; ++x)
            {
                await responseStream.WriteAsync(GetWeatherData());

                await Task.Delay(500);
            }
        }
Example #24
0
        public WeatherReport QueryForecast(WeatherRequest request)
        {
            var url  = string.Format(URL, request.City, _apiKey);
            var json = _requester.Request(url);

            return(new WeatherReport
            {
                City = request.City,
                JSON = json,
                Date = DateTime.Now
            });
        }
        private WeatherDataReply GetWeatherData(WeatherRequest request)
        {
            var rnd = new Random((int)DateTime.Now.Ticks);

            return(new WeatherDataReply
            {
                Temperature = rnd.Next(10) + 65,
                Location = request.Location,
                Windspeed = rnd.Next(10),
                Winddirection = rnd.Next(360)
            });
        }
        public IHttpActionResult Get([FromUri] WeatherRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = _weatherBusinessLogic
                         .GetWeather(request);

            return(Ok(result));
        }
        public override async Task RequestStreamData(WeatherRequest request, IServerStreamWriter <WeatherDataReply> responseStream, ServerCallContext context)
        {
            while (true)
            {
                var weatherData = await GetWeatherData(request);

                await responseStream.WriteAsync(weatherData);

                _logger.LogInformation("Wait for the delay to pass");
                await Task.Delay(5 * 1000);// Delay 5 seconds for testing. Change to (3600 * 1000) for hourly queries
            }
        }
        public async Task <IHttpActionResult> GetWeather([FromUri] WeatherRequest request)
        {
            var query = GetWeatherDataQuery.Create(
                request.Country.Trim(),
                request.City.Trim(),
                TemperatureScale.Celsius);
            var result = await queryDispatcher.ProcessAsync(query);

            var response = responseBuilder.MapWeatherDataResponse(result);

            return(response);
        }
Example #29
0
        public async Task APIRequest()
        {
            var request = new WeatherRequest()
            {
                lon = (decimal)55.751999,
                lat = (decimal)37.617734
            };
            var provider = new OpenWeatherProvider(Configuration);
            var result   = await provider.GetCurrentWeather(request);

            Assert.True(string.IsNullOrEmpty(result.errorMessage));
            Assert.Contains("id", result.weather);
        }
Example #30
0
        public override async Task <WeatherItemResponseMultiple> Get(WeatherRequest request, ServerCallContext context)
        {
            _logger.LogInformation("Begin grpc call WeatherService.Get");
            var rng         = new Random();
            var weatherList = Enumerable.Range(1, 5).Select(index => new Weather
            {
                Date         = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary      = Summaries[rng.Next(Summaries.Length)]
            }).ToList();

            return(MapToResponse(weatherList));
        }