Program.cs

 avatar
user_7238188
csharp
7 months ago
11 kB
0
Indexable
Never
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

using MediatR;

//using BUMA.Shared.Services.Logging.Api.Extensions;
//using BUMA.Shared.Services.Logging.Domain.Interfaces;
//using BUMA.Shared.Services.Logging.Infrastructure.Data.MsSQL.Repositories;
//using BUMA.Shared.Services.Logging.Api.Factories;
//using BUMA.Shared.Services.Logging.Domain.SeedWork;
//using BUMA.Shared.Services.Logging.Infrastructure.Data.MsSQL.EntityFramework;
//using BUMA.Shared.Services.Logging.Application.Queries.ErrorLog;

using Microsoft.EntityFrameworkCore;
using System.Reflection;

using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Mvc;

using static CSharpFunctionalExtensions.Result;

using BUMA.Shared.Services.Net5.HealthMonitor;
using Buma.Shared.Services.Net5.Logging;
using Buma.Shared.Services.Net5.SwaggerMiddleware;
using BUMA.BSpace.Services.Shared.DatabaseConfiguration;
using System.Net;
using BUMA.LineUp.Services.General.Api.Extensions;
using BUMA.LineUp.Services.General.Infra.IoC;
using BUMA.LineUp.Services.General.Domain.Models.Response;
using BUMA.LineUp.Services.General.Infra.Data.MsSQL.Base;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Extensions.Configuration.AzureKeyVault;
using Azure.Extensions.AspNetCore.Configuration.Secrets;
using BUMA.LineUp.Services.General.Domain.Models.Configuration;

//using Microsoft.Extensions.Configuration.AzureKeyVault;

var serviceName = "Service General API";
var tempFolder = Path.GetTempPath();

var builder = WebApplication.CreateBuilder(args);

