public async Task <WeatherResult> GetCurrentWeatherByCityAsync(string city, string measurement)
        {
            using var client = new HttpClient();
            string connectionString      = SecretsVault.GetOpenWeatherConnectionString(city, measurement);
            HttpResponseMessage response = await client.GetAsync(connectionString);

            if (response.IsSuccessStatusCode)
            {
                CurrentWeatherByCityResponse weatherData = JsonConvert.DeserializeObject <CurrentWeatherByCityResponse>(
                    await response.Content.ReadAsStringAsync()
                    );

                return(new WeatherResult()
                {
                    City = weatherData.Name,
                    Country = weatherData.Sys.Country,
                    WeatherDescription = weatherData.Weather[0].Description,
                    TemperatureCurrent = weatherData.Main.Temp,
                    TemoeratureFeeling = weatherData.Main.FeelsLike,
                    TemperatureMin = weatherData.Main.TempMin,
                    TemperatureMax = weatherData.Main.TempMax,
                    HumidityPercent = (int)weatherData.Main.Humidity,
                    WindSpeed = weatherData.Wind.Speed,
                    WindDirection = (int)weatherData.Wind.Deg
                });
            }
            else
            {
                throw new RestException(HttpStatusCode.BadRequest, ExceptionMessages.WeatherQueryFailed);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Configures services, called by the runtime
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            ISecretsVault secretsVault = new SecretsVault(HostingEnvironment);

            services.AddDbContext <Db>(options => options.UseSqlite(secretsVault.DbConnectionString));
            services.AddIdentity <User, IdentityRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail      = false;
                config.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultPhoneProvider;
            })
            .AddEntityFrameworkStores <Db>()
            .AddRoles <IdentityRole>()
            .AddDefaultTokenProviders();

            // ===== Add Jwt Authentication ========
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = secretsVault.JwtIssuer,
                    ValidAudience    = secretsVault.JwtIssuer,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretsVault.JwtKey)),
                    ClockSkew        = TimeSpan.Zero // remove delay of token when expire
                };
            }).AddFacebook(facebookOptions =>        // are these really needed?
            {
                facebookOptions.AppId     = secretsVault.FbAppId;
                facebookOptions.AppSecret = secretsVault.FbSecret;
            });;

            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddTransient <IJwtOptions, SecretsVault>();
            services.AddTransient <IAuthMessageSenderOptions, SecretsVault>();
            services.AddTransient <IFacebookAuthOptions, SecretsVault>();
            services.AddSingleton <IDispatcher, Dispatcher>();
            services.AddSingleton <IHostedService, ScheduledWateringService>();
            services.AddSingleton <ITokenGenerator, TokenGenerator>();
            services.AddSingleton <IInternalCommsService, InternalCommsService>();
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddTransient <IPushNotificationService, PushNotificationService>();
            services.AddTransient <ISeedDatabaseService, SeedDatabaseService>();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddHttpClient();
            services.AddGraphQLServices();


            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1.1", new Info
                {
                    Title   = "Meridia API",
                    Version = "1.1"
                });
                c.DescribeAllEnumsAsStrings();
                //Set the comments path for the swagger json and ui.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "api.xml");
                c.IncludeXmlComments(xmlPath);

                c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type     = "oauth2",
                    Flow     = "password",
                    TokenUrl = Path.Combine(HostingEnvironment.WebRootPath, "/api/account/swaggerLogin")
                });
                c.OperationFilter <SecurityRequirementsOperationFilter>();
            });
        }