Beispiel #1
0
        public void ParseSection(IConfigurationSection section)
        {
            IEnumerable <KeyValuePair <string, string> > props = section.AsEnumerable();
            bool writeOuter = section.GetChildren().Count() > 0;

            if (writeOuter)
            {
                sb.AppendLine("\"" + section.Key + "\" : {");
            }
            foreach (KeyValuePair <string, string> kvp in section.AsEnumerable())
            {
                //value is actually at this level, should have no extra :'s
                //value == null could be either a section or a value that is truly null.  Oh Well.
                if (kvp.Value != null && !kvp.Key.Replace(section.Path + ":", "").Contains(":"))
                {
                    //remove the path from the key
                    sb.AppendLine("\"" + kvp.Key.Replace(section.Path + ":", "") + "\" : \"" + kvp.Value + "\",");
                    //we rely on json.net to remove the trailing commas
                }
            }
            foreach (IConfigurationSection sect in section.GetChildren())
            {
                ParseSection(sect);
            }
            if (writeOuter)
            {
                sb.AppendLine("},");
            }
        }
        static void Main(string[] args)
        {
            //var builder = new ConfigurationBuilder()
            //    .SetBasePath( Directory.GetCurrentDirectory())
            //    .AddJsonFile("appsettings.json");

            //IConfiguration config = new ConfigurationBuilder()
            //    .AddJsonFile("appsettings.json", true, true)
            //    .Build();

            IConfiguration config = GetConfig();

            // Get Health Status from Elastic Search
            // Convert Health Json to Log Analytics Json
            // Log Health Status to Log Analytics

            IConfigurationSection myArraySection = config.GetSection("ElasticSearch");
            var itemArray = myArraySection.AsEnumerable();

            foreach (var s in itemArray)
            {
                if (string.IsNullOrEmpty(s.Value))
                {
                    continue;
                }

                var json   = GetData(s.Value, config["UserName"], config["Password"]);
                var status = PostData(json, config["CustomerId"], config["SharedKey"], config["LogName"]);
            }
        }
Beispiel #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddControllersAsServices().AddNewtonsoftJson();

            IConfigurationSection originsSection = Configuration.GetSection(AllowedOrigins);

            string[] origns = originsSection.AsEnumerable().Where(s => s.Value != null).Select(a => a.Value).ToArray();
            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Test API", Version = "v1"
                });

                c.DescribeAllParametersInCamelCase();
            });
            #endregion
            services.AddCors(options =>
            {
                options.AddPolicy(AllowedOrigins,
                                  builder =>
                {
                    builder.WithOrigins(origns)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });
            });
            services.AddSignalR();
            #region AutoMapper
            services.AddAutoMapper(typeof(BookMapping).Assembly);
            #endregion
        }