try
{
    if (!builder.Configuration.GetValue<string>("bspace2:HostName").Contains("localhost") && !string.IsNullOrWhiteSpace(builder.Configuration.GetValueFromHierarchy<string>("bspace2:KeyVaultName")))
    {
        var keyvaultURL = string.Format("https://{0}.vault.azure.net/", builder.Configuration.GetValue<string>("bspace2:KeyVaultName"));
        var client = new SecretClient(new Uri(keyvaultURL), new DefaultAzureCredential());
        builder.Configuration.AddAzureKeyVault(client, new KeyVaultSecretManager());
    }

    // Comment By Ricky
    //if (!builder.Configuration.GetValue<string>("bspace2:HostName").Contains("localhost"))
    //{
    //	if (!string.IsNullOrWhiteSpace(builder.Configuration.GetValueFromHierarchy<string>("bspace2:KeyVaultName")))
    //	{
    //		builder.Configuration.AddKeyVaultForManagedIdentity(builder.Configuration, "bspace2:KeyVaultName");
    //	}
    //}

    //builder.Services.AddOptions();
    //builder.Services.AddMemoryCache();
    //builder.Services.AddRouting(options => options.LowercaseUrls = true);         

    DependencyContainer.RegisterServices(builder.Services, builder.Configuration);

    // Add services to the container.
    builder.Services.AddControllers();
    //penambahan config API
    builder.Services.Configure<ApiBehaviorOptions>(opt =>
    {
        opt.InvalidModelStateResponseFactory = actionContext =>
        {
            var errors = actionContext.ModelState
                .Where(w => w.Value.Errors.Count > 0)
                .Select(s => s.Value.Errors.FirstOrDefault()?.ErrorMessage)
                .ToList();

            return new BadRequestObjectResult(new ApiResponse()
            {
                Title = "Validation",
                StatusCode = (int)HttpStatusCode.BadRequest,
                Result = new ServiceResult()
                {
                    Message = "Wrong Input Parameter",
                    IsError = true,
                    Content = errors
                }
            });
        };
    });

    builder.Services.Configure<ApiUrls>(builder.Configuration.GetSection("bspace2:Api"));

    if (!builder.Configuration.GetValue<string>("bspace2:HostName").Contains("localhost"))
    {
        //builder.Services.AddSingleton<ISubscriptionClient>(x => new SubscriptionClient(builder.Configuration.GetValueFromHierarchy<string>("SERVICEBUS:DIGITALBUS001:CONNECTIONSTRING"),
        //    builder.Configuration.GetValueFromHierarchy<string>("SERVICEBUS:DIGITALBUS001:BACKGROUNDERRORLOG:TOPICNAME"),
        //    builder.Configuration.GetValueFromHierarchy<string>("SERVICEBUS:DIGITALBUS001:BACKGROUNDERRORLOG:3RDPARTY:SUBSCRIPTIONAME")));

        var connectionString = builder.Configuration.GetValueFromHierarchy<string>(ManagedIdentitySqlConnectionSecret.SqlGeneralDB);
        builder.Services.AddDbContext<SqlDBContext>(options => options.UseSqlServer(connectionString, providerOptions => providerOptions.EnableRetryOnFailure()));
    }
    else
    {
        //builder.Services.AddSingleton<ISubscriptionClient>(x => new SubscriptionClient(builder.Configuration.GetValue<string>("ServiceBus:ConnectionString"),
        //    builder.Configuration.GetValue<string>("ServiceBus:TopicName"),
        //    builder.Configuration.GetValue<string>("ServiceBus:SubscriptionName")));

        var connectionString = builder.Configuration.GetValue<string>("bspace2:Database:Localhost");
        builder.Services.AddDbContext<SqlDBContext>(options => options.UseSqlServer(connectionString, providerOptions => providerOptions.EnableRetryOnFailure()));
    }

    builder.Services.AddAuthentication(options =>
    {
        options.DefaultScheme = AzureADDefaults.AuthenticationScheme;
    }).AddJwtBearer("AzureAD", options =>
    {
        options.Authority = builder.Configuration.GetValue<string>("bspace2:AzureAd:Instance") + builder.Configuration.GetValueFromHierarchy<string>("bspace2:AzureAd:TenantId");
        options.TokenValidationParameters = new TokenValidationParameters()
        {

            ValidateIssuer = true,
            ValidAudiences = new List<string> {
                builder.Configuration.GetValueFromHierarchy<string>("bspace2:AzureAd:ClientId"),
                builder.Configuration.GetValueFromHierarchy<string>("bspace2:AzureAd:WebClientId")
            }
        };
    });

    if (!builder.Configuration.GetValue<string>("bspace2:HostName").Contains("localhost"))
    {
        SwaggerConfig.AddSwaggerGenWithOAuth(builder.Services,
                    builder.Configuration.GetValue<string>("bspace2:Version"),
                    builder.Configuration.GetValue<string>("bspace2:HostName"),
                    builder.Configuration.GetValue<string>("bspace2:SwaggerBasePath"),
                    builder.Configuration.GetValueFromHierarchy<string>("bspace2:AzureAd:TenantId"),
                    serviceName);

        builder.Services.AddStandardLogging(
            builder.Configuration.GetValueFromHierarchy<string>("bspace2:ApplicationInsights:InstrumentationKey"),
            builder.Configuration.GetValue<string>("Logging:LogLevel:Default"),
            tempFolder);
    }
    else
    {
        //SwaggerConfig.AddSwaggerGenWithOAuth(builder.Services,
        //    builder.Configuration.GetValue<string>("bspace2:Version"),
        //    builder.Configuration.GetValue<string>("bspace2:HostName"),
        //    string.Empty,
        //    builder.Configuration.GetValue<string>("bspace2:AzureAd:TenantId"),
        //    serviceName);

        //builder.Services.AddStandardLogging(
        //    builder.Configuration.GetValue<string>("bspace2:ApplicationInsights:InstrumentationKey"),
        //    builder.Configuration.GetValue<string>("Logging:LogLevel:Default"),
        //    tempFolder);
    }

    //builder.Services.AddScoped<IErrorLogRepository, ErrorLogRepository>();
    //builder.Services.AddScoped<ILogRepository, LogRepository>();

    //builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
    //builder.Services.AddSingleton<ICommandFactory, CommandFactory>();

    //builder.Services.AddMediatR(typeof(PostLogCommandHandler).GetTypeInfo().Assembly);
    //builder.Services.AddMediatR(typeof(GetErrorLogQueryHandler).GetTypeInfo().Assembly);

    builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

    builder.Services.AddHostedService<HealthCheckHostedService>();
    builder.Services.AddSingleton<ReadinessHealthCheck>();
    builder.Services.AddSingleton<LivenessHealthCheck>();
    builder.Services.AddHealthChecks()
        .AddLivenessHealthCheck("Liveness", HealthStatus.Unhealthy, new List<string>() { "Liveness" })
        .AddReadinessHealthCheck("Readiness", HealthStatus.Unhealthy, new List<string> { "Readiness" });

    builder.Services.AddApplicationInsightsTelemetry();
    builder.Services.AddSingleton<ITelemetryInitializer, CloudRoleNameTelemetryInitializer>();

    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen(c => c.DescribeAllParametersInCamelCase());

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    //app.AddLoggingMiddleware();
    //app.AddExceptionHandlerMiddleware();

    //if (builder.Configuration.GetValue<string>("bspace2:HostName").Contains("localhost"))
    //{
    //    SwaggerConfig.UseSwaggerWithOAuth(app, app.Environment,
    //        serviceName,
    //        builder.Configuration.GetValue<string>("bspace2:AzureAd:ClientId"),
    //        builder.Configuration.GetValue<string>("bspace2:AzureAd:ClientId"));
    //}
    //else
    //{
    //    SwaggerConfig.UseSwaggerWithOAuth(app, app.Environment,
    //        serviceName,
    //        builder.Configuration.GetValueFromHierarchy<string>("bspace2:AzureAd:ClientId"),
    //        builder.Configuration.GetValueFromHierarchy<string>("bspace2:AzureAd:ClientId"));
    //}

    //app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapControllers();

    ///MANDATORY
    app.UseHealthChecks("/health/live", new HealthCheckOptions()
    {
        Predicate = check => check.Name == "Liveness"
    })
    .UseHealthChecks("/health/ready", new HealthCheckOptions()
    {
        Predicate = check => check.Name == "Readiness",
    });
    ///MANDATORY
    ///
    app.Run();
}
catch (Exception ex)
{
    throw new Exception(ex.Message);
}


Leave a Comment