diff --git a/API.md b/API.md new file mode 100644 index 0000000..1ca045f --- /dev/null +++ b/API.md @@ -0,0 +1,274 @@ +# API Documentation + +This document provides detailed information about the Weather API endpoints. + +## Base URL + +When running in Codespaces or locally: +- **Development**: `https://localhost:8080` or forwarded Codespaces URL + +## API Endpoints + +### 1. Get Weather Forecast + +Retrieves a 5-day weather forecast. + +**Endpoint**: `GET /weatherforecast` + +**Parameters**: None + +**Response**: +```json +[ + { + "date": "2024-01-15", + "temperatureC": 10, + "temperatureF": 50, + "summary": "Cool" + }, + { + "date": "2024-01-16", + "temperatureC": 15, + "temperatureF": 59, + "summary": "Mild" + } +] +``` + +**Response Fields**: +- `date` (string): Date in ISO 8601 format (DateOnly) +- `temperatureC` (integer): Temperature in Celsius +- `temperatureF` (integer): Temperature in Fahrenheit (calculated) +- `summary` (string): Weather description + +**Example Request**: +```bash +curl https://localhost:8080/weatherforecast +``` + +**Possible Summaries**: +- Freezing +- Bracing +- Chilly +- Cool +- Mild +- Warm +- Balmy +- Hot +- Sweltering +- Scorching + +--- + +### 2. Get Sunset Time + +Retrieves the sunset time for a specific date. + +**Endpoint**: `GET /sunset` + +**Parameters**: +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| date | DateOnly | No | Today | Target date for sunset calculation | + +**Response**: +```json +{ + "date": "2024-01-15", + "sunsetTime": "18:30:00", + "formattedTime": "06:30 PM" +} +``` + +**Response Fields**: +- `date` (string): Date in ISO 8601 format +- `sunsetTime` (string): Sunset time in 24-hour format +- `formattedTime` (string): Sunset time in 12-hour format with AM/PM + +**Example Requests**: +```bash +# Get today's sunset +curl https://localhost:8080/sunset + +# Get sunset for a specific date +curl "https://localhost:8080/sunset?date=2024-06-21" +``` + +**Notes**: +- The sunset calculation is simplified and based on day of year +- Real-world applications should use astronomical calculations based on latitude and longitude +- The calculation simulates seasonal variation with ±2 hours around 6:00 PM base time + +--- + +### 3. Get Sunset Time Range + +Retrieves sunset times for a range of consecutive days. + +**Endpoint**: `GET /sunset/range` + +**Parameters**: +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| startDate | DateOnly | No | Today | Starting date for the range | +| days | integer | No | 7 | Number of days to calculate | + +**Response**: +```json +[ + { + "date": "2024-01-15", + "sunsetTime": "18:30:00", + "formattedTime": "06:30 PM" + }, + { + "date": "2024-01-16", + "sunsetTime": "18:31:00", + "formattedTime": "06:31 PM" + } +] +``` + +**Response Fields**: +- Array of `SunsetInfo` objects (same structure as single sunset endpoint) + +**Example Requests**: +```bash +# Get next 7 days of sunsets (default) +curl https://localhost:8080/sunset/range + +# Get next 14 days starting from today +curl "https://localhost:8080/sunset/range?days=14" + +# Get 10 days starting from a specific date +curl "https://localhost:8080/sunset/range?startDate=2024-06-01&days=10" +``` + +--- + +## Interactive API Documentation + +When running in development mode, you can access interactive API documentation: + +### Scalar API Reference +Navigate to `/scalar` in your browser to access the Scalar interactive API documentation. + +**Features**: +- **Interactive Testing**: Test API endpoints directly from the browser +- **Request/Response Examples**: See example requests and responses +- **Schema Documentation**: View detailed schema definitions +- **Try It Out**: Execute API calls with custom parameters + +**Example**: `https://localhost:8080/scalar` + +### OpenAPI Specification +The raw OpenAPI specification is available at `/openapi/v1.json` + +--- + +## Error Handling + +### HTTP Status Codes + +| Status Code | Description | +|-------------|-------------| +| 200 OK | Request successful | +| 400 Bad Request | Invalid parameters provided | +| 500 Internal Server Error | Server error occurred | + +### Error Response Format +```json +{ + "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", + "title": "Bad Request", + "status": 400, + "detail": "Invalid date format" +} +``` + +--- + +## Date Formats + +All date parameters accept ISO 8601 format: +- `YYYY-MM-DD` (e.g., `2024-01-15`) + +--- + +## CORS Configuration + +Currently, the API does not have CORS configured. If you need to call the API from a different origin in development, you'll need to add CORS middleware. + +--- + +## Rate Limiting + +This sample application does not implement rate limiting. For production use, consider implementing rate limiting to protect the API from abuse. + +--- + +## Authentication + +This sample application does not require authentication. For production use, consider implementing authentication using: +- JWT tokens +- OAuth 2.0 +- API keys + +--- + +## Versioning + +The current API does not have versioning. For production applications, consider implementing API versioning using: +- URL path versioning (e.g., `/v1/weatherforecast`) +- Header versioning +- Query parameter versioning + +--- + +## Client Examples + +### JavaScript/TypeScript +```javascript +// Fetch weather forecast +const response = await fetch('https://localhost:8080/weatherforecast'); +const weatherData = await response.json(); +console.log(weatherData); + +// Fetch sunset with parameters +const sunsetResponse = await fetch('https://localhost:8080/sunset?date=2024-06-21'); +const sunsetData = await sunsetResponse.json(); +console.log(sunsetData.formattedTime); +``` + +### C# (.NET) +```csharp +using var httpClient = new HttpClient(); +httpClient.BaseAddress = new Uri("https://localhost:8080"); + +// Fetch weather forecast +var weatherData = await httpClient.GetFromJsonAsync("/weatherforecast"); + +// Fetch sunset with parameters +var sunsetData = await httpClient.GetFromJsonAsync("/sunset?date=2024-06-21"); +``` + +### Python +```python +import requests + +# Fetch weather forecast +response = requests.get('https://localhost:8080/weatherforecast') +weather_data = response.json() + +# Fetch sunset with parameters +sunset_response = requests.get('https://localhost:8080/sunset', params={'date': '2024-06-21'}) +sunset_data = sunset_response.json() +``` + +--- + +## Additional Resources + +- [ASP.NET Core OpenAPI Documentation](https://learn.microsoft.com/aspnet/core/fundamentals/openapi/) +- [Scalar API Documentation Tool](https://scalar.com/) +- [OpenAPI Specification](https://swagger.io/specification/) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..2a71146 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,160 @@ +# Architecture + +This document describes the technical architecture of the .NET Codespaces sample application. + +## Overview + +The application consists of two main components: + +``` +┌─────────────────┐ ┌─────────────────┐ +│ │ │ │ +│ Frontend │────────▶│ Backend │ +│ (Blazor) │ HTTP │ (Web API) │ +│ Port: 8081 │ │ Port: 8080 │ +│ │ │ │ +└─────────────────┘ └─────────────────┘ +``` + +## Frontend Application + +### Technology Stack +- **Framework**: ASP.NET Core 9.0 +- **UI Framework**: Blazor Server-Side +- **Programming Language**: C# +- **Target Framework**: .NET 9.0 + +### Components + +#### Pages +- **FetchData.razor**: Main page that displays weather forecast data +- **Error.cshtml**: Error handling page +- **_Host.cshtml**: Blazor host page + +#### Data Services +- **WeatherForecastClient**: HTTP client service that fetches weather data from the backend API +- **WeatherForecast**: Data model for weather information + +### Configuration +- The frontend connects to the backend API using the `WEATHER_URL` environment variable +- Configured in `appsettings.json` and `appsettings.Development.json` + +## Backend Application + +### Technology Stack +- **Framework**: ASP.NET Core 9.0 Minimal APIs +- **API Documentation**: OpenAPI with Scalar UI +- **Programming Language**: C# +- **Target Framework**: .NET 9.0 + +### API Endpoints + +#### Weather Forecast Endpoints +1. **GET /weatherforecast** + - Returns 5-day weather forecast + - Response: Array of `WeatherForecast` objects + +2. **GET /sunset** + - Returns sunset time for a specific date + - Query Parameters: + - `date` (optional): Target date (defaults to today) + - Response: `SunsetInfo` object + +3. **GET /sunset/range** + - Returns sunset times for a range of days + - Query Parameters: + - `startDate` (optional): Starting date (defaults to today) + - `days` (optional): Number of days (default: 7) + - Response: Array of `SunsetInfo` objects + +### Data Models + +#### WeatherForecast +```csharp +record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) +{ + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); +} +``` + +#### SunsetInfo +```csharp +record SunsetInfo(DateOnly Date, TimeOnly SunsetTime) +{ + public string FormattedTime => SunsetTime.ToString("hh:mm tt"); +} +``` + +### Features +- **OpenAPI Integration**: Automatically generated API documentation +- **Scalar UI**: Interactive API documentation and testing interface (available at `/scalar`) +- **Codespaces Port Forwarding**: Custom OpenAPI document transformer to handle GitHub Codespaces port forwarding + +## Development Container + +### Base Image +- `mcr.microsoft.com/dotnet/sdk:9.0` + +### Features +- Docker-in-Docker +- GitHub CLI +- PowerShell +- Azure Developer CLI (azd) +- .NET Runtime 8.0 and ASP.NET Core 8.0 + +### VS Code Extensions +- Azure Pack +- GitHub Copilot +- GitHub Actions +- C# Dev Kit + +### Port Configuration +- **8080**: Backend API (Weather API) +- **8081**: Frontend Application (Blazor UI) + +## Build and Runtime + +### Build Process +The project uses standard .NET build tools: +- `dotnet build`: Compiles the application +- `dotnet publish`: Creates deployment artifacts +- `dotnet watch`: Enables hot reload during development + +### Launch Configuration +The VS Code launch configuration supports: +- Running frontend and backend independently +- **Run All**: Compound configuration to start both services simultaneously + +## Environment Variables + +### Frontend +- `WEATHER_URL`: Base URL for the backend API (required) +- `ASPNETCORE_ENVIRONMENT`: Environment setting (Development/Production) + +### Backend +- `ASPNETCORE_ENVIRONMENT`: Environment setting (Development/Production) + +## Dependencies + +### Backend Dependencies +- `Microsoft.AspNetCore.OpenApi` (v9.0.*) +- `Scalar.AspNetCore` (v2.0.*) + +### Frontend Dependencies +- Standard ASP.NET Core 9.0 libraries (no additional packages) + +## Security Considerations + +1. **HTTPS Redirection**: Both frontend and backend enforce HTTPS redirection +2. **Development Mode**: OpenAPI/Scalar endpoints are only available in Development environment +3. **Exception Handling**: Production environment uses exception handler middleware + +## Scalability Notes + +This is a sample application designed for learning and demonstration purposes. For production use, consider: +- Adding authentication and authorization +- Implementing caching strategies +- Adding database persistence +- Implementing proper logging and monitoring +- Using a reverse proxy (e.g., nginx, YARP) +- Containerizing the applications with Docker diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..055992f --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,45 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added +- Comprehensive documentation in Markdown format + - README.md - Enhanced main documentation with quick reference + - API.md - Detailed API endpoint documentation + - ARCHITECTURE.md - Technical architecture guide + - DEVELOPMENT.md - Development setup and workflow guide + - CONTRIBUTING.md - Contribution guidelines + - CHANGELOG.md - This changelog file + +## [1.0.0] - Initial Release + +### Added +- Backend Weather API built with ASP.NET Core 9.0 Minimal APIs + - GET /weatherforecast endpoint for 5-day weather forecast + - GET /sunset endpoint for sunset time calculation + - GET /sunset/range endpoint for multiple days sunset times +- Frontend Blazor Server-Side application + - Weather data display page + - Integration with backend API +- OpenAPI/Swagger integration +- Scalar interactive API documentation +- GitHub Codespaces configuration +- Dev Container support +- VS Code launch configurations for debugging +- Hot reload support for rapid development + +### Features +- .NET 9.0 framework +- Server-side Blazor UI +- RESTful API with OpenAPI specification +- Interactive API testing with Scalar +- Docker Dev Container support +- One-click GitHub Codespaces setup + +[unreleased]: https://github.com/github/dotnet-codespaces/compare/v1.0.0...HEAD +[1.0.0]: https://github.com/github/dotnet-codespaces/releases/tag/v1.0.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..dfc3720 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,290 @@ +# Contributing to .NET Codespaces + +Thank you for your interest in contributing to this project! This document provides guidelines and instructions for contributing. + +## Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## How Can I Contribute? + +### Reporting Bugs + +Before creating bug reports, please check the existing issues to avoid duplicates. When creating a bug report, include as many details as possible: + +- **Use a clear and descriptive title** +- **Describe the exact steps to reproduce the problem** +- **Provide specific examples** to demonstrate the steps +- **Describe the behavior you observed** and what you expected to see +- **Include screenshots** if relevant +- **Note your environment**: OS, .NET version, browser, etc. + +**Bug Report Template:** +```markdown +**Description:** +A clear description of the bug. + +**Steps to Reproduce:** +1. Go to '...' +2. Click on '...' +3. See error + +**Expected Behavior:** +What you expected to happen. + +**Actual Behavior:** +What actually happened. + +**Environment:** +- OS: [e.g., Windows 11, macOS 14, Ubuntu 22.04] +- .NET Version: [e.g., 9.0] +- Browser: [e.g., Chrome 120] +- Codespaces: [Yes/No] + +**Additional Context:** +Any other relevant information. +``` + +### Suggesting Enhancements + +Enhancement suggestions are tracked as GitHub issues. When creating an enhancement suggestion: + +- **Use a clear and descriptive title** +- **Provide a detailed description** of the suggested enhancement +- **Explain why this enhancement would be useful** +- **List any alternatives** you've considered + +**Enhancement Template:** +```markdown +**Is your feature request related to a problem?** +A clear description of the problem. + +**Describe the solution you'd like:** +A clear description of what you want to happen. + +**Describe alternatives you've considered:** +Any alternative solutions or features you've considered. + +**Additional context:** +Any other context or screenshots. +``` + +### Pull Requests + +We actively welcome your pull requests: + +1. **Fork the repository** and create your branch from `main` +2. **Make your changes** following the coding standards +3. **Test your changes** thoroughly +4. **Update documentation** if needed +5. **Write clear commit messages** +6. **Submit a pull request** + +## Development Process + +### Setting Up Your Development Environment + +1. **Fork and clone the repository:** + ```bash + git clone https://github.com/YOUR-USERNAME/dotnet-codespaces.git + cd dotnet-codespaces + ``` + +2. **Open in Codespaces or Dev Container** (recommended) + - Or install .NET 9.0 SDK for local development + +3. **Create a new branch:** + ```bash + git checkout -b feature/your-feature-name + ``` + +### Making Changes + +1. **Keep changes focused**: Each PR should address a single concern +2. **Follow existing code style**: Match the style of the surrounding code +3. **Write meaningful commit messages**: + ``` + Add sunset API endpoint + + - Implement GET /sunset endpoint + - Add sunset time calculation logic + - Update API documentation + ``` + +4. **Test your changes**: + - Manually test the application + - Ensure all existing functionality still works + - Test in both Codespaces and local environments if possible + +### Code Style Guidelines + +#### C# Code Style + +- Use **PascalCase** for class names, method names, and properties +- Use **camelCase** for local variables and parameters +- Use **descriptive names** that clearly indicate purpose +- Follow standard C# naming conventions +- Use **implicit typing** (`var`) when the type is obvious +- Keep methods **short and focused** (single responsibility) +- Add **XML documentation comments** for public APIs + +**Example:** +```csharp +/// +/// Calculates the sunset time for a given date. +/// +/// The target date. +/// The calculated sunset time. +public static TimeOnly CalculateSunsetTime(DateOnly date) +{ + // Implementation +} +``` + +#### Blazor/Razor Code Style + +- Use **PascalCase** for component names +- Keep components **focused and reusable** +- Use **code-behind** files for complex logic +- Follow **Blazor best practices** + +#### General Guidelines + +- **Use meaningful variable names**: Avoid single-letter names except for loop counters +- **Comment complex logic**: Explain why, not what +- **Keep files focused**: Each file should have a single, clear purpose +- **Avoid magic numbers**: Use named constants +- **Handle errors gracefully**: Add appropriate error handling + +### Commit Messages + +Write clear, concise commit messages: + +- **First line**: Short summary (50 chars or less) +- **Blank line** +- **Detailed description**: Explain what and why, not how +- **Reference issues**: Include issue numbers when applicable + +**Good commit message example:** +``` +Add sunset time calculation endpoint + +Implement a new API endpoint that calculates sunset times +based on the day of year. This provides a simplified +calculation for demonstration purposes. + +Fixes #123 +``` + +**Poor commit message example:** +``` +fix stuff +``` + +### Pull Request Process + +1. **Update documentation**: Ensure README, API.md, or other docs are updated +2. **Self-review**: Review your own PR before requesting reviews +3. **Request review**: Tag relevant maintainers +4. **Address feedback**: Respond to review comments promptly +5. **Keep PR updated**: Merge main branch if needed to resolve conflicts + +**Pull Request Template:** +```markdown +## Description +Brief description of changes. + +## Type of Change +- [ ] Bug fix +- [ ] New feature +- [ ] Documentation update +- [ ] Code refactoring + +## Testing +Describe how you tested your changes. + +## Checklist +- [ ] My code follows the style guidelines +- [ ] I have performed a self-review +- [ ] I have commented complex code +- [ ] I have updated documentation +- [ ] My changes generate no new warnings +- [ ] I have tested my changes +``` + +## Contributor License Agreement (CLA) + +This project welcomes contributions and suggestions. Most contributions require you to agree to a +Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us +the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide +a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions +provided by the bot. You will only need to do this once across all repos using our CLA. + +## Testing Guidelines + +### Manual Testing Checklist + +Before submitting a PR, verify: + +- [ ] Backend starts without errors +- [ ] Frontend starts without errors +- [ ] Frontend can connect to backend +- [ ] All API endpoints work correctly +- [ ] Scalar documentation is accessible +- [ ] No console errors in browser +- [ ] Application works in Codespaces +- [ ] Application works in Dev Container +- [ ] Application works in local development + +### Adding Tests + +While this sample project doesn't currently include automated tests, we welcome contributions that add: + +- Unit tests using xUnit +- Integration tests +- End-to-end tests + +## Documentation + +Good documentation is essential: + +- **Update README.md** for user-facing changes +- **Update API.md** for API changes +- **Update DEVELOPMENT.md** for development process changes +- **Update ARCHITECTURE.md** for architectural changes +- **Add code comments** for complex logic +- **Include examples** where helpful + +## Review Process + +1. **Automated checks**: CI/CD checks must pass +2. **Code review**: At least one maintainer review required +3. **Testing**: Changes must be tested +4. **Documentation**: Documentation must be updated +5. **CLA**: CLA must be signed + +## Getting Help + +- **Documentation**: Check existing documentation first +- **Issues**: Search existing issues for similar problems +- **Discussions**: Use GitHub Discussions for questions +- **Contact**: Reach out to maintainers if needed + +## Recognition + +Contributors will be recognized in: +- GitHub contributors list +- Release notes (for significant contributions) + +Thank you for contributing! 🎉 + +## Additional Resources + +- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/) +- [GitHub Flow](https://guides.github.com/introduction/flow/) +- [Writing Good Commit Messages](https://chris.beams.io/posts/git-commit/) +- [ASP.NET Core Contribution Guidelines](https://github.com/dotnet/aspnetcore/blob/main/CONTRIBUTING.md) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md new file mode 100644 index 0000000..cebb956 --- /dev/null +++ b/DEVELOPMENT.md @@ -0,0 +1,315 @@ +# Development Guide + +This guide helps you set up and develop the .NET Codespaces sample application. + +## Prerequisites + +### For GitHub Codespaces +- A GitHub account +- Access to GitHub Codespaces + +### For Local Development +- [.NET 9.0 SDK](https://dotnet.microsoft.com/download/dotnet/9.0) or later +- [Visual Studio Code](https://code.visualstudio.com/) +- [C# Dev Kit extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) +- [Docker](https://www.docker.com/products/docker-desktop) (for Dev Container support) + +## Getting Started + +### Option 1: GitHub Codespaces (Recommended) + +1. Click the "Open in GitHub Codespaces" badge in the README +2. Wait for the codespace to initialize (this may take a few minutes) +3. Once ready, the dependencies will be automatically restored + +[![Open in GitHub Codespaces](https://img.shields.io/static/v1?style=for-the-badge&label=GitHub+Codespaces&message=Open&color=lightgrey&logo=github)](https://codespaces.new/github/dotnet-codespaces) + +### Option 2: Dev Container (Local) + +1. Clone the repository: + ```bash + git clone https://github.com/github/dotnet-codespaces.git + cd dotnet-codespaces + ``` + +2. Open in VS Code: + ```bash + code . + ``` + +3. When prompted, click "Reopen in Container" + - Alternatively, press `F1` and select "Dev Containers: Reopen in Container" + +4. Wait for the container to build and initialize + +### Option 3: Local Development (Without Container) + +1. Clone the repository: + ```bash + git clone https://github.com/github/dotnet-codespaces.git + cd dotnet-codespaces + ``` + +2. Restore dependencies: + ```bash + cd SampleApp + dotnet restore + ``` + +3. Set the environment variable for the frontend to communicate with the backend: + - **Windows (PowerShell)**: + ```powershell + $env:WEATHER_URL="https://localhost:8080" + ``` + - **macOS/Linux (Bash)**: + ```bash + export WEATHER_URL="https://localhost:8080" + ``` + +## Running the Application + +### Using VS Code Debug Configuration (Recommended) + +1. Open the Run and Debug view (`Ctrl+Shift+D` or `Cmd+Shift+D`) +2. Select "Run All" from the dropdown +3. Press `F5` or click the green play button +4. Both backend and frontend will start automatically +5. Your browser will open automatically to the frontend and backend Scalar documentation + +### Running Manually + +#### Start Backend +```bash +cd SampleApp/BackEnd +dotnet run +``` + +The backend will start on `https://localhost:8080` +- API: `https://localhost:8080/weatherforecast` +- Scalar docs: `https://localhost:8080/scalar` + +#### Start Frontend +In a new terminal: +```bash +cd SampleApp/FrontEnd +export WEATHER_URL="https://localhost:8080" # or $env:WEATHER_URL on Windows +dotnet run +``` + +The frontend will start on `https://localhost:8081` + +## Building the Application + +### Build All Projects +```bash +cd SampleApp +dotnet build +``` + +### Build Specific Project +```bash +# Backend +dotnet build SampleApp/BackEnd/BackEnd.csproj + +# Frontend +dotnet build SampleApp/FrontEnd/FrontEnd.csproj +``` + +## Testing the Application + +### Manual Testing + +1. **Test the Backend API**: + - Navigate to `https://localhost:8080/scalar` + - Use the interactive API documentation to test endpoints + - Try the "Test Request" button for each endpoint + +2. **Test the Frontend**: + - Navigate to `https://localhost:8081` + - Verify that weather data loads correctly + - Check browser console for any errors + +3. **Test Backend API Directly**: + ```bash + # Weather forecast + curl https://localhost:8080/weatherforecast + + # Sunset time + curl "https://localhost:8080/sunset?date=2024-06-21" + + # Sunset range + curl "https://localhost:8080/sunset/range?days=7" + ``` + +### Unit Testing +Currently, this sample application does not include unit tests. To add tests: + +1. Create test projects: + ```bash + dotnet new xunit -n BackEnd.Tests + dotnet new xunit -n FrontEnd.Tests + ``` + +2. Add test project references: + ```bash + cd BackEnd.Tests + dotnet add reference ../BackEnd/BackEnd.csproj + ``` + +3. Run tests: + ```bash + dotnet test + ``` + +## Development Workflow + +### Hot Reload + +The application supports hot reload for rapid development: + +```bash +# Backend with hot reload +cd SampleApp/BackEnd +dotnet watch run + +# Frontend with hot reload +cd SampleApp/FrontEnd +dotnet watch run +``` + +Any code changes will automatically trigger a rebuild and restart. + +### Debugging + +1. Set breakpoints in your code +2. Use the "Run All" or individual launch configurations +3. Step through code using VS Code debugger +4. Inspect variables and call stack + +### Code Formatting + +Format code using: +```bash +dotnet format +``` + +## Project Structure + +``` +dotnet-codespaces/ +├── .devcontainer/ # Dev container configuration +│ └── devcontainer.json +├── .vscode/ # VS Code settings and launch configs +│ ├── launch.json +│ ├── settings.json +│ └── tasks.json +├── SampleApp/ # Main application +│ ├── BackEnd/ # Weather API +│ │ ├── Program.cs # API endpoints and configuration +│ │ └── BackEnd.csproj +│ ├── FrontEnd/ # Blazor web application +│ │ ├── Data/ # Data models and services +│ │ ├── Pages/ # Blazor pages +│ │ ├── Shared/ # Shared components +│ │ ├── wwwroot/ # Static files +│ │ ├── Program.cs # App configuration +│ │ └── FrontEnd.csproj +│ └── SampleApp.sln # Solution file +├── images/ # Documentation images +├── ARCHITECTURE.md # Architecture documentation +├── API.md # API documentation +├── DEVELOPMENT.md # This file +└── readme.md # Main README +``` + +## Common Development Tasks + +### Adding a New API Endpoint + +1. Open `SampleApp/BackEnd/Program.cs` +2. Add a new `MapGet`, `MapPost`, etc. before `app.Run()`: + ```csharp + app.MapGet("/myendpoint", () => + { + return new { message = "Hello World" }; + }) + .WithName("MyEndpoint"); + ``` +3. The endpoint will automatically appear in the OpenAPI/Scalar documentation + +### Adding a New Blazor Page + +1. Create a new `.razor` file in `SampleApp/FrontEnd/Pages/` +2. Add the `@page` directive at the top: + ```razor + @page "/mypage" + +