Beispiel #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Retrieve the environment specific extension secret from the azure vault.
            IConfigurationSection certificateData = Configuration.GetSection("VSTSExtensionCertificates");
            var combinedKeys = certificateData.AsEnumerable().Where(keyValue => !string.IsNullOrWhiteSpace(keyValue.Value)).Select(x => x.Value).ToList();
            // Retrieve additional dev extensions secrets from application settings.
            IConfigurationSection developerCertificateData = Configuration.GetSection("DeveloperOverrideCertificates");

            combinedKeys.AddRange(developerCertificateData.AsEnumerable().Where(keyValue => !string.IsNullOrWhiteSpace(keyValue.Value)).Select(x => x.Value));

            services.AddApplicationInsightsTelemetry();

            services.AddCors();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                // Configure JWT Bearer Auth to expect our security key
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    LifetimeValidator     = (before, expires, token, param) => { return(expires > DateTime.UtcNow); },
                    ValidateAudience      = false,
                    ValidateIssuer        = false,
                    ValidateActor         = false,
                    ValidateLifetime      = true,
                    RequireSignedTokens   = true,
                    RequireExpirationTime = true,
                    IssuerSigningKeys     = combinedKeys.Select(e => new SymmetricSecurityKey(Encoding.UTF8.GetBytes(e))),
                };

                // We have to hook the OnMessageReceived event in order to
                // allow the JWT authentication handler to read the access
                // token from the query string when a WebSocket or
                // Server-Sent Events request comes in.
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/collaborationUpdates"))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddSignalR().AddAzureSignalR(Configuration.GetValue <string>("SignalRServiceConnectionString"));
            services.Configure <AppInsightsSettings>(Configuration.GetSection("ApplicationInsights"));
        }
        public async Task InvokeAsync(HttpContext context)
        {
            bool Permission = false;
            IConfigurationSection configurationSection             = _config.GetSection("Whitelist");
            IEnumerable <KeyValuePair <string, string> > whiteList = configurationSection.AsEnumerable();

            var RemoteIp = context.Connection.RemoteIpAddress.MapToIPv4().GetAddressBytes();

            foreach (var a in whiteList)
            {
                IPAddress testAdress;
                bool      ParseResult = IPAddress.TryParse(a.Value, out testAdress);

                if (ParseResult)
                {
                    byte[] testBytes = testAdress.GetAddressBytes();
                    if (testBytes.SequenceEqual(RemoteIp))
                    {
                        Permission = true;
                        break;
                    }
                }
            }

            if (Permission)
            {
                await _next.Invoke(context);
            }
            else
            {
                context.Response.StatusCode = 403;
            }
        }
        public async Task <Dictionary <string, decimal> > Handle(GetCryptoCurrencyExchangeRatesQuery request,
                                                                 CancellationToken cancellationToken)
        {
            IConfigurationSection currencySection = _configuration.GetSection("AvailableCurrencies");
            var symbols = currencySection.AsEnumerable()
                          .Where(c => !string.IsNullOrEmpty(c.Value))
                          .Select(c => c.Value);

            var usdPrice = await _cryptoCurrencyService.GetLatestPrice(request.Symbol).ConfigureAwait(false);

            var exchangeRate = await _exchangeRateService.GetLatestRate(string.Join(",", symbols))
                               .ConfigureAwait(false);

            var prices = new Dictionary <string, decimal>();

            // calculate price based on currency rate
            foreach (var symbol in symbols)
            {
                if (symbol.Equals("usd", StringComparison.InvariantCultureIgnoreCase))
                {
                    prices.Add("USD", usdPrice);
                }
                else
                {
                    var priceWithRate = usdPrice * exchangeRate.Rates[symbol];
                    prices.Add(symbol, priceWithRate);
                }
            }


            return(prices);
        }
Beispiel #7
0
        /// <summary>
        /// Add the user secrets from the project referencing the NuGet package
        /// </summary>
        /// <returns>Additional strings to be considered as program arguments</returns>
        private static IEnumerable <string> FindUserSecrets()
        {
            const string  fbitDelimiter   = "fbit:";
            List <string> fbitUserSecrets = new List <string>();
            string        userSecretsId   = ProjectFileHelper.GetUserSecretsId(Environment.CurrentDirectory);

            if (!string.IsNullOrWhiteSpace(userSecretsId))
            {
                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.AddUserSecrets(userSecretsId);
                IConfiguration        configuration = builder.Build();
                IConfigurationSection fbitSection   = configuration.GetSection("fbit");
                foreach (KeyValuePair <string, string> kvp in fbitSection.AsEnumerable())
                {
                    if (!kvp.Key.StartsWith(fbitDelimiter))
                    {
                        continue;
                    }

                    string argument = kvp.Key.Substring(fbitDelimiter.Length);
                    fbitUserSecrets.AddRange(new[] { argument, kvp.Value });
                }
            }

            return(fbitUserSecrets);
        }
Beispiel #8
0
 protected string[] StringArray(IConfigurationSection section)
 {
     return(section
            .AsEnumerable(true)
            .Select(x => x.Value.TrimStart().TrimEnd().ToLower())
            .ToArray());
 }
Beispiel #9
0
        public static Dictionary <string, object> GetAllUperCaseOf(IConfigurationSection config)
        {
            var result  = new ObjectDictionary();
            var keyDict = config.AsEnumerable(true).ToObjectDictionary();

            return(keyDict.MergeIntoObjectDictionary());
        }
Beispiel #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger)
        {
            // Retrieve allowed origins from the application settings.
            IConfigurationSection allowedOriginData = Configuration.GetSection("AllowedOrigin");
            var allowedOrigins = allowedOriginData.AsEnumerable().Where(keyValue => !string.IsNullOrWhiteSpace(keyValue.Value)).Select(x => x.Value).ToArray();

            app.UseRouting();

            app.UseCors(builder => { builder.WithOrigins(allowedOrigins).AllowAnyHeader().AllowAnyMethod().AllowCredentials(); });

            app.UseWebSockets();

            app.UseAuthentication();

            app.UseAzureSignalR(routes => { routes.MapHub <ReflectBackend.ReflectHub>("/collaborationUpdates"); });

            app.Use(async(context, next) =>
            {
                context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
                await next();
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/health", async context =>
                {
                    logger.LogInformation("Received health request");
                    await context.Response.WriteAsync("App Running....");
                });
            });
        }
