Code Monkey home page Code Monkey logo

bet.aspnetcore's Introduction

Bet.AspNetCore Libraries

GitHub license Build status NuGet Nuget feedz.io

The second letter in the Hebrew alphabet is the ב bet/beit. Its meaning is "house". In the ancient pictographic Hebrew it was a symbol resembling a tent on a landscape.

Note: Pre-release packages are distributed via feedz.io.

This goal of this repo is to provide with a reusable functionality for developing Microservices with Docker and Kubernetes. These libraries extend Microsoft.Extensions and Microsoft.AspNetCore namespaces accordingly.

Hire me

Please send email if you consider to hire me.

buymeacoffee

Give a Star! ⭐

If you like or are using this project to learn or start your solution, please give it a star. Thanks!

AspNetCore specific functionality

  1. Bet.AspNetCore specific functionality for web applications.
  2. Bet.AspNetCore.HealthChecks provides with HealthChecks for most common scenarios of the web application.
  3. Bet.AspNetCore.Logging contains logging functionality for AspNetCore applications such as azure analyzer and AppInsight extends Serilog.
  4. Bet.AspNetCore.ReCapture - a package for Google ReCapture.
  5. Bet.AspNetCore.LetsEncrypt - enables SSL inside of docker container i.e. hosted in Azure Containers.
  6. Bet.AspNetCore.Middleware
  7. Bet.AspNetCore.AzureStorage - extends AspNetCore and enables usage of Azure Blob Storage, Queues, Tables with MSI identity or token.
  8. Bet.AspNetCore.Jwt - Provides a simple and a quick way to get started with JWT authentication for your app.
  9. Bet.AspNetCore.ApiKeyAuthentication Provides with custom authentication for Web Apis with Query Url parameter or Header.

Sample Applications

All of the sample applications are deployable to local Kubernetes Cluster.

  1. Bet.AspNetCore.Sample - AspNetCore Web App with spam and sentiment prediction models based on (ML.NET). Utiizes the following libraries

  2. Bet.K8s.Web.Sample - AspNetCore Web App with spam and sentiment prediction models.

  3. LetsEncryptWeb - AspNetCore Web App with spam and sentiment prediction models.

DotNetCore CLI global tools

  1. AppAuthentication - enables Microsoft Managed Identity (MSI) testing Azure Key Vault or Azure Blob Storage access from Docker Container in Local development based on token authentication. AppAuthentication
    # adds local tool manifest file
    dotnet new tool-manifest

    # install appauthentication local version
    dotnet tool install appauthentication

Bet.Extensions libraries that build on Microsoft.Extensions:

  1. Bet.Extensions - extends many DotNetCore classes.
  2. Bet.Extensions.Options - extends Options with common functionality such as Bind() validations.
  3. Bet.Extensions.Logging - extends shared/common logging functionality.
  4. Bet.Extensions.Hosting - extends generic functionality for IHost.
  5. Bet.Extensions.AzureVault - extends Azure Vault functionality.
  6. Bet.Extensions.AzureStorage - extends MSI and regular access to Azure Storage Blob or Queue.
  7. Bet.Extensions.HealthChecks - extends useful HealChecks for Kubernetes, including Worker tcp based healthchecks.
  8. Bet.Extensions.HealthChecks.AzureStorage - provides with HealthChecks Azure Storage
  9. Bet.Extensions.DataProtection - extends DataProtection to store encryption keys on Azure Storage Blob.

About Docker Images

This repo is utilizing King David Consulting LLC Docker Images:

bet.aspnetcore's People

Contributors

kdcllc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

bet.aspnetcore's Issues

Configuration validations enhancement

At the present time, the logic for validation of the Configurations will not return all of the registered validation errors. The desired outcome is to allow to loop thru all of the registered configurations and return a collection of the validation exceptions.

Add SSL Certificate Check for the site.

In many cases, SSL Certificates expire and the health check of the site can be invalided based on that check.

This can be useful in conjunction with a custom publisher to request a new SSL for example for Let's Encrypt Authority.

AppAuthentication adding support for localhost

  1. AppAuthentication adding support for localhost
    There are scenarios where it is beneficial to enable MSI for localhost testing.
    All possible Connection string options can be found here.
    Examples:

RunAs=Developer; DeveloperTool=AzureCli
RunAs=Developer; DeveloperTool=VisualStudio

Usage:

 appauthentication run -a -l
  1. Add LogLevel functionality

Modify all possible switches

  • --authority:authid or -a:authid
  • --verbose:debug
  • --token-provider:AzureCli or -t:VisualStudio (default VisualStudio)
  • --environment:Production or -e:Development
  • --resource:test or -r:someresource
  • --port:1010 or -p:2323
  • --config:file or -c:appsettings.config
  • --fix or -f
  • --local or -l (default Docker)

Add Azure Storage Blob and Queue Library

