Rpic.Web.Extensions 0.2.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package Rpic.Web.Extensions --version 0.2.2                
NuGet\Install-Package Rpic.Web.Extensions -Version 0.2.2                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Rpic.Web.Extensions" Version="0.2.2" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Rpic.Web.Extensions --version 0.2.2                
#r "nuget: Rpic.Web.Extensions, 0.2.2"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Rpic.Web.Extensions as a Cake Addin
#addin nuget:?package=Rpic.Web.Extensions&version=0.2.2

// Install Rpic.Web.Extensions as a Cake Tool
#tool nuget:?package=Rpic.Web.Extensions&version=0.2.2                

Web Extensions - Retail Package Integration Concept (RPIC)

Introduction

The package is designed to be used in conjunction with the Retail Package Integration Concept (RPIC) and provides a set of utility classes and methods to simplify the integration of Retail Packages into .NET Web Applications and Web APIs.

Features include:

  • Azure App Configration: Provides a simple way to access configuration settings stored in Azure App Configuration.
  • Application Configuration: Provides a simple way to access configuration settings stored in appSettings.json.
  • Logging: Provides a simple way to log messages to the console and Application Insights.
  • Telemetry: Provides a simple way to log telemetry to Application Insights.
  • Logging Middleware: Provides a simple way to log requests and responses to the console and Application Insights.
  • Exception Handling Middleware: Provides a simple way to log exceptions to the console and Application Insights.
  • JSON Serialization: Provides a simple way to serialize and deserialize JSON data.

Installation

Install the package from NuGet:

dotnet add package Rpic.Web.Extensions

Example Usage

The following example demonstrates how to use the extensions in a .NET Web API project.

using Rpic.Web.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Register services with the dependency injection container
builder
    .ConfigureJson() // Configure JSON serialization    
    .AddConfigSection<ServiceConfiguration>("Service") // Add the service configuration
    .Services
        .AddLogger<Program>() // Configure logging
        .AddSwagger("rpic.picklist.v1.yaml") // Required for OpenAPI
        .ConfigureApplicationInsights() // Configure Application Insights
        .AddStoreInformationService() // Configure the store 
        //
        // Add further dependency injection for custom services here
        //
        .AddNewtonsoftJson(options => // Serialize enums as strings
        {
            options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
        });

var app = builder.Build();

// Configure the application
app
    .ConfigureSwagger() // Configure Swagger UI
    .HandleExceptions<ServiceException>( //Handle exceptions
        async (exception, context) =>
        {
            await exception.HandleException(context);
        }
    )
    .MapControllers();  // Configure routes for classes inheriting from ControllerBase in the /Controllers folder

app.Run();

To get the Swagger to generate from the XML comments and the OpenAPI specification, add the following to the .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <GenerateDocumentationFile>true</GenerateDocumentationFile>
    </PropertyGroup>
    <Target Name="CopyOpenApiFiles" AfterTargets="Build">
        <Copy SourceFiles="..\..\..\..\api\rpic.picklist.v1.yaml" DestinationFolder="$(OutputPath)" />
    </Target>
</Project>

Configuration

If you are using Azure App Configuration then you will need to add the following configuration to your appsettings.json file:

{
  "AzureAppConfig": {
    "Endpoint": "Endpoint=https://configname.azconfig.io;Id=MYID;Secret=MYSECRET",
    "FailoverEndpoint": "https://configname-failover.azconfig.io",
    "Identity": "ManagedIdentityGuidHere",
    "Franchisee": "Client1",
    "Region": "Region1",
    "Section": "MFT",
    "EnableFeatureFlags": true,
    "EnableRefreshCallback": true,
    "CacheExpiration": 10
    }
}
Details
  • Endpoint: The Azure App Configuration endpoint. Can either be a URL or a connection string. If a URL is used, then authentication will use the managed identity of the Azure Container App Service.
  • FailoverEndpoint: The failover Azure App Configuration endpoint. Used to provide redundancy in case the primary endpoint is unavailable. Only available for RBAC authentication using a managed identity.
  • Identity: The managed identity unique client ID. Used to authenticate with Azure App Configuration. If not provided, then the system managed identity of the Azure Container App Service will be used.
  • Franchisee: The Franchisee name. Used to segment the configuration settings between multiple Franchisee Azure subscriptions.
  • Region: The Region name. Used to segment the configuration settings between multiple Regions.
  • Section: The Section name. Used to segment the configuration settings between multiple services.
  • EnableFeatureFlags: Enable or disable the feature flags.
  • EnableRefreshCallback: Enable or disable the refresh callback. This will cause Azure App Configuration to call the service and force a configuration refresh should the configuration settings change.
  • CacheExpiration: The cache expiration time in seconds.

Notes on Feature Flags