Beispiel #11
0
        public void WhenICallTheElasticSearchHealthAPI()
        {
            IConfigurationSection myArraySection = config.GetSection("ElasticSearch");
            var itemArray = myArraySection.AsEnumerable();
            var item      = itemArray.GetEnumerator().Current.Key;

            json = Program.GetData(item, config["UserName"], config["Password"]);
        }
Beispiel #12
0
        public override Task DoWork(CancellationToken cancellationToken)
        {
            IConfigurationSection currencySection = _configuration.GetSection("AvailableCurrencies");
            var symbols = currencySection.AsEnumerable()
                          .Where(c => !string.IsNullOrEmpty(c.Value))
                          .Select(c => c.Value);

            return(_exchangeRateService.GetLatestRate(string.Join(",", symbols)));
        }
Beispiel #13
0
 public void Load(IConfigurationSection config)
 {
     foreach (var configSection in config.AsEnumerable())
     {
         if (configSection.Key.StartsWith("ExcludedNames:"))
         {
             _excludedNames.Add(configSection.Key.Substring(configSection.Key.IndexOf(":") + 1), Convert.ToBoolean(configSection.Value));
         }
     }
 }
Beispiel #14
0
        private static string FindFriendlyDbName(string connectionString, IConfigurationSection friendlyDbNames)
        {
            foreach (KeyValuePair <string, string> kv in friendlyDbNames.AsEnumerable(true))
            {
                if (connectionString.Contains(kv.Value, StringComparison.OrdinalIgnoreCase))
                {
                    return(kv.Key);
                }
            }

            return(null);
        }
        private IEnumerable <string> GetConfigModule()
        {
            ConfigurationBuilder configBuilder = new ConfigurationBuilder();

            configBuilder.AddJsonFile(@".\app.config.json");
            IConfiguration        config        = configBuilder.Build();
            IConfigurationSection moduelSection = config.GetSection("UI:modules");
            IEnumerable <string>  modules       = moduelSection.AsEnumerable()
                                                  .Where(m => m.Key != "UI:modules")
                                                  .Select(m => config[m.Key]);

            return(modules);
        }
Beispiel #16
0
        public static IHealthBuilder ReadFrom(
            this IHealthConfigurationBuilder configurationBuilder,
            IConfigurationSection configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            configurationBuilder.Extend(configuration.AsEnumerable());

            return(configurationBuilder.Builder);
        }
Beispiel #17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            IConfigurationSection myArraySection = Configuration.GetSection("corsOrigins");
            var corsOrigins = (from i in myArraySection.AsEnumerable()
                               where i.Value != null
                               select i.Value).ToArray();

            foreach (var item in corsOrigins)
            {
                System.Console.WriteLine("allow cors have " + item);
            }
            printSystemInfo();

            app.UseCors(builder => builder
                        .WithOrigins(corsOrigins)
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials()
                        );
            // app.UseHttpsRedirection();

            Utils.DbInitializer.MigrateLatest(app);
            Utils.DbInitializer.Seed(app);
            //不要所有的程序都对这flag进行操作
            //Utils.DbInitializer.CheckIfClearFlags(app);

            app.UseRouting();

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });


            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub <NotificationsHub>("/notifications");
                endpoints.MapControllers();
            });
        }
Beispiel #18
0
        private IEnumerable <string> GetArrayItem(string sectionName)
        {
            IConfigurationSection myArraySection = this.Configuration.GetSection(sectionName);
            var itemArray = myArraySection.AsEnumerable();

            foreach (KeyValuePair <string, string> item in itemArray)
            {
                if (Equals(item.Value, null))
                {
                    continue;
                }

                yield return(item.Value);
            }
        }
