void Add(LightConfigurator settings, MyObjectBuilderType blockType, params string[] subtypes) { BlockHandling blockHandling; if (!monitorTypes.TryGetValue(blockType, out blockHandling)) { blockHandling = new BlockHandling(); monitorTypes.Add(blockType, blockHandling); } if (subtypes == null || subtypes.Length == 0) { blockHandling.ConfiguratorForAll = settings; } else { if (blockHandling.ConfiguratorPerSubtype == null) { blockHandling.ConfiguratorPerSubtype = new Dictionary <string, LightConfigurator>(); } foreach (var subtype in subtypes) { if (blockHandling.ConfiguratorPerSubtype.ContainsKey(subtype)) { SimpleLog.Error(this, $"Subtype '{subtype}' for type {blockType.ToString()} was already previously registered!"); continue; } blockHandling.ConfiguratorPerSubtype.Add(subtype, settings); } } }
/// <summary> /// Add JWT support on authentication /// </summary> /// <param name="services"></param> public static void AddAuth(this IServiceCollection services, bool hasIdentityServer) { config = LightConfigurator.Config <AuthConfiguration>("Auth"); SecurityKey key = null; if (config.Credentials) { key = AddSecurityKey(); } if (!hasIdentityServer) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtOpt => { jwtOpt.Authority = config.Authority; jwtOpt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = config.Issuer, ValidateAudience = true, ValidAudiences = config.Audiencies.Split(','), IssuerSigningKey = key }; jwtOpt.Events = new JwtBearerEvents(); jwtOpt.RequireHttpsMetadata = config.RequireHttpsMetadata; }); } }
void CreateLogicFor(IMySlimBlock slimBlock, LightConfigurator settings) { var def = (MyCubeBlockDefinition)slimBlock.BlockDefinition; if (def.BlockTopology == MyBlockTopology.Cube && def.Model == null) { // deformable armor not supported. return; } var block = slimBlock.FatBlock; if (block == null) { SimpleLog.Error(this, $"{slimBlock.BlockDefinition.Id.ToString()} has no fatblock?! buildRatio={slimBlock.BuildLevelRatio.ToString()}; damageRatio={slimBlock.DamageRatio.ToString()}"); return; } if (blockLogics.ContainsKey(block.EntityId)) { BlockMarkedForClose(block); } var logic = new BlockLogic(this, block, settings); block.OnMarkForClose += BlockMarkedForClose; blockLogics[block.EntityId] = logic; }
/// <summary> /// Resilient request using Polly /// </summary> /// <param name="URL"></param> /// <param name="httpClient"></param> /// <param name="http"></param> /// <param name="data"></param> /// <returns></returns> internal async Task <HttpResponseMessage> ResilientRequest(string URL, HttpClient httpClient, WorkBenchServiceHttp http, ByteArrayContent data = null) { if (_stub) { var config = new MockData().GetMockData <StubAPIConfiguration>("stubAPIData"); if (config != null) { HostStubAPIConfiguration host = config.Hosts.Where(x => x.Name == _apiname).FirstOrDefault(); if (host != null) { MethodStubAPIConfiguration method = host.Methods.Where(x => x.WorkBenchServiceHttp == http && Regex.Matches(URL, x.Route, RegexOptions.IgnoreCase).FirstOrDefault() != null ).FirstOrDefault(); string jsonString = (new { PayLoad = method.Response, critics = new List <Critic>() }).ToStringCamelCase(); return(await Task.FromResult(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(jsonString, System.Text.Encoding.UTF8), })); } else { throw new LightException($"Workbench cannot made the request for: {URL} by STUB, there isn't host for request."); } } else { throw new LightException($"Workbench cannot made the request for: {URL} by STUB, check the configuration file."); } } else { if (this.Polly != null) { return(await this.Polly.ResilientRequest(URL, httpClient, http, LightConfigurator.Config <ApiConfiguration>(this._apiname).Polly, data)); } else { switch (http) { case WorkBenchServiceHttp.GET: return(await httpClient.GetAsync(URL)); case WorkBenchServiceHttp.POST: return(await httpClient.PostAsync(URL, data)); case WorkBenchServiceHttp.PUT: return(await httpClient.PutAsync(URL, data)); case WorkBenchServiceHttp.DELETE: return(await httpClient.DeleteAsync(URL)); default: throw new LightException($"Workbench cannot made the request for: {URL}"); } } } }
/// <summary> /// Initialize support of Cache and read file config /// </summary> public override void Initialize() { config = LightConfigurator.Config <MemoryCacheConfiguration>("MemoryCache"); options = new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromSeconds(config.SlidingExpirationSeconds), AbsoluteExpiration = DateTimeOffset.FromUnixTimeSeconds(config.AbsoluteExpirationRelativeToNowSeconds) }; }
// Initialize all clients for send to cloudWatch with the clients AmazonCloudWatchEventsClient and AmazonCloudWatchClient public override void Initialize() { //Get all configuration on appsettings. CloudWatchConfiguration cloudWatchConfiuration = LightConfigurator.Config <CloudWatchConfiguration>("CloudWatch"); //Generate a client to send events with te configuration access key and secret key. _amazonCloudEvents = new AmazonCloudWatchEventsClient(cloudWatchConfiuration.AccessKeyID, cloudWatchConfiuration.SecretAccessKey); //Generate a client to send metrics and alarms with te configuration access key and secret key. _amazonCloud = new AmazonCloudWatchClient(cloudWatchConfiuration.AccessKeyID, cloudWatchConfiuration.SecretAccessKey); }
/// <summary> /// Create a JWT of Amaw /// </summary> /// <param name="email"></param> /// <param name="name"></param> /// <param name="mockClaims"></param> /// <returns></returns> public static string CreateToken(string email, string name, ClaimsIdentity mockClaims) { var config = LightConfigurator.Config <AuthConfiguration>("Auth"); string tokenString; try { var tokenHandler = new JwtSecurityTokenHandler(); var audiences = config.Audiencies.Split(','); var rsaConfig = LightConfigurator.Config <SigningCredentialsConfig>("SigningCredentials"); RSAParameters rsaParameters = new RSAParameters { D = Convert.FromBase64String(rsaConfig.D), DP = Convert.FromBase64String(rsaConfig.DP), DQ = Convert.FromBase64String(rsaConfig.DQ), Exponent = Convert.FromBase64String(rsaConfig.Exponent), InverseQ = Convert.FromBase64String(rsaConfig.InverseQ), Modulus = Convert.FromBase64String(rsaConfig.Modulus), P = Convert.FromBase64String(rsaConfig.P), Q = Convert.FromBase64String(rsaConfig.Q) }; SecurityKey key = new RsaSecurityKey(rsaParameters); key.KeyId = rsaConfig.KeyId; var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials (key, SecurityAlgorithms.RsaSha256); var tokenDescriptor = new SecurityTokenDescriptor { SigningCredentials = signingCredentials, Issuer = config.Authority, Audience = (audiences != null && audiences.Length > 0) ? audiences[0] : null, Subject = mockClaims, Expires = DateTime.Now.AddMinutes(60), NotBefore = DateTime.Now }; var token = tokenHandler.CreateToken(tokenDescriptor); tokenString = tokenHandler.WriteToken(token); } catch (SecurityTokenValidationException) { return(null); } catch (ArgumentException) { return(null); } return(tokenString); }
/// <summary> /// Get connection settings /// </summary> /// <param name="TagConfigName"></param> private string GetConnection(string TagConfigName) { if (string.IsNullOrEmpty(TagConfigName)) // Load specific settings if provided { config = LightConfigurator.Config <HubConfiguration>("EventHub"); } else { config = LightConfigurator.Config <HubConfiguration>($"EventHub_{TagConfigName}"); } return(config.ConnectionString); }
// Initialize will retrieve the authentication token from the configuration file set in "appsettings.json". // Also, it will instantiate a telemetry client to send all Azure portal pro requests. public override void Initialize() { AppInsightsConfiguration appInsightsConfiguration = LightConfigurator.Config <AppInsightsConfiguration>("ApplicationInsights"); TelemetryConfiguration aiConfig = new TelemetryConfiguration(); aiConfig.InstrumentationKey = appInsightsConfiguration.InstrumentationKey; // automatically correlate all telemetry data with request aiConfig.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer()); TelemetryClient = TelemetryClient ?? new TelemetryClient(aiConfig); }
public AquariumCatalog( IGlassTickness glassTickness, IGlassCatalog catalog, SkimmerConfigurator skimmerConfigurator, PumpConfiguratior pumpConfigurator, LightConfigurator lightConfigurator) { _glassTickness = glassTickness; _catalog = catalog; _skimmerConfigurator = skimmerConfigurator; _pumpConfigurator = pumpConfigurator; _ligthConfigurator = lightConfigurator; }
public void Initialize() { //Get the configuration on appsetting. But in this case the features can be accessed outside from the repository this.mediaStorageConfiguration = LightConfigurator.Config <MediaStorageConfiguration>("MediaStorage"); this.Conection = mediaStorageConfiguration.ConnectionString; this.Permission = mediaStorageConfiguration.Permission; this.Container = mediaStorageConfiguration.Container; // If the MS has the configuration outside from the repository will be used this context and not inside if (WorkBench.Repository != null) { WorkBench.Repository.SetMediaStorage(this); } }
/// <summary> /// Add Swagger support for Microservice. /// </summary> /// <param name="service"></param> public static void AddSwagger(this IServiceCollection services) { config = LightConfigurator.Config <SwaggerConfiguration>("Swagger"); ///Fill all versions declareted services.AddSwaggerGen(c => { foreach (var version in config.Versions) { c.SwaggerDoc(version.Name, new Info { Version = version.Name, Title = version.Info.Title, Description = version.Info.Description, TermsOfService = version.Info.TermsOfService, Contact = new Contact { Name = version.Info.Contact.Name, Email = version.Info.Contact.Email, Url = version.Info.Contact.Url }, License = new License { Name = version.Info.License.Name, Url = version.Info.License.Url } }); } c.IgnoreObsoleteActions(); ///Set the comments path for the swagger json and ui. var basePath = PlatformServices.Default.Application.ApplicationBasePath; var appName = PlatformServices.Default.Application.ApplicationName; var xmlPath = Path.Combine(basePath, $"{appName}.xml"); c.IncludeXmlComments(xmlPath); c.SchemaFilter <SwaggerIgnoreFilter>(); c.DocumentFilter <RemoveVerbsFilter>(); c.AddSecurityDefinition("Bearer", new ApiKeyScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[] {} } }); c.EnableAnnotations(); }); }
/// <summary> /// Initialize File repository /// </summary> public override void Initialize() { if (string.IsNullOrEmpty(this._suffixName)) // Load specific settings if provided { this.config = LightConfigurator.Config <FileDBConfiguration>($"{nameof(FileDB)}"); } else { this.config = LightConfigurator.Config <FileDBConfiguration>($"{nameof(FileDB)}_{this._suffixName}"); } ///Initialize File instance with provided settings LoadConfigurations(); }
public BlockLogic(AttachedLightsSession session, IMyCubeBlock block, LightConfigurator configurator) { Session = session; Block = block; this.configurator = configurator; Block.IsWorkingChanged += WorkingChanged; WorkingChanged(Block); if (maxViewRangeSq > 0) { session.ViewDistanceChecks.Add(Block.EntityId, RangeCheck); } }
/// <summary> /// Get connection settings /// </summary> /// <param name="TagConfigName"></param> private void SetConnection(string TagConfigName) { GooglePubSubConfiguration config = null; if (string.IsNullOrEmpty(TagConfigName)) // Load specific settings if provided { config = LightConfigurator.Config <GooglePubSubConfiguration>($"GooglePubSub"); } else { config = LightConfigurator.Config <GooglePubSubConfiguration>($"GooglePubSub_{TagConfigName}"); } ProjectID = config.ProjectID; }
/// <summary> /// Initialize support of Cache and read file config /// </summary> public override void Initialize() { config = LightConfigurator.Config <AzureRedisConfiguration>("AzureRedis"); _redisClient = new RedisCache(new RedisCacheOptions() { Configuration = config.Configuration, InstanceName = config.InstanceName }); _options = new DistributedCacheEntryOptions() { SlidingExpiration = TimeSpan.FromSeconds(config.SlidingExpirationSeconds), AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(config.AbsoluteExpirationRelativeToNowSeconds) }; }
/// <summary> /// Get connection settings /// </summary> /// <param name="TagConfigName"></param> private void SetConnection(string TagConfigName) { MessageBrokerConfiguration config = null; if (string.IsNullOrEmpty(TagConfigName)) // Load specific settings if provided { config = LightConfigurator.Config <MessageBrokerConfiguration>($"{nameof(TagConfigName)}"); } else { config = LightConfigurator.Config <MessageBrokerConfiguration>($"ServiceBus_{TagConfigName}"); } ConnectionString = config.ConnectionString; }
/// <summary> /// Get connection settings /// </summary> /// <param name="TagConfigName"></param> private SqsSnsConfiguration GetConnection(string TagConfigName) { SqsSnsConfiguration config = null; if (string.IsNullOrEmpty(TagConfigName)) // Load specific settings if provided { config = LightConfigurator.Config <SqsSnsConfiguration>($"{nameof(TagConfigName)}"); } else { config = LightConfigurator.Config <SqsSnsConfiguration>($"SqsSns_{TagConfigName}"); } return(config); }
/// <summary> /// Add API Versioning the default version is 1.0 /// and we're going to read the version number from the media type /// incoming requests should have a accept header like this: Accept: application/json;v=1.0 /// </summary> /// <param name="services"></param> /// <param name="majorVersion"></param> /// <param name="minorVersion"></param> public static void AddApiVersion(this IServiceCollection services) { config = LightConfigurator.Config <SwaggerConfiguration>("Swagger"); var ver = config.Versions.FirstOrDefault(p => p.Name == config.ActiveVersion); if (ver != null) { services.AddApiVersioning(o => { o.DefaultApiVersion = new ApiVersion(int.Parse(ver.Info.Version), 0); o.AssumeDefaultVersionWhenUnspecified = true; o.ApiVersionReader = new MediaTypeApiVersionReader(); }); } }
/// <summary> /// Use Swagger for Liquid Microservice. /// </summary> /// <param name="service"></param> public static IApplicationBuilder UseOpenApiSwagger(this IApplicationBuilder builder) { config = LightConfigurator.Config <SwaggerConfiguration>("Swagger"); builder.UseSwaggerUI(c => { ///Fill all versions declareted foreach (var version in config.Versions) { c.SwaggerEndpoint($"/swagger/{version.Name}/swagger.json", $"{version.Name} Docs"); } }); return(builder); }
/// <summary> /// Implementation of connection service bus /// </summary> /// <typeparam name="T">Type of the queue or topic</typeparam> /// <param name="item">Item queue or topic</param> /// <returns>StringConnection of the ServiceBus</returns> private string GetConnection <T>(KeyValuePair <MethodInfo, T> item) { MethodInfo method = item.Key; string connectionKey = GetKeyConnection(method); if (string.IsNullOrEmpty(connectionKey)) // Load specific settings if provided { config = LightConfigurator.Config <HubConfiguration>($"{nameof(EventHub)}"); } else { config = LightConfigurator.Config <HubConfiguration>($"{nameof(EventHub)}_{connectionKey}"); } return(config.ConnectionString); }
/// <summary> /// Initialize Dynamo DB repository /// </summary> public override void Initialize() { //Change collection in Runtime base.TargetVarience(InjectTarget); if (string.IsNullOrEmpty(this._suffixName)) // Load specific settings if provided { this.config = LightConfigurator.Config <DynamoDBConfiguration>($"{nameof(DynamoDB)}"); } else { this.config = LightConfigurator.Config <DynamoDBConfiguration>($"{nameof(DynamoDB)}_{this._suffixName}"); } ///Initialize DynamoDB instance with provided settings LoadConfigurations(); }
/// <summary> /// Implementation of connection service bus /// </summary> /// <typeparam name="T">Type of the queue or topic</typeparam> /// <param name="item">Item queue or topic</param> /// <returns>Config Connection</returns> private SqsSnsConfiguration GetConnection <T>(KeyValuePair <MethodInfo, T> item) { MethodInfo method = item.Key; string connectionKey = GetKeyConnection(method); SqsSnsConfiguration config = null; if (string.IsNullOrEmpty(connectionKey)) // Load specific settings if provided { config = LightConfigurator.Config <SqsSnsConfiguration>($"{nameof(SqsSns)}"); } else { config = LightConfigurator.Config <SqsSnsConfiguration>($"{nameof(SqsSns)}_{connectionKey}"); } return(config); }
/// <summary> /// Use CrossOrigin for Liquid Microservice. /// </summary> /// <param name="builder"></param> public static IApplicationBuilder UseCrossOrigin(this IApplicationBuilder builder) { CorsConfiguration config = LightConfigurator.Config <CorsConfiguration>("Cors"); string[] origins = { "" }; string[] headers = { "" }; string[] methods = { "" }; // Always there is "," separating on the string of configuration //unless used just a domain to configuration if (config.Origins.Contains(",")) { origins = config.Origins.Split(','); } else { origins[0] = config.Origins; } // Always there is "," separating on the string of configuration //unless used just a domain to configuration if (config.Headers.Contains(",")) { headers = config.Headers.Split(','); } else { headers[0] = config.Headers; } // Always there is "," separating on the string of configuration //unless used just a domain to configuration if (config.Methods.Contains(",")) { methods = config.Methods.Split(','); } else { methods[0] = config.Methods; } builder.UseCors(b => { b.WithOrigins(origins); b.WithHeaders(headers); b.WithMethods(methods); }); return(builder); }
/// <summary> /// Use CrossOrigin for Liquid Microservice. /// </summary> /// <param name="configuration"></param> public static IConfiguration UseSecrets(this IConfiguration configuration) { SecretsConfiguration config = LightConfigurator.Config <SecretsConfiguration>("Secrets"); if (config.Enable) { if (config.Module.ToUpperInvariant() == "K8S_SECRETS") { var builder = new ConfigurationBuilder() .AddConfiguration(configuration) .SetBasePath(configuration.GetValue <string>(WebHostDefaults.ContentRootKey)) .AddJsonFile($"secrets/appsettings.{config.Name.ToLower()}.k8ssecrets.json", optional: true, reloadOnChange: true); configuration = (IConfiguration)builder.Build(); } } return(configuration); }
/// <summary> /// Inicialize the cambright /// </summary> public override void Initialize() { nLoggerConfiguration = LightConfigurator.Config <NLoggerConfiguration>("NLogger"); EnabledLogTrafic = nLoggerConfiguration.EnabledLogTrafic; isRegistryTelemetry = nLoggerConfiguration.IntegratedTelemetry; LoggingConfiguration config = new LoggingConfiguration(); // Step 2. Create targets var consoleTarget = new ColoredConsoleTarget("default") { Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}" }; config.AddTarget(consoleTarget); var fileTarget = new FileTarget("onFile") { Layout = nLoggerConfiguration.Layout, FileName = nLoggerConfiguration.FileName, ArchiveFileName = nLoggerConfiguration.FileName + "-{##}.log", FileNameKind = FilePathKind.Relative, FileAttributes = Win32FileAttributes.Normal, CreateDirs = true, ArchiveAboveSize = 102400, ArchiveNumbering = ArchiveNumberingMode.Sequence, MaxArchiveFiles = 100, ConcurrentWrites = true, KeepFileOpen = true, DeleteOldFileOnStartup = true }; config.AddTarget(fileTarget); // Step 3. Define rules config.AddRuleForOneLevel(NLog.LogLevel.FromString(nLoggerConfiguration.LogLevel), fileTarget); // only errors to file config.AddRuleForAllLevels(consoleTarget); // all to console // Step 4. Activate the configuration LogManager.Configuration = config; logger = LogManager.GetLogger("NLogger"); }
/// <summary> /// Add JWT support on authentication /// </summary> /// <param name="services"></param> public static void AddLocalization(this IApplicationBuilder builder) { var config = LightConfigurator.Config <LocalizationConfig>("Localization"); if (config != null) { IList <CultureInfo> supportedCultures = new List <CultureInfo>(); foreach (var item in config.SupportedCultures) { supportedCultures.Add(new CultureInfo(item)); } builder.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture(config.DefaultCulture), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }); } }
public static SecurityKey AddSecurityKey() { var rsaConfig = LightConfigurator.Config <SigningCredentialsConfig>("SigningCredentials"); RSAParameters rsaParameters = new RSAParameters { D = Convert.FromBase64String(rsaConfig.D), DP = Convert.FromBase64String(rsaConfig.DP), DQ = Convert.FromBase64String(rsaConfig.DQ), Exponent = Convert.FromBase64String(rsaConfig.Exponent), InverseQ = Convert.FromBase64String(rsaConfig.InverseQ), Modulus = Convert.FromBase64String(rsaConfig.Modulus), P = Convert.FromBase64String(rsaConfig.P), Q = Convert.FromBase64String(rsaConfig.Q) }; SecurityKey key = new RsaSecurityKey(rsaParameters); key.KeyId = rsaConfig.KeyId; return(key); }
/// <summary> /// This method authenticates and authorizes each requests by apiName and Token /// </summary> /// <param name="apiName">name of the API</param> /// <param name="token">token authentication</param> protected AbstractApiWrapper(string apiName, string token) { _apiname = apiName; if (token != null) { _token = token; } /// verify the section configuration through API configuration by api name /// to build the ENDPOINT var config = LightConfigurator.Config <ApiConfiguration>(apiName); if (config != null) { string host = config.Host; int port = config.Port ?? -1; string suffix = config.Suffix ?? string.Empty; _suffix = suffix; _endpoint = $"{host}{((port > 0) ? ":" + port.ToString() + "/" : "/")}{((!string.IsNullOrEmpty(suffix)) ? suffix + "/" : "")}"; _stub = config.Stub; } }
/// <summary> /// Add JWT support on authentication /// </summary> /// <param name="services"></param> public static void AddAuth(this IServiceCollection services, bool hasIdentityServer) { config = LightConfigurator.Config <AuthConfiguration>("Auth"); var rsaConfig = LightConfigurator.Config <SigningCredentialsConfig>("SigningCredentials"); RSAParameters rsaParameters = new RSAParameters { D = Convert.FromBase64String(rsaConfig.D), DP = Convert.FromBase64String(rsaConfig.DP), DQ = Convert.FromBase64String(rsaConfig.DQ), Exponent = Convert.FromBase64String(rsaConfig.Exponent), InverseQ = Convert.FromBase64String(rsaConfig.InverseQ), Modulus = Convert.FromBase64String(rsaConfig.Modulus), P = Convert.FromBase64String(rsaConfig.P), Q = Convert.FromBase64String(rsaConfig.Q) }; SecurityKey key = new RsaSecurityKey(rsaParameters); key.KeyId = rsaConfig.KeyId; if (!hasIdentityServer) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtOpt => { jwtOpt.Authority = config.Authority; jwtOpt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = config.Authority, ValidateAudience = true, ValidAudiences = config.Audiencies.Split(','), IssuerSigningKey = key }; jwtOpt.Events = new JwtBearerEvents(); jwtOpt.RequireHttpsMetadata = config.RequireHttpsMetadata; }); } }