public class Program
private static bool development = true;
private readonly OcelotConfigBuilder _ocelotConfigBuilder;
public IConfiguration Configuration { get; }
private ModuleManager<IServiceCollection> _moduleManager;
public Program(IConfiguration configuration)
Configuration = configuration;
_ocelotConfigBuilder = new OcelotConfigBuilder(Configuration);
public static void Main(string[] args)
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, errors) =>
if (development)
return true;
return errors == SslPolicyErrors.None;
};
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.With<MethodInvocationEnricher>()
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss} [{Level}]
[{CorrelationID}] [{InvocationContextClassName}] [{InvocationContextMethodName}]
{Message} {NewLine} {Exception}") // Updated output template
.WriteTo.File("C:\\logcontext\\loglog.txt",
outputTemplate: "{Timestamp:HH:mm:ss} [{Level}]
[{CorrelationID}] [{InvocationContextClassName}] [{InvocationContextMethodName}]
{Message} {NewLine} {Exception}",
rollingInterval: RollingInterval.Day)
.CreateLogger();
CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.UseKestrel()
.UseIIS()
.UseStartup<Program>();
webBuilder.ConfigureAppConfiguration(ConfigureConfig);
}).ConfigureServices(
services =>
services.AddSingleton<IHttpContextAccessor,
HttpContextAccessor>();
services.AddSingleton<ICustomIsomSerializer,
CustomIsomSerializer>();
services.AddSingleton<IDeviceSearchRequestMapper,
DeviceSearchRequestMapper>();
})
.UseServiceProviderFactory(new AutofacServiceProviderFactory());
private static void ConfigureLogger(HostBuilderContext arg1,
LoggerConfiguration arg2)
arg2.ReadFrom.Configuration(arg1.Configuration);
//arg2.ReadFrom.Configuration(arg1.Configuration);
}
private static void ConfigureConfig(WebHostBuilderContext hostingContext,
IConfigurationBuilder configBuilder)
configBuilder.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath).AddJso
nFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.
{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
.AddEnvironmentVariables();
var config = configBuilder.Build();
var deploymentType = config.GetValue<string>("DeploymentType");
configBuilder.AddOcelot($"./GatewayConfig/{deploymentType}",
hostingContext.HostingEnvironment).AddOcelotWithSwaggerSupport((o) => { o.Folder =
$"GatewayConfig/{deploymentType}"; });
// This method gets called by the runtime. Use this method to add services to
the container.
public void ConfigureServices(IServiceCollection services)
services.AddHealthChecks();
services.AddHttpContextAccessor();
ConfigureSwagger(services);
SetUpAuthentication(services);
var mvcBuilder = services.AddControllers().AddJsonOptions(opts =>
opts.JsonSerializerOptions.Converters.Add(new
JsonStringEnumConverter());
});
var path = AppDomain.CurrentDomain.BaseDirectory;
//services.AddControllers().AddNewtonsoftJson(opts =>
//{
// opts.SerializerSettings.Converters.Add(new StringEnumConverter());
//});
var moduleManager = ModuleManager<IServiceCollection>.Create(services,
path);
moduleManager.InitializeModule();
_moduleManager = moduleManager;
foreach (var assembly in moduleManager.LoadedAssemblies)
mvcBuilder.AddApplicationPart(assembly);
services.AddCors(options =>
options.AddPolicy("AllowOrigin",
builder =>
builder.WithOrigins(Configuration.GetSection("AllowedOrigins").Value).AllowCredenti
als().AllowAnyHeader().AllowAnyMethod());
});
services.AddSwaggerForOcelot(Configuration);
services.AddOcelot().AddCacheManager(x =>
x.WithDictionaryHandle();
})
.AddPolly()
.AddDelegatingHandler<SpaceIsomSearchHandler>()
.AddDelegatingHandler<SpaceIsomHandler>()
.AddDelegatingHandler<DeviceIsomHandler>()
.AddDelegatingHandler<DoorOperationsHandler>()
.AddDelegatingHandler<TokenHandler>()
.AddDelegatingHandler<RevokeTokenHandler>()
.AddDelegatingHandler<UnAcknowledgeAlarmsRollUpHandler>()
.AddDelegatingHandler<AcknowledgeAlarmsRollUpHandler>()
.AddDelegatingHandler<MaxproAuthenticationHandler>()
.AddDelegatingHandler<StreamConfigHandler>()
.AddDelegatingHandler<CameraStreamConfigHandler>()
.AddDelegatingHandler<MaxproStreamConfigHandler>()
.AddDelegatingHandler<CameraHandler>()
.AddDelegatingHandler<ValidateSupervisorPinIsomHandler>()
.AddDelegatingHandler<RecorderSummaryHandler>()
.AddDelegatingHandler<RecordingUnavailabilityHandler>()
.AddDelegatingHandler<HostInjectorDelegatingHandler>()
.AddDelegatingHandler<CameraConfigHandler>();
services.AddOptions();
services.AddScoped<IGatewayNegotiate, GatewayNegotiateService>();
services.AddScoped<IApiClientHelper, ApiClientHelper>();
services.AddScoped<IDeviceDetailHelper, DeviceDetailHelper>();
services.AddScoped<IUvisomRequestHandler, UvisomRequestHandler>();
services.AddTransient<IEntityMapper, EntityMapper>();
services.AddOptions();
private void SetUpAuthentication(IServiceCollection services)
if
(Configuration.GetValue<string>("DeploymentType").Equals("IntegratedSecurity",
StringComparison.InvariantCultureIgnoreCase) ||
Configuration.GetValue<string>("DeploymentType").Equals("PROWATCH",
StringComparison.InvariantCultureIgnoreCase))
//Create Seri Logger Instance and add it to Log Factory to fetch a ILogger
Instance
////For Logging Authentication Validation
var seriLogger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.CreateLogger();
var logFactory = LoggerFactory.Create(builder =>
builder.AddSerilog(seriLogger);
});
Microsoft.Extensions.Logging.ILogger logger =
logFactory.CreateLogger(LogLevel.Information.ToString());
services.AddICAuthentication(Configuration, logger);
else
AuthSetup.ConfigureAuthentication(services, Configuration);
if (!Configuration.GetValue<bool>("AllowAnonymous"))
services.AddMvc(options =>
options.EnableEndpointRouting = false;
}).AddControllersAsServices();
else
services.AddMvc(options =>
options.EnableEndpointRouting = false;
options.Filters.Add(new AllowAnonymousFilter());
}).AddControllersAsServices();
public void ConfigureContainer(ContainerBuilder containerBuilder)
{
containerBuilder.RegisterGeneric(typeof(AppLogger<>)).As(typeof(IAppLogger<>));
// This method gets called by the runtime. Use this method to configure
the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
if (app != null && env != null)
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
new MvcOptions().EnableEndpointRouting = false;
HoneyEngine.ServiceProvider = app.ApplicationServices;
_moduleManager.StartModule(app.ApplicationServices);
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.UseRouting();
app.UseSerilogRequestLogging();
app.UseCors(builder =>
builder.WithOrigins(Configuration.GetSection("AllowedOrigins").Value).AllowCredenti
als().AllowAnyHeader().AllowAnyMethod());
app.UseMiddleware<ApiLoggerMiddleware>();
app.UseMiddleware<NegotiateMiddleware>();
app.UseMiddleware<NegotiateMiddlewareV2>();
app.UseSwaggerForOcelotUI(options =>
_ocelotConfigBuilder.GetSwaggerConfiguration(options));
app.UseOcelot(_ocelotConfigBuilder.GetOcelotPipelineConfiguration()).Wait();
app.UseMvc();
UserLocalization(app);
private static void ConfigureSwagger(IServiceCollection services)
services.AddSwaggerGen(c =>
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Honeywell
Security API Management", Version = "v1" });
var xmlFiles =
Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"*.xml");
foreach (var xmlFile in xmlFiles)
c.IncludeXmlComments(xmlFile);
c.EnableAnnotations();
var securityScheme = new OpenApiSecurityScheme
Description = "Please enter into field the word 'Bearer'
followed by a space and the JWT value",
Name = "Bearer",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "bearer"
};
c.IgnoreObsoleteActions();
c.AddSecurityDefinition("Bearer", securityScheme);
// Add security requirements globally. If needs to be unique
per operation then use IOperationFilter.
var securityRequirement = new OpenApiSecurityRequirement
new OpenApiSecurityScheme
Reference = new OpenApiReference {Type =
ReferenceType.SecurityScheme, Id = "Bearer"}
},
new[] {"Bearer"}
};
c.AddSecurityRequirement(securityRequirement);
});
services.AddSwaggerGenNewtonsoftSupport();
private void UserLocalization(IApplicationBuilder app)
// use localization
var supportedCulturesStrings =
Configuration.GetSection("SupportedCultures").Get<string[]>();
var supportedCultures = supportedCulturesStrings.Select(item => new
CultureInfo(item)).ToList();
var options = new RequestLocalizationOptions
DefaultRequestCulture = new
RequestCulture(Configuration.GetSection("DefaultRequestCulture").Value),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
app.UseRequestLocalization(options);
}
}