Beispiel #19
0
        static void Print()
        {
            Console.WriteLine(configuration["AppSettings:instance"]);
            Console.WriteLine(configuration["AppSettings:version"]);

            IConfigurationSection myArraySection = configuration.GetSection("Email:ToEmails");
            var itemArray = myArraySection.AsEnumerable();

            foreach (var email in itemArray)
            {
                if (email.Value != null)
                {
                    Console.WriteLine(email.Value);
                }
            }
        }
        public List <string> GetConfigValues(string key)
        {
            List <string>         values         = new List <string>();
            IConfigurationSection myArraySection = configurationRoot.GetSection(key);
            var itemArray = myArraySection.AsEnumerable();

            foreach (var item in itemArray)
            {
                values.Add(item.Value);
            }
            if (values.Count > 0)
            {
                values.RemoveAt(0);
            }
            return(values);
        }
 private void LoadRules(LoggerFilterOptions options, IConfigurationSection configurationSection, string logger)
 {
     foreach (var section in configurationSection.AsEnumerable(true))
     {
         if (TryGetSwitch(section.Value, out var level))
         {
             var category = section.Key;
             if (category.Equals(DefaultCategory, StringComparison.OrdinalIgnoreCase))
             {
                 category = null;
             }
             var newRule = new LoggerFilterRule(logger, category, level, null);
             options.Rules.Add(newRule);
         }
     }
 }
Beispiel #22
0
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc((option) => {
         option.EnableEndpointRouting = false;
     }).AddJsonOptions((options) => {
         options.JsonSerializerOptions.PropertyNamingPolicy = null;
         options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
         options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter());
         options.JsonSerializerOptions.Converters.Add(new DateTimeNullableConverter());
     });
     // 配置反向代理转接,以确保获得的客户端地址信息的正确性.
     services.Configure <ForwardedHeadersOptions>(options => {
         options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
         // 设置允许受信任的代理网络转接头(防止受到 IP 欺骗攻击)。
         IConfigurationSection section         = Configuration.GetSection("ForwardedHeadersOptions").GetSection("KnownProxies");
         KeyValuePair <string, string>[] array = section.AsEnumerable().ToArray();
         if (array != null && array.Length > 0)
         {
             foreach (KeyValuePair <string, string> item in array)
             {
                 if (string.IsNullOrEmpty(item.Value))
                 {
                     continue;
                 }
                 options.KnownProxies.Add(System.Net.IPAddress.Parse(item.Value));
             }
         }
     });
     // 配置 http POST 最大上传限制
     services.Configure <FormOptions>(options => {
         long lengthLimit = 1024000000;
         IConfigurationSection frmOptions = Configuration.GetSection("FormOptions");
         if (frmOptions != null)
         {
             lengthLimit = frmOptions.GetValue <long>("MultipartBodyLengthLimit");
         }
         options.MultipartBodyLengthLimit = lengthLimit;
     });
     services.AddSession((configure) => {
         configure.IdleTimeout = TimeSpan.FromMinutes(45);
         configure.IOTimeout   = TimeSpan.FromMinutes(45);
     });
     services.AddHttpContextAccessor();
     services.AddSingleton(typeof(HtmlEncoder), HtmlEncoder.Create(UnicodeRanges.All)); // cshtml 视图的 Unicode 编码处理.
     services.AddScoped <WebApiExceptionFilter>();
     ConfigureDatabase(services);
 }
Beispiel #23
0
        private void LoadRules(LoggerFilterOptions options, IConfigurationSection configurationSection, string logger)
        {
            foreach (var section in configurationSection.AsEnumerable(true))
            {
                LogLevel level;
                if (TryGetSwitch(section.Value, out level))
                {
                    var category = section.Key;
                    if (category == "Default")
                    {
                        category = null;
                    }

                    var newRule = new LoggerFilterRule(logger, category, level, null);
                    options.Rules.Add(newRule);
                }
            }
        }
Beispiel #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            #region Add Controllers + As Service To Implment Property Injection
            services.AddControllersWithViews().AddControllersAsServices().AddNewtonsoftJson();
            #endregion

            #region AutoMapper
            services.AddAutoMapper(typeof(ProductMapping).Assembly);
            #endregion

            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "E-Vision Sample API", Version = "v1"
                });

                c.DescribeAllParametersInCamelCase();
                c.DescribeAllEnumsAsStrings();
                c.DescribeStringEnumsInCamelCase();
            });
            #endregion

            #region CORS
            IConfigurationSection originsSection = Configuration.GetSection(AllowedOrigins);
            string[] origns = originsSection.AsEnumerable().Where(s => s.Value != null).Select(a => a.Value).ToArray();

            services.AddCors(options =>
            {
                options.AddPolicy(AllowedOrigins,
                                  builder =>
                {
                    builder.WithOrigins("http://localhost:4200")

                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });
            });
            #endregion
        }