Feature flags are a powerful tool for managing feature releases and can be used to control the rollout of new features to users. By using feature flags, you can enable or disable features at runtime without requiring a code deployment. This allows you to test new features with a subset of users before rolling them out to everyone.

  1. Configuration: Set the EnableFeatureFlags property to true in the AzureAppConfig section of the appsettings.json or the environment variables.

  2. Usage: Use the IFeatureManager to check if a feature is enabled or disabled.

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.FeatureManagement;
    
    public class HomeController : Controller
    {
        private readonly IFeatureManager _featureManager;
    
        public HomeController(IFeatureManager featureManager)
        {
            _featureManager = featureManager;
        }
    
        public async Task<IActionResult> Index()
        {
            if (await _featureManager.IsEnabledAsync("BetaFeature"))
            {
                // Logic for when the feature is enabled
                ViewData["Message"] = "Beta feature is enabled!";
            }
            else
            {
                // Logic for when the feature is disabled
                ViewData["Message"] = "Beta feature is not enabled.";
            }
    
            return View();
        }
    }
    
  3. Middle-Ware Alternative Usage: Use the FeatureFlagMiddleware to check if a feature is enabled or disabled. You can filter requests based on the feature flag.

    using Microsoft.AspNetCore.Http;
    using Microsoft.FeatureManagement;
    
    public class FeatureFlagMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IFeatureManager _featureManager;
    
        public FeatureFlagMiddleware(RequestDelegate next, IFeatureManager featureManager)
        {
            _next = next;
            _featureManager = featureManager;
        }
    
        public async Task Invoke(HttpContext context)
        {
            if (await _featureManager.IsEnabledAsync("BetaFeature"))
            {
                // Logic for when the feature is enabled
                context.Response.Headers.Add("Feature-Flag", "BetaFeatureEnabled");
            }
            else
            {
                // Logic for when the feature is disabled
                context.Response.Headers.Add("Feature-Flag", "BetaFeatureDisabled");
            }
    
            // Check if the entire service is in maintenance mode and
            // we should not accept requests at this time.
            if (await _featureManager.IsEnabledAsync("MaintenanceMode"))
            {
                context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
                await context.Response.WriteAsync("The site is under maintenance.");
            }
            else
            {
                await _next(context);
            }
    
            await _next(context);
        }
    }
    

    You will need to register the middleware in the Startup.cs file:

    app.UseMiddleware<FeatureFlagMiddleware>();
    

Function Documentation

AddConfigSection<T>

public static WebApplicationBuilder AddConfigSection<T>(
    this WebApplicationBuilder builder,
    string sectionName) where T : class
Parameters
  • builder: The WebApplicationBuilder object.
  • sectionName: The name of the configuration section.
Returns
  • WebApplicationBuilder: The updated WebApplicationBuilder object.

GetExceptionMessage

public static string GetExceptionMessage(this HttpStatusCode status, string objectName)
Parameters
  • status: The status code.
  • objectName: The name of the object type.
Returns
  • string: The exception message based on the status code.

HandleExceptions<T>

public static WebApplication HandleExceptions<T>(this WebApplication app, Func<T, HttpContext, Task>? typeHandler = null)
Parameters
  • app: The web application that raised the exception.
  • typeHandler: Optional handler for specific exception type.
Returns
  • WebApplication: The app for method chaining.

ToJson

public static string ToJson(this object obj)
Parameters
  • obj: The object reference.
Returns
  • string: The object as a JSON string.

ConfigureJson

public static WebApplicationBuilder ConfigureJson(this WebApplicationBuilder builder)
Parameters
  • builder: The web application builder.
Returns
  • WebApplicationBuilder: The updated WebApplicationBuilder object.

AddLogger<T>

public static IServiceCollection AddLogger<T>(this IServiceCollection services)
Parameters
  • services: The IServiceCollection to add the services to.
Returns
  • IServiceCollection: The modified IServiceCollection.

ConfigureApplicationInsights

public static IServiceCollection ConfigureApplicationInsights(this IServiceCollection services)
Parameters
  • services: The IServiceCollection to add the services to.
Returns
  • IServiceCollection: The modified IServiceCollection.

ConfigureSwagger

public static WebApplication ConfigureSwagger(this WebApplication app)
Parameters
  • app: The WebApplication to configure Swagger for.
Returns
  • WebApplication: The configured WebApplication.

AddSwagger

public static IServiceCollection AddSwagger(this IServiceCollection services, string filePath)
Parameters
  • services: The services collection used to register Swagger.
  • filePath: The relative path to the OpenAPI specification.
Returns
  • IServiceCollection: The modified service collection.

AddSwagger

public static IServiceCollection AddSwagger(this IServiceCollection services, OpenApiInfo? info = null)
Parameters
  • services: The IServiceCollection to add the Swagger configuration to.
  • info: The OpenApiInfo to use for the Swagger documentation.
Returns
  • IServiceCollection: The modified IServiceCollection.
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Rpic.Web.Extensions:

Package Downloads
Inter.IKEA.EDG.Inventory

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.2.3 606 7/29/2024
0.2.2 65 7/28/2024
0.2.0 113 7/26/2024