Skip to content
This repository was archived by the owner on Nov 30, 2023. It is now read-only.

Commit 577a6fe

Browse files
authored
Added C# (.NET) definition with PostgreSQL container (#1257)
1 parent 4648136 commit 577a6fe

File tree

12 files changed

+558
-1
lines changed

12 files changed

+558
-1
lines changed

containers/dotnet-mssql/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
## Summary
44

5-
*Develop C# and .NET Core based applications. Includes all needed SDKs, extensions, dependencies and an MS SQL container for parallel database development. Adds an additional MS SQL container to the C# (.NET Core) container definion and deploys any .dacpac files from the mssql .devcontainer folder.*
5+
*Develop C# and .NET Core based applications. Includes all needed SDKs, extensions, dependencies and an MS SQL container for parallel database development. Adds an additional MS SQL container to the C# (.NET Core) container definition and deploys any .dacpac files from the mssql .devcontainer folder.*
66

77
| Metadata | Value |
88
|----------|-------|
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# [Choice] .NET version: 6.0, 5.0, 3.1, 6.0-bullseye, 5.0-bullseye, 3.1-bullseye, 6.0-focal, 5.0-focal, 3.1-focal
2+
ARG VARIANT="6.0"
3+
FROM mcr.microsoft.com/vscode/devcontainers/dotnet:0-${VARIANT}
4+
5+
# [Choice] Node.js version: none, lts/*, 16, 14, 12, 10
6+
ARG NODE_VERSION="none"
7+
RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi
8+
9+
# [Optional] Uncomment this section to install additional OS packages.
10+
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
11+
# && apt-get -y install --no-install-recommends <your-package-list-here>
12+
13+
# [Optional] Uncomment this line to install global node packages.
14+
# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>" 2>&1
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
{
2+
"name": "C# (.NET) and PostgreSQL (Community)",
3+
"dockerComposeFile": "docker-compose.yml",
4+
"service": "app",
5+
"workspaceFolder": "/workspace",
6+
7+
// Set *default* container specific settings.json values on container create.
8+
"settings": {},
9+
10+
// Add the IDs of extensions you want installed when the container is created.
11+
"extensions": ["ms-dotnettools.csharp"],
12+
13+
// Use 'forwardPorts' to make a list of ports inside the container available locally.
14+
// "forwardPorts": [5000, 5001],
15+
16+
// [Optional] To reuse of your local HTTPS dev cert:
17+
//
18+
// 1. Export it locally using this command:
19+
// * Windows PowerShell:
20+
// dotnet dev-certs https --trust; dotnet dev-certs https -ep "$env:USERPROFILE/.aspnet/https/aspnetapp.pfx" -p "SecurePwdGoesHere"
21+
// * macOS/Linux terminal:
22+
// dotnet dev-certs https --trust; dotnet dev-certs https -ep "${HOME}/.aspnet/https/aspnetapp.pfx" -p "SecurePwdGoesHere"
23+
//
24+
// 2. Uncomment these 'remoteEnv' lines:
25+
// "remoteEnv": {
26+
// "ASPNETCORE_Kestrel__Certificates__Default__Password": "SecurePwdGoesHere",
27+
// "ASPNETCORE_Kestrel__Certificates__Default__Path": "/home/vscode/.aspnet/https/aspnetapp.pfx",
28+
// },
29+
//
30+
// 3. Next, copy your certificate into the container:
31+
// 1. Start the container
32+
// 2. Drag ~/.aspnet/https/aspnetapp.pfx into the root of the file explorer
33+
// 3. Open a terminal in VS Code and run "mkdir -p /home/vscode/.aspnet/https && mv aspnetapp.pfx /home/vscode/.aspnet/https"
34+
35+
// Use 'postCreateCommand' to run commands after the container is created.
36+
// "postCreateCommand": "dotnet --info",
37+
38+
// Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
39+
"remoteUser": "vscode"
40+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
version: '3.8'
2+
3+
services:
4+
app:
5+
build:
6+
context: .
7+
dockerfile: Dockerfile
8+
args:
9+
# Update 'VARIANT' to pick a version of .NET: 3.1, 5.0, 6.0
10+
VARIANT: "6.0"
11+
# Optional version of Node.js
12+
NODE_VERSION: "lts/*"
13+
14+
volumes:
15+
- ..:/workspace:cached
16+
17+
# Overrides default command so things don't shut down after the process ends.
18+
command: sleep infinity
19+
20+
# Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function.
21+
network_mode: service:db
22+
23+
# Uncomment the next line to use a non-root user for all processes.
24+
# user: vscode
25+
26+
# Use "forwardPorts" in **devcontainer.json** to forward an app port locally.
27+
# (Adding the "ports" property to this file will not forward from a Codespace.)
28+
29+
db:
30+
image: postgres:14.1
31+
restart: unless-stopped
32+
volumes:
33+
- postgres-data:/var/lib/postgresql/data
34+
environment:
35+
POSTGRES_PASSWORD: postgres
36+
POSTGRES_USER: postgres
37+
POSTGRES_DB: postgres
38+
39+
# Add "forwardPorts": ["5432"] to **devcontainer.json** to forward PostgreSQL locally.
40+
# (Adding the "ports" property to this file will not forward from a Codespace.)
41+
42+
volumes:
43+
postgres-data:

containers/dotnet-postgres/.npmignore

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
README.md
2+
test-project
3+
history
4+
definition-manifest.json
5+
.devcontainer/library-scripts/README.md
6+
.vscode
7+
.npmignore
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"version": "0.2.0",
3+
"configurations": [
4+
{
5+
// Use IntelliSense to find out which attributes exist for C# debugging
6+
// Use hover for the description of the existing attributes
7+
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
8+
"name": ".NET Core Launch (console)",
9+
"type": "coreclr",
10+
"request": "launch",
11+
"preLaunchTask": "build",
12+
// If you have changed target frameworks, make sure to update the program path.
13+
"program": "${workspaceFolder}/test-project/bin/Debug/net6.0/aspnetapp.dll",
14+
"args": [],
15+
"cwd": "${workspaceFolder}/test-project",
16+
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
17+
"console": "internalConsole",
18+
"stopAtEntry": false
19+
},
20+
{
21+
"name": ".NET Core Attach",
22+
"type": "coreclr",
23+
"request": "attach"
24+
}
25+
]
26+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
{
2+
"version": "2.0.0",
3+
"tasks": [
4+
{
5+
"label": "build",
6+
"command": "dotnet",
7+
"type": "process",
8+
"args": [
9+
"build",
10+
"${workspaceFolder}/test-project/aspnetapp.csproj",
11+
"/property:GenerateFullPaths=true",
12+
"/consoleloggerparameters:NoSummary"
13+
],
14+
"problemMatcher": "$msCompile"
15+
},
16+
{
17+
"label": "publish",
18+
"command": "dotnet",
19+
"type": "process",
20+
"args": [
21+
"publish",
22+
"${workspaceFolder}/test-project/aspnetapp.csproj",
23+
"/property:GenerateFullPaths=true",
24+
"/consoleloggerparameters:NoSummary"
25+
],
26+
"problemMatcher": "$msCompile"
27+
},
28+
{
29+
"label": "watch",
30+
"command": "dotnet",
31+
"type": "process",
32+
"args": [
33+
"watch",
34+
"run",
35+
"${workspaceFolder}/test-project/aspnetapp.csproj",
36+
"/property:GenerateFullPaths=true",
37+
"/consoleloggerparameters:NoSummary"
38+
],
39+
"problemMatcher": "$msCompile"
40+
}
41+
]
42+
}

containers/dotnet-postgres/README.md

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
# C# (.NET) and PostgreSQL (Community)
2+
3+
## Summary
4+
5+
*Develop C# and .NET Core based applications. Includes all needed SDKs, extensions, dependencies and a PostgreSQL container for parallel database development. Adds an additional PostgreSQL container to the C# (.NET Core) container definition.*
6+
7+
| Metadata | Value |
8+
|----------|-------|
9+
| *Contributors* | [Berkays](https://github.com/Berkays) |
10+
| *Categories* | Core, Languages |
11+
| *Definition type* | Docker Compose |
12+
| *Published image architecture(s)* | x86-64 |
13+
| *Available image variants* | [See C# (.NET) definition](../dotnet). |
14+
| *Works in Codespaces* | Yes |
15+
| *Container host OS support* | Linux, macOS, Windows |
16+
| *Container OS* | Ubuntu (`-focal`), Debian (`-bullseye`) |
17+
| *Languages, platforms* | .NET, .NET Core, C#, PostgreSQL |
18+
19+
## Description
20+
This definition creates two containers, one for C# (.NET) and one for PostgreSQL. VS Code will attach to the .NET Core container, and from within that container the PostgreSQL container will be available on **`localhost`** port 5432. By default, the `postgre` user password is `postgre`. Default database parameters may be changed in `docker-compose.yml` file if desired.
21+
22+
## Using this definition
23+
24+
While this definition should work unmodified, you can select the version of .NET Core the container uses by updating the `VARIANT` arg in the included `docker-compose.yml` (and rebuilding if you've already created the container).
25+
26+
```yaml
27+
args:
28+
VARIANT: "3.1-focal"
29+
```
30+
31+
This will use an Ubuntu 20.04/focal based .NET image by default.
32+
33+
### Debug Configuration
34+
35+
Only the integrated terminal is supported by the Remote - Containers extension. You may need to modify your `.vscode/launch.json` configurations to include the following:
36+
37+
```json
38+
"console": "integratedTerminal"
39+
```
40+
41+
### Using the forwardPorts property
42+
43+
By default, ASP.NET Core only listens to localhost inside the container. As a result, we recommend using the `forwardPorts` property in `.devcontainer/devcontainer.json` (available in v0.98.0+) to make these ports available locally.
44+
45+
```json
46+
"forwardPorts": [5000, 5001]
47+
```
48+
49+
The `appPort` property [publishes](https://docs.docker.com/config/containers/container-networking/#published-ports) rather than forwards the port, so applications need to listen to `*` or `0.0.0.0` for the application to be accessible externally. This conflicts with ASP.NET Core's defaults, but fortunately the `forwardPorts` property does not have this limitation.
50+
51+
If you've already opened your folder in a container, rebuild the container using the **Remote-Containers: Rebuild Container** command from the Command Palette (<kbd>F1</kbd>) so the settings take effect.
52+
53+
### Enabling HTTPS in ASP.NET Core
54+
55+
To enable HTTPS in ASP.NET, you can mount an exported copy of your local dev certificate.
56+
57+
1. Export it using the following command:
58+
59+
**Windows PowerShell**
60+
61+
```powershell
62+
dotnet dev-certs https --trust; dotnet dev-certs https -ep "$env:USERPROFILE/.aspnet/https/aspnetapp.pfx" -p "SecurePwdGoesHere"
63+
```
64+
65+
**macOS/Linux terminal**
66+
67+
```powershell
68+
dotnet dev-certs https --trust; dotnet dev-certs https -ep "${HOME}/.aspnet/https/aspnetapp.pfx" -p "SecurePwdGoesHere"
69+
```
70+
71+
2. Add the following in to `.devcontainer/devcontainer.json`:
72+
73+
```json
74+
"remoteEnv": {
75+
"ASPNETCORE_Kestrel__Certificates__Default__Password": "SecurePwdGoesHere",
76+
"ASPNETCORE_Kestrel__Certificates__Default__Path": "/home/vscode/.aspnet/https/aspnetapp.pfx",
77+
}
78+
```
79+
80+
3. Finally, make the certificate available in the container as follows:
81+
82+
1. Start the container/codespace
83+
2. Drag `~/.aspnet/https/aspnetapp.pfx` from your local machine into the root of the File Explorer in VS Code.
84+
3. Open a terminal in VS Code and run:
85+
```bash
86+
mkdir -p /home/vscode/.aspnet/https && mv aspnetapp.pfx /home/vscode/.aspnet/https
87+
```
88+
89+
If you've already opened your folder in a container, rebuild the container using the **Remote-Containers: Rebuild Container** command from the Command Palette (<kbd>F1</kbd>) so the settings take effect.
90+
91+
### Installing Node.js or the Azure CLI
92+
93+
Given how frequently ASP.NET applications use Node.js for front end code, this container also includes Node.js. You can change the version of Node.js installed or disable its installation by updating the `args` property in `.devcontainer/docker-compose.yml`.
94+
95+
```yaml
96+
args:
97+
VARIANT: "3.1-focal"
98+
NODE_VERSION: "16" # Set to "none" to skip Node.js installation
99+
```
100+
101+
If you would like to install the Azure CLI, you can reference [a dev container feature](https://aka.ms/vscode-remote/containers/dev-container-features) by adding the following to `.devcontainer/devcontainer.json`:
102+
103+
```json
104+
{
105+
"features": {
106+
"azure-cli": "latest"
107+
}
108+
}
109+
```
110+
111+
If you've already opened your folder in a container, rebuild the container using the **Remote-Containers: Rebuild Container** command from the Command Palette (<kbd>F1</kbd>) so the settings take effect.
112+
113+
## PostgreSQL Configuration
114+
A secondary container for PostgreSQL is defined in `devcontainer.json` and `docker-compose.yml` files. This container is deployed from the latest version available at the time of this commit. `latest` tag is avoided to prevent breaking bugs. The default `postgres` user password is set to `postgres`. The database instance uses the default port of `5432`.
115+
116+
### Changing the postgres user password
117+
To change the `postgres` user password, change the value in `docker-compose.yml` and `devcontainer.json`.
118+
119+
## Adding the definition to your folder
120+
121+
1. If this is your first time using a development container, please see getting started information on [setting up](https://aka.ms/vscode-remote/containers/getting-started) Remote-Containers or [creating a codespace](https://aka.ms/ghcs-open-codespace) using GitHub Codespaces.
122+
123+
2. Start VS Code and open your project folder or connect to a codespace.
124+
125+
3. Press <kbd>F1</kbd> select and **Add Development Container Configuration Files...** command for **Remote-Containers** or **Codespaces**.
126+
127+
> **Note:** If needed, you can drag-and-drop the `.devcontainer` folder from this sub-folder in a locally cloned copy of this repository into the VS Code file explorer instead of using the command.
128+
129+
4. Select this definition. You may also need to select **Show All Definitions...** for it to appear.
130+
131+
5. Finally, press <kbd>F1</kbd> and run **Remote-Containers: Reopen Folder in Container** or **Codespaces: Rebuild Container** to start using the definition.
132+
133+
## Testing the definition
134+
135+
This definition includes some test code that will help you verify it is working as expected on your system. Follow these steps:
136+
137+
1. If this is your first time using a development container, please follow the [getting started steps](https://aka.ms/vscode-remote/containers/getting-started) to set up your machine.
138+
2. Clone this repository.
139+
3. Start VS Code, press <kbd>F1</kbd>, and select **Remote-Containers: Open Folder in Container...**
140+
4. Select the `containers/dotnet-postgres` folder.
141+
5. After the folder has opened in the container, if prompted to restore packages in a notification, click "Restore".
142+
6. After packages are restored, press <kbd>F5</kbd> to start the project. *Note: if Auto Forward Ports has been disabled, you will need to manually forward port 8090 from the container with "Remote-Containers: Forward Ports..."*
143+
7. Open the browser to [localhost:8090](http://localhost:8090).
144+
8. You should see "The databases are: postgres, template1, template0" after the page loads.
145+
9. From here, you can add breakpoints or edit the contents of the `test-project` folder to do further testing.
146+
147+
## License
148+
149+
Copyright (c) Microsoft Corporation. All rights reserved.
150+
151+
Licensed under the MIT License. See [LICENSE](https://github.com/microsoft/vscode-dev-containers/blob/main/LICENSE).
152+
153+
Licenses for [POSTGRESQL](https://www.postgresql.org/about/licence/)
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*-------------------------------------------------------------------------------------------------------------
2+
* Copyright (c) Microsoft Corporation. All rights reserved.
3+
* Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
4+
*-------------------------------------------------------------------------------------------------------------*/
5+
6+
using Microsoft.AspNetCore.Hosting;
7+
using Microsoft.AspNetCore.Builder;
8+
using Microsoft.AspNetCore.Http;
9+
using System.Threading.Tasks;
10+
using Npgsql;
11+
12+
namespace aspnetapp
13+
{
14+
public class Program
15+
{
16+
private static string Host = "db";
17+
private static string User = "postgres";
18+
private static string DBname = "postgres";
19+
private static string Password = "postgres";
20+
private static string Port = "5432";
21+
22+
public static async Task Main(string[] args)
23+
{
24+
string databaseNames = "";
25+
26+
var connString = $"Host={Host};Port={Port};Username={User};Password={Password};Database={DBname}";
27+
28+
await using var conn = new NpgsqlConnection(connString);
29+
await conn.OpenAsync();
30+
31+
await using (var query = new NpgsqlCommand("SELECT datname FROM pg_database", conn))
32+
await using (var reader = await query.ExecuteReaderAsync())
33+
{
34+
while (await reader.ReadAsync())
35+
databaseNames += $"{reader.GetString(0)}, ";
36+
}
37+
38+
databaseNames = databaseNames.Substring(0, databaseNames.Length - 2);
39+
var host = new WebHostBuilder()
40+
.UseKestrel()
41+
.UseUrls("http://0.0.0.0:8090")
42+
.Configure(app => app.Run(async context =>
43+
{
44+
await context.Response.WriteAsync("The databases are: " + databaseNames);
45+
}))
46+
.Build();
47+
48+
host.Run();
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)