Beispiel #25
0
        private void ConfigureCorsServices(IServiceCollection services)
        {
            string[] origins = new[] { "http://localhost:4200" };

            IConfigurationSection section = Configuration.GetSection("AllowedOrigins");

            if (section.Exists())
            {
                origins = section.AsEnumerable()
                          .Where(p => !string.IsNullOrEmpty(p.Value))
                          .Select(p => p.Value).ToArray();
            }

            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder.AllowAnyMethod()
                .AllowAnyHeader()
                // https://github.com/aspnet/SignalR/issues/2110 for AllowCredentials
                .AllowCredentials()
                .WithOrigins(origins);
            }));
        }
Beispiel #26
0
        public Provider(IConfigurationSection section)
        {
            //Set the name of the provider
            _ProviderName = section["name"];

            //Set the type of the provider
            _ProviderType = section["type"];

            if (section["providerLevel"] != null)
            {
                _ProviderLevel = section["providerLevel"];
            }

            //Store all the attributes in the attributes bucket
            foreach (var kp in section.AsEnumerable().Where(c => c.Value != null))
            {
                var keyShortName = kp.Key.Split(':').Last();
                if (keyShortName != "name" && keyShortName != "type" && keyShortName != "providerLevel")
                {
                    _ProviderAttributes.Add(keyShortName, kp.Value);
                }
            }
        }
Beispiel #27
0
        private void CreateSections(IConfiguration config, IServiceProvider serviceProvider)
        {
            IConfigurationSection configurationSection = config.GetSection("Sections");
            var sections = configurationSection.AsEnumerable();

            if (sections.Count() == 0)
            {
                return;
            }

            sections = sections.Reverse();

            var dbContext = serviceProvider.GetRequiredService <ApplicationDbContext>();

            foreach (var section in sections)
            {
                if (section.Value == null)
                {
                    continue;
                }

                var searchingSection = dbContext.Sections.FirstOrDefault(s => s.Name.Equals(section.Value));

                if (searchingSection == null)
                {
                    var newSection = new Section
                    {
                        Name          = section.Value,
                        Topics        = new List <Topic>(),
                        Accessibility = Accessibility.FullAccess
                    };
                    dbContext.Sections.Add(newSection);
                    dbContext.SaveChanges();
                }
            }
        }
