コード例 #1
0
        public async Task TestMethod1()
        {
            var request  = new WeatherForecastRequest();
            var handler  = new WeatherForecastRequestHandler();
            var response = await handler.Handle(request, new CancellationToken());

            response.Count.Should().Be.EqualTo(5);
        }
コード例 #2
0
        public IActionResult Get([FromQuery] WeatherForecastRequest request, [Hateoas][FromRoute] WeatherForecastRoute route)
        {
            var response = _getWeatherUseCase.GetWeatherExecute(request);

            request.Summary = "testeHateoas";

            return(Ok(response));
        }
コード例 #3
0
        public IActionResult ApiErrorValidationErrorResult([FromBody] WeatherForecastRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(null);
            }

            return(new ApiResponse(Get(), StatusCodes.Status202Accepted));
        }
コード例 #4
0
        public Task <List <WeatherForecastDTO> > Handle(WeatherForecastRequest request, CancellationToken cancellationToken)
        {
            var rng  = new Random();
            var data = Enumerable.Range(1, 5).Select(index => new WeatherForecastDTO
            {
                Date         = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary      = Summaries[rng.Next(Summaries.Length)]
            }).ToList();

            return(Task.FromResult(data));
        }
コード例 #5
0
ファイル: ApiTest.cs プロジェクト: zhuzhenguang/Phoenicia
        public async Task should_create_weather_forecast()
        {
            HttpClient httpClient = Factory.CreateClient();

            var request = new WeatherForecastRequest
            {
                Temperature = 20,
                Summary     = "hello, this is temperature"
            };
            HttpResponseMessage responseMessage = await httpClient.PostAsync("weatherforecast", request);

            Assert.Equal(HttpStatusCode.Created, responseMessage.StatusCode);
        }
コード例 #6
0
        public override Task <WeatherForecastResponse> Forecast(WeatherForecastRequest request, Grpc.Core.ServerCallContext context)
        {
            var weatherForecast = new WeatherForecast();

            return(Task.FromResult(
                       new WeatherForecastResponse {
                Date = new Google.Protobuf.WellKnownTypes.Timestamp {
                    Seconds = weatherForecast.Date.Second
                },
                TemperatureC = weatherForecast.TemperatureC,
                TemperatureF = weatherForecast.TemperatureF,
                Summary = weatherForecast.Summary,
            }
                       ));
        }
コード例 #7
0
        public Task <List <WeatherForecasrResponse> > GetWeatherForecasts(WeatherForecastRequest request, CallContext context = default)
        {
            if (request.ReturnCount > 999999)
            {
                throw new RpcException(new Status(StatusCode.InvalidArgument, "Return count is too large."));
            }

            var rng     = new Random();
            var results = Enumerable.Range(1, request.ReturnCount).Select(index => new WeatherForecasrResponse
            {
                Date         = DateTime.UtcNow.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary      = Summaries[rng.Next(Summaries.Length)]
            }).ToList();

            return(Task.FromResult(results));
        }
コード例 #8
0
        public WeatherForecastResponse GetWeatherExecute(WeatherForecastRequest request)
        {
            var rng = new Random();

            var listatempo = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date         = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary      = Summaries[rng.Next(Summaries.Length)]
            }).ToArray();

            //ValidaLista<WeatherForecast> validaLista = new ValidaLista<WeatherForecast>();
            var wheather = new WeatherForecastResponse();

            wheather.Weathers = listatempo;
            //listaComUmItem.Add(validaLista.ObtemPrimeirItemLista<WeatherForecastResponse>(listatempo, request.Summary));

            return(wheather);
        }
コード例 #9
0
        static async Task Main(string[] args)
        {
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client  = new WeatherService.WeatherServiceClient(channel);
            var request = new WeatherForecastRequest
            {
                CityName = "Berlin",
                FromDate = Timestamp.FromDateTime(DateTime.Now.ToUniversalTime()),
                ToDate   = Timestamp.FromDateTime(DateTime.Now.ToUniversalTime().AddDays(5))
            };
            var result = await client.GetWeatherForecastAsync(request);

            foreach (var item in result.Items)
            {
                Console.WriteLine($"Weather for {item.CityName} in {item.Date} is {item.Summary} {item.TemperatureC}°C/{ item.TemperatureK}K");
            }

            Console.ReadLine();
        }