Add library that abstract interaction with Azure Storage Blob and Queue.

  • Injectable named StorageAccountOptions that provides with the ability to create CloudStorageAccount based on the configuration provided via configurations or inline.

  • IStorageBlob<TOptions> where TOptions : StorageBlobOptions

  • IStorageQueue<TOptions> where TOptions : StorageQueueOptions

Split Project into separate packages

In preparation for the 3.0 release of DotNetCore the libraries must not share IHost and IWebHost in the same libraries. Proposed separation:

  1. Bet.Extensions generic functionality for DotNetCore in general.

    • Bet.Extensions.Options - includes Application Options and Bind() validations.
    • Bet.Extensions.Logging - includes shared/common logging functionality.
    • Bet.Extensions.Hosting - includes Generic Hosting functionality.
    • Bet.Extensions.AzureVault - includes Azure Vault functionality.
    • Bet.Extensions - includes extensions methods for DotNetCore.
  2. Bet.AspNetCore specific functionality for web applications.

    • Bet.AspNetCore.HealthChecks contains HealthChecks for most common scenarios of the web application.
    • Bet.AspNetCore.Logging contains logging functionality for AspNetCore applications.
    • Bet.AspNetCore - default location for AspNetCore.

Machine Learning ML.NET Framework for AspNetCore WebAPI

The problem when running/scoring an ML.NET model in multi-threaded applications comes when you want to do single predictions with the PredictionEngine object and you want to cache that object (i.e. as Singleton) so it is being reused by multiple Http requests (therefore it would be accessed by multiple threads). That’s is a problem because the Prediction Engine is not thread-safe ML.NET issue, Nov 2018.

Add Serilog Logging Support

Upgrade Notes for AspNetCore 3.0 Release Version

Update to support easy migration of ML.NET generated code from ML.NET Model Builder (Preview)

#34

  1. Implement ModelCreationBuilder
 public abstract class ModelCreationBuilder<TInput, TOutput, TResult> : IModelCreationBuilder<TInput, TOutput, TResult>

  1. Copy trainingPipeline generated code from
  public static IEstimator<ITransformer> BuildTrainingPipeline(MLContext mlContext)

To newly created class

 public override TrainingPipelineResult BuildTrainingPipeline()
        {
            return BuildTrainingPipeline(() =>
            {
                 // STEP 2: Common data process configuration with pipeline data transformations
                var dataProcessPipeline = MLContext.Transforms.Text.FeaturizeText(outputColumnName: "Features", inputColumnName: nameof(SentimentIssue.Text));

                // STEP 3: Set the training algorithm, then create and config the modelBuilder
                var trainer = MLContext.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: "Label", featureColumnName: "Features");
                var trainingPipeline = dataProcessPipeline.Append(trainer);

                return new TrainingPipelineResult(trainingPipeline, trainer.ToString());
            });
        }

Upgrade to .NET Core 3.0 Preview 7 - July 23, 2019

The latest dotnetcore 3.0 preview 7 is released and it comes with production support, so it seems that Microsoft already using it for hosting their websites.

Download and Install

Update HealthChecks with IHostApplicationLifetime dotnet/aspnetcore#7749

Add Azure Vault Support

Add Azure Vault Key Configuration provider that can be used with MSI and without MSI token provider.

-How to use managed identities for App Service and Azure Functions

-Add method to get an access token

-Using Azure KeyVault to manage secrets of eShopOnContainers

-Connection String Support

Everything can be done thru:

<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="2.2.0" />

This what the alternative code would look like:

       var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
        configBuilder.AddAzureKeyVault(options.BaseUrl, kv, new DefaultKeyVaultSecretManager());

        public static async Task<string> GetToken(string authority, string resource, string scope)
        {
            var options = Configuration.Bind<AzureVaultOptions>("AzureVault");

            var authContext = new AuthenticationContext(authority);
            ClientCredential clientCred = new ClientCredential(options.ClientId, options.ClientSecret);
            AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);

            if (result == null)
                throw new InvalidOperationException("Failed to obtain the JWT token");

            return result.AccessToken;
        }

Issue of using outside of MSI

Get access token using Microsoft.Azure.Services.AppAuthentication in a container

Add HealthChecks support

Some project Ideas:

HealthChecks in General

SIGTERM HealthCheck based on IApplicationLifetime

 if (appLifetime.ApplicationStopping.IsCancellationRequested)
                    {
                        return HealthCheckResult.Unhealthy();
                    }

                    return HealthCheckResult.Healthy();

Add Support for SSL Certificates for ASP.NET Core + Let's Encrypt

Azure introduced Web App Containers but WebJobs are not supported thus LetsEncrypt webjob is not an option for such hosting scenarios for custom certificates.

Nate Mcmaster LetsEncrypt is archived and no longer provides with support. So use some of the ideas to create a middleware that runs the communication protocol of Authentication and stores actual certificate either on the file system or file specified storage.

  • On App starts loading Program.cs, checking the validity and if needed Acquiring a certificate
  • Hosted job to check for certificate expiration