Beispiel #28
0
        // GET: LEDScreens
        public async Task <IActionResult> Index(string SortOrder,
                                                string NameFilter,
                                                int?MonitoringPostIdFilter,
                                                int?PageSize,
                                                int?PageNumber)
        {
            List <LEDScreen> ledScreens = new List <LEDScreen>();

            ViewBag.NameFilter             = NameFilter;
            ViewBag.MonitoringPostIdFilter = MonitoringPostIdFilter;

            ViewBag.NameSort           = SortOrder == "Name" ? "NameDesc" : "Name";
            ViewBag.MonitoringPostSort = SortOrder == "MonitoringPost" ? "MonitoringPostDesc" : "MonitoringPost";

            string url        = "api/LEDScreens",
                   route      = "",
                   routeCount = "";

            if (!string.IsNullOrEmpty(SortOrder))
            {
                route += string.IsNullOrEmpty(route) ? "?" : "&";
                route += $"SortOrder={SortOrder}";
            }
            if (NameFilter != null)
            {
                route      += string.IsNullOrEmpty(route) ? "?" : "&";
                route      += $"Name={NameFilter}";
                routeCount += string.IsNullOrEmpty(routeCount) ? "?" : "&";
                routeCount += $"Name={NameFilter}";
            }
            if (MonitoringPostIdFilter != null)
            {
                route      += string.IsNullOrEmpty(route) ? "?" : "&";
                route      += $"MonitoringPostId={MonitoringPostIdFilter}";
                routeCount += string.IsNullOrEmpty(routeCount) ? "?" : "&";
                routeCount += $"MonitoringPostId={MonitoringPostIdFilter}";
            }
            IConfigurationSection pageSizeListSection = Startup.Configuration.GetSection("PageSizeList");
            var pageSizeList = pageSizeListSection.AsEnumerable().Where(p => p.Value != null);

            ViewBag.PageSizeList = new SelectList(pageSizeList.OrderBy(p => p.Key)
                                                  .Select(p =>
            {
                return(new KeyValuePair <string, string>(p.Value ?? "0", p.Value));
            }), "Key", "Value");
            if (PageSize == null)
            {
                PageSize = Convert.ToInt32(pageSizeList.Min(p => p.Value));
            }
            if (PageSize == 0)
            {
                PageSize = null;
            }
            if (PageSize != null)
            {
                route += string.IsNullOrEmpty(route) ? "?" : "&";
                route += $"PageSize={PageSize.ToString()}";
                if (PageNumber == null)
                {
                    PageNumber = 1;
                }
            }
            if (PageNumber != null)
            {
                route += string.IsNullOrEmpty(route) ? "?" : "&";
                route += $"PageNumber={PageNumber.ToString()}";
            }
            HttpResponseMessage response      = await _HttpApiClient.GetAsync(url + route),
                                responseCount = await _HttpApiClient.GetAsync(url + "/count" + routeCount);

            if (response.IsSuccessStatusCode)
            {
                ledScreens = await response.Content.ReadAsAsync <List <LEDScreen> >();
            }
            int ledScreenCount = 0;

            if (responseCount.IsSuccessStatusCode)
            {
                ledScreenCount = await responseCount.Content.ReadAsAsync <int>();
            }
            ViewBag.SortOrder  = SortOrder;
            ViewBag.PageSize   = PageSize;
            ViewBag.PageNumber = PageNumber != null ? PageNumber : 1;
            ViewBag.TotalPages = PageSize != null ? (int)Math.Ceiling(ledScreenCount / (decimal)PageSize) : 1;
            ViewBag.StartPage  = PageNumber - 5;
            ViewBag.EndPage    = PageNumber + 4;
            if (ViewBag.StartPage <= 0)
            {
                ViewBag.EndPage  -= (ViewBag.StartPage - 1);
                ViewBag.StartPage = 1;
            }
            if (ViewBag.EndPage > ViewBag.TotalPages)
            {
                ViewBag.EndPage = ViewBag.TotalPages;
                if (ViewBag.EndPage > 10)
                {
                    ViewBag.StartPage = ViewBag.EndPage - 9;
                }
            }

            List <MonitoringPost> monitoringPosts       = new List <MonitoringPost>();
            string urlMonitoringPosts                   = "api/MonitoringPosts",
                   routeMonitoringPosts                 = "";
            HttpResponseMessage responseMonitoringPosts = await _HttpApiClient.GetAsync(urlMonitoringPosts + routeMonitoringPosts);

            if (responseMonitoringPosts.IsSuccessStatusCode)
            {
                monitoringPosts = await responseMonitoringPosts.Content.ReadAsAsync <List <MonitoringPost> >();
            }
            ViewBag.MonitoringPosts = new SelectList(monitoringPosts.OrderBy(m => m.Name), "Id", "Name");

            return(View(ledScreens));
        }
        public static void AddAPIConfig(this IServiceCollection services, IConfiguration configuration, bool useCORS = default, bool useSwagger = default, bool useFluentValidation = default)
        {
            #region App localization
            services.Configure <RequestLocalizationOptions>(options =>
            {
                options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture(ResourceEnum.Language.en.ToString());
                options.SupportedCultures     = new List <CultureInfo> {
                    new CultureInfo(ResourceEnum.Language.en.ToString())
                };

                options.RequestCultureProviders.Insert(0, new Microsoft.AspNetCore.Localization.CustomRequestCultureProvider(context =>
                {
                    string userLangs   = context.Request.Headers["Accept-Language"].ToString();
                    string firstLang   = userLangs.Split(',').FirstOrDefault();
                    string defaultLang = string.IsNullOrEmpty(firstLang) ? ResourceEnum.Language.en.ToString() : firstLang;
                    return(System.Threading.Tasks.Task.FromResult(new Microsoft.AspNetCore.Localization.ProviderCultureResult(defaultLang, defaultLang)));
                }));
            });
            #endregion

            #region MVC Core
            if (useFluentValidation)
            {
                services.AddControllers().AddFluentValidation().AddControllersAsServices();
            }
            else
            {
                services.AddControllers().AddControllersAsServices();
            }

            AppSettings appSettings = new AppSettings();
            configuration.Bind("AppSettings", appSettings);
            services.AddSingleton(appSettings);

            SeriLogSettings seriLogSettings = new SeriLogSettings();
            configuration.Bind("SeriLog", seriLogSettings);
            services.AddSingleton(seriLogSettings);
            #endregion

            #region Swagger
            if (useSwagger)
            {
                SwaggerSettings swaggerSettings = new SwaggerSettings();
                configuration.Bind("SwaggerSettings", swaggerSettings);
                services.AddSingleton(swaggerSettings);

                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc(swaggerSettings.Version, new OpenApiInfo
                    {
                        Title       = swaggerSettings.Title,
                        Version     = swaggerSettings.Version,
                        Description = swaggerSettings.Description
                    });
                    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        Description = swaggerSettings.Description,
                        Name        = "Authorization",
                        In          = ParameterLocation.Header,
                        Type        = SecuritySchemeType.ApiKey,
                        Scheme      = "Bearer"
                    });
                    c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.SecurityScheme,
                                    Id   = "Bearer"
                                },
                                Scheme = "oauth2",
                                Name   = "Bearer",
                                In     = ParameterLocation.Header,
                            },
                            new System.Collections.Generic.List <string>()
                        }
                    });
                    c.CustomSchemaIds(i =>
                                      i.FullName.Replace("Unicom.Notifications.Core.DTOs.UseCase.Escalation.", string.Empty)
                                      .Replace("Unicom.Notifications.SharedKernal.Helper.HttpInOutHandler.", string.Empty)
                                      .Replace("Unicom.Notifications.SharedKernal.Enum.", string.Empty)
                                      .Replace("System.Collections.Generic.", string.Empty)
                                      .Replace("Unicom.Notifications.SharedKernal.Helper.Pagination.", string.Empty)
                                      .Replace("Unicom.Notifications.Core.DTOs.UseCase.Notification.", string.Empty)
                                      .Replace("Unicom.Notifications.Core.", string.Empty)
                                      .Replace("Unicom.Notifications.SharedKernal.", string.Empty)
                                      .Replace("Unicom.Notifications.Core.DTOs.UseCase.User.", string.Empty)
                                      .Replace("`1[[", "[")
                                      .Replace("`2[[", "[")
                                      .Replace(", Unicom.Notification.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]", "]")
                                      .Replace(", NotificationHubSystem.SharedKernal, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]", string.Empty)
                                      .Replace(", System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]", string.Empty)
                                      .Replace("[System.String", "System.String")
                                      .Replace("HttpEnum+", "HttpEnum.")
                                      );
                });
            }
            #endregion

            #region CORS
            if (useCORS)
            {
                IConfigurationSection originsSection = configuration.GetSection(AllowedOrigins);
                string[] origns = originsSection.AsEnumerable().Where(s => s.Value != null).Select(a => a.Value).ToArray();
                services.AddCors(options =>
                {
                    options.AddPolicy(AllowedOrigins, builder => builder.WithOrigins(origns).AllowAnyMethod().AllowAnyHeader());
                });
            }
            #endregion
        }