My Page

+ ``` +3. Add navigation link in `Shared/NavMenu.razor` + +### Adding a New NuGet Package + +```bash +cd SampleApp/BackEnd # or FrontEnd +dotnet add package PackageName +``` + +### Updating .NET Version + +1. Update `TargetFramework` in `.csproj` files +2. Update base image in `.devcontainer/devcontainer.json` +3. Rebuild the dev container + +## Environment Variables + +### Backend +- `ASPNETCORE_ENVIRONMENT`: Set to `Development` or `Production` +- `ASPNETCORE_URLS`: Override default URLs (e.g., `https://localhost:8080`) + +### Frontend +- `ASPNETCORE_ENVIRONMENT`: Set to `Development` or `Production` +- `WEATHER_URL`: Backend API base URL (required) +- `ASPNETCORE_URLS`: Override default URLs (e.g., `https://localhost:8081`) + +## Troubleshooting + +### Port Already in Use +If ports 8080 or 8081 are already in use: +1. Stop the existing processes +2. Or change ports in `launch.json` and `devcontainer.json` + +### Frontend Can't Connect to Backend +1. Verify `WEATHER_URL` environment variable is set correctly +2. Check that backend is running on the expected port +3. Check for HTTPS certificate issues in development + +### Dev Container Won't Build +1. Ensure Docker is running +2. Try rebuilding: `F1` → "Dev Containers: Rebuild Container" +3. Check Docker logs for error messages + +### Hot Reload Not Working +1. Ensure you're using `dotnet watch run` +2. Check that files are being saved +3. Some changes require a full rebuild (e.g., project file changes) + +### HTTPS Certificate Issues +In development, you may need to trust the .NET development certificate: +```bash +dotnet dev-certs https --trust +``` + +## Additional Resources + +- [ASP.NET Core Documentation](https://learn.microsoft.com/aspnet/core/) +- [Blazor Documentation](https://learn.microsoft.com/aspnet/core/blazor/) +- [.NET CLI Reference](https://learn.microsoft.com/dotnet/core/tools/) +- [Visual Studio Code Documentation](https://code.visualstudio.com/docs) +- [Dev Containers Documentation](https://code.visualstudio.com/docs/devcontainers/containers) + +## Getting Help + +- Check the [GitHub Issues](https://github.com/github/dotnet-codespaces/issues) +- Review [ASP.NET Core documentation](https://learn.microsoft.com/aspnet/core/) +- Ask questions in [GitHub Discussions](https://github.com/github/dotnet-codespaces/discussions) diff --git a/DOCS_INDEX.md b/DOCS_INDEX.md new file mode 100644 index 0000000..a435cca --- /dev/null +++ b/DOCS_INDEX.md @@ -0,0 +1,168 @@ +# Documentation Index + +Welcome to the .NET Codespaces project documentation! This index will help you find the right documentation for your needs. + +## 📖 Getting Started + +**New to the project?** Start here: + +1. **[README.md](README.md)** - Start here for project overview and quick start +2. **[DEVELOPMENT.md](DEVELOPMENT.md)** - Set up your development environment + +## 📚 Core Documentation + +### For Users + +- **[README.md](README.md)** + - Project overview and features + - Quick start guide + - Running the application + - Basic usage instructions + +- **[API.md](API.md)** + - Complete API endpoint reference + - Request/response examples + - API authentication and error handling + - Client examples in multiple languages + +### For Developers + +- **[DEVELOPMENT.md](DEVELOPMENT.md)** + - Development environment setup + - Building and running the application + - Development workflow and best practices + - Debugging and troubleshooting + - Common development tasks + +- **[ARCHITECTURE.md](ARCHITECTURE.md)** + - System architecture overview + - Component descriptions + - Technology stack details + - Data flow and integration points + - Security considerations + +### For Contributors + +- **[CONTRIBUTING.md](CONTRIBUTING.md)** + - How to contribute + - Code style guidelines + - Pull request process + - Testing guidelines + - Code of conduct + +- **[CHANGELOG.md](CHANGELOG.md)** + - Version history + - Release notes + - Breaking changes + - New features and improvements + +## 🎯 Quick Navigation by Task + +### I want to... + +#### Use the Application +→ Read [README.md](README.md) sections: +- Getting Started +- Quick Reference +- API Endpoints + +#### Understand How It Works +→ Read [ARCHITECTURE.md](ARCHITECTURE.md) sections: +- Overview +- Frontend Application +- Backend Application +- Technology Stack + +#### Set Up Development Environment +→ Read [DEVELOPMENT.md](DEVELOPMENT.md) sections: +- Prerequisites +- Getting Started +- Running the Application + +#### Use the API +→ Read [API.md](API.md) sections: +- API Endpoints +- Request/Response Examples +- Interactive API Documentation + +#### Contribute Code +→ Read [CONTRIBUTING.md](CONTRIBUTING.md) sections: +- Development Process +- Code Style Guidelines +- Pull Request Process + +#### Debug Issues +→ Read [DEVELOPMENT.md](DEVELOPMENT.md) sections: +- Debugging +- Troubleshooting +- Common Development Tasks + +#### Check Recent Changes +→ Read [CHANGELOG.md](CHANGELOG.md) + +## 📋 Documentation Standards + +All documentation in this project follows these standards: + +- **Markdown Format**: All docs use GitHub-flavored Markdown (.md) +- **Structure**: Clear hierarchy with headers and subheaders +- **Code Examples**: Syntax-highlighted code blocks where appropriate +- **Links**: Cross-references between related documentation +- **Images**: Screenshots and diagrams where helpful +- **Keep Current**: Documentation updated with code changes + +## 🔍 Finding Information + +### By Topic + +| Topic | Document | Section | +|-------|----------|---------| +| API Endpoints | [API.md](API.md) | API Endpoints | +| Architecture | [ARCHITECTURE.md](ARCHITECTURE.md) | All | +| Building | [DEVELOPMENT.md](DEVELOPMENT.md) | Building the Application | +| Code Style | [CONTRIBUTING.md](CONTRIBUTING.md) | Code Style Guidelines | +| Contributing | [CONTRIBUTING.md](CONTRIBUTING.md) | All | +| Debugging | [DEVELOPMENT.md](DEVELOPMENT.md) | Debugging | +| Dev Environment | [DEVELOPMENT.md](DEVELOPMENT.md) | Getting Started | +| Features | [README.md](README.md) | Features | +| Getting Started | [README.md](README.md) | Getting Started | +| Pull Requests | [CONTRIBUTING.md](CONTRIBUTING.md) | Pull Request Process | +| Quick Reference | [README.md](README.md) | Quick Reference | +| Running the App | [DEVELOPMENT.md](DEVELOPMENT.md) | Running the Application | +| Technology Stack | [ARCHITECTURE.md](ARCHITECTURE.md) | Technology Stack | +| Testing | [DEVELOPMENT.md](DEVELOPMENT.md) | Testing the Application | +| Troubleshooting | [DEVELOPMENT.md](DEVELOPMENT.md) | Troubleshooting | +| Version History | [CHANGELOG.md](CHANGELOG.md) | All | + +## 🤝 Contributing to Documentation + +Documentation improvements are always welcome! If you find: + +- Typos or errors +- Missing information +- Outdated content +- Opportunities for clarity + +Please submit a pull request or open an issue. See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. + +## 📞 Additional Help + +If you can't find what you're looking for: + +1. Check the [GitHub Issues](https://github.com/github/dotnet-codespaces/issues) +2. Search existing documentation +3. Ask in [GitHub Discussions](https://github.com/github/dotnet-codespaces/discussions) +4. Open a new issue with the `documentation` label + +## 🔗 External Resources + +- [ASP.NET Core Documentation](https://learn.microsoft.com/aspnet/core/) +- [Blazor Documentation](https://learn.microsoft.com/aspnet/core/blazor/) +- [.NET 9 Documentation](https://learn.microsoft.com/dotnet/core/whats-new/dotnet-9) +- [GitHub Codespaces Documentation](https://docs.github.com/codespaces) +- [Scalar API Documentation](https://github.com/scalar/scalar) + +--- + +**Last Updated**: December 2024 +**Documentation Version**: 1.0 diff --git a/README.md b/README.md new file mode 100644 index 0000000..e42a9f1 --- /dev/null +++ b/README.md @@ -0,0 +1,151 @@ +# GitHub Codespaces ♥️ .NET + +Want to try out the latest performance improvements coming with .NET for web development? + +This repo builds a Weather API, OpenAPI integration to test with [Scalar](https://learn.microsoft.com/aspnet/core/fundamentals/openapi/using-openapi-documents?view=aspnetcore-9.0#use-scalar-for-interactive-api-documentation), and displays the data in a web application using Blazor with .NET. + +We've given you both a frontend and backend to play around with and where you go from here is up to you! + +Everything you do here is contained within this one codespace. There is no repository on GitHub yet. If and when you're ready you can click "Publish Branch" and we'll create your repository and push up your project. If you were just exploring then and have no further need for this code then you can simply delete your codespace and it's gone forever. + +## 📚 Documentation + +**[📖 Documentation Index](DOCS_INDEX.md)** - Complete documentation sitemap and navigation guide + +### Core Documents + +- **[API Documentation](API.md)** - Detailed API endpoint reference +- **[Architecture Guide](ARCHITECTURE.md)** - Technical architecture overview +- **[Development Guide](DEVELOPMENT.md)** - Setup and development workflow +- **[Contributing Guide](CONTRIBUTING.md)** - How to contribute to this project +- **[Changelog](CHANGELOG.md)** - Version history and release notes + +## ✨ Features + +- **Backend API**: ASP.NET Core 9.0 Minimal APIs with weather and sunset endpoints +- **Frontend**: Blazor Server-Side application for displaying weather data +- **Interactive API Docs**: Scalar UI for testing and exploring the API +- **OpenAPI Support**: Auto-generated API documentation +- **Dev Container**: Fully configured development environment +- **Hot Reload**: Instant feedback during development +- **GitHub Codespaces**: One-click cloud development environment + +## 🛠️ Technology Stack + +- **.NET 9.0**: Latest .NET framework +- **ASP.NET Core**: High-performance web framework +- **Blazor**: Modern web UI framework +- **OpenAPI/Scalar**: API documentation and testing +- **GitHub Codespaces**: Cloud development environment + +### Run Options + +[![Open in GitHub Codespaces](https://img.shields.io/static/v1?style=for-the-badge&label=GitHub+Codespaces&message=Open&color=lightgrey&logo=github)](https://codespaces.new/github/dotnet-codespaces) +[![Open in Dev Container](https://img.shields.io/static/v1?style=for-the-badge&label=Dev+Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/github/dotnet-codespaces) + +You can also run this repository locally by following these instructions: +1. Clone the repo to your local machine `git clone https://github.com/github/dotnet-codespaces` +1. Open repo in VS Code + +## 🚀 Getting Started + +1. **📤 One-click setup**: [Open a new Codespace](https://codespaces.new/github/dotnet-codespaces), giving you a fully configured cloud developer environment. +2. **▶️ Run all, one-click again**: Use VS Code's built-in *Run* command and open the forwarded ports *8080* and *8081* in your browser. + +![Debug menu in VS Code showing Run All](images/RunAll.png) + +3. The Blazor web app and Scalar can be open by heading to **/scalar** in your browser. On Scalar, head to the backend API and click "Test Request" to call and test the API. + +![A website showing weather](images/BlazorApp.png) + +!["UI showing testing an API"](images/scalar.png) + + +4. **🔄 Iterate quickly:** Codespaces updates the server on each save, and VS Code's debugger lets you dig into the code execution. + +5. To stop running, return to VS Code, and click Stop twice in the debug toolbar. + +![VS Code stop debugging on both backend and frontend](images/StopRun.png) + +## 📖 Quick Reference + +### Project Structure +``` +dotnet-codespaces/ +├── SampleApp/ +│ ├── BackEnd/ # Weather API (Port 8080) +│ ├── FrontEnd/ # Blazor Web App (Port 8081) +│ └── SampleApp.sln +├── .devcontainer/ # Dev container configuration +└── .vscode/ # VS Code settings and launch configs +``` + +### API Endpoints + +The backend provides the following endpoints: + +- **GET /weatherforecast** - Get 5-day weather forecast +- **GET /sunset?date={date}** - Get sunset time for a date +- **GET /sunset/range?startDate={date}&days={number}** - Get sunset times for multiple days +- **GET /scalar** - Interactive API documentation + +For detailed API documentation, see [API.md](API.md). + +### Development Commands + +```bash +# Build the solution +dotnet build SampleApp/SampleApp.sln + +# Run backend +cd SampleApp/BackEnd && dotnet run + +# Run frontend (requires WEATHER_URL env variable) +cd SampleApp/FrontEnd && dotnet run + +# Watch mode (hot reload) +dotnet watch run +``` + +For more development information, see [DEVELOPMENT.md](DEVELOPMENT.md). + +## 🏗️ Architecture + +This application uses a simple client-server architecture: + +- **Frontend (Blazor)**: Server-side Blazor application that renders UI and communicates with the backend +- **Backend (ASP.NET Core)**: RESTful API using Minimal APIs pattern with OpenAPI documentation + +For detailed architecture information, see [ARCHITECTURE.md](ARCHITECTURE.md). + +## 🤝 Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a +Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us +the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide +a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions +provided by the bot. You will only need to do this once across all repos using our CLA. + +For detailed contribution guidelines, see [CONTRIBUTING.md](CONTRIBUTING.md). + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## 📝 License + +This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft +trademarks or logos is subject to and must follow +[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). +Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. +Any use of third-party trademarks or logos are subject to those third-party's policies. + +## 🔗 Additional Resources + +- [ASP.NET Core Documentation](https://learn.microsoft.com/aspnet/core/) +- [Blazor Documentation](https://learn.microsoft.com/aspnet/core/blazor/) +- [.NET 9 Documentation](https://learn.microsoft.com/dotnet/core/whats-new/dotnet-9) +- [GitHub Codespaces Documentation](https://docs.github.com/codespaces) +- [Scalar API Documentation](https://github.com/scalar/scalar) diff --git a/readme.md b/readme.md deleted file mode 100644 index 6a0b6a2..0000000 --- a/readme.md +++ /dev/null @@ -1,61 +0,0 @@ -# GitHub Codespaces ♥️ .NET - -Want to try out the latest performance improvements coming with .NET for web development? - -This repo builds a Weather API, OpenAPI integration to test with [Scalar](https://learn.microsoft.com/aspnet/core/fundamentals/openapi/using-openapi-documents?view=aspnetcore-9.0#use-scalar-for-interactive-api-documentation), and displays the data in a web application using Blazor with .NET. - -We've given you both a frontend and backend to play around with and where you go from here is up to you! - -Everything you do here is contained within this one codespace. There is no repository on GitHub yet. If and when you’re ready you can click "Publish Branch" and we’ll create your repository and push up your project. If you were just exploring then and have no further need for this code then you can simply delete your codespace and it's gone forever. - -### Run Options - -[![Open in GitHub Codespaces](https://img.shields.io/static/v1?style=for-the-badge&label=GitHub+Codespaces&message=Open&color=lightgrey&logo=github)](https://codespaces.new/github/dotnet-codespaces) -[![Open in Dev Container](https://img.shields.io/static/v1?style=for-the-badge&label=Dev+Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/github/dotnet-codespaces) - -You can also run this repository locally by following these instructions: -1. Clone the repo to your local machine `git clone https://github.com/github/dotnet-codespaces` -1. Open repo in VS Code - -## Getting started - -1. **📤 One-click setup**: [Open a new Codespace](https://codespaces.new/github/dotnet-codespaces), giving you a fully configured cloud developer environment. -2. **▶️ Run all, one-click again**: Use VS Code's built-in *Run* command and open the forwarded ports *8080* and *8081* in your browser. - -![Debug menu in VS Code showing Run All](images/RunAll.png) - -3. The Blazor web app and Scalar can be open by heading to **/scalar** in your browser. On Scalar, head to the backend API and click "Test Request" to call and test the API. - -![A website showing weather](images/BlazorApp.png) - -!["UI showing testing an API"](images/scalar.png) - - -4. **🔄 Iterate quickly:** Codespaces updates the server on each save, and VS Code's debugger lets you dig into the code execution. - -5. To stop running, return to VS Code, and click Stop twice in the debug toolbar. - -![VS Code stop debuggin on both backend and frontend](images/StopRun.png) - - -## Contributing - -This project welcomes contributions and suggestions. Most contributions require you to agree to a -Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us -the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. - -When you submit a pull request, a CLA bot will automatically determine whether you need to provide -a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions -provided by the bot. You will only need to do this once across all repos using our CLA. - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or -contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - -## Trademarks - -This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft -trademarks or logos is subject to and must follow -[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). -Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. -Any use of third-party trademarks or logos are subject to those third-party's policies.