Desired designed features

  • Storing Let's Encrypt SSL Certificates in Azure Vault, file system, and Web Site App.
  • Logic to renew SSL certificate
  • Support for wild card SSL certificates

Add Configuration Debugging information

When multiple configurations providers are used it is hard to troubleshoot what values is being set for a certain Option within the application especially when Azure Vault or other secure vaults are used to provide an application with the configurations.

Desired outcome is to enable this kind of logging on the program start:

            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, configBuilder) =>
                {
                    var configuration = configBuilder.Build();

                    var logFactory = new LoggerFactory()
                                .AddConsole(LogLevel.Debug)
                                .AddDebug();

                    var logger = logFactory.CreateLogger(nameof(Program));
                    configuration.DebugConfigurations(logger);
                })

                .UseStartup<Startup>()
                .ConfigureKestrel(a => a.AddServerHeader = false);

This issue depends on the implementation of https://github.com/kdcllc/dabarblog/issues/8.

Migration of LoggerFactory https://docs.microsoft.com/en-us/aspnet/core/migration/logging-nonaspnetcore?view=aspnetcore-2.2

Fix issue with Serilog Extension methods

  1. The default name for the Azure Log Analytics was not checking for null and the name for the app had an issue with characters being in the name.

  2. Update serilog-sinks-azure-analytics which will require the following being set up.
    For ApplicationInsights Sink to work we need to make sure that we add in Startup.cs file:

            var instrumentId = Configuration.Bind<ApplicationInsightsOptions>("ApplicationInsights",true);

            services.AddApplicationInsightsTelemetry(options =>
            {
                options.InstrumentationKey = instrumentId.InstrumentationKey;
            });

Bet.Extensions.AzureVault - Validation with Secret ID and App Id fails

When Secret Id and App Id is present the exception is raised:

Microsoft.Azure.KeyVault.Models.KeyVaultErrorException
 HResult=0x80131500
 Message=Operation returned an invalid status code 'Forbidden'
 Source=Microsoft.Azure.KeyVault

This was due to the logic of not catching generic exceptions and also the need to remove all azure vault sources from the configurations.

Continue work on ML Model Builder integration with th CI/DI model generation

In real life senarios, ML models should be built or rebuilt within a certain interval of time for example as new prediction occurs, we would like to retrain the model to reflect the newly collected data. While AutoML tool is great for prototyping it doesn't address the issue of the production training of the models.

Add separate sample project

  • To include the start jobs for model generations.
  • To include job for app onstart to load the existing model for performance
    Bet.ML.WebApi.Sample.csproj

Bug: ConfigureWithDataAnnotationsValidation should have access the IConfiguration instance

Previous usage:

 services.ConfigureWithDataAnnotationsValidation<FakeOptionsWithDatatAnnotations>(sectionName: "FakeOptions");

Throws exception even if there are valid values

Value = '((Microsoft.Extensions.Options.OptionsManager<Bet.AspNetCore.UnitTest.FakeOptionsWithDatatAnnotations>)options).Value' threw an exception of type 'Microsoft.Extensions.Options.OptionsValidationException'

Should be:

  services.ConfigureWithDataAnnotationsValidation<FakeOptionsWithDatatAnnotations>(Configuration, sectionName: "FakeOptions");

Must add a positive unit test scenario as well to test a happy path.

Adding a Factory Service To Bet.Extensions

Possibly adding a simple interface base on Injecting a Factory Service in ASP.NET Core and the idea of using Func<> as DI like so:

services.AddScoped<ServiceA>();  
    services.AddScoped<ServiceB>();  
    services.AddScoped<ServiceC>();  
  
    services.AddTransient<Func<ServiceEnum, IService>>(serviceProvider => key =>  
    {  
        switch (key)  
        {  
            case ServiceEnum.A:  
                return serviceProvider.GetService<ServiceA>();  
            case ServiceEnum.B:  
                return serviceProvider.GetService<ServiceB>();  
            case ServiceEnum.C:  
                return serviceProvider.GetService<ServiceC>();  
            default:  
                return null;   
        }  
    });  
       public ValuesController(Func<ServiceEnum, IService> serviceResolver)  
       {  
           var service = serviceResolver(ServiceEnum.A);  
       }  

Based on Registering multiple implementations of the same interface in ASP.NET Core

[DotNetCore] - Upgrade to .NET Core 3.0.0 Preview 8

Announcement Core 3.0 Preview 8

Release Notes

-DotNetCore

Breaking Changes

Features

Updates to the Codebase

    <!--https://github.com/aspnet/AspNetCore/issues/11636-->
    <!--https://github.com/aspnet/AspNetCore/issues/11226-->
    <GeneratePackageOnBuild>false</GeneratePackageOnBuild>

Refactoring the duplicates for `IModelBuilderService`

Refactor the code that is being replicated right now for:

  • SentimentModelBuilderService
  • SpamModelBuilderService

beta package

dotnet add package Bet.Extensions.ML --version 1.3.1-beta1 --source https://www.myget.org/F/kdcllc/api/v3/index.json

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.