Beispiel #30
0
        // GET: MeasuredParameters
        public async Task <IActionResult> Index(string SortOrder,
                                                string NameKKFilter,
                                                string NameRUFilter,
                                                string NameENFilter,
                                                int?EcomonCodeFilter,
                                                string OceanusCodeFilter,
                                                string KazhydrometCodeFilter,
                                                int?PageSize,
                                                int?PageNumber)
        {
            List <MeasuredParameter> measuredParameters = new List <MeasuredParameter>();

            ViewBag.NameKKFilter          = NameKKFilter;
            ViewBag.NameRUFilter          = NameRUFilter;
            ViewBag.NameENFilter          = NameENFilter;
            ViewBag.EcomonCodeFilter      = EcomonCodeFilter;
            ViewBag.OceanusCodeFilter     = OceanusCodeFilter;
            ViewBag.KazhydrometCodeFilter = KazhydrometCodeFilter;

            ViewBag.NameKKSort          = SortOrder == "NameKK" ? "NameKKDesc" : "NameKK";
            ViewBag.NameRUSort          = SortOrder == "NameRU" ? "NameRUDesc" : "NameRU";
            ViewBag.NameENSort          = SortOrder == "NameEN" ? "NameENDesc" : "NameEN";
            ViewBag.EcomonCodeSort      = SortOrder == "EcomonCode" ? "EcomonCodeDesc" : "EcomonCode";
            ViewBag.OceanusCodeSort     = SortOrder == "OceanusCode" ? "OceanusCodeDesc" : "OceanusCode";
            ViewBag.KazhydrometCodeSort = SortOrder == "KazhydrometCode" ? "KazhydrometCodeDesc" : "KazhydrometCode";

            string url        = "api/MeasuredParameters",
                   route      = "",
                   routeCount = "";

            if (!string.IsNullOrEmpty(SortOrder))
            {
                route += string.IsNullOrEmpty(route) ? "?" : "&";
                route += $"SortOrder={SortOrder}";
            }
            if (!string.IsNullOrEmpty(NameKKFilter))
            {
                route      += string.IsNullOrEmpty(route) ? "?" : "&";
                route      += $"NameKK={NameKKFilter}";
                routeCount += string.IsNullOrEmpty(routeCount) ? "?" : "&";
                routeCount += $"NameKK={NameKKFilter}";
            }
            if (!string.IsNullOrEmpty(NameRUFilter))
            {
                route      += string.IsNullOrEmpty(route) ? "?" : "&";
                route      += $"NameRU={NameRUFilter}";
                routeCount += string.IsNullOrEmpty(routeCount) ? "?" : "&";
                routeCount += $"NameRU={NameRUFilter}";
            }
            if (!string.IsNullOrEmpty(NameENFilter))
            {
                route      += string.IsNullOrEmpty(route) ? "?" : "&";
                route      += $"NameEN={NameENFilter}";
                routeCount += string.IsNullOrEmpty(routeCount) ? "?" : "&";
                routeCount += $"NameEN={NameENFilter}";
            }
            if (EcomonCodeFilter != null)
            {
                route      += string.IsNullOrEmpty(route) ? "?" : "&";
                route      += $"EcomonCode={EcomonCodeFilter}";
                routeCount += string.IsNullOrEmpty(routeCount) ? "?" : "&";
                routeCount += $"EcomonCode={EcomonCodeFilter}";
            }
            if (OceanusCodeFilter != null)
            {
                route      += string.IsNullOrEmpty(route) ? "?" : "&";
                route      += $"OceanusCode={OceanusCodeFilter}";
                routeCount += string.IsNullOrEmpty(routeCount) ? "?" : "&";
                routeCount += $"OceanusCode={OceanusCodeFilter}";
            }
            if (KazhydrometCodeFilter != null)
            {
                route      += string.IsNullOrEmpty(route) ? "?" : "&";
                route      += $"KazhydrometCode={KazhydrometCodeFilter}";
                routeCount += string.IsNullOrEmpty(routeCount) ? "?" : "&";
                routeCount += $"KazhydrometCode={KazhydrometCodeFilter}";
            }
            IConfigurationSection pageSizeListSection = Startup.Configuration.GetSection("PageSizeList");
            var pageSizeList = pageSizeListSection.AsEnumerable().Where(p => p.Value != null);

            ViewBag.PageSizeList = new SelectList(pageSizeList.OrderBy(p => p.Key)
                                                  .Select(p =>
            {
                return(new KeyValuePair <string, string>(p.Value ?? "0", p.Value));
            }), "Key", "Value");
            if (PageSize == null)
            {
                PageSize = Convert.ToInt32(pageSizeList.Min(p => p.Value));
            }
            if (PageSize == 0)
            {
                PageSize = null;
            }
            if (PageSize != null)
            {
                route += string.IsNullOrEmpty(route) ? "?" : "&";
                route += $"PageSize={PageSize.ToString()}";
                if (PageNumber == null)
                {
                    PageNumber = 1;
                }
            }
            if (PageNumber != null)
            {
                route += string.IsNullOrEmpty(route) ? "?" : "&";
                route += $"PageNumber={PageNumber.ToString()}";
            }
            HttpResponseMessage response      = await _HttpApiClient.GetAsync(url + route),
                                responseCount = await _HttpApiClient.GetAsync(url + "/count" + routeCount);

            if (response.IsSuccessStatusCode)
            {
                measuredParameters = await response.Content.ReadAsAsync <List <MeasuredParameter> >();
            }
            int measuredParametersCount = 0;

            if (responseCount.IsSuccessStatusCode)
            {
                measuredParametersCount = await responseCount.Content.ReadAsAsync <int>();
            }
            ViewBag.SortOrder  = SortOrder;
            ViewBag.PageSize   = PageSize;
            ViewBag.PageNumber = PageNumber != null ? PageNumber : 1;
            ViewBag.TotalPages = PageSize != null ? (int)Math.Ceiling(measuredParametersCount / (decimal)PageSize) : 1;
            ViewBag.StartPage  = PageNumber - 5;
            ViewBag.EndPage    = PageNumber + 4;
            if (ViewBag.StartPage <= 0)
            {
                ViewBag.EndPage  -= (ViewBag.StartPage - 1);
                ViewBag.StartPage = 1;
            }
            if (ViewBag.EndPage > ViewBag.TotalPages)
            {
                ViewBag.EndPage = ViewBag.TotalPages;
                if (ViewBag.EndPage > 10)
                {
                    ViewBag.StartPage = ViewBag.EndPage - 9;
                }
            }

            return(View(measuredParameters));
        }