### Set up local development environment with bash Source: https://context7_llms Commands to clone the aspire.dev repository, install dependencies, and start the development server. This setup is necessary for contributing to the project. ```bash git clone https://github.com/microsoft/aspire.dev.git cd aspire.dev npm install npm run dev ``` ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Aspire CLI Version Output Example Source: https://aspire.dev/get-started/install-cli An example of the output you should expect after successfully running the `aspire --version` command. This output confirms the installation and indicates the specific version of the Aspire CLI installed on your system. The `+{commitSHA}` part is specific to pre-release versions. ```text 13.0.0+{commitSHA} ``` -------------------------------- ### Basic WebApplication Setup with Endpoint Source: https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis Shows minimal WebApplication setup with a simple endpoint configuration. Demonstrates creating WebApplication instance, mapping a GET endpoint to root path, and running the application. ```csharp var app = WebApplication.Create(args); var message = app.Configuration["HelloKey"] ?? "Config failed!"; app.MapGet("/", () => message); app.Run(); ``` -------------------------------- ### Manage Installation Modal and Settings (JavaScript) Source: https://aspire.dev/get-started/github-codespaces Handles the display and behavior of an installation modal, including selecting build quality (release, staging, dev) and persisting the choice in local storage. Also manages theme selection, keyboard layout pickers, and language selection. ```javascript const m="aspire-install-channel";function u(t){const e=document.getElementById("install-cli-modal");if(e){e.querySelectorAll(".code-wrapper, .quality-aside").forEach(n=>{const a=n.getAttribute("data-version")||n.getAttribute("data-quality");n.style.display=a===t?"block":"none"});try{localStorage.setItem(m,t)}catch{}}}function y(){try{const t=localStorage.getItem(m);if(t==="release"||t==="staging"||t==="dev")return t}catch{}return"release"}function s(){const t=document.getElementById("install-cli-modal");if(!t)return;const e=t.querySelector("#version-select"),n=t.querySelector(".select-icon"),a=document.querySelector("[data-open-install-modal]"),l=t.querySelector("[data-close-modal]");e&&(e.addEventListener("change",o=>{const r=o.target.value;u(r),n?.classList.remove("rotated")}),e.addEventListener("mousedown",()=>n?.classList.add("rotated")),(e.parentElement??e).addEventListener("blur",()=>n?.classList.remove("rotated"))),a&&a.addEventListener("click",o=>{o.preventDefault();const g=document.querySelector("starlight-menu-button button")?.getAttribute("aria-expanded")==="true";if(window.innerWidth<800||g){window.location.assign("/get-started/install-cli/");return}t.showModal();const d=a.getBoundingClientRect(),i=t.querySelector(".modal-content");if(i&&(i.style.position="",i.style.top="",i.style.right="",window.innerWidth>=1152&&(i.style.position="absolute",i.style.top=`${d.bottom+8}px`,i.style.right=`${window.innerWidth-d.right}px`)),e){const c=y();e.value=c,u(c)}}),l?.addEventListener("click",()=>t.close()),t.addEventListener("click",o=>{o.target===t&&t.close()}),t.addEventListener("keydown",o=>{o.key==="Escape"&&t.close()}),window.addEventListener("resize",()=>{window.innerWidth<800&&t.open&&t.close()})}document.addEventListener("click",t=>{if(!t.target.closest("[data-open-install-modal]"))return;t.preventDefault();const l=document.querySelector("starlight-menu-button button")?.getAttribute("aria-expanded")==="true";if(window.innerWidth<800||l){window.location.assign("/get-started/install-cli/");return}});document.readyState==="loading"?document.addEventListener("DOMContentLoaded",s):s();document.addEventListener("astro:page-load",s); ``` ```javascript StarlightKbdProvider.updateKbdPickers(typeof localStorage !== 'undefined' && localStorage.getItem('sl-kbd-type')) customElements.define("starlight-kbd-picker",class extends HTMLElement{ constructor(){ super(), this.querySelector("select")?.addEventListener("change",e=>{ if(e.currentTarget instanceof HTMLSelectElement){ StarlightKbdProvider.updateKbdPickers(e.currentTarget.value); for(const t of document.querySelectorAll("[data-sl-kbd-type]")) t.getAttribute("data-sl-kbd-type")===e.currentTarget.value ?t.setAttribute("data-sl-kbd-active", "") :t.removeAttribute("data-sl-kbd-active"); typeof localStorage<"u"&&localStorage.setItem("sl-kbd-type",e.currentTarget.value) } }) } }); ``` ```javascript const r="starlight-theme",o=e=>e==="auto"||e==="dark"||e==="light"?e:"auto",c=()=>o(typeof localStorage<"u"&&localStorage.getItem(r));function n(e){typeof localStorage<"u"&&localStorage.setItem(r,e==="light"||e==="dark"?e:"",) }const l=()=>matchMedia("(prefers-color-scheme: light)").matches?"light":"dark";function t(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e==="auto"?l():e,n(e)}matchMedia("(prefers-color-scheme: light)").addEventListener("change",()=>{c()==="auto"&&t("auto")});class s extends HTMLElement{constructor(){super(),t(c()),this.querySelector("select")?.addEventListener("change",a=>{a.currentTarget instanceof HTMLSelectElement&&t(o(a.currentTarget.value))})}}customElements.define("starlight-theme-select",s); ``` ```javascript class s extends HTMLElement{constructor(){super();const e=this.querySelector("select");e&&(e.addEventListener("change",t=>{t.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=t.currentTarget.value)}),window.addEventListener("pageshow",t=>{if(!t.persisted)return;const n=e.querySelector("option[selected]")?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}}customElements.define("starlight-lang-select",s); ``` -------------------------------- ### C# Application Setup and Basic GET Endpoints Source: https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis Configures WebApplication with in-memory DbContext and basic GET endpoints for listing and retrieving Todo items. Uses TodoItemDTO for output. Purpose: API bootstrapping. Dependencies: Microsoft.EntityFrameworkCore, TodoApi.Models. Limitations: In-memory DB not for production. ```csharp using Microsoft.EntityFrameworkCore; using TodoApi.Models; var builder = WebApplication.CreateBuilder(args); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddDbContext(opt => opt.UseInMemoryDatabase("TodoList")); var app = builder.Build(); app.MapGet("/todoitems", async (TodoDb db) => await db.Todos.Select(x => new TodoItemDTO(x)).ToListAsync()); app.MapGet("/todoitems/{id}", async (int Id, TodoDb Db) => await Db.Todos.FindAsync(Id) is Todo todo ? Results.Ok(new TodoItemDTO(todo)) : Results.NotFound()); // Remaining code removed for brevity. ``` -------------------------------- ### Aspire AppHost Equivalent for Volumes and Bind Mounts Source: https://aspire.dev/app-host/migrate-from-docker-compose Demonstrates the Aspire AppHost configuration in C# that mirrors the Docker Compose setup for volumes and bind mounts. It shows how to declare named volumes and apply bind mounts with read-only options. ```csharp var builder = DistributedApplication.CreateBuilder(args); // Create a named volume for sharing data var appData = builder.AddVolume("app-data"); var app = builder.AddContainer("app", "myapp", "latest") .WithVolume(appData, "/data") .WithBindMount("./config", "/app/config", isReadOnly: true); var worker = builder.AddContainer("worker", "myworker", "latest") .WithVolume(appData, "/shared"); builder.Build().Run(); ``` -------------------------------- ### Install Aspire CLI Source: https://aspire.dev/integrations/cloud/azure/azure-cosmos-db Instructions for installing the Aspire Command Line Interface (CLI). This is a prerequisite for using many of Aspire's features and integrations. The installation process typically involves using a package manager or a direct download. ```bash dotnet workload install aspire ``` -------------------------------- ### Manage Install CLI Modal and Theme/Keyboard Settings (JavaScript) Source: https://aspire.dev/integrations/databases/sql-server Handles the display and behavior of the installation modal, including version selection and persistence using local storage. It also manages theme and keyboard layout selections across the Starlight framework. ```javascript const m="aspire-install-channel";function u(t){const e=document.getElementById("install-cli-modal");if(e){e.querySelectorAll(".code-wrapper, .quality-aside").forEach(n=>{const a=n.getAttribute("data-version")||n.getAttribute("data-quality");n.style.display=a===t?"block":"none"});try{localStorage.setItem(m,t)}catch{}}}function y(){try{const t=localStorage.getItem(m);if(t==="release"||t==="staging"||t==="dev")return t}catch{}return"release"}function s(){const t=document.getElementById("install-cli-modal");if(!t)return;const e=t.querySelector("#version-select"),n=t.querySelector(".select-icon"),a=document.querySelector("[data-open-install-modal]"),l=t.querySelector("[data-close-modal]");e&&(e.addEventListener("change",o=>{const r=o.target.value;u(r),n?.classList.remove("rotated")}),e.addEventListener("mousedown",()=>n?.classList.add("rotated")), e.addEventListener("blur",()=>n?.classList.remove("rotated"))),a&&a.addEventListener("click",o=>{o.preventDefault();const g=document.querySelector("starlight-menu-button button")?.getAttribute("aria-expanded")==="true";if(window.innerWidth<800||g){window.location.assign("/get-started/install-cli/");return}t.showModal();const d=a.getBoundingClientRect(),i=t.querySelector(".modal-content");if(i&&(i.style.position="",i.style.top="",i.style.right="",window.innerWidth>=1152&&(i.style.position="absolute",i.style.top=`${d.bottom+8}px`,i.style.right=`${window.innerWidth-d.right}px`)),e){const c=y();e.value=c,u(c)}}),l?.addEventListener("click",()=>t.close()),t.addEventListener("click",o=>{o.target===t&&t.close()}),t.addEventListener("keydown",o=>{o.key==="Escape"&&t.close()}),window.addEventListener("resize",()=>{window.innerWidth<800&&t.open&&t.close()})}document.addEventListener("click",t=>{if(!t.target.closest("[data-open-install-modal]"))return;t.preventDefault();const l=document.querySelector("starlight-menu-button button")?.getAttribute("aria-expanded")==="true";if(window.innerWidth<800||l){window.location.assign("/get-started/install-cli/");return}});document.readyState==="loading"?document.addEventListener("DOMContentLoaded",s):s();document.addEventListener("astro:page-load",s); ``` ```javascript StarlightKbdProvider.updateKbdPickers(typeof localStorage !== 'undefined' && localStorage.getItem('sl-kbd-type')) customElements.define("starlight-kbd-picker",class extends HTMLElement{ constructor(){ super() this.querySelector("select")?.addEventListener("change", e => { if (e.currentTarget instanceof HTMLSelectElement) { StarlightKbdProvider.updateKbdPickers(e.currentTarget.value) for (const t of document.querySelectorAll("[data-sl-kbd-type]")) { t.getAttribute("data-sl-kbd-type") === e.currentTarget.value ? t.setAttribute("data-sl-kbd-active", "") : t.removeAttribute("data-sl-kbd-active") } typeof localStorage < "u" && localStorage.setItem("sl-kbd-type", e.currentTarget.value) } }) } }); ``` ```javascript const r="starlight-theme",o=e=>e==="auto"||e==="dark"||e==="light"?e:"auto",c=()=>o(typeof localStorage<"u"&&localStorage.getItem(r));function n(e){typeof localStorage<"u"&&localStorage.setItem(r,e==="light"||e==="dark"?e:"white")}const l=()=>matchMedia("(prefers-color-scheme: light)").matches?"light":"dark";function t(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e==="auto"?l():e,n(e)}matchMedia("(prefers-color-scheme: light)").addEventListener("change",()=>{ c()==="auto"&&t("auto")});class s extends HTMLElement{ constructor(){ super() t(c()) this.querySelector("select")?.addEventListener("change", a => { a.currentTarget instanceof HTMLSelectElement && t(o(a.currentTarget.value)) }) } } customElements.define("starlight-theme-select",s); ``` ```javascript class s extends HTMLElement{ constructor(){ super() const e=this.querySelector("select") e && ( e.addEventListener("change", t => { t.currentTarget instanceof HTMLSelectElement && (window.location.pathname = t.currentTarget.value) }), window.addEventListener("pageshow", t => { if (!t.persisted) return const n = e.querySelector("option\[selected\]")?.index n !== e.selectedIndex && (e.selectedIndex = n ?? 0) }) ) } } customElements.define("starlight-lang-select",s); ``` -------------------------------- ### Creating a New Aspire Project Source: https://aspire.dev/app-host/migrate-from-docker-compose Command to generate a new .NET Aspire starter project. This is the initial step in creating an Aspire application host. ```bash aspire new aspire-starter -o MyApp ``` -------------------------------- ### Download and Install Aspire LLM with Single Command (Bash) Source: https://aspire.dev/reference/cli/install-script This command downloads and installs the Aspire LLM development tools in a single step using Bash. It pipes the output of `curl` directly to `bash`, executing the installation script and skipping PATH modification. This is a convenient option for quick setups. ```bash curl -fsSL https://aspire.dev/install.sh | bash -s -- --skip-path ``` -------------------------------- ### Integrate Telemetry Configuration into FastAPI Application Source: https://aspire.dev/dashboard/standalone-for-python Updates the main FastAPI application file (`main.py`) to include the newly configured telemetry setup. This version of `main.py` also includes example endpoints for testing. ```python import logging from fastapi import FastAPI from telemetry import configure_telemetry logging.basicConfig(level=logging.INFO) app = FastAPI() # Configure telemetry for standalone dashboard tracer = configure_telemetry(app, service_name="weather-api") logger = logging.getLogger(__name__) # Example endpoints (replace or extend these based on your application needs) @app.get("/") async def root(): logger.info("Root endpoint called") return {"message": "Hello from FastAPI with Aspire dashboard!"} @app.get("/health") async def health(): logger.info("Health check called") return {"status": "healthy"} @app.get("/simulate-error") async def simulate_error(): logger.warning("This is a simulated warning.") logger.error("This is a simulated error.") return {"message": "Simulated warning and error logs generated"} ``` -------------------------------- ### Test Support Ticket API Endpoint Source: https://aspire.dev/integrations/databases/efcore/migrations Example HTTP request to test the /api/SupportTickets/1 endpoint of the Support Ticket API. This verifies the API's functionality after setup. ```http GET /api/SupportTickets/1 HTTP/1.1 Host: example.com Accept: application/json ``` -------------------------------- ### Start Aspire MCP Server with Options Source: https://aspire.dev/reference/cli/commands/aspire-mcp-start Demonstrates starting the Aspire MCP server with common command-line options. The --help option displays usage information, while --debug enables detailed logging. The --wait-for-debugger option pauses execution until a debugger is attached. ```bash aspire mcp start -?, -h, --help ``` ```bash aspire mcp start -d, --debug ``` ```bash aspire mcp start --wait-for-debugger ``` -------------------------------- ### Run Aspire Dashboard using Docker Source: https://aspire.dev/dashboard/standalone-for-python Starts the Aspire dashboard as a Docker container, exposing necessary ports for access and telemetry ingestion. The key for accessing the dashboard is displayed in the Docker logs. ```shell docker run --rm -it -p 18888:18888 -p 4317:18889 --name aspire-dashboard mcr.microsoft.com/dotnet/aspire-dashboard:latest ``` -------------------------------- ### Configuration: Use Inline Delegates Source: https://aspire.dev/integrations/databases/sql-server Configures SQL Server client options inline by passing an Action delegate to the AddSqlServerClient method, for example, to disable health checks directly in the code. ```APIDOC ## POST /api/users ### Description Configures SQL Server client options inline by passing an `Action` delegate to the `AddSqlServerClient` method, for example, to disable health checks directly in the code. ### Method POST ### Endpoint `/api/users` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **connectionName** (string) - Required - The name of the SQL Server connection. - **settings** (object) - Required - An object defining the settings to configure inline. - **DisableHealthChecks** (boolean) - Whether to disable health checks. ### Request Example ```json { "connectionName": "database", "settings": { "DisableHealthChecks": true } } ``` ### Response #### Success Response (200) - **message** (string) - A success message indicating the client was configured using inline delegates. #### Response Example ```json { "message": "SQL Server client configured via inline delegates." } ``` ``` -------------------------------- ### WebApplicationBuilder Environment and Path Configuration Source: https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis Shows how to configure content root, application name, environment, and web root path using WebApplicationOptions. Demonstrates initialization with custom settings for staging environment and custom web root directory. ```csharp var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args, ApplicationName = typeof(Program).Assembly.FullName, ContentRootPath = Directory.GetCurrentDirectory(), EnvironmentName = Environments.Staging, WebRootPath = "customwwwroot" }); Console.WriteLine($"Application Name: {builder.Environment.ApplicationName}"); Console.WriteLine($"Environment Name: {builder.Environment.EnvironmentName}"); Console.WriteLine($"ContentRoot Path: {builder.Environment.ContentRootPath}"); Console.WriteLine($"WebRootPath: {builder.Environment.WebRootPath}"); var app = builder.Build(); ``` -------------------------------- ### Cosmos DB Connection String Configuration in appsettings.json Source: https://aspire.dev/integrations/cloud/azure/azure-cosmos-db An example of how to define a Cosmos DB connection string within the `ConnectionStrings` section of `appsettings.json`. The `CosmosConnection` name used here corresponds to the name passed to `AddCosmosDbContext`. ```json { "ConnectionStrings": { "CosmosConnection": "AccountEndpoint=https://{account_name}.documents.azure.com:443/;AccountKey={account_key};" } } ``` -------------------------------- ### Create WebApplication without Explicit WebApplicationBuilder Source: https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis This C# code demonstrates creating a WebApplication instance directly using `WebApplication.Create(args)`. This method initializes the application with preconfigured defaults, simplifying the setup compared to using `WebApplicationBuilder`. It then maps a 'Hello World!' GET route and runs the application. ```csharp var app = WebApplication.Create(args); app.MapGet("/", () => "Hello World!"); app.Run(); ``` -------------------------------- ### Docker Compose Volumes and Bind Mounts Source: https://aspire.dev/app-host/migrate-from-docker-compose Example of defining custom volumes and bind mounts in a Docker Compose file. It showcases named volumes for data sharing and bind mounts for configuration, including read-only access. ```yaml version: '3.8' services: app: image: myapp:latest volumes: - app_data:/data - ./config:/app/config:ro worker: image: myworker:latest volumes: - app_data:/shared volumes: app_data: ``` -------------------------------- ### Add Database, API, and Frontend with References (C#) Source: https://aspire.dev/ Sets up an AppHost with a PostgreSQL database, an API service, and a Vite frontend. The API references the database, and the frontend references the API, establishing a service dependency chain. ```csharp var builder = DistributedApplication.CreateBuilder(args); // Add database var postgres = builder.AddPostgres("db") .AddDatabase("appdata"); // Add API service and reference the database var api = builder.AddProject("api", "../api/ApiService.csproj") .WithReference(postgres); // Add frontend service and reference the API var frontend = builder.AddViteApp("frontend", "../frontend") .WithHttpEndpoint(env: "PORT") .WithReference(api); builder.Build().Run(); ``` -------------------------------- ### Configure Cosmos DB Tracing via appsettings.json Source: https://aspire.dev/integrations/cloud/azure/azure-cosmos-db An example of disabling tracing for the Entity Framework Core Cosmos DB integration using configuration settings. This is done by setting `DisableTracing` to `true` within the `Aspire.Microsoft.EntityFrameworkCore.Cosmos` section of `appsettings.json`. ```json { "Aspire": { "Microsoft": { "EntityFrameworkCore": { "Cosmos": { "DisableTracing": true } } } } } ``` -------------------------------- ### Entity Framework Core Migrations Example (C#) Source: https://aspire.dev/integrations/frameworks/rust Demonstrates how to apply migrations for Entity Framework Core. This typically involves using the .NET CLI or Package Manager Console to execute migration commands against a database. ```csharp dotnet ef migrations add InitialCreate dotnet ef database update ``` -------------------------------- ### Ensuring Service Startup Order with WaitFor in Aspire AppHost Source: https://aspire.dev/app-host/migrate-from-docker-compose To guarantee that a service starts only after its dependencies are ready, use the `WaitFor()` method in your AppHost configuration. This is crucial for applications where the startup order impacts functionality, as `WithReference()` only handles service discovery. ```csharp var api = builder.AddProject("api") .WithReference(database) // Service discovery .WaitFor(database); // Startup ordering ``` -------------------------------- ### Create WebApplication Instance Source: https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis Illustrates different ways to create a `WebApplication` instance, either by explicitly creating a `WebApplicationBuilder` first or by using the `WebApplication.Create()` method, which initializes with preconfigured defaults. ```C# var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run(); ``` ```C# var app = WebApplication.Create(args); app.MapGet("/", () => "Hello World!"); app.Run(); ``` -------------------------------- ### Create Python Starter Template with Aspire CLI Source: https://context7_llms Demonstrates how to create a new full-stack Python starter template using the Aspire CLI. This template includes a FastAPI backend, Vite + React frontend, OpenTelemetry, and optional Redis caching. ```bash aspire new aspire-py-starter ``` -------------------------------- ### Build Basic Resource Model in Aspire using C# Source: https://context7_llms This C# code establishes a fundamental AppHost setup in Aspire, defining a resource model with PostgreSQL database, an API project, and an NPM web app, using references to manage dependencies. It leverages Aspire's helper methods for port allocation, environment variables, and startup order, requiring the Aspire framework and no additional inputs beyond project references. ```C# var builder = DistributedApplication.CreateBuilder(args); var db = builder.AddPostgres("pg").AddDatabase("appdata"); var api = builder.AddProject("api").WithReference(db); var web = builder.AddNpmApp("web", "../web").WithReference(api); builder.Build().Run(); ``` -------------------------------- ### Configuring Custom Container Health Checks in Aspire AppHost Source: https://aspire.dev/app-host/migrate-from-docker-compose For custom container health checks, utilize the `WithHealthCheck()` method. This allows you to define the executable, arguments, and timing parameters (interval, timeout, start period) for Aspire to monitor the health of non-HTTP services. ```csharp var rabbit = builder.AddContainer("rabbitmq", "rabbitmq", "4.1.4-management-alpine") .WithHealthCheck("rabbitmqctl", ["ping"], interval: TimeSpan.FromSeconds(30), timeout: TimeSpan.FromSeconds(10), startPeriod: TimeSpan.FromSeconds(10)); ``` -------------------------------- ### Install Bun Packages Before Running Source: https://aspire.dev/integrations/frameworks/bun-apps Shows how to ensure that all necessary Bun packages are installed before the Bun application starts. This is achieved by chaining the `WithBunPackageInstaller()` method after `AddBunApp`, which automatically runs `bun install`. ```csharp var builder = DistributedApplication.CreateBuilder(args); var bunApp = builder.AddBunApp("bun-api", "../bun-app") .WithBunPackageInstaller() .WithHttpEndpoint(port: 3000, env: "PORT"); // After adding all resources, run the app... ``` -------------------------------- ### Aspire CLI Publish Examples Source: https://aspire.dev/reference/cli/commands/aspire-publish These examples demonstrate how to use the 'aspire publish' command. They cover publishing the current directory's AppHost projects, publishing a specific project, and publishing a project with custom arguments. ```bash aspire publish aspire publish --project './projects/apphost/orchestration.AppHost.csproj' aspire publish --project './projects/apphost/orchestration.AppHost.csproj' -- -fast ``` -------------------------------- ### Basic ASP.NET Core Minimal API Setup Source: https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis Provides the fundamental code structure for an ASP.NET Core Minimal API application, generated by the `dotnet new web` command or the Empty Web template in Visual Studio. It includes the `WebApplicationBuilder`, `WebApplication`, and a simple MapGet endpoint. ```csharp var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run(); ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://aspire.dev/community/contributor-guide Installs project dependencies using the pnpm package manager. Ensure Node.js and pnpm are installed beforehand. This command should be run after navigating into the cloned aspire.dev directory. ```bash pnpm install ``` -------------------------------- ### AddNodeApp Migration Examples (C#) Source: https://aspire.dev/whats-new/aspire-13 Provides examples of migrating AddNodeApp configurations in Aspire 13.0. Demonstrates both direct script path configuration and using package.json scripts with package manager integrations. ```csharp // Before (9.x) var app = builder.AddNodeApp("frontend", "../frontend/server.js", "../frontend"); // After (13.0) var app = builder.AddNodeApp("frontend", "../frontend", "server.js"); // Or use package.json script var app = builder.AddNodeApp("frontend", "../frontend", "server.js") .WithNpm() .WithRunScript("dev"); ``` -------------------------------- ### Install OpenTelemetry Packages for FastAPI and HTTPLib Source: https://aspire.dev/dashboard/standalone-for-python Installs essential OpenTelemetry packages required for instrumenting FastAPI applications and HTTP client requests (httpx). These packages enable the collection of tracing and metrics data. ```shell uv add opentelemetry-instrumentation-fastapi opentelemetry-instrumentation-httpx ``` -------------------------------- ### Install Project Dependencies with npm Source: https://aspire.dev/community/contributor-guide Installs project dependencies using the npm package manager. This is an alternative to using pnpm. Ensure Node.js is installed beforehand. Run this command after navigating into the cloned aspire.dev directory. ```bash npm install ``` -------------------------------- ### Aspire Resource Optional Wiring Examples Source: https://context7_llms Illustrates common optional wiring configurations for Aspire resources using fluent extension methods. Covers setting up endpoints, health checks, container images, entrypoints, arguments, environment variables, and event subscriptions. ```csharp // Endpoints: .WithEndpoint(port: hostPort, targetPort: containerPort, name: endpointName) // Health checks: .WithHealthCheck(healthCheckKey) // Container images / registries: .WithImage(imageName, imageTag) .WithImageRegistry(registryUrl) // Entrypoint and args: .WithEntrypoint("/bin/sh") .WithArgs(context => { /* build args */ return Task.CompletedTask; }) // Environment variables: .WithEnvironment(context => new("ENV_VAR", valueProvider)) // Event subscriptions: builder.Eventing.Subscribe(resource, handler); ``` -------------------------------- ### Install Aspire CLI on macOS/Linux (curl) Source: https://aspire.dev/dashboard/standalone-for-python Installs the Aspire CLI on macOS or Linux using curl to download and execute a script. This method allows for specifying the build quality, with 'staging' and 'dev' options for prerelease versions. ```bash curl -Ls https://aspire.dev/install.sh | sh ``` ```bash sh <(curl -Ls https://aspire.dev/install.sh) -Quality staging ``` ```bash sh <(curl -Ls https://aspire.dev/install.sh) -Quality dev ``` -------------------------------- ### Configure Qdrant Client with Configuration Providers Source: https://aspire.dev/integrations/databases/qdrant Set up the Qdrant client by leveraging configuration providers, such as appsettings.json. This method allows for structured configuration of the client's endpoint and key within the application's settings. ```json { "Aspire": { "Qdrant": { "Client": { "Endpoint": "http://localhost:6334/", "Key": "123456!@#$%" } } } } ``` -------------------------------- ### Manage Sidebar State with JavaScript Source: https://aspire.dev/app-host/migrate-from-docker-compose This JavaScript code manages the state of a sidebar component, likely for a web application. It uses sessionStorage to persist the open state of sidebar details and the scroll position. The code includes functions to get and set the sidebar state, and event listeners for visibility changes and page hiding to ensure state is saved. ```javascript const a=document.getElementById("starlight\_\_sidebar"),n=a?.querySelector("sl-sidebar-state-persist"),o="sl-sidebar-state",i=()=>{ let t=[] const e=n?.dataset.hash||"" try{ const s=sessionStorage.getItem(o), r=JSON.parse(s||"{}") Array.isArray(r.open)&&r.hash===e&&(t=r.open) }catch{} return{hash:e,open:t,scroll:a?.scrollTop||0} }, c=t=>{ try{ sessionStorage.setItem(o,JSON.stringify(t)) }catch{} }, d=()=>c(i()), l=(t,e)=>{ const s=i() s.open[e]=t, c(s) }; n?.addEventListener("click",t=>{ if(!(t.target instanceof Element))return const e=t.target.closest("summary")?.closest("details") if(!e)return const s=e.querySelector("sl-sidebar-restore") const r=parseInt(s?.dataset.index||"",10) isNaN(r)||l(!e.open,r) }); addEventListener("visibilitychange",()=>{ document.visibilityState==="hidden"&&d() }); addEventListener("pageHide",d) ``` -------------------------------- ### Combine API, Custom Container, and Database (C#) Source: https://aspire.dev/ This comprehensive snippet demonstrates setting up an Azure PostgreSQL database, an API service that references and waits for the database, and a custom container deployed to Kubernetes. It illustrates dependency management and deployment configurations. ```csharp var postgres = builder.AddAzurePostgresFlexibleServer("db") .AddDatabase("appdata") .WithDataVolume() .RunAsContainer(); var api = builder.AddProject("api", "../api/ApiService.csproj") .WithReference(postgres) .WaitFor(postgres) .PublishAsAzureContainerApp(); var customContainer = builder.AddContainer("mycustomcontainer", "myregistry/myapp", "latest") .WithHttpEndpoint(targetPort: 8080) .PublishAsKubernetes(); ``` -------------------------------- ### Initialize new Aspire solution Source: https://context7_llms Initializes a new Aspire solution interactively with automatic setup of AppHost, project discovery, and configuration. Does not add resources like databases or caches. ```bash # Initialize a new Aspire solution - interactive prompts guide you through setup aspire init ``` -------------------------------- ### Run Azure Cosmos DB Emulator Locally Source: https://aspire.dev/integrations/cloud/azure/azure-cosmos-db This C# code snippet shows how to configure an Azure Cosmos DB resource to run locally using the Azure Cosmos DB Emulator. The `RunAsEmulator()` method is chained to the resource builder, which automatically provisions and starts a local emulator container accessible by the Aspire application. This is useful for local development and testing. ```csharp var builder = DistributedApplication.CreateBuilder(args); var cosmos = builder.AddAzureCosmosDB("cosmos-db") .RunAsEmulator(); // After adding all resources, run the app... ``` -------------------------------- ### Run Aspire Deployment Pipeline Steps Source: https://aspire.dev/whats-new/aspire-13 Provides examples of using the 'aspire do' command to execute various pipeline steps like 'deploy' and 'publish'. It shows how to specify output paths, target environments, and logging levels for detailed troubleshooting. ```bash # Runs all steps necessary to deploy the app aspire do deploy # Custom output path for publishing aspire do publish --output-path ./artifacts # Target specific environment for deployment aspire do deploy --environment Production # Verbose logging for troubleshooting aspire do deploy --log-level debug ``` -------------------------------- ### Retrieve SearchClient and Get Document Count (C#) Source: https://aspire.dev/integrations/cloud/azure/azure-ai-search Demonstrates how to obtain a SearchClient from an injected SearchIndexClient to perform queries. This example shows how to get the document count for a specific index. ```csharp public class ExampleService(SearchIndexClient indexClient){ public async Task GetDocumentCountAsync( string indexName, CancellationToken cancellationToken) { var searchClient = indexClient.GetSearchClient(indexName); var documentCountResponse = await searchClient.GetDocumentCountAsync( cancellationToken); return documentCountResponse.Value; } } ``` -------------------------------- ### Add Postgres, API, and Custom Container Source: https://context7_llms Sets up a PostgreSQL database, an API service referencing the database, and a custom container with an HTTP endpoint. This demonstrates a multi-component application setup. ```csharp var builder = DistributedApplication.CreateBuilder(args); // Add database var postgres = builder.AddPostgres("db") .AddDatabase("appdata"); // Add API service and reference the database var api = builder.AddProject("api", "../api/ApiService.csproj") .WithReference(postgres); // Add custom container var customContainer = builder.AddContainer("mycustomcontainer", "myregistry/myapp", "latest") .WithHttpEndpoint(targetPort: 8080); builder.Build().Run(); ``` -------------------------------- ### Clone Sample App from GitHub Source: https://aspire.dev/integrations/databases/efcore/migrations This command clones the sample Azure App Service application from GitHub, which is used throughout the tutorial to demonstrate EF Core migrations. ```bash git clone https://github.com/MicrosoftDocs/aspire-docs-samples/ ``` -------------------------------- ### Manage Installation Modal and Settings (JavaScript) Source: https://aspire.dev/integrations/cloud/azure/configure-container-apps Handles the display and behavior of the installation modal, including selecting build quality and managing theme and language preferences using local storage. ```javascript const m="aspire-install-channel";function u(t){const e=document.getElementById("install-cli-modal");if(e){e.querySelectorAll(".code-wrapper, .quality-aside").forEach(n=>{const a=n.getAttribute("data-version")||n.getAttribute("data-quality");n.style.display=a===t?"block":"none"});try{localStorage.setItem(m,t)}catch{}}}function y(){try{const t=localStorage.getItem(m);if(t==="release"||t==="staging"||t==="dev")return t}catch{}return"release"}function s(){const t=document.getElementById("install-cli-modal");if(!t)return;const e=t.querySelector("#version-select"),n=t.querySelector(".select-icon"),a=document.querySelector("[data-open-install-modal]"),l=t.querySelector("[data-close-modal]");e&&(e.addEventListener("change",o=>{const r=o.target.value;u(r),n?.classList.remove("rotated")}),e.addEventListener("mousedown",()=>n?.classList.add("rotated")),e.addEventListener("blur",()=>n?.classList.remove("rotated"))),a&&a.addEventListener("click",o=>{o.preventDefault();const g=document.querySelector("starlight-menu-button button")?.getAttribute("aria-expanded")==="true";if(window.innerWidth<800||g){window.location.assign("/get-started/install-cli/");return}t.showModal();const d=a.getBoundingClientRect(),i=t.querySelector(".modal-content");if(i&&(i.style.position="",i.style.top="",i.style.right="",window.innerWidth>=1152&&(i.style.position="absolute",i.style.top=`${d.bottom+8}px`,i.style.right=`${window.innerWidth-d.right}px`)),e){const c=y();e.value=c,u(c)}}),l?.addEventListener("click",()=>t.close()),t.addEventListener("click",o=>{o.target===t&&t.close()}),t.addEventListener("keydown",o=>{o.key==="Escape"&&t.close()}),window.addEventListener("resize",()=>{window.innerWidth<800&&t.open&&t.close()})}document.addEventListener("click",t=>{if(!t.target.closest("[data-open-install-modal]"))return;t.preventDefault();const l=document.querySelector("starlight-menu-button button")?.getAttribute("aria-expanded")==="true";if(window.innerWidth<800||l){window.location.assign("/get-started/install-cli/");return}});document.readyState==="loading"?document.addEventListener("DOMContentLoaded",s):s();document.addEventListener("astro:page-load",s); ``` ```javascript customElements.define("starlight-kbd-picker",class extends HTMLElement{constructor(){super(),this.querySelector("select")?.addEventListener("change",e=>{if(e.currentTarget instanceof HTMLSelectElement){StarlightKbdProvider.updateKbdPickers(e.currentTarget.value);for(const t of document.querySelectorAll("[data-sl-kbd-type]"))t.getAttribute("data-sl-kbd-type")===e.currentTarget.value?t.setAttribute("data-sl-kbd-active",""):t.removeAttribute("data-sl-kbd-active");typeof localStorage<"u"&&localStorage.setItem("sl-kbd-type",e.currentTarget.value)}})}}); ``` ```javascript const r="starlight-theme",o=e=>e==="auto"||e==="dark"||e==="light"?e:"auto";const c=()=>o(typeof localStorage<"u"&&localStorage.getItem(r));function n(e){typeof localStorage<"u"&&localStorage.setItem(r,e==="light"||e==="dark"?e:""}const l=()=>matchMedia("(prefers-color-scheme: light)").matches?"light":"dark";function t(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e==="auto"?l():e,n(e)}matchMedia("(prefers-color-scheme: light)").addEventListener("change",()=>{c()==="auto"&&t("auto")});class s extends HTMLElement{constructor(){super(),t(c()),this.querySelector("select")?.addEventListener("change",a=>{a.currentTarget instanceof HTMLSelectElement&&t(o(a.currentTarget.value))})}}customElements.define("starlight-theme-select",s); ``` ```javascript class s extends HTMLElement{constructor(){super();const e=this.querySelector("select");e&&(e.addEventListener("change",t=>{t.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=t.currentTarget.value)}),window.addEventListener("pageshow",t=>{if(!t.persisted)return;const n=e.querySelector("option[selected]")?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}}customElements.define("starlight-lang-select",s); ``` -------------------------------- ### Install Cosmos DB EF Core Package with .NET CLI Source: https://aspire.dev/integrations/cloud/azure/azure-cosmos-db Installs the Aspire Microsoft Entity Framework Core Cosmos DB integration package using the .NET CLI. This is a prerequisite for using Cosmos DB with Entity Framework Core in an Aspire application. ```bash dotnet add package Aspire.Microsoft.EntityFrameworkCore.Cosmos ``` -------------------------------- ### Manage Aspire CLI Install Modal (JavaScript) Source: https://aspire.dev/architecture/resource-examples This JavaScript code manages the display and behavior of an installation modal for the Aspire CLI. It handles user selection of build quality, theme, keyboard type, and language. ```javascript const m="aspire-install-channel";function u(t){const e=document.getElementById("install-cli-modal");if(e){e.querySelectorAll(".code-wrapper, .quality-aside").forEach(n=>{const a=n.getAttribute("data-version")||n.getAttribute("data-quality");n.style.display=a===t?"block":"none"});try{localStorage.setItem(m,t)}catch{}}}function y(){try{const t=localStorage.getItem(m);if(t==="release"||t==="staging"||t==="dev")return t}catch{}return"release"}function s(){const t=document.getElementById("install-cli-modal");if(!t)return;const e=t.querySelector("#version-select"),n=t.querySelector(".select-icon"),a=document.querySelector("[data-open-install-modal]"),l=t.querySelector("[data-close-modal]");e&&(e.addEventListener("change",o=>{const r=o.target.value;u(r),n?.classList.remove("rotated")}),e.addEventListener("mousedown",()=>n?.classList.add("rotated")), e.addEventListener("blur",()=>n?.classList.remove("rotated"))),a&&a.addEventListener("click",o=>{o.preventDefault();const g=document.querySelector("starlight-menu-button button")?.getAttribute("aria-expanded")==="true";if(window.innerWidth<800||g){window.location.assign("/get-started/install-cli/");return}t.showModal();const d=a.getBoundingClientRect(),i=t.querySelector(".modal-content");if(i&&(i.style.position="",i.style.top="",i.style.right="",window.innerWidth>=1152&&(i.style.position="absolute",i.style.top=`${d.bottom+8}px`,i.style.right=`${window.innerWidth-d.right}px`)),e){const c=y();e.value=c,u(c)}}),l?.addEventListener("click",()=>t.close()),t.addEventListener("click",o=>{o.target===t&&t.close()}),t.addEventListener("keydown",o=>{o.key==="Escape"&&t.close()}),window.addEventListener("resize",()=>{window.innerWidth<800&&t.open&&t.close()})}document.addEventListener("click",t=>{if(!t.target.closest("[data-open-install-modal]"))return;t.preventDefault();const l=document.querySelector("starlight-menu-button button")?.getAttribute("aria-expanded")==="true";if(window.innerWidth<800||l){window.location.assign("/get-started/install-cli/");return}});document.readyState==="loading"?document.addEventListener("DOMContentLoaded",s):s();document.addEventListener("astro:page-load",s); ``` ```javascript Select keyboard type macOSWindowsLinux StarlightKbdProvider.updateKbdPickers(typeof localStorage !== 'undefined' && localStorage.getItem('sl-kbd-type')) customElements.define("starlight-kbd-picker",class extends HTMLElement{constructor(){super(),this.querySelector("select")?.addEventListener("change",e=>{if(e.currentTarget instanceof HTMLSelectElement){StarlightKbdProvider.updateKbdPickers(e.currentTarget.value);for(const t of document.querySelectorAll("[data-sl-kbd-type]"))t.getAttribute("data-sl-kbd-type")===e.currentTarget.value?t.setAttribute("data-sl-kbd-active",""):t.removeAttribute("data-sl-kbd-active");typeof localStorage<"u"&&localStorage.setItem("sl-kbd-type",e.currentTarget.value)}})}}); ``` ```javascript Select theme DarkLightAuto StarlightThemeProvider.updatePickers(); const r="starlight-theme",o=e=>e==="auto"||e==="dark"||e==="light"?e:"auto",c=()=>o(typeof localStorage<"u"&&localStorage.getItem(r));function n(e){typeof localStorage<"u"&&localStorage.setItem(r,e==="light"||e==="dark"?e:""}const l=()=>matchMedia("(prefers-color-scheme: light)").matches?"light":"dark";function t(e){StarlightThemeProvider.updatePickers(e),document.documentElement.dataset.theme=e==="auto"?l():e,n(e)}matchMedia("(prefers-color-scheme: light)").addEventListener("change",()=>{c()==="auto"&&t("auto")});class s extends HTMLElement{constructor(){super(),t(c()),this.querySelector("select")?.addEventListener("change",a=>{a.currentTarget instanceof HTMLSelectElement&&t(o(a.currentTarget.value))})}}customElements.define("starlight-theme-select",s); ``` ```javascript Select language EnglishDeutschEspañol日本語FrançaisItalianoBahasa Indonesia简体中文Português do BrasilPortuguês한국어TürkçeРусскийहिंदीDanskУкраїнська class s extends HTMLElement{constructor(){super();const e=this.querySelector("select");e&&(e.addEventListener("change",t=>{t.currentTarget instanceof HTMLSelectElement&&(window.location.pathname=t.currentTarget.value)}),window.addEventListener("pageshow",t=>{if(!t.persisted)return;const n=e.querySelector("option[selected]")?.index;n!==e.selectedIndex&&(e.selectedIndex=n??0)}))}}customElements.define("starlight-lang-select",s); ```