コード例 #10
0
        public override Task <WeatherForecastResponse> GetWeatherForecast(WeatherForecastRequest request,
                                                                          ServerCallContext context)
        {
            WEATHER_FORECAST result = null;

            using var executor = new ServiceExecutorManager <IGetWeatherForecastSvc>(new GetWeatherForecastSvc());
            executor.SetRequest(o => o.Request = new WeatherForecastRequestDto {
                ID = request.Id
            })
            .OnExecuted(o => {
                result = o.Result;
                return(true);
            });
            return(Task.FromResult(new WeatherForecastResponse {
                Id = result.ID,
                Date = result.DATE.ToString(),
                TemperatureC = result.TEMPERATURE_C.Value,
                TemperatureF = result.TEMPERATURE_F.Value,
                Summary = result.SUMMARY
            }));
        }
コード例 #11
0
        public async override Task GetWeatherForecastStream(WeatherForecastRequest request, IServerStreamWriter <WeatherForecast> responseStream, ServerCallContext context)
        {
            var getWeatherForecastsQuery = Enumerable
                                           .Range(1, request.NumberOfDays)
                                           .Select(index =>
            {
                var date = Timestamp.FromDateTimeOffset(DateTime.UtcNow.AddDays(index));
                return(_weatherForecastGenerator.GenerateWeatherForecast(Timestamp.FromDateTimeOffset(DateTime.UtcNow.AddDays(index))));
            });

            foreach (var day in getWeatherForecastsQuery)
            {
                if (context.CancellationToken.IsCancellationRequested)
                {
                    break;
                }

                await Task.Delay(request.Delay.ToTimeSpan());

                await responseStream.WriteAsync(day);

                _logger.LogInformation($"weather forecast sent on {day.Date:dd:MM:yyyy}");
            }
        }
コード例 #12
0
        public override Task <WeatherForecastResponse> GetWeatherForecast(WeatherForecastRequest request, ServerCallContext context)
        {
            //Get random weather for a specific region.
            var rng             = new Random();
            var value           = rng.Next(-20, 55);
            var weatherForecast = Enumerable.Range(1, 5).Select(index => new WeatherForecastItem
            {
                CityName     = request.CityName,
                Date         = Timestamp.FromDateTime(DateTime.Now.ToUniversalTime().AddDays(index)),
                TemperatureC = value,
                TemperatureK = 32 + (int)(value / 0.5556),
                Summary      = Summaries[rng.Next(Summaries.Length)]
            }).ToArray();

            //Create response
            var result = new WeatherForecastResponse();

            foreach (var weather in weatherForecast)
            {
                result.Items.Add(weather);
            }

            return(Task.FromResult(result));
        }
コード例 #13
0
        public ActionResult Post(WeatherForecastRequest weatherForecastRequest)
        {
            // NOTE: The weatherForecastRequest has been validated by the relative WeatherForecastRequestValidator.

            // TIP: It's recommended to create thin API Controllers, containing only the intended
            // application code logic calls. This is just an example to show how the
            // `ConsistentApiResponseErrors` library handle the input-validation errors and exceptions.


            // Generating an Application exception (for the sake of this example):
            // Let's assume that we must have a forecast for each day, and that a forecast already
            // exists for the date 2021-03-21.
            if (weatherForecastRequest.Date == new DateTime(2021, 3, 24))
            {
                throw new EntityExistsException("The requested weather forecast exists.");
            }

            // Generating an Unhandled Exceptions (for the sake of this example):
            if (weatherForecastRequest.Date == new DateTime(2021, 3, 23))
            {
                // Try to create a non-valid date, resulting in an exception:
                weatherForecastRequest.Date = new DateTime(2021, 2, 31);
            }


            // Return the created resource:
            WeatherForecastResposne forecastResposne = new WeatherForecastResposne()
            {
                Id           = Guid.NewGuid(),
                Date         = weatherForecastRequest.Date,
                Summary      = weatherForecastRequest.Summary,
                TemperatureC = weatherForecastRequest.TemperatureC
            };

            return(Ok(forecastResposne));
        }
コード例 #14
0
        /// <summary>
        /// Start the handler
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <IReadOnlyList <WeatherForecastDto> > Handle(WeatherForecastRequest request, CancellationToken cancellationToken)
        {
            var result = await _weatherForecastService.GetAllAsync();

            return(result);
        }
