public async Task <ActionResult> ReportWeatherForecast(WeatherForecastDto forecastDto) { if (forecastDto.TemperatureC < -100) { return(BadRequest()); } var persistentWeatherForecastDto = new PersistentWeatherForecastDto( Guid.NewGuid(), forecastDto.TenantId, forecastDto.UserId, forecastDto.Date, forecastDto.TemperatureC, forecastDto.Summary); var entityEntry = await _db.WeatherForecasts.AddAsync(persistentWeatherForecastDto); await _db.SaveChangesAsync(); await _flurlClient.Request("notifications").PostJsonAsync( new WeatherForecastSuccessfullyReportedEventDto( forecastDto.TenantId, forecastDto.UserId, forecastDto.TemperatureC)); return(Ok(new ForecastCreationResultDto(entityEntry.Entity.Id))); }
public IActionResult Create([FromBody] WeatherForecastDto weatherForecastDto) { WeatherForecast weatherForecast = new WeatherForecast(weatherForecastDto.Date, weatherForecastDto.TemperatureC); holder.Values.Add(weatherForecast); return(Ok()); }
public NotificationsDriverExtension(string userId, string tenantId, WireMockServer wireMockServer, WeatherForecastDto weatherForecastDto) { _userId = userId; _tenantId = tenantId; _wireMockServer = wireMockServer; _weatherForecastDto = weatherForecastDto; }
public IActionResult Create([FromBody] WeatherForecastDto input) { WeatherForecast weatherForecast = new WeatherForecast(); weatherForecast.TemperatureC = input.TemperatureC; weatherForecast.Date = input.Date; weatherForecast.Summary = "Created by Web service"; _holder.Values.Add(weatherForecast); return(Ok()); }
static void Main(string[] args) { Console.WriteLine("Service started"); InitializeIoc(); var requestResults = GetCurrentRequest(); foreach (var result in requestResults) { var info = new WeatherForecastDto() { City = result.RequestedCity, DailyTemperature = new Temperature() { Highest = result.DailyHighestTemp, Lowest = result.DailyLowestTemp }, WeeklyTemperature = new Temperature() { Highest = result.WeeklyHighestTemp, Lowest = result.WeeklyLowestTemp } }; var serializedResult = JsonConvert.SerializeObject(info); Console.WriteLine("PreviousRequests:"); Console.WriteLine(serializedResult); } HubConnection connection = new HubConnectionBuilder() .WithUrl("http://localhost:64368/serverhub") .WithAutomaticReconnect() .Build(); connection.Closed += async(error) => { await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); }; connection.StartAsync(); connection.On <string, string>("ReceiveMessage", (string elapsedTime, string message) => { Console.WriteLine("New Service Request: "); Console.WriteLine($"Total Time Elapsed: {elapsedTime} - Service Message : {message}"); }); Console.ReadLine(); }
private async Task <IFlurlResponse> AttemptToReportForecastViaHttp() { var forecastDto = new WeatherForecastDto(_tenantId, _userId, _dateTime, _temperatureC, _summary); _driverContext.SaveAsLastReportedForecast(forecastDto); var httpResponse = await _httpClient .Request("WeatherForecast") .AllowAnyHttpStatus() .PostJsonAsync(forecastDto); return(httpResponse); }
public IEnumerable <WeatherForecast> Get() { //FLUENT API VALIDATION var dtoToBeValidated = new WeatherForecastDto(); var results = _validator.Validate(dtoToBeValidated, ruleSet: "all"); var rng = new Random(); return(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()); }
public async Task ReportForecast() { var forecastDto = new WeatherForecastDto( _tenantId, _userId, Any.DateTime(), Any.Integer(), Any.String()); using var httpResponse = await _httpClient .Request("WeatherForecast") .PostJsonAsync(forecastDto); var jsonResponse = await httpResponse.GetJsonAsync <ForecastCreationResultDto>(); _driverContext.SaveAsLastReportedForecast(forecastDto); _driverContext.SaveAsLastForecastReportResult(jsonResponse); }
public void ShouldSerializeAndParse() { //Arrange var jsonSerializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var weatherForecastDto = new WeatherForecastDto ( aDate: DateTime.MinValue.ToUniversalTime(), aSummary: "Summary 1", aTemperatureC: 24 ); string json = JsonSerializer.Serialize(weatherForecastDto, jsonSerializerOptions); //Act WeatherForecastDto parsed = JsonSerializer.Deserialize <WeatherForecastDto>(json, jsonSerializerOptions); //Assert weatherForecastDto.TemperatureC.ShouldBe(parsed.TemperatureC); weatherForecastDto.Summary.ShouldBe(parsed.Summary); weatherForecastDto.Date.ShouldBe(parsed.Date); }
public RetrievedForecast(IFlurlResponse httpResponse, WeatherForecastDto lastInputForecastDto) { _httpResponse = httpResponse; _lastInputForecastDto = lastInputForecastDto; }
public async Task ShouldAllowRetrievingReportedForecast() { var tenantId = Any.String(); var userId = Any.String(); using var notificationRecipient = WireMockServer.Start(); notificationRecipient.Given( Request.Create() .WithPath("/notifications") .UsingPost()).RespondWith( Response.Create() .WithStatusCode(HttpStatusCode.OK)); var inputForecastDto = new WeatherForecastDto( tenantId, userId, Any.DateTime(), Any.Integer(), Any.String()); using var host = Host .CreateDefaultBuilder() .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseTestServer() .ConfigureAppConfiguration(appConfig => { appConfig.AddInMemoryCollection(new Dictionary <string, string> { ["NotificationsConfiguration:BaseUrl"] = notificationRecipient.Urls.Single() }); }) .UseEnvironment("Development") .UseStartup <Startup>(); }).Build(); await host.StartAsync(); var client = new FlurlClient(host.GetTestClient()); using var postJsonAsync = await client.Request("WeatherForecast") .PostJsonAsync(inputForecastDto); var resultDto = await postJsonAsync.GetJsonAsync <ForecastCreationResultDto>(); using var httpResponse = await client.Request("WeatherForecast") .AppendPathSegment(resultDto.Id) .AllowAnyHttpStatus() .GetAsync(); var weatherForecastDto = await httpResponse.GetJsonAsync <WeatherForecastDto>(); weatherForecastDto.Should().BeEquivalentTo(inputForecastDto); notificationRecipient.LogEntries.Should().ContainSingle(entry => entry.RequestMatchResult.IsPerfectMatch && entry.RequestMessage.Path == "/notifications" && entry.RequestMessage.Method == "POST" && JsonConvert.DeserializeObject <WeatherForecastSuccessfullyReportedEventDto>( entry.RequestMessage.Body) == new WeatherForecastSuccessfullyReportedEventDto( tenantId, userId, inputForecastDto.TemperatureC)); }
public ServiceResult <WeatherForecastDto> GetWeatherInfoByCityName(string cityName) { try { var cacheKey = cityName + DateTime.Now.Date.ToString("yyyyMMdd"); var checkCache = _distributedCache.GetAsync(cacheKey).GetAwaiter().GetResult(); if (checkCache != null) { var serializedResult = Encoding.UTF8.GetString(checkCache); var cacheResult = JsonConvert.DeserializeObject <WeatherForecastDto>(serializedResult); return(new ServiceResult <WeatherForecastDto>(cacheResult, ServiceResultStatusEnum.Success)); } else { var checkDb = _weatherForecastRepository.GetWeatherForecast(cityName); if (checkDb != null) { var serviceResult = new WeatherForecastDto() { City = cityName, DailyTemperature = new Temperature() { Highest = checkDb.DailyHighestTemp, Lowest = checkDb.DailyLowestTemp }, WeeklyTemperature = new Temperature() { Highest = checkDb.WeeklyHighestTemp, Lowest = checkDb.WeeklyLowestTemp } }; return(new ServiceResult <WeatherForecastDto>(serviceResult, ServiceResultStatusEnum.Success)); } else { var coordinates = _locationIQ.GetLocationCoordinatesByCityName(cityName); if (coordinates != null) { var firstResult = coordinates.FirstOrDefault(); var weatherDetails = _darkSky.GetWeatherDetailsByCoordinates(firstResult.lat, firstResult.lon); if (weatherDetails != null) { var weeklyHighest = new List <float>(); var weeklyLowest = new List <float>(); var currentDay = new List <float>(); foreach (var item in weatherDetails.Daily.Data) { weeklyHighest.Add(item.TemperatureHigh); weeklyLowest.Add(item.TemperatureLow); } foreach (var item in weatherDetails.Hourly.Data) { currentDay.Add(item.Temperature); } var serviceResult = new WeatherForecastDto() { City = cityName, DailyTemperature = new Temperature() { Highest = currentDay.Max(), Lowest = currentDay.Min() }, WeeklyTemperature = new Temperature() { Highest = weeklyHighest.Max(), Lowest = weeklyLowest.Min() } }; var serializedResult = JsonConvert.SerializeObject(serviceResult); var encodedResult = Encoding.UTF8.GetBytes(serializedResult); var options = new DistributedCacheEntryOptions() .SetAbsoluteExpiration(DateTime.Now.AddHours(1)); _distributedCache.SetAsync(cacheKey, encodedResult, options); var mappedResult = _mapper.Map <WeatherForecastDto, WeatherForecast>(serviceResult); mappedResult.CreatedOn = DateTime.Now; _unitOfWork.WeatherForecastRepository.Add(mappedResult); _unitOfWork.SaveChanges(); return(new ServiceResult <WeatherForecastDto>(serviceResult, ServiceResultStatusEnum.Success)); } } } } return(new ServiceResult <WeatherForecastDto>(null, ServiceResultStatusEnum.Fail, "No location can be found.")); } catch (Exception ex) { return(new ServiceResult <WeatherForecastDto>(null, ServiceResultStatusEnum.Error, "An unexpected error occured during service operations.")); } }