### Quick Start: Initialize Schemata Web Application Source: https://github.com/cyprincess/schemata/blob/master/README.md This snippet shows the command-line instructions to create a new .NET web project and add the Schemata.Application.Complex.Targets package. It serves as the initial setup for using the Schemata framework. ```shell dotnet new web dotnet add package --prerelease Schemata.Application.Complex.Targets ``` -------------------------------- ### Install Schemata DSL Package Source: https://github.com/cyprincess/schemata/blob/master/generators/Schemata.DSL/README.md This command adds the Schemata DSL package to your .NET project. Ensure you are using a prerelease version. ```shell dotnet add package --prerelease Schemata.DSL ``` -------------------------------- ### Schemata DSL Basic Grammar Example Source: https://github.com/cyprincess/schemata/blob/master/generators/Schemata.DSL/README.md This C# code snippet demonstrates the basic grammar of the Schemata DSL. It defines traits for identifiers and timestamps, an entity that uses these traits, and specifies fields with constraints and an object for response generation. ```csharp Namespace Example Trait Identifier { long id [primary key] } Trait Timestamp { timestamp? creation_date timestamp? modification_date } Trait Entity { Use Identifier, Timestamp } Entity User { Use Entity string email_address [b tree] string phone_number [b tree] string password string nickname Object response { id nickname email_address [omit] obfuscated_email_address [omit] = obfuscate(email_address) phone_number [omit] obfuscated_phone_number [omit] = obfuscate(phone_number) } } ``` -------------------------------- ### Example Azure Pipelines YAML for 1ES Managed Templates Source: https://github.com/cyprincess/schemata/blob/master/eng/common/template-guidance.md This snippet demonstrates how to use the 1ES pipeline templates, specifically referencing 'azure-pipelines/MicroBuild.1ES.Official.yml' and configuring multiple outputs for artifact publishing. It shows how to consolidate outputs in 'Build.ArtifactStagingDirectory' to reduce security scans, a feature exclusive to 1ES PT publishing. ```yaml extends: template: azure-pipelines/MicroBuild.1ES.Official.yml@MicroBuildTemplate parameters: stages: - stage: build jobs: - template: /eng/common/templates-official/jobs/jobs.yml@self parameters: # 1ES makes use of outputs to reduce security task injection overhead templateContext: outputs: - output: pipelineArtifact displayName: 'Publish logs from source' continueOnError: true condition: always() targetPath: $(Build.ArtifactStagingDirectory)/artifacts/log artifactName: Logs jobs: - job: Windows steps: - script: echo "friendly neighborhood" > artifacts/marvel/spiderman.txt # copy build outputs to artifact staging directory for publishing - task: CopyFiles@2 displayName: Gather build output inputs: SourceFolder: '$(Build.SourcesDirectory)/artifacts/marvel' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/marvel' ``` -------------------------------- ### Define a Module with C# Source: https://github.com/cyprincess/schemata/blob/master/targets/Schemata.Module.Targets/README.md This C# code demonstrates how to define a custom module by inheriting from 'ModuleBase'. It specifies the module's order and priority, and includes placeholder methods for service configuration and application setup. This is fundamental for integrating custom logic into the Schemata framework. ```csharp public class Module : ModuleBase { public override int Order => 0; public override int Priority => 1; public void ConfigureServices(IServiceCollection services) { // } public void Configure(IApplicationBuilder app, IServiceProvider sp) { // } } ``` -------------------------------- ### Configure Modular Application Architecture (C#) Source: https://context7.com/cyprincess/schemata/llms.txt Enables a dynamic module loading and isolation system in ASP.NET Core applications using Schemata. This feature allows for organizing application logic into distinct modules, which can be loaded dynamically. The example shows how to enable modularity, define a module, and hints at using a custom module provider for more advanced loading strategies. ```csharp using Microsoft.AspNetCore.Builder; using Schemata.Abstractions.Modular; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.UseRouting(); schema.UseTenancy().UseHostResolver(); // Enable modular architecture schema.UseModular(); // Uses DefaultModulesRunner and DefaultModulesProvider schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Define a module [Module("Orders", Priority = 100)] public class OrdersModule : ModuleBase { public override void ConfigureServices( IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment) { services.AddScoped(); services.AddDbContext(options => options.UseSqlServer(configuration.GetConnectionString("Orders"))); } public override void ConfigureApplication( IApplicationBuilder app, IConfiguration configuration, IWebHostEnvironment environment) { // Configure middleware } } // Custom module provider public class CustomModulesProvider : IModulesProvider { public Task> GetModulesAsync(CancellationToken ct = default) { // Load modules from database, files, or assembly scanning var modules = new List { new OrdersModule(), new PaymentsModule(), new ShippingModule() }; return Task.FromResult>(modules); } } // Use custom provider // schema.UseModular(); ``` -------------------------------- ### Schemata DSL Definition (SKM) Source: https://context7.com/cyprincess/schemata/llms.txt Defines entities, traits, and relationships using the Schemata Domain Specific Language (DSL). This example illustrates how to create reusable traits like 'Identifier' and 'Timestamp', compose them into an 'Entity' trait, and then define specific entities such as 'User' and 'Order' with their properties, constraints, and response object structures. ```skm Namespace Example Trait Identifier { long id [primary key] } Trait Timestamp { timestamp? creation_date timestamp? modification_date } Trait Entity { Use Identifier, Timestamp } Entity User { Use Entity string email_address [b tree] string phone_number [b tree] string password string nickname Object response { id nickname email_address [omit] obfuscated_email_address [omit] = obfuscate(email_address) phone_number [omit] obfuscated_phone_number [omit] = obfuscate(phone_number) } } Entity Order { Use Entity long user_id [b tree, foreign key references User.id] decimal total_amount string status Object summary { id total_amount status } Object detail { Use summary user_id creation_date } } ``` -------------------------------- ### Configure Snake_case JSON Serialization (C#) Source: https://context7.com/cyprincess/schemata/llms.txt Configures snake_case JSON serialization with custom converters in ASP.NET Core applications using Schemata. This setup allows for property name transformation (e.g., firstName to first_name) and enum value formatting (e.g., OrderStatus.InProgress to in-progress). It also handles JavaScript 53-bit integer limits and allows reading numbers from strings, with a default MaxDepth of 32, which can be customized. ```csharp using Microsoft.AspNetCore.Builder; using System.Text.Json; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.UseRouting(); schema.UseControllers(); // JSON serializer with built-in conventions schema.UseJsonSerializer(); // - snake_case property names (firstName -> first_name) // - kebab-case enum values (OrderStatus.InProgress -> in-progress) // - Handles JavaScript 53-bit integer limits // - Allows reading numbers from strings // - MaxDepth: 32 // Customize JSON options schema.Configure(options => { options.MaxDepth = 64; options.WriteIndented = true; }); }); var app = builder.Build(); app.Run(); // Example: API returns snake_case JSON public class UserController : ControllerBase { [HttpGet] public IActionResult Get() { return Ok(new { FirstName = "John", // Serialized as: "first_name": "john" LastName = "Doe", // Serialized as: "last_name": "doe" EmailAddress = "j@d.com" // Serialized as: "email_address": "j@d.com" }); } } ``` -------------------------------- ### Application Bootstrap with Schemata Source: https://context7.com/cyprincess/schemata/llms.txt Initializes a Schemata application, configuring core features such as logging, HTTPS, routing, and controllers. It demonstrates the builder pattern for setting up the application pipeline and services. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { // Core features schema.UseLogging(); schema.UseDeveloperExceptionPage(); schema.UseForwardedHeaders(); schema.UseHttps(); schema.UseCookiePolicy(); schema.UseCors(); schema.UseRouting(); schema.UseControllers(); schema.UseJsonSerializer(); // Configure services schema.ConfigureServices(services => { services.AddDistributedMemoryCache(); }); }); var app = builder.Build(); app.Run(); ``` -------------------------------- ### Repository Pattern with Entity Framework Core Source: https://context7.com/cyprincess/schemata/llms.txt Configures the repository pattern using Entity Framework Core within the Schemata framework. It includes registering custom advices, setting up the EF Core context, and demonstrates basic repository usage in a controller for listing and creating products. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.ConfigureServices(services => { // Register custom advice for additional logic services.AddTransient(typeof(IRepositoryAddAsyncAdvice<>), typeof(MyCustomAdvice<>)); // Configure repository with EF Core services.AddRepository(typeof(MyRepository<>)) .UseEntityFrameworkCore((sp, options) => options.UseSqlServer(schema.Configuration.GetConnectionString("Default"))); }); schema.UseRouting(); schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Repository interface usage public class MyRepository : EntityFrameworkCoreRepository, IRepository where T : class { public MyRepository(MyDbContext context, IServiceProvider services) : base(context, services) { } } // Using repository in controller public class ProductController : ControllerBase { private readonly IRepository _repository; public ProductController(IRepository repository) { _repository = repository; } [HttpGet] public async Task GetAll(CancellationToken ct) { var products = await _repository.ListAsync(p => p.IsActive, ct) .ToListAsync(ct); return Ok(products); } [HttpPost] public async Task Create([FromBody] Product product, CancellationToken ct) { await _repository.AddAsync(product, ct); await _repository.CommitAsync(ct); return CreatedAtAction(nameof(GetAll), new { id = product.Id }, product); } } ``` -------------------------------- ### Configure Multi-Tenancy with Alternative Resolvers in C# Source: https://context7.com/cyprincess/schemata/llms.txt This C# snippet illustrates configuring multi-tenancy using alternative tenant resolution strategies like request headers, paths, or query strings. It shows how to enable header, path, query, and principal resolvers for tenant identification. Dependencies include Microsoft.AspNetCore.Builder. ```csharp using Microsoft.AspNetCore.Builder; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.UseRouting(); // Resolve tenant from header: X-Tenant-Id: tenant-guid schema.UseTenancy, Guid>() .UseHeaderResolver(); // Alternative: Resolve from path: /api/tenants/{tenantId}/resources // schema.UseTenancy, Guid>() // .UsePathResolver(); // Alternative: Resolve from query: ?tenant=tenant-guid // schema.UseTenancy, Guid>() // .UseQueryResolver(); // Alternative: Resolve from user principal claim // schema.UseTenancy, Guid>() // .UsePrincipalResolver(); schema.UseControllers(); }); var app = builder.Build(); app.Run(); ``` -------------------------------- ### Configure Schemata Application Services and Middleware Source: https://github.com/cyprincess/schemata/blob/master/README.md This C# code demonstrates the configuration of a Schemata application. It includes setting up essential services like logging, exception handling, repositories, caching, security, identity, authorization, and mapping using the Schemata framework's extension methods. ```csharp var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.UseLogging(); schema.UseDeveloperExceptionPage(); schema.ConfigureServices(services => { services.AddTransient(typeof(IRepositoryAddAsyncAdvice<>), typeof(MyAdviceAddAsync<>)); services.AddRepository(typeof(MyRepository<>)) .UseEntityFrameworkCore((sp, options) => options.UseSqlServer(schema.Configuration.GetConnectionString("Default"))); services.AddDistributedMemoryCache(); }); schema.UseForwardedHeaders(); schema.UseHttps(); schema.UseCookiePolicy(); schema.UseSession(); schema.UseCors(); schema.UseRouting(); schema.UseControllers(); schema.UseJsonSerializer(); schema.UseTenancy() .UseHostResolver(); schema.UseModular(); schema.UseSecurity(); schema.UseIdentity(); schema.UseAuthorization(options => { options.AddEphemeralEncryptionKey() .AddEphemeralSigningKey(); }) .UseCodeFlow() .UseRefreshTokenFlow() .UseDeviceFlow() .UseIntrospection() .UseCaching(); schema.UseWorkflow(); // You can also utilize UseAutoMapper() once you've incorporated the Schemata.Mapping.AutoMapper package into your project. schema.UseMapster() .Map(map => { map.For(d => d.DisplayName).From(s => s.Name); map.For(d => d.Age).From(s => s.Age).Ignore((s, d) => s.Age < 18); map.For(d => d.Grade).Ignore() .For(d => d.Sex).From(s => s.Sex.ToString()); }); schema.UseResource() .MapHttp() }); var app = builder.Build(); app.Run(); ``` -------------------------------- ### Configure Workflow State Machine with Transitions (C#) Source: https://context7.com/cyprincess/schemata/llms.txt This C# code configures a workflow state machine using Schemata. It sets up the service collection, defines entity repositories, and configures the workflow with custom response mapping and optional audit/validation. It also demonstrates how to use the workflow in a controller. ```csharp using Microsoft.AspNetCore.Builder; using Schemata.Workflow.Skeleton.Entities; using Schemata.Workflow.Skeleton.Models; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.ConfigureServices(services => { services.AddRepository(typeof(MyRepository<>)) .UseEntityFrameworkCore((sp, options) => options.UseSqlServer(schema.Configuration.GetConnectionString("Default"))); }); schema.UseRouting(); // Configure workflow with custom response mapping schema.UseWorkflow( configure: options => { options.EnableAudit = true; options.EnableValidation = true; }, mapping: map => { map.For(d => d.Id).From(s => s.Workflow.Id); map.For(d => d.State).From(s => s.Instance.State); map.For(d => d.OrderNumber).From(s => s.Instance.OrderNumber); map.For(d => d.Graph).From(s => s.Graph); map.For(d => d.AvailableTransitions).From(s => s.Transitions); }); schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Workflow entities public class OrderWorkflow : SchemataWorkflow { public string OrderNumber { get; set; } = string.Empty; } public class OrderTransition : SchemataTransition { } public class OrderWorkflowResponse : WorkflowResponse { public string OrderNumber { get; set; } = string.Empty; public List AvailableTransitions { get; set; } = new(); } // Use workflow in controller public class OrderController : ControllerBase { private readonly IWorkflowService _workflowService; [HttpPost("orders/{id}/submit")] public async Task SubmitOrder(long id, CancellationToken ct) { var result = await _workflowService.TransitionAsync(id, "submit", ct); return Ok(result); } } ``` -------------------------------- ### Repository Pattern with LINQ to DB Source: https://context7.com/cyprincess/schemata/llms.txt Configures the repository pattern using LINQ to DB within the Schemata framework for high-performance queries. It demonstrates setting up the LINQ to DB connection and custom data connection class. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using LinqToDB; using LinqToDB.Data; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.ConfigureServices(services => { services.AddRepository(typeof(LinqToDbRepository<>)) .UseLinqToDb((sp, options) => options .UseSqlServer(schema.Configuration.GetConnectionString("Default"))); }); schema.UseRouting(); schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Custom data connection public class MyDataConnection : DataConnection { public MyDataConnection(DataOptions options) : base(options.Options) { } public ITable Users => this.GetTable(); public ITable Orders => this.GetTable(); } ``` -------------------------------- ### Configure Multi-Tenancy with Host Resolver in C# Source: https://context7.com/cyprincess/schemata/llms.txt This snippet shows how to configure multi-tenancy in an ASP.NET Core application where tenants are resolved based on the HTTP host. It demonstrates setting up tenant-specific database contexts and accessing tenant information within controllers. Dependencies include Microsoft.AspNetCore.Builder and Schemata.Tenancy.Skeleton.Entities. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Schemata.Tenancy.Skeleton.Entities; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.UseRouting(); // Configure tenancy with host-based resolution schema.UseTenancy, Guid>((services, tenant) => { // Configure services per tenant if (tenant != null) { services.AddDbContext(options => options.UseSqlServer(tenant.ConnectionString)); } }).UseHostResolver(); schema.UseModular(); schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Tenant will be resolved from subdomain: tenant1.example.com -> tenant1 // Access current tenant in controllers public class DataController : ControllerBase { private readonly ITenantManager, Guid> _tenantManager; public DataController(ITenantManager, Guid> tenantManager) { _tenantManager = tenantManager; } [HttpGet] public async Task GetTenantInfo() { var tenant = await _tenantManager.GetCurrentAsync(); return Ok(new { tenant.Id, tenant.Name }); } } ``` -------------------------------- ### Generate Schemata DSL Code (Shell) Source: https://context7.com/cyprincess/schemata/llms.txt Provides instructions for adding the Schemata.DSL package to a .NET project and running the code generator to produce C# classes from .skm (Schemata DSL) files. The generated code includes entity classes with attributes, response Data Transfer Objects (DTOs), repository configurations, and validation rules, facilitating rapid development. ```shell dotnet add package --prerelease Schemata.DSL # Run code generator to produce C# classes from .skm files # Generated classes include: # - Entity classes with attributes # - Response DTOs # - Repository configurations # - Validation rules ``` -------------------------------- ### Add Schemata Module Package with .NET CLI Source: https://github.com/cyprincess/schemata/blob/master/targets/Schemata.Module.Targets/README.md This snippet shows how to set up a new C# class library and add the Schemata.Module.Complex.Targets package using the .NET CLI. It's a prerequisite for using the Schemata module in your project. ```shell dotnet new classlib dotnet add package --prerelease Schemata.Module.Complex.Targets ``` -------------------------------- ### Configure ASP.NET Core Identity with Bearer Token Auth in C# Source: https://context7.com/cyprincess/schemata/llms.txt This C# code configures ASP.NET Core Identity with custom options and Bearer Token authentication. It demonstrates setting up Entity Framework Core for data persistence and specifies settings for password policies, user requirements, and token expiration. Dependencies include Microsoft.AspNetCore.Builder and Microsoft.AspNetCore.Identity. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Schemata.Identity.Skeleton.Entities; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.ConfigureServices(services => { services.AddRepository(typeof(MyRepository<>)) .UseEntityFrameworkCore((sp, options) => options.UseSqlServer(schema.Configuration.GetConnectionString("Default"))); }); schema.UseRouting(); schema.UseSecurity(); // Configure Identity with custom options schema.UseIdentity( identify: options => { // Identity-specific options }, configure: options => { options.Password.RequireDigit = true; options.Password.RequiredLength = 8; options.User.RequireUniqueEmail = true; }, build: builder => { // Customize IdentityBuilder }, bearer: options => { options.BearerTokenExpiration = TimeSpan.FromHours(1); }); schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Identity endpoints are automatically mapped: // POST /register - User registration // POST /login - User login (returns bearer token) // POST /refresh - Token refresh // GET /manage/info - User info ``` -------------------------------- ### Resource Service with HTTP Endpoints Source: https://context7.com/cyprincess/schemata/llms.txt Generates RESTful endpoints with Google AIP compliance, mapping resources to HTTP endpoints. ```APIDOC ## Resource Service with HTTP Endpoints ### Description Generates RESTful endpoints with Google AIP compliance, mapping resources to HTTP endpoints. ### Method N/A (Configuration Setup) ### Endpoint N/A (Configuration Setup) ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example (C#) ```csharp using Microsoft.AspNetCore.Builder; using Schemata.Abstractions.Resource; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.ConfigureServices(services => { services.AddRepository(typeof(MyRepository<>)) .UseEntityFrameworkCore((sp, options) => options.UseSqlServer(schema.Configuration.GetConnectionString("Default"))); }); schema.UseRouting(); // Enable resource service with HTTP mapping schema.UseResource() .MapHttp(); schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Define resource with attributes [Resource(entity: typeof(Product), request: typeof(ProductRequest), detail: typeof(ProductDetail), summary: typeof(ProductSummary))] [HttpResource("products")] // Maps to /api/products public class ProductResource { // Endpoints are automatically generated: // GET /api/products - List products // GET /api/products/{id} - Get product // POST /api/products - Create product // PUT /api/products/{id} - Update product // DELETE /api/products/{id} - Delete product // PATCH /api/products/{id} - Partial update } public class Product { public long Id { get; set; } public string Name { get; set; } = string.Empty; public decimal Price { get; set; } public DateTime CreateTime { get; set; } } public class ProductRequest { public string Name { get; set; } = string.Empty; public decimal Price { get; set; } } public class ProductDetail { public long Id { get; set; } public string Name { get; set; } = string.Empty; public decimal Price { get; set; } public DateTime CreateTime { get; set; } } public class ProductSummary { public long Id { get; set; } public string Name { get; set; } = string.Empty; } ``` ``` -------------------------------- ### Workflow Engine Configuration Source: https://context7.com/cyprincess/schemata/llms.txt Configures the workflow state machine with transitions, including custom response mapping and audit/validation enablement. ```APIDOC ## Workflow Engine Configuration ### Description Configures the workflow state machine with transitions, including custom response mapping and audit/validation enablement. ### Method N/A (Configuration Setup) ### Endpoint N/A (Configuration Setup) ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example (C#) ```csharp using Microsoft.AspNetCore.Builder; using Schemata.Workflow.Skeleton.Entities; using Schemata.Workflow.Skeleton.Models; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.ConfigureServices(services => { services.AddRepository(typeof(MyRepository<>)) .UseEntityFrameworkCore((sp, options) => options.UseSqlServer(schema.Configuration.GetConnectionString("Default"))); }); schema.UseRouting(); // Configure workflow with custom response mapping schema.UseWorkflow( configure: options => { options.EnableAudit = true; options.EnableValidation = true; }, mapping: map => { map.For(d => d.Id).From(s => s.Workflow.Id); map.For(d => d.State).From(s => s.Instance.State); map.For(d => d.OrderNumber).From(s => s.Instance.OrderNumber); map.For(d => d.Graph).From(s => s.Graph); map.For(d => d.AvailableTransitions).From(s => s.Transitions); }); schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Workflow entities public class OrderWorkflow : SchemataWorkflow { public string OrderNumber { get; set; } = string.Empty; } public class OrderTransition : SchemataTransition { } public class OrderWorkflowResponse : WorkflowResponse { public string OrderNumber { get; set; } = string.Empty; public List AvailableTransitions { get; set; } = new(); } // Use workflow in controller public class OrderController : ControllerBase { private readonly IWorkflowService _workflowService; [HttpPost("orders/{id}/submit")] public async Task SubmitOrder(long id, CancellationToken ct) { var result = await _workflowService.TransitionAsync(id, "submit", ct); return Ok(result); } } ``` ``` -------------------------------- ### Configure OpenID Connect Authorization Server with Multiple Flows in C# Source: https://context7.com/cyprincess/schemata/llms.txt This C# code configures an ASP.NET Core application to act as an OpenID Connect Authorization Server. It sets up various OAuth 2.0 and OpenID Connect flows, including authorization code, refresh token, device, and client credentials flows. It also configures token introspection, end-session, revocation, and caching. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.ConfigureServices(services => { services.AddRepository(typeof(MyRepository<>)) .UseEntityFrameworkCore((sp, options) => options.UseSqlServer(schema.Configuration.GetConnectionString("Default"))); services.AddDistributedMemoryCache(); }); schema.UseRouting(); schema.UseSecurity(); schema.UseIdentity(); // Configure authorization server with multiple flows schema.UseAuthorization(options => { options.AddEphemeralEncryptionKey() .AddEphemeralSigningKey(); // Production: use AddEncryptionKey() and AddSigningKey() with certificates }) .UseCodeFlow() // OAuth 2.0 Authorization Code Flow .UseRefreshTokenFlow() // Refresh Token Flow .UseDeviceFlow() // Device Authorization Flow .UseClientCredentialsFlow() // Client Credentials Flow .UseIntrospection() // Token Introspection .UseEndSession() // OpenID Connect Logout .UseRevocation() // Token Revocation .UseCaching(); // Redis/Memory cache for tokens schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Authorization endpoints are automatically mapped: // GET /connect/authorize - Authorization endpoint // POST /connect/token - Token endpoint // POST /connect/device - Device authorization // POST /connect/introspect - Token introspection // POST /connect/revoke - Token revocation // GET /connect/logout - Logout endpoint ``` -------------------------------- ### Generate RESTful Endpoints with Google AIP Compliance (C#) Source: https://context7.com/cyprincess/schemata/llms.txt This C# code sets up a resource service in Schemata to generate RESTful endpoints adhering to Google AIP standards. It configures services, enables the resource service with HTTP mapping, and defines resources using attributes for automatic endpoint generation. ```csharp using Microsoft.AspNetCore.Builder; using Schemata.Abstractions.Resource; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.ConfigureServices(services => { services.AddRepository(typeof(MyRepository<>)) .UseEntityFrameworkCore((sp, options) => options.UseSqlServer(schema.Configuration.GetConnectionString("Default"))); }); schema.UseRouting(); // Enable resource service with HTTP mapping schema.UseResource() .MapHttp(); schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Define resource with attributes [Resource(entity: typeof(Product), request: typeof(ProductRequest), detail: typeof(ProductDetail), summary: typeof(ProductSummary))] [HttpResource("products")] // Maps to /api/products public class ProductResource { // Endpoints are automatically generated: // GET /api/products - List products // GET /api/products/{id} - Get product // POST /api/products - Create product // PUT /api/products/{id} - Update product // DELETE /api/products/{id} - Delete product // PATCH /api/products/{id} - Partial update } public class Product { public long Id { get; set; } public string Name { get; set; } = string.Empty; public decimal Price { get; set; } public DateTime CreateTime { get; set; } } public class ProductRequest { public string Name { get; set; } = string.Empty; public decimal Price { get; set; } } public class ProductDetail { public long Id { get; set; } public string Name { get; set; } = string.Empty; public decimal Price { get; set; } public DateTime CreateTime { get; set; } } public class ProductSummary { public long Id { get; set; } public string Name { get; set; } = string.Empty; } ``` -------------------------------- ### Configure Object Mapping with Mapster in C# Source: https://context7.com/cyprincess/schemata/llms.txt This C# code demonstrates how to configure object mapping using the Mapster library within an ASP.NET Core application. It shows how to define custom mappings between entities and DTOs, including transformations, conditional mapping, and ignoring fields. ```csharp using Microsoft.AspNetCore.Builder; using Schemata.Mapping.Skeleton; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.UseRouting(); // Configure Mapster with custom mappings schema.UseMapster() .Map(map => { map.For(d => d.DisplayName).From(s => s.FirstName + " " + s.LastName); map.For(d => d.Age).From(s => s.BirthDate).With((s, d) => DateTime.Now.Year - s.BirthDate.Year); map.For(d => d.Email).From(s => s.EmailAddress); map.For(d => d.InternalId).Ignore(); }); schema.UseControllers(); }); var app = builder.Build(); app.Run(); // Use mapper in services public class UserService { private readonly ISimpleMapper _mapper; public UserService(ISimpleMapper mapper) { _mapper = mapper; } public async Task GetUser(int id) { var entity = await _repository.GetAsync(id); return _mapper.Map(entity); } public async Task> GetUsers() { var entities = await _repository.ListAsync(); return _mapper.Map>(entities); } } ``` -------------------------------- ### Configure Advanced Object Mapping with Conditional Logic in C# Source: https://context7.com/cyprincess/schemata/llms.txt This C# code snippet illustrates advanced object mapping with Mapster, focusing on conditional field mapping. It demonstrates how to map fields, ignore them based on specific conditions, and perform complex transformations for DTO creation within an ASP.NET Core application. ```csharp using Microsoft.AspNetCore.Builder; var builder = WebApplication.CreateBuilder(args) .UseSchemata(schema => { schema.UseMapster() .Map(map => { // Basic field mapping map.For(d => d.Name).From(s => s.ProductName); map.For(d => d.Price).From(s => s.UnitPrice); // Conditional mapping - ignore if condition is true map.For(d => d.Discount) .From(s => s.DiscountPercent) .Ignore((s, d) => s.DiscountPercent <= 0); // Ignore field completely map.For(d => d.InternalCode).Ignore(); // Complex transformation map.For(d => d.Category) .From(s => s.CategoryId.ToString()); }); schema.UseControllers(); }); var app = builder.Build(); app.Run(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.