コード例 #15
0
 private WeatherForecastResponse ConvertToServiceModel(CurrentWeatherResponse currentWeather, WeatherForecastRequest request)
 {
     return(new WeatherForecastResponse
     {
         Location = request.Location,
         Tempreature = new Tempreature
         {
             Format = "Celsius",
             Value = currentWeather.Temperature.Value
         },
         Humidity = currentWeather.Humidity.Value
     });
 }
コード例 #16
0
        public async System.Threading.Tasks.Task <WeatherForecastResponse> GetWeatherForecastAsync(WeatherForecastRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request object is null");
            }
            if (request.Configuration == null)
            {
                throw new ArgumentNullException("configuration object is null");
            }
            if (string.IsNullOrEmpty(request.Configuration.ApiKey))
            {
                throw new ArgumentException("Api key is missing");
            }
            if (request.Location == null)
            {
                throw new ArgumentNullException("Location object is null");
            }
            if (string.IsNullOrEmpty(request.Location.City))
            {
                throw new ArgumentException("Location city is missing");
            }
            var client = new OpenWeatherMapClient(request.Configuration.ApiKey);

            try
            {
                var currentWeather = await client.CurrentWeather.GetByName(request.Location.City, MetricSystem.Metric);

                return(ConvertToServiceModel(currentWeather, request));
            }
            catch (Exception ex)
            {
                var logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex);
                return(WeatherForecastResponse.Null);
            }
        }
コード例 #17
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);

                var delay = new Duration()
                {
                    Seconds = 1
                };

                #region Server streaming call

                var weatherForecastRequest = new WeatherForecastRequest
                {
                    NumberOfDays = 30,
                    Delay        = delay
                };

                using var weatherForecastStreamCall = _weatherForecastClient
                                                      .GetWeatherForecastStream(weatherForecastRequest);

                await foreach (var weatherForecast in weatherForecastStreamCall.ResponseStream.ReadAllAsync(stoppingToken))
                {
                    var date = weatherForecast.Date.ToDateTime();
                    await Console.Out.WriteLineAsync($"Date: {date:dd-MM-yyyy} | Temparature: {weatherForecast.TemperatureC,3} | Summary: {weatherForecast.Summary}");
                }

                #endregion

                #region Client streaming call

                //var getWeatherForecastsByDateQuerires = Enumerable
                //    .Range(1, 5)
                //    .Select(index => new WeatherForecastByDateRequest
                //    {
                //        Date = Timestamp.FromDateTimeOffset(DateTime.UtcNow.AddDays(index)),
                //        Delay = delay
                //    });

                //using var weatherForecastStreamCall = _weatherForecastClient
                //    .GetWeatherForecastByDate();

                //foreach (var request in getWeatherForecastsByDateQuerires)
                //{
                //    await weatherForecastStreamCall.RequestStream.WriteAsync(request);
                //}

                //await weatherForecastStreamCall.RequestStream.CompleteAsync();
                //var results = await weatherForecastStreamCall;

                //foreach (var weatherForecast in results.WeatherForecasts)
                //{
                //    var date = weatherForecast.Date.ToDateTime();
                //    await Console.Out.WriteLineAsync($"Date: {date:dd-MM-yyyy} | Temparature: {weatherForecast.TemperatureC,3} | Summary: {weatherForecast.Summary}");
                //}

                #endregion


                #region Bi-directional streaming call

                //var getWeatherForecastsByDateQuerires = Enumerable
                //    .Range(1, 5)
                //    .Select(index => new WeatherForecastByDateRequest
                //    {
                //        Date = Timestamp.FromDateTimeOffset(DateTime.UtcNow.AddDays(index)),
                //        Delay = delay
                //    });

                //using var weatherForecastStreamCall = _weatherForecastClient
                //    .GetWeatherForecastByDateStream();

                //var readTask = Task.Run(async () =>
                //{
                //    await foreach (var weatherForecast in weatherForecastStreamCall.ResponseStream.ReadAllAsync(stoppingToken))
                //    {
                //        var date = weatherForecast.Date.ToDateTime();
                //        await Console.Out.WriteLineAsync($"Date: {date:dd-MM-yyyy} | Temparature: {weatherForecast.TemperatureC,3} | Summary: {weatherForecast.Summary}");
                //    }
                //});

                //foreach (var request in getWeatherForecastsByDateQuerires)
                //{
                //    await weatherForecastStreamCall.RequestStream.WriteAsync(request);
                //}

                //await weatherForecastStreamCall.RequestStream.CompleteAsync();
                //await readTask;

                #endregion
            }
        }