forked from Alexey/DAS_2024_1
Compare commits
20 Commits
balakhonov
...
kuzarin_ma
| Author | SHA1 | Date | |
|---|---|---|---|
| 8eedde24a1 | |||
| 829a04a913 | |||
| 253ad80e31 | |||
| f980a74f5e | |||
| e10ae36577 | |||
| 46b8ecfc54 | |||
| 262193a301 | |||
| 48711e14e3 | |||
| 39664ac3a1 | |||
| 7af877c37a | |||
| 7d2ae7430d | |||
| ec21e89033 | |||
| afddfcf91f | |||
| 9b0cb3582d | |||
| 37080832d5 | |||
| 39fdc511ee | |||
| 2714d4e718 | |||
| b8a59b4932 | |||
| 4af4abcb7f | |||
| e6dcbeb800 |
6
.idea/.gitignore
generated
vendored
Normal file
6
.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
/DAS_2024_1.iml
|
||||
/modules.xml
|
||||
/vcs.xml
|
||||
61
borschevskaya_anna_lab_1/README.md
Normal file
61
borschevskaya_anna_lab_1/README.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# Отчет. Лабораторная работа 1
|
||||
|
||||
В рамках лабораторной работы с помощью технологии контейнеризации docker были развернуты сервисы:
|
||||
- Redmine - система баг-трекинга
|
||||
- Postgres - СУБД
|
||||
- RabbitMQ - брокер сообщений
|
||||
|
||||
## Описание
|
||||
В docker-compose.yml файле описаны настройки для запуска трех выбранных сервисов в контейнерах. Для большинства строк файла оставлены
|
||||
комментарии, объясняющие содержимое файла.
|
||||
|
||||
Стоит отметить, для сервиса Redmine было принято решение в качестве сервера баз данных не использовать базу данных по умолчанию - SQLite,
|
||||
а поднять внешний сервер баз данных Postgres, который был запущен в рамках этого же файла docker-compose.yml.
|
||||
|
||||
Для того, чтобы при старте postgres уже была создана база данных для Redmine, а также пользователь, под учетной записью
|
||||
которого будет работать Redmine, был написан скрипт init-database.sh с использованием bash и sql:
|
||||
```
|
||||
# Создаем пользователя redmine и БД redminedb
|
||||
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
|
||||
CREATE USER redmine WITH PASSWORD 'redmine-password';
|
||||
CREATE DATABASE redminedb;
|
||||
GRANT ALL PRIVILEGES ON DATABASE redminedb TO redmine;
|
||||
EOSQL
|
||||
|
||||
# Даем права на схему public
|
||||
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USERNAME" -d redminedb <<-EOSQL
|
||||
ALTER SCHEMA public OWNER TO redmine;
|
||||
GRANT ALL ON SCHEMA public TO redmine;
|
||||
EOSQL
|
||||
```
|
||||
|
||||
Этот скрипт монтируется в директорию контейнера postgres ``docker-entrypoint-initdb.d``, которая является специальной точкой входа
|
||||
для инициализации БД и содержит соответствующие скрипты.
|
||||
|
||||
## Как запустить
|
||||
Для того, чтобы запустить сервисы, необходимо выполнить следующие действия:
|
||||
1. Установить и запустить Docker Engine или Docker Desktop (включает в себя Docker Engine и предоставляет UI)
|
||||
2. Через консоль перейти в папку, в которой расположен файл docker-compose.yml
|
||||
3. Выполнить команду:
|
||||
```
|
||||
docker compose up -d
|
||||
```
|
||||
В случае успешного запуска всех контейнеров в консоли будет выведено следующее сообщение:
|
||||
```
|
||||
[+] Running 3/3
|
||||
✔ Container rabbitmq Started 0.8s
|
||||
✔ Container redmine Started 1.2s
|
||||
✔ Container postgres Started 0.5s
|
||||
```
|
||||
Также будет создана папка postgres_data, которая монтируется в контейнере postgres
|
||||
|
||||
Мы также можем увидеть статус всех запущенных контейнеров, если выполним команду:
|
||||
```
|
||||
docker ps
|
||||
```
|
||||
Или обратившись к логам каждого из контейнеров:
|
||||
``
|
||||
docker logs <container_name>
|
||||
``
|
||||
## Видео-отчет
|
||||
Работоспособность лабораторной работы можно оценить в следующем [видео](https://disk.yandex.ru/d/15QhUl3KQYSavA).
|
||||
34
borschevskaya_anna_lab_1/docker-compose.yml
Normal file
34
borschevskaya_anna_lab_1/docker-compose.yml
Normal file
@@ -0,0 +1,34 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:latest # название и версия образа docker
|
||||
container_name: postgres # название контейнера
|
||||
environment: # блок переменных окружения, которые будут использованы для запуска и настройки
|
||||
POSTGRES_USERNAME: postgres # имя пользователя супер-пользователя СУБД
|
||||
POSTGRES_PASSWORD: postgres-admin # имя пользователя супер-пользователя СУБД
|
||||
PGDATA: "/var/lib/postgresql/data/pgdata" # путь к директории, где Postgres будет хранить свои данные.
|
||||
ports:
|
||||
- "5432:5432" # пробрасываем стандартный порт для доступа к postgres
|
||||
volumes:
|
||||
- ./postgres_data:/var/lib/postgresql/data/ # монтируем локальную директорию в директорию внутри контейнера с данными базы данных
|
||||
- ./init-database.sh:/docker-entrypoint-initdb.d/init-database.sh # Монтирует скрипт инициализации базы данных в специальную директорию внутри контейнера.
|
||||
redmine:
|
||||
image: redmine
|
||||
container_name: redmine
|
||||
ports:
|
||||
- "8080:3000"
|
||||
environment:
|
||||
REDMINE_DB_POSTGRES: postgres # хост, на котором расположена база данных Postgres
|
||||
REDMINE_DB_USERNAME: redmine # имя пользователя для подключения к базе данных Redmine
|
||||
REDMINE_DB_DATABASE: redminedb # база данных, к которой будет подключаться Redmine
|
||||
REDMINE_DB_PASSWORD: redmine-password # пароль, который будет использоваться для подключения
|
||||
depends_on: # обозначаем зависимость запуска сервиса redmine от запуска сервиса postgres
|
||||
- postgres
|
||||
rabbitmq:
|
||||
container_name: rabbitmq
|
||||
image: rabbitmq:3-management
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: rabbit # переопределяем значения имя для пользователя, который создается по умолчанию
|
||||
RABBITMQ_DEFAULT_PASS: rabbit-password # переопределяем значения пароля для пользователя, который создается по умолчанию
|
||||
ports:
|
||||
- "15672:15672" # порт для доступа к веб-интерфейсу
|
||||
- "5672:5672" # порт для доступа через протокол AMQP к брокеру сообщений
|
||||
15
borschevskaya_anna_lab_1/init-database.sh
Normal file
15
borschevskaya_anna_lab_1/init-database.sh
Normal file
@@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Создаем пользователя redmine и БД redminedb
|
||||
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
|
||||
CREATE USER redmine WITH PASSWORD 'redmine-password';
|
||||
CREATE DATABASE redminedb;
|
||||
GRANT ALL PRIVILEGES ON DATABASE redminedb TO redmine;
|
||||
EOSQL
|
||||
|
||||
# Даем права на схему public
|
||||
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USERNAME" -d redminedb <<-EOSQL
|
||||
ALTER SCHEMA public OWNER TO redmine;
|
||||
GRANT ALL ON SCHEMA public TO redmine;
|
||||
EOSQL
|
||||
33
dozorova_alena_lab_1/docker-compose.yml
Normal file
33
dozorova_alena_lab_1/docker-compose.yml
Normal file
@@ -0,0 +1,33 @@
|
||||
services:
|
||||
mediawiki:
|
||||
image: mediawiki
|
||||
restart: always
|
||||
ports:
|
||||
- 8080:80
|
||||
volumes:
|
||||
- ./volumes/mediawiki:/var/www/html/images
|
||||
postgres:
|
||||
image: postgres:12.20-alpine3.20
|
||||
restart: always
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: example
|
||||
ports:
|
||||
- 5432:5432
|
||||
volumes:
|
||||
- ./volumes/database:/var/lib/mysql
|
||||
git:
|
||||
image: gitea/gitea:1.22.2
|
||||
container_name: gitea
|
||||
environment:
|
||||
- USER_UID=1000
|
||||
- USER_GID=1000
|
||||
restart: always
|
||||
volumes:
|
||||
- ./volumes/gitea:/data
|
||||
- ./volumes/timezone:/etc/timezone:ro
|
||||
- ./volumes/localtime:/etc/localtime:ro
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "222:22"
|
||||
|
||||
35
dozorova_alena_lab_1/readme.md
Normal file
35
dozorova_alena_lab_1/readme.md
Normal file
@@ -0,0 +1,35 @@
|
||||
|
||||
# Лабораторная работа 1 Дозорова ПИбд-42
|
||||
В рамках лабораторной работы были развернуты три сервиса с помощью docker-compose:
|
||||
- Postgres
|
||||
- MediaWiki
|
||||
- gitea
|
||||
## Пример docker-compose для одного из сервисов
|
||||
```
|
||||
postgres: - название сервиса
|
||||
image: postgres:12.20-alpine3.20 - разворачиваемый образ
|
||||
restart: always - параметр, означающий перезапуск при падении
|
||||
environment: - переменные среды для сервиса
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: example
|
||||
ports: - проброшенные порты с хоста внутрь контейнера
|
||||
- 5432:5432
|
||||
volumes: - проброшенные тома с хоста внутрь контейнера
|
||||
- ./database:/var/lib/mysql
|
||||
```
|
||||
## Запуск
|
||||
Для запуска лабораторной работы необходимо иметь запущенный Docker\Docker Desktop на устройстве.
|
||||
Необходимо перейти в папку, где располагается yml файл. Далее открыть терминал и ввести команду:
|
||||
```
|
||||
docker compose up
|
||||
```
|
||||
Для выполнения в фоновом режиме можно использовать флаг `-d`. Результат выполнения:
|
||||
```
|
||||
[+] Running 3/3
|
||||
✔ Container dozorova_alena_lab_1-mediawiki-1 Started 0.7s
|
||||
✔ Container gitea Started 1.0s
|
||||
✔ Container dozorova_alena_lab_1-postgres-1 Started 1.0s
|
||||
```
|
||||
|
||||
## Видео демонстрация
|
||||
Видеодемонстрация доступна по ссылке: https://drive.google.com/file/d/1cT-p-od2BjCloeTr7kcMGm9hb3htsxcs/view?usp=sharing
|
||||
1
dozorova_alena_lab_1/volumes/gitea/git/.ssh/environment
Normal file
1
dozorova_alena_lab_1/volumes/gitea/git/.ssh/environment
Normal file
@@ -0,0 +1 @@
|
||||
GITEA_CUSTOM=/data/gitea
|
||||
98
dozorova_alena_lab_1/volumes/gitea/gitea/conf/app.ini
Normal file
98
dozorova_alena_lab_1/volumes/gitea/gitea/conf/app.ini
Normal file
@@ -0,0 +1,98 @@
|
||||
APP_NAME = Gitea: Git with a cup of tea
|
||||
RUN_MODE = prod
|
||||
RUN_USER = git
|
||||
WORK_PATH = /data/gitea
|
||||
|
||||
[repository]
|
||||
ROOT = /data/git/repositories
|
||||
|
||||
[repository.local]
|
||||
LOCAL_COPY_PATH = /data/gitea/tmp/local-repo
|
||||
|
||||
[repository.upload]
|
||||
TEMP_PATH = /data/gitea/uploads
|
||||
|
||||
[server]
|
||||
APP_DATA_PATH = /data/gitea
|
||||
DOMAIN = localhost
|
||||
SSH_DOMAIN = localhost
|
||||
HTTP_PORT = 3000
|
||||
ROOT_URL = http://localhost:3000/
|
||||
DISABLE_SSH = false
|
||||
SSH_PORT = 22
|
||||
SSH_LISTEN_PORT = 22
|
||||
LFS_START_SERVER = true
|
||||
LFS_JWT_SECRET = FrtpRwqeQpRvyJJfayYEK45J0u7LF9mFMnzXzJyxaIM
|
||||
OFFLINE_MODE = true
|
||||
|
||||
[database]
|
||||
PATH = /data/gitea/gitea.db
|
||||
DB_TYPE = postgres
|
||||
HOST = postgres:5432
|
||||
NAME = postgres
|
||||
USER = postgres
|
||||
PASSWD = example
|
||||
LOG_SQL = false
|
||||
SCHEMA =
|
||||
SSL_MODE = disable
|
||||
|
||||
[indexer]
|
||||
ISSUE_INDEXER_PATH = /data/gitea/indexers/issues.bleve
|
||||
|
||||
[session]
|
||||
PROVIDER_CONFIG = /data/gitea/sessions
|
||||
PROVIDER = file
|
||||
|
||||
[picture]
|
||||
AVATAR_UPLOAD_PATH = /data/gitea/avatars
|
||||
REPOSITORY_AVATAR_UPLOAD_PATH = /data/gitea/repo-avatars
|
||||
|
||||
[attachment]
|
||||
PATH = /data/gitea/attachments
|
||||
|
||||
[log]
|
||||
MODE = console
|
||||
LEVEL = info
|
||||
ROOT_PATH = /data/gitea/log
|
||||
|
||||
[security]
|
||||
INSTALL_LOCK = true
|
||||
SECRET_KEY =
|
||||
REVERSE_PROXY_LIMIT = 1
|
||||
REVERSE_PROXY_TRUSTED_PROXIES = *
|
||||
INTERNAL_TOKEN = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE3MjYyNTM3NDl9.qF5HZNwWbJzZ1e8Tt-jQZnMgGF1WY-NAruXLpw7kT4o
|
||||
PASSWORD_HASH_ALGO = pbkdf2
|
||||
|
||||
[service]
|
||||
DISABLE_REGISTRATION = false
|
||||
REQUIRE_SIGNIN_VIEW = false
|
||||
REGISTER_EMAIL_CONFIRM = false
|
||||
ENABLE_NOTIFY_MAIL = false
|
||||
ALLOW_ONLY_EXTERNAL_REGISTRATION = false
|
||||
ENABLE_CAPTCHA = false
|
||||
DEFAULT_KEEP_EMAIL_PRIVATE = false
|
||||
DEFAULT_ALLOW_CREATE_ORGANIZATION = true
|
||||
DEFAULT_ENABLE_TIMETRACKING = true
|
||||
NO_REPLY_ADDRESS = noreply.localhost
|
||||
|
||||
[lfs]
|
||||
PATH = /data/git/lfs
|
||||
|
||||
[mailer]
|
||||
ENABLED = false
|
||||
|
||||
[openid]
|
||||
ENABLE_OPENID_SIGNIN = true
|
||||
ENABLE_OPENID_SIGNUP = true
|
||||
|
||||
[cron.update_checker]
|
||||
ENABLED = false
|
||||
|
||||
[repository.pull-request]
|
||||
DEFAULT_MERGE_STYLE = merge
|
||||
|
||||
[repository.signing]
|
||||
DEFAULT_TRUST_MODEL = committer
|
||||
|
||||
[oauth2]
|
||||
JWT_SECRET = K4ExL3zYsTAxp7e0CYQu6tbChCprQfp8OrIFeCEUFHQ
|
||||
22
dozorova_alena_lab_1/volumes/gitea/gitea/home/.gitconfig
Normal file
22
dozorova_alena_lab_1/volumes/gitea/gitea/home/.gitconfig
Normal file
@@ -0,0 +1,22 @@
|
||||
[diff]
|
||||
algorithm = histogram
|
||||
[core]
|
||||
logallrefupdates = true
|
||||
quotePath = false
|
||||
commitGraph = true
|
||||
[gc]
|
||||
reflogexpire = 90
|
||||
writeCommitGraph = true
|
||||
[user]
|
||||
name = Gitea
|
||||
email = gitea@fake.local
|
||||
[receive]
|
||||
advertisePushOptions = true
|
||||
procReceiveRefs = refs/for
|
||||
[fetch]
|
||||
writeCommitGraph = true
|
||||
[safe]
|
||||
directory = *
|
||||
[uploadpack]
|
||||
allowfilter = true
|
||||
allowAnySHA1InWant = true
|
||||
@@ -0,0 +1 @@
|
||||
{"storage":"boltdb","index_type":"scorch"}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":4}
|
||||
Binary file not shown.
52
dozorova_alena_lab_1/volumes/gitea/gitea/jwt/private.pem
Normal file
52
dozorova_alena_lab_1/volumes/gitea/gitea/jwt/private.pem
Normal file
@@ -0,0 +1,52 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
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
|
||||
XXGE9FRK35yA3VEgydvvn1EVHrDSqa0=
|
||||
-----END PRIVATE KEY-----
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
MANIFEST-000000
|
||||
@@ -0,0 +1,6 @@
|
||||
=============== Sep 13, 2024 (UTC) ===============
|
||||
18:55:55.362150 log@legend F·NumFile S·FileSize N·Entry C·BadEntry B·BadBlock Ke·KeyError D·DroppedEntry L·Level Q·SeqNum T·TimeElapsed
|
||||
18:55:55.371211 db@open opening
|
||||
18:55:55.373794 version@stat F·[] S·0B[] Sc·[]
|
||||
18:55:55.381350 db@janitor F·2 G·0
|
||||
18:55:55.381573 db@open done T·10.223409ms
|
||||
Binary file not shown.
@@ -0,0 +1,9 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS
|
||||
1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQRQ+roZZ007kQa7Gww2JTmmVFw127Mu
|
||||
q28jcvF0dwxqed4YB66jve6n53CCFIiwRUgdL7xTznuc7zK4ubvLzZv8AAAAsI/K32qPyt
|
||||
9qAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFD6uhlnTTuRBrsb
|
||||
DDYlOaZUXDXbsy6rbyNy8XR3DGp53hgHrqO97qfncIIUiLBFSB0vvFPOe5zvMri5u8vNm/
|
||||
wAAAAhAKA0+nR1F1bBt7+aACPRfCKhwM97EucHO6IwHYNilS57AAAAEXJvb3RAMmRlMzY5
|
||||
MmIzZTlhAQIDBAUG
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -0,0 +1 @@
|
||||
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFD6uhlnTTuRBrsbDDYlOaZUXDXbsy6rbyNy8XR3DGp53hgHrqO97qfncIIUiLBFSB0vvFPOe5zvMri5u8vNm/w= root@2de3692b3e9a
|
||||
@@ -0,0 +1,7 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACCucAFJv9K4Cdh00YUz8Jqpoi+fvsHi4bIA/RzpKhWTuAAAAJjklphJ5JaY
|
||||
SQAAAAtzc2gtZWQyNTUxOQAAACCucAFJv9K4Cdh00YUz8Jqpoi+fvsHi4bIA/RzpKhWTuA
|
||||
AAAEDQcq4vet1WGsAxpKoaeA0RT/1lPObea7lkRE35BWZHn65wAUm/0rgJ2HTRhTPwmqmi
|
||||
L5++weLhsgD9HOkqFZO4AAAAEXJvb3RAMmRlMzY5MmIzZTlhAQIDBA==
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -0,0 +1 @@
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIK5wAUm/0rgJ2HTRhTPwmqmiL5++weLhsgD9HOkqFZO4 root@2de3692b3e9a
|
||||
38
dozorova_alena_lab_1/volumes/gitea/ssh/ssh_host_rsa_key
Normal file
38
dozorova_alena_lab_1/volumes/gitea/ssh/ssh_host_rsa_key
Normal file
@@ -0,0 +1,38 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
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
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -0,0 +1 @@
|
||||
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDeYsKB62LerAZIBDCEwqEj+JR4UoCLQGXBLegjaip0zj/EuBP3RiQZQ+KPqwXdzN+2qHDNMhckOWsSSsHec5kIhD8w0iOuVims3bBcYK3CHy8Gw4MBHgV79Q+PRNPZh0YCRjyGBtLos821DStQkERYIDst8z5LAWHqCE0H70u6UEsx9mxt3UreEDEKyM8c50R6ZTYJF2yyRCGd/0FGlfl7ktg2ERFZ9wWiVZGRWXyjLakchwjt9nmufMi7Uga1F/4u7mPqwIcHK4WE4C3EcuMrfjjp2UJC7DS8wstZFkDN+K/k0WosOMmUIDZeNMeYgNJULivkm0xY8TvsoWDHI6kglP1kRD4PuVOhgKAF7I3Xsiw+TsOI6cMB6jiser3HfLCeEHHBWWXgDHZz8tiRnLWTkE0pYTKRfLx7bT7cQ84/NBzZUXBqaBzzKei6hSkn9Yy0dNzCQdXCQTaN+gFd4T+IHS0mOWunzSeMZdoeC40z6eXcDjKjzkykbX93WhbX4q8= root@2de3692b3e9a
|
||||
33
emelyanov_artem_lab_1/README.md
Normal file
33
emelyanov_artem_lab_1/README.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# Docker Compose: PostgreSQL, RabbitMQ, Nginx
|
||||
|
||||
## Описание проекта
|
||||
|
||||
Этот проект разворачивает три сервиса с помощью Docker Compose:
|
||||
1. **PostgreSQL** — реляционная база данных.
|
||||
2. **RabbitMQ** — брокер сообщений с панелью управления.
|
||||
3. **Nginx** — веб-сервер и реверс-прокси.
|
||||
|
||||
|
||||
## Команды для запуска
|
||||
|
||||
Чтобы развернуть и запустить проект, выполните следующие шаги:
|
||||
1. Убедитесь, что у вас установлен Docker и Docker Compose.
|
||||
2. Перейдите в директорию с файлом docker-compose.yml.
|
||||
3. Запустите сервисы командой: docker-compose up --build
|
||||
|
||||
## Сервисы и порты
|
||||
1. **PostgreSQL:**
|
||||
**Порт:** 5432
|
||||
**Доступ:** Локально, через любые приложения, подключающиеся к базе данных PostgreSQL.
|
||||
|
||||
|
||||
2. **RabbitMQ:**
|
||||
**Порт для приложений:** 5672
|
||||
**Панель управления RabbitMQ:** Доступна по адресу [http://localhost:15672/](http://localhost:15672/) (логин: `user`, пароль: `password`).
|
||||
|
||||
|
||||
3. **Nginx:**
|
||||
**Порт:** 80
|
||||
**Назначение:** Используется как реверс-прокси для распределения трафика.
|
||||
|
||||
## Видео https://drive.google.com/file/d/1qzc_IFZBFkUVGJ97bkcsKpbwn8pw3Hay/view
|
||||
34
emelyanov_artem_lab_1/docker-compose.yml
Normal file
34
emelyanov_artem_lab_1/docker-compose.yml
Normal file
@@ -0,0 +1,34 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
# База данных PostgreSQL
|
||||
postgres:
|
||||
image: postgres:15
|
||||
container_name: postgres-db
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: mydb
|
||||
ports:
|
||||
- "5432:5432"
|
||||
|
||||
# RabbitMQ
|
||||
rabbitmq:
|
||||
image: rabbitmq:3-management
|
||||
container_name: rabbitmq
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: user
|
||||
RABBITMQ_DEFAULT_PASS: password
|
||||
ports:
|
||||
- "5672:5672" # для приложений
|
||||
- "15672:15672" # для панели управления
|
||||
|
||||
# Nginx для реверс-прокси (если нужно для других сервисов)
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
container_name: nginx
|
||||
ports:
|
||||
- "80:80"
|
||||
depends_on:
|
||||
- rabbitmq
|
||||
|
||||
14
kuzarin_maxim_lab_1/.env
Normal file
14
kuzarin_maxim_lab_1/.env
Normal file
@@ -0,0 +1,14 @@
|
||||
# Переменные для базы данных
|
||||
POSTGRES_TAG=latest # Берём последнююю версию postgres. Пока это не принципиально
|
||||
POSTGRES_DATA_DIR=./postgres-data
|
||||
POSTGRES_PASSWORD=postgres_password
|
||||
|
||||
# Переменные для Web gui для БД
|
||||
DB_GUI_IMAGE=adminer # Самый легковесный Web gui для postgres(и не только)
|
||||
DB_GUI_CONTEINER_PORT=8080
|
||||
|
||||
# Переменные для брокера сообщения RabbitMQ
|
||||
RABBIT_TAG=3.10.7-management # Тут есть встроенный Web интерфейс
|
||||
RABBIT_DATA_DIR=./rabbit-data
|
||||
RABBIT_USERNAME=user
|
||||
RABBIT_PASSWORD=password
|
||||
2
kuzarin_maxim_lab_1/.gitignore
vendored
Normal file
2
kuzarin_maxim_lab_1/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
postgres-data/
|
||||
rabbit-data/
|
||||
27
kuzarin_maxim_lab_1/README.md
Normal file
27
kuzarin_maxim_lab_1/README.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Лабораторная работа 1
|
||||
Данная работа посвящена работе с docker compose и поднятию сервисов, необходимых для последующего выполнения работ.
|
||||
## Описание
|
||||
В качестве сервисов были выбраны:
|
||||
- СУБД - Postgres
|
||||
- Web интерфейс для БД Postgres - Adminer
|
||||
- Брокер сообщений - RabbitMQ (+ Web интерфейс)
|
||||
## Запуск
|
||||
Для запуска лабораторной работы необходимо иметь запущенный движок Docker на устройстве.
|
||||
Необходимо перейти в папку, где располагается данный файл. Далее открыть терминал и ввести команду:
|
||||
```
|
||||
docker compose up -d
|
||||
```
|
||||
В данном случае флаг `-d` не обязателен. Он лишь позволит оставить консоль интерактивной (запускает все контейнеры в фоновом режиме).
|
||||
В случае, если в консоли отобразился подобный текст и появилась возможность вводить команды - сервисы успешно запущены.
|
||||
```
|
||||
[+] Running 4/4
|
||||
✔ Network kuzarin_maxim_lab_1_default Created 0.0s
|
||||
✔ Container kuzarin_maxim_lab_1-db-1 Started 0.7s
|
||||
✔ Container kuzarin_maxim_lab_1-rabbit-1 Started 0.7s
|
||||
✔ Container kuzarin_maxim_lab_1-db_web_gui-1 Started 0.7s
|
||||
```
|
||||
## Описание compose файла
|
||||
В docker-compose файле все уникальные строчки помечены комментариями. Они описывают их предназначения, и иногда обосновывают принятые решения.
|
||||
Так же комментарии присутствуют в файле .env, где хранятся переменные среды, нужные для работы compose файла.
|
||||
## Видео демонстрация
|
||||
Был записан видеоролик, демонстрирующий процесс запуска и работы сервисов. Он расположен по [адресу](https://drive.google.com/file/d/1ouUc-3eYhaJIR0HhD4b_Lj73oxEqORpA/view?usp=sharing)
|
||||
31
kuzarin_maxim_lab_1/docker-compose.yml
Normal file
31
kuzarin_maxim_lab_1/docker-compose.yml
Normal file
@@ -0,0 +1,31 @@
|
||||
services:
|
||||
db: # База данных
|
||||
image: postgres:${POSTGRES_TAG} # Берём тег образа из переменной среды
|
||||
restart: always # Автоматический перезапуск контейнера, если он упал
|
||||
ports: # проброс портов
|
||||
- 5432:5432 # Так как на хосте нет postgres, порт по умолчанию можно использовать свободно
|
||||
volumes: # Указываем проброс папок
|
||||
- ${POSTGRES_DATA_DIR}:/var/lib/postgresql/data # Данные postgres хранятся в /var/lib/postgresql/data.
|
||||
# А на хосте монтируем туда, куда указано в переменной
|
||||
environment: # Указываем переменные среды
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} # Пароль от учётки postgres берём из переменных среды
|
||||
|
||||
db_web_gui: # Интерфейс для доступа к БД (на компе нет PgAdmin)
|
||||
image: ${DB_GUI_IMAGE} # Их есть много разных, так что имя образа из env
|
||||
restart: always
|
||||
ports:
|
||||
- 8080:${DB_GUI_CONTEINER_PORT} # Так как Web GUI разные, то и порт может быть разный. Берём из env
|
||||
|
||||
rabbit: # Rabbit тоже понадобится в будущем
|
||||
image: rabbitmq:${RABBIT_TAG} # Определяем тегом версию
|
||||
restart: always
|
||||
ports:
|
||||
- 5672:5672 # Это порт доступа к брокеру (если буду разрабатывать на локале)
|
||||
- 8081:15672 # А это порт для Web GUI. Для удобста на хосте это 8081, близко к БД
|
||||
volumes:
|
||||
- ${RABBIT_DATA_DIR}:/var/lib/rabbitmq # У Rabbit так же можно пробросить папку, чтобы не терять данные
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: ${RABBIT_USERNAME} # Логин для пользователя Rabbit Берём из env
|
||||
RABBITMQ_DEFAULT_PASS: ${RABBIT_PASSWORD} # Пароль для пользователя Rabbit. Берём из env
|
||||
|
||||
|
||||
30
kuzarin_maxim_lab_2/.dockerignore
Normal file
30
kuzarin_maxim_lab_2/.dockerignore
Normal file
@@ -0,0 +1,30 @@
|
||||
**/.classpath
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/azds.yaml
|
||||
**/bin
|
||||
**/charts
|
||||
**/docker-compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
LICENSE
|
||||
README.md
|
||||
!**/.gitignore
|
||||
!.git/HEAD
|
||||
!.git/config
|
||||
!.git/packed-refs
|
||||
!.git/refs/heads/**
|
||||
490
kuzarin_maxim_lab_2/.gitignore
vendored
Normal file
490
kuzarin_maxim_lab_2/.gitignore
vendored
Normal file
@@ -0,0 +1,490 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from `dotnet new gitignore`
|
||||
|
||||
# dotenv files
|
||||
.env
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ww][Ii][Nn]32/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# Tye
|
||||
.tye/
|
||||
|
||||
# ASP.NET Scaffolding
|
||||
ScaffoldingReadMe.txt
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.tlog
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Coverlet is a free, cross platform Code Coverage Tool
|
||||
coverage*.json
|
||||
coverage*.xml
|
||||
coverage*.info
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
|
||||
*.vbp
|
||||
|
||||
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
|
||||
*.dsw
|
||||
*.dsp
|
||||
|
||||
# Visual Studio 6 technical files
|
||||
*.ncb
|
||||
*.aps
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# Visual Studio History (VSHistory) files
|
||||
.vshistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
|
||||
# VS Code files for those working on multiple tools
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
*.code-workspace
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Windows Installer files from build outputs
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# JetBrains Rider
|
||||
*.sln.iml
|
||||
.idea
|
||||
|
||||
##
|
||||
## Visual studio for Mac
|
||||
##
|
||||
|
||||
|
||||
# globs
|
||||
Makefile.in
|
||||
*.userprefs
|
||||
*.usertasks
|
||||
config.make
|
||||
config.status
|
||||
aclocal.m4
|
||||
install-sh
|
||||
autom4te.cache/
|
||||
*.tar.gz
|
||||
tarballs/
|
||||
test-results/
|
||||
|
||||
# Mac bundle stuff
|
||||
*.dmg
|
||||
*.app
|
||||
|
||||
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
# Dump file
|
||||
*.stackdump
|
||||
|
||||
# Folder config file
|
||||
[Dd]esktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# Vim temporary swap files
|
||||
*.swp
|
||||
|
||||
# Delete volumes
|
||||
/volumes
|
||||
|
||||
# Delete .vs folder
|
||||
/.vs/*
|
||||
37
kuzarin_maxim_lab_2/DAaS_FileConnections.sln
Normal file
37
kuzarin_maxim_lab_2/DAaS_FileConnections.sln
Normal file
@@ -0,0 +1,37 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.10.34916.146
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DAaS_FileConnections", "DAaS_FileConnections\DAaS_FileConnections.csproj", "{23B07B06-0AB4-42F8-9753-264639E1D38B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FirstApplication", "FirstApplication\FirstApplication.csproj", "{FBC01B2E-C887-42D1-A899-3C4781EF67E9}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SecondApplication", "SecondApplication\SecondApplication.csproj", "{5888DB56-82F2-467D-8F6B-AB94CC4A33B5}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{23B07B06-0AB4-42F8-9753-264639E1D38B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{23B07B06-0AB4-42F8-9753-264639E1D38B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{23B07B06-0AB4-42F8-9753-264639E1D38B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{23B07B06-0AB4-42F8-9753-264639E1D38B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{FBC01B2E-C887-42D1-A899-3C4781EF67E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{FBC01B2E-C887-42D1-A899-3C4781EF67E9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FBC01B2E-C887-42D1-A899-3C4781EF67E9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FBC01B2E-C887-42D1-A899-3C4781EF67E9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5888DB56-82F2-467D-8F6B-AB94CC4A33B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5888DB56-82F2-467D-8F6B-AB94CC4A33B5}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5888DB56-82F2-467D-8F6B-AB94CC4A33B5}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5888DB56-82F2-467D-8F6B-AB94CC4A33B5}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {E290B7D1-0F4E-406E-ADF3-8F543C0FA96E}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="PIHelperSh.RandomEx" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
29
kuzarin_maxim_lab_2/DAaS_FileConnections/Program.cs
Normal file
29
kuzarin_maxim_lab_2/DAaS_FileConnections/Program.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
|
||||
using PIHelperSh.RandomEx.Extentions;
|
||||
|
||||
string inputPath = Environment.GetEnvironmentVariable("INPUT_PATH") ?? ".\\input1";
|
||||
string outputPath = Environment.GetEnvironmentVariable("OUTPUT_PATH") ?? ".\\output1";
|
||||
|
||||
if(!Directory.Exists(inputPath))
|
||||
Directory.CreateDirectory(inputPath);
|
||||
|
||||
if(!Directory.Exists(outputPath))
|
||||
Directory.CreateDirectory(outputPath);
|
||||
|
||||
var rnd = new Random();
|
||||
|
||||
for (int i = 0; i < rnd.Next(1000); i++)
|
||||
{
|
||||
using var writer = new StreamWriter(Path.Combine(inputPath, $"{rnd.NextString(10)}.txt"), false);
|
||||
|
||||
for (int j = 0; j < rnd.Next(1000); j++)
|
||||
|
||||
{
|
||||
writer.WriteLine(rnd.Next());
|
||||
}
|
||||
writer.Close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
35
kuzarin_maxim_lab_2/FirstApplication/Dockerfile
Normal file
35
kuzarin_maxim_lab_2/FirstApplication/Dockerfile
Normal file
@@ -0,0 +1,35 @@
|
||||
# Это базовый образ для сборки.
|
||||
FROM mcr.microsoft.com/dotnet/runtime:8.0 AS base
|
||||
# Указываем рабочий каталог для следующих комманд
|
||||
WORKDIR /app
|
||||
|
||||
# Проект нужно сначала собрать, поэтому берём sdk
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
# Это пременная. Будем собирать в режиме Relece.
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
# Копируем из папки хоста в контейнер
|
||||
COPY ["FirstApplication.csproj", "FirstApplication/"]
|
||||
# Выполняем комманду для загрузки всех нужных зависимостей
|
||||
RUN dotnet restore "FirstApplication/FirstApplication.csproj"
|
||||
# Назначаем новую базовую папку
|
||||
WORKDIR "/src/FirstApplication"
|
||||
# Копируем всё в папку для сборки
|
||||
COPY . .
|
||||
# Выполняем сборку проекта
|
||||
RUN dotnet build "FirstApplication.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
# В этот этап попадает всё, что было в publish
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
# Публикуем всё в папку /app/publish
|
||||
RUN dotnet publish "FirstApplication.csproj" -c $BUILD_CONFIGURATION -o /app/publish --self-contained false --no-restore
|
||||
|
||||
# Берём тот образ, что определили в первой строке
|
||||
FROM base AS final
|
||||
# Указываем рабочую директорию
|
||||
WORKDIR /app
|
||||
# Из опубликованного блока берём то, что опубликовано и закидывае в /app
|
||||
COPY --from=publish /app/publish .
|
||||
# Указываем комманду запуска приложения (когда контейнер запустится, то начнёт с этого)
|
||||
ENTRYPOINT ["dotnet", "FirstApplication.dll"]
|
||||
15
kuzarin_maxim_lab_2/FirstApplication/FirstApplication.csproj
Normal file
15
kuzarin_maxim_lab_2/FirstApplication/FirstApplication.csproj
Normal file
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
17
kuzarin_maxim_lab_2/FirstApplication/Program.cs
Normal file
17
kuzarin_maxim_lab_2/FirstApplication/Program.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
Console.WriteLine("Запущен первый сервис");
|
||||
string inputPath = Environment.GetEnvironmentVariable("INPUT_PATH") ?? "./input1";
|
||||
string outputPath = Environment.GetEnvironmentVariable("OUTPUT_PATH") ?? "./output1";
|
||||
|
||||
if (!Directory.Exists(inputPath))
|
||||
Directory.CreateDirectory(inputPath);
|
||||
|
||||
if (!Directory.Exists(outputPath))
|
||||
Directory.CreateDirectory(outputPath);
|
||||
|
||||
var file = new DirectoryInfo(inputPath).EnumerateFiles().Aggregate((x, y) => x.Length > y.Length ? x : y);
|
||||
|
||||
var outputFilePath = Path.Combine(outputPath, "data.txt");
|
||||
|
||||
if(File.Exists(outputFilePath))
|
||||
File.Delete(outputFilePath);
|
||||
File.Move(file.FullName, Path.Combine(outputPath, "data.txt"));
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"profiles": {
|
||||
"FirstApplication": {
|
||||
"commandName": "Project"
|
||||
},
|
||||
"Container (Dockerfile)": {
|
||||
"commandName": "Docker"
|
||||
}
|
||||
}
|
||||
}
|
||||
25
kuzarin_maxim_lab_2/README.md
Normal file
25
kuzarin_maxim_lab_2/README.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# Лабораторная работа 2
|
||||
Данная работа посвящена теме создания контейнеров из исходного кода посредства dockerfile, а так же взаимодействию сервисов через общие папки
|
||||
## Описание
|
||||
Был варана следующая комбинация вариантов:
|
||||
- Первое приложение - 0-ой
|
||||
- Второе приложение - 1-ый
|
||||
В результате, после запуска система изучит папку ./volumes/input, найдёт самый большой файл, а затем найдёт в нём самое большое число, выведя в директорию ./volumes/output файл с его квадратом.
|
||||
Буфер же, по сути не имеет физического отображения на папку хоста.
|
||||
## Запуск
|
||||
Для запуска лабораторной работы необходимо иметь запущенный движок Docker на устройстве.
|
||||
Необходимо перейти в папку, где располагается данный файл. Далее открыть терминал и ввести команду:
|
||||
```
|
||||
docker compose up --build
|
||||
```
|
||||
В данном случае флаг `--build` заставит систему в любом случае собрать образы из исходников (даже если они уже есть).
|
||||
В результате, после сборки оба сервиса запустятся и выведут в консоль логи примерно следующего содержания:
|
||||
## Описание dockerfile файла
|
||||
Подробное описание дано в виде комментариев в самом файле первого сервиса. Так как для разработки использовался .net 8.0, команд довольно много. При этом, так как второй сервис написан на той же платформе, особенных отличий двух docekrfile-ов нет(кроме пути
|
||||
## Описание compose файла
|
||||
Благодаря директиве `depends_on` в compose файле второй сервис будет ждать, пока не будет поднят первый сервис, и только потом начнёт подниматься.
|
||||
Директива `build` позволяет использовать в compose не уже готовый образ, а тот, что будет собран непосредственно в момент запуска(если он уже существует и нет флага силовой сборки, будет использоваться существующий образ)
|
||||
Область volumes позволяет создать буферную область. Эту папку можно монтировать как результирующую для первого сервиса и исходную - для второго
|
||||
## Видеодемонстрация
|
||||
Был записан видеоролик, демонстрирующий процесс запуска и работы сервисов. Он расположен по [адресу](https://drive.google.com/file/d/1sACiKx3_HRApa89a7LZFAZV05o7POhq6/view?usp=sharing)
|
||||
|
||||
20
kuzarin_maxim_lab_2/SecondApplication/Dockerfile
Normal file
20
kuzarin_maxim_lab_2/SecondApplication/Dockerfile
Normal file
@@ -0,0 +1,20 @@
|
||||
FROM mcr.microsoft.com/dotnet/runtime:8.0 AS base
|
||||
WORKDIR /app
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
COPY ["SecondApplication.csproj", "SecondApplication/"]
|
||||
RUN dotnet restore "./SecondApplication/SecondApplication.csproj"
|
||||
WORKDIR "/src/SecondApplication"
|
||||
COPY . .
|
||||
RUN dotnet build "SecondApplication.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "SecondApplication.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "SecondApplication.dll"]
|
||||
31
kuzarin_maxim_lab_2/SecondApplication/Program.cs
Normal file
31
kuzarin_maxim_lab_2/SecondApplication/Program.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
Console.WriteLine("Запущен второй сервис");
|
||||
string inputPath = Environment.GetEnvironmentVariable("INPUT_PATH") ?? ".\\input2";
|
||||
string outputPath = Environment.GetEnvironmentVariable("OUTPUT_PATH") ?? ".\\output2";
|
||||
|
||||
if (!Directory.Exists(outputPath))
|
||||
Directory.CreateDirectory(outputPath);
|
||||
|
||||
var inputFilePath = Path.Combine(inputPath, "data.txt");
|
||||
var outputFilePath = Path.Combine(outputPath, "result.txt");
|
||||
|
||||
if (!File.Exists(inputFilePath))
|
||||
{
|
||||
Console.WriteLine($"Нет исходного файла {inputFilePath}");
|
||||
return;
|
||||
}
|
||||
|
||||
using var reader = new StreamReader(inputFilePath);
|
||||
|
||||
long maxNumber = 0;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var str = reader.ReadLine();
|
||||
if (str == null) break;
|
||||
|
||||
if (long.TryParse(str, out var number) && number > maxNumber)
|
||||
maxNumber = number;
|
||||
}
|
||||
|
||||
File.WriteAllText(outputFilePath, (maxNumber * maxNumber).ToString());
|
||||
Console.WriteLine($"Результат выполнения: {maxNumber * maxNumber}");
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"profiles": {
|
||||
"SecondApplication": {
|
||||
"commandName": "Project"
|
||||
},
|
||||
"Container (Dockerfile)": {
|
||||
"commandName": "Docker"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
22
kuzarin_maxim_lab_2/docker-compose.yml
Normal file
22
kuzarin_maxim_lab_2/docker-compose.yml
Normal file
@@ -0,0 +1,22 @@
|
||||
services:
|
||||
first:
|
||||
build: ./FirstApplication/
|
||||
volumes:
|
||||
- ./volumes/input:/var/data
|
||||
- buffer:/var/result
|
||||
environment:
|
||||
INPUT_PATH: "/var/data"
|
||||
OUTPUT_PATH: "/var/result"
|
||||
|
||||
second:
|
||||
build: ./SecondApplication/
|
||||
depends_on:
|
||||
- first
|
||||
volumes:
|
||||
- buffer:/var/data
|
||||
- ./volumes/output:/var/result
|
||||
environment:
|
||||
INPUT_PATH: "/var/data"
|
||||
OUTPUT_PATH: "/var/result"
|
||||
volumes:
|
||||
buffer:
|
||||
30
kuzarin_maxim_lab_3/.dockerignore
Normal file
30
kuzarin_maxim_lab_3/.dockerignore
Normal file
@@ -0,0 +1,30 @@
|
||||
**/.classpath
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/azds.yaml
|
||||
**/bin
|
||||
**/charts
|
||||
**/docker-compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
LICENSE
|
||||
README.md
|
||||
!**/.gitignore
|
||||
!.git/HEAD
|
||||
!.git/config
|
||||
!.git/packed-refs
|
||||
!.git/refs/heads/**
|
||||
63
kuzarin_maxim_lab_3/.gitattributes
vendored
Normal file
63
kuzarin_maxim_lab_3/.gitattributes
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
###############################################################################
|
||||
# Set default behavior to automatically normalize line endings.
|
||||
###############################################################################
|
||||
* text=auto
|
||||
|
||||
###############################################################################
|
||||
# Set default behavior for command prompt diff.
|
||||
#
|
||||
# This is need for earlier builds of msysgit that does not have it on by
|
||||
# default for csharp files.
|
||||
# Note: This is only used by command line
|
||||
###############################################################################
|
||||
#*.cs diff=csharp
|
||||
|
||||
###############################################################################
|
||||
# Set the merge driver for project and solution files
|
||||
#
|
||||
# Merging from the command prompt will add diff markers to the files if there
|
||||
# are conflicts (Merging from VS is not affected by the settings below, in VS
|
||||
# the diff markers are never inserted). Diff markers may cause the following
|
||||
# file extensions to fail to load in VS. An alternative would be to treat
|
||||
# these files as binary and thus will always conflict and require user
|
||||
# intervention with every merge. To do so, just uncomment the entries below
|
||||
###############################################################################
|
||||
#*.sln merge=binary
|
||||
#*.csproj merge=binary
|
||||
#*.vbproj merge=binary
|
||||
#*.vcxproj merge=binary
|
||||
#*.vcproj merge=binary
|
||||
#*.dbproj merge=binary
|
||||
#*.fsproj merge=binary
|
||||
#*.lsproj merge=binary
|
||||
#*.wixproj merge=binary
|
||||
#*.modelproj merge=binary
|
||||
#*.sqlproj merge=binary
|
||||
#*.wwaproj merge=binary
|
||||
|
||||
###############################################################################
|
||||
# behavior for image files
|
||||
#
|
||||
# image files are treated as binary by default.
|
||||
###############################################################################
|
||||
#*.jpg binary
|
||||
#*.png binary
|
||||
#*.gif binary
|
||||
|
||||
###############################################################################
|
||||
# diff behavior for common document formats
|
||||
#
|
||||
# Convert binary document formats to text before diffing them. This feature
|
||||
# is only available from the command line. Turn it on by uncommenting the
|
||||
# entries below.
|
||||
###############################################################################
|
||||
#*.doc diff=astextplain
|
||||
#*.DOC diff=astextplain
|
||||
#*.docx diff=astextplain
|
||||
#*.DOCX diff=astextplain
|
||||
#*.dot diff=astextplain
|
||||
#*.DOT diff=astextplain
|
||||
#*.pdf diff=astextplain
|
||||
#*.PDF diff=astextplain
|
||||
#*.rtf diff=astextplain
|
||||
#*.RTF diff=astextplain
|
||||
363
kuzarin_maxim_lab_3/.gitignore
vendored
Normal file
363
kuzarin_maxim_lab_3/.gitignore
vendored
Normal file
@@ -0,0 +1,363 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ww][Ii][Nn]32/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Oo]ut/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# ASP.NET Scaffolding
|
||||
ScaffoldingReadMe.txt
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Coverlet is a free, cross platform Code Coverage Tool
|
||||
coverage*.json
|
||||
coverage*.xml
|
||||
coverage*.info
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
31
kuzarin_maxim_lab_3/DSaC.sln
Normal file
31
kuzarin_maxim_lab_3/DSaC.sln
Normal file
@@ -0,0 +1,31 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.10.34916.146
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DSaC", "DSaC\DSaC.csproj", "{C1051C12-D7D0-4C77-AFBC-4F5FFD8EE367}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DSaC_second", "DSaC_second\DSaC_second.csproj", "{64F78585-2BBC-4656-BC50-41FBB8917719}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{C1051C12-D7D0-4C77-AFBC-4F5FFD8EE367}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C1051C12-D7D0-4C77-AFBC-4F5FFD8EE367}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C1051C12-D7D0-4C77-AFBC-4F5FFD8EE367}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C1051C12-D7D0-4C77-AFBC-4F5FFD8EE367}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{64F78585-2BBC-4656-BC50-41FBB8917719}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{64F78585-2BBC-4656-BC50-41FBB8917719}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{64F78585-2BBC-4656-BC50-41FBB8917719}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{64F78585-2BBC-4656-BC50-41FBB8917719}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {30D05708-634E-4FDE-9BCA-5A1B7A5EFF59}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,88 @@
|
||||
using DSaC.Models.DTOs;
|
||||
using DSaC.Models.Internal.Queries;
|
||||
using DSaC.Models.Internal.Сommands;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||
|
||||
namespace DSaC.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class CounterpartiesController : ControllerBase
|
||||
{
|
||||
private readonly IMediator mediator;
|
||||
|
||||
public CounterpartiesController(IMediator mediator)
|
||||
{
|
||||
this.mediator = mediator;
|
||||
}
|
||||
|
||||
[HttpGet("")]
|
||||
public async Task<IActionResult> GetCounterparties(
|
||||
[FromQuery] int page = 0,
|
||||
[FromQuery] int pageSize = 10,
|
||||
[FromQuery] List<Guid>? ids = null
|
||||
)
|
||||
{
|
||||
var request = new GetCounterpartiesQuery
|
||||
{
|
||||
Page = page,
|
||||
PageSize = pageSize,
|
||||
Ids = ids
|
||||
};
|
||||
|
||||
var response = await mediator.Send(request);
|
||||
|
||||
return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
|
||||
}
|
||||
|
||||
[HttpGet("{uuid:guid}")]
|
||||
public async Task<IActionResult> GetFullCounterparty([FromRoute] Guid uuid)
|
||||
{
|
||||
var request = new GetCounterpartyQuery
|
||||
{
|
||||
Id = uuid
|
||||
};
|
||||
|
||||
var response = await mediator.Send(request);
|
||||
|
||||
return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
|
||||
}
|
||||
|
||||
[HttpPost("")]
|
||||
public async Task<IActionResult> CreateCounterparty([FromBody] CounterpartyBaseDto dto)
|
||||
{
|
||||
var response = await mediator.Send(new CreateCounterpartyCommand()
|
||||
{
|
||||
Model = dto
|
||||
});
|
||||
|
||||
return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
|
||||
}
|
||||
|
||||
[HttpPut("{uuid:guid}")]
|
||||
public async Task<IActionResult> UpdateRecord([FromRoute] Guid uuid, [FromBody] CounterpartyViewDto dto)
|
||||
{
|
||||
var response = await mediator.Send(new UpdateCounterpartyCommand()
|
||||
{
|
||||
Id=uuid,
|
||||
Model = dto
|
||||
});
|
||||
|
||||
return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
|
||||
}
|
||||
|
||||
[HttpDelete("{uuid:guid}")]
|
||||
public async Task<IActionResult> DeleteRecord([FromRoute] Guid uuid)
|
||||
{
|
||||
var response = await mediator.Send(new DeleteCounterpartyCommand()
|
||||
{
|
||||
Id = uuid,
|
||||
});
|
||||
|
||||
return !response.IsError ? Ok() : StatusCode(response.ErrorCode!.Value, response.ErrorText);
|
||||
}
|
||||
}
|
||||
}
|
||||
26
kuzarin_maxim_lab_3/DSaC/DSaC.csproj
Normal file
26
kuzarin_maxim_lab_3/DSaC/DSaC.csproj
Normal file
@@ -0,0 +1,26 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>55894bef-8317-4e30-a5f0-4dcd5c3f861e</UserSecretsId>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MediatR" Version="12.4.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.8">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.12" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.4" />
|
||||
<PackageReference Include="PIHelperSh.Configuration" Version="1.0.1" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
14
kuzarin_maxim_lab_3/DSaC/Database/DsacContext.cs
Normal file
14
kuzarin_maxim_lab_3/DSaC/Database/DsacContext.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using DSaC.Database.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DSaC.Database
|
||||
{
|
||||
public class DsacContext: DbContext
|
||||
{
|
||||
public DsacContext(DbContextOptions options) : base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public DbSet<Counterparty> Counterparties { get; set; }
|
||||
}
|
||||
}
|
||||
24
kuzarin_maxim_lab_3/DSaC/Database/Models/Counterparty.cs
Normal file
24
kuzarin_maxim_lab_3/DSaC/Database/Models/Counterparty.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using AutoMapper;
|
||||
using DSaC.Models.DTOs;
|
||||
using DSaC.Models.Internal.Сommands;
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace DSaC.Database.Models
|
||||
{
|
||||
[Table("counterparty")]
|
||||
[AutoMap(typeof(CounterpartyBaseDto))]
|
||||
[AutoMap(typeof(CounterpartyViewDto))]
|
||||
public class Counterparty
|
||||
{
|
||||
[Key]
|
||||
[Column("id")]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[Required]
|
||||
[MaxLength(255)]
|
||||
[Column("name")]
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
||||
24
kuzarin_maxim_lab_3/DSaC/Dockerfile
Normal file
24
kuzarin_maxim_lab_3/DSaC/Dockerfile
Normal file
@@ -0,0 +1,24 @@
|
||||
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
|
||||
WORKDIR /app
|
||||
EXPOSE 8080
|
||||
EXPOSE 8081
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
COPY ["DSaC.csproj", "DSaC/"]
|
||||
RUN dotnet restore "DSaC/DSaC.csproj"
|
||||
WORKDIR "/src/DSaC"
|
||||
COPY . .
|
||||
RUN dotnet build "DSaC.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "DSaC.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "DSaC.dll"]
|
||||
@@ -0,0 +1,51 @@
|
||||
using AutoMapper;
|
||||
using DSaC.Database;
|
||||
using DSaC.Database.Models;
|
||||
using DSaC.Logic.Handlers.Queries;
|
||||
using DSaC.Models.DTOs;
|
||||
using DSaC.Models.Internal;
|
||||
using DSaC.Models.Internal.Сommands;
|
||||
using MediatR;
|
||||
|
||||
namespace DSaC.Logic.Handlers.Commands
|
||||
{
|
||||
public class CreateCounterpartyCommandHandler : IRequestHandler<CreateCounterpartyCommand, ResponseModel<CounterpartyViewDto>>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public CreateCounterpartyCommandHandler(ILogger<CreateCounterpartyCommandHandler> logger, DsacContext context, IMapper mapper)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<ResponseModel<CounterpartyViewDto>> Handle(CreateCounterpartyCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var model = _mapper.Map<Counterparty>(request.Model);
|
||||
|
||||
var res = await _context.AddAsync(model);
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return new()
|
||||
{
|
||||
Value = _mapper.Map<CounterpartyViewDto>(res.Entity)
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on creating counterparty");
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cannot create counterparty"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using AutoMapper;
|
||||
using DSaC.Database;
|
||||
using DSaC.Database.Models;
|
||||
using DSaC.Models.DTOs;
|
||||
using DSaC.Models.Internal;
|
||||
using DSaC.Models.Internal.Сommands;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DSaC.Logic.Handlers.Commands
|
||||
{
|
||||
public class DeleteCounterpartyCommandHandler: IRequestHandler<DeleteCounterpartyCommand, ResponseModel>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public DeleteCounterpartyCommandHandler(ILogger<DeleteCounterpartyCommandHandler> logger, DsacContext context, IMapper mapper)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<ResponseModel> Handle(DeleteCounterpartyCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var res = await _context.Counterparties.Where(x=>x.Id == request.Id).ExecuteDeleteAsync();
|
||||
|
||||
if (res == 1)return new();
|
||||
|
||||
return new()
|
||||
{
|
||||
ErrorText = "Cannot find object to delete",
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on deleteing counterparty");
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cannot delete counterparty"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using AutoMapper;
|
||||
using DSaC.Database;
|
||||
using DSaC.Database.Models;
|
||||
using DSaC.Models.DTOs;
|
||||
using DSaC.Models.Internal;
|
||||
using DSaC.Models.Internal.Сommands;
|
||||
using MediatR;
|
||||
|
||||
namespace DSaC.Logic.Handlers.Commands
|
||||
{
|
||||
public class UpdateCounterpartyCommandHandler: IRequestHandler<UpdateCounterpartyCommand, ResponseModel<CounterpartyViewDto>>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public UpdateCounterpartyCommandHandler(ILogger<UpdateCounterpartyCommandHandler> logger, DsacContext context, IMapper mapper)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<ResponseModel<CounterpartyViewDto>> Handle(UpdateCounterpartyCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var model = _mapper.Map<Counterparty>(request.Model);
|
||||
|
||||
var res = _context.Update(model);
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return new()
|
||||
{
|
||||
Value = _mapper.Map<CounterpartyViewDto>(res.Entity)
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on updating counterparty");
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cannot update counterparty"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using AutoMapper;
|
||||
using DSaC.Database;
|
||||
using DSaC.Models.DTOs;
|
||||
using DSaC.Models.Internal;
|
||||
using DSaC.Models.Internal.Queries;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DSaC.Logic.Handlers.Queries
|
||||
{
|
||||
public class GetCounterpartiesQueryHandler : IRequestHandler<GetCounterpartiesQuery, ResponseModel<List<CounterpartyViewDto>>>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public GetCounterpartiesQueryHandler(ILogger<GetCounterpartiesQueryHandler> logger, DsacContext context, IMapper mapper)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<ResponseModel<List<CounterpartyViewDto>>> Handle(GetCounterpartiesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var res = await _context.Counterparties
|
||||
.Where(x=>request.Ids == null || request.Ids.Contains(x.Id))
|
||||
.Skip(request.Page * request.PageSize).Take(request.PageSize)
|
||||
.ToListAsync();
|
||||
|
||||
return new()
|
||||
{
|
||||
Value = res.Select(_mapper.Map<CounterpartyViewDto>).ToList(),
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on getting records");
|
||||
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.BadRequest,
|
||||
ErrorText = "Cannot get Counterparties by this request",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using AutoMapper;
|
||||
using DSaC.Database;
|
||||
using DSaC.Models.DTOs;
|
||||
using DSaC.Models.Internal;
|
||||
using DSaC.Models.Internal.Queries;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DSaC.Logic.Handlers.Queries
|
||||
{
|
||||
public class GetCounterpartyQueryHandler: IRequestHandler<GetCounterpartyQuery, ResponseModel<CounterpartyViewDto>>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public GetCounterpartyQueryHandler(ILogger<GetCounterpartyQueryHandler> logger, DsacContext context, IMapper mapper)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<ResponseModel<CounterpartyViewDto>> Handle(GetCounterpartyQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var res = await _context.Counterparties.FirstOrDefaultAsync(x=>x.Id == request.Id);
|
||||
|
||||
if (res == null)
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Counterparty with this ID does not exsist",
|
||||
};
|
||||
|
||||
return new()
|
||||
{
|
||||
Value = _mapper.Map<CounterpartyViewDto>(res),
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on getting record");
|
||||
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cannot get Counterparty by id",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
60
kuzarin_maxim_lab_3/DSaC/Migrations/20240907133944_InitMigraton.Designer.cs
generated
Normal file
60
kuzarin_maxim_lab_3/DSaC/Migrations/20240907133944_InitMigraton.Designer.cs
generated
Normal file
@@ -0,0 +1,60 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using DSaC.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC.Migrations
|
||||
{
|
||||
[DbContext(typeof(DsacContext))]
|
||||
[Migration("20240907133944_InitMigraton")]
|
||||
partial class InitMigraton
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "8.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("DSaC.Database.Models.Counterparty", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("ContractNumber")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("character varying(50)")
|
||||
.HasColumnName("contract_number");
|
||||
|
||||
b.Property<string>("ManagerName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("character varying(255)")
|
||||
.HasColumnName("manager_name");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("character varying(255)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("counterparty");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitMigraton : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "counterparty",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
name = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),
|
||||
contract_number = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
|
||||
manager_name = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_counterparty", x => x.id);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "counterparty");
|
||||
}
|
||||
}
|
||||
}
|
||||
64
kuzarin_maxim_lab_3/DSaC/Migrations/20240907140843_ChangingContractInfo.Designer.cs
generated
Normal file
64
kuzarin_maxim_lab_3/DSaC/Migrations/20240907140843_ChangingContractInfo.Designer.cs
generated
Normal file
@@ -0,0 +1,64 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using DSaC.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC.Migrations
|
||||
{
|
||||
[DbContext(typeof(DsacContext))]
|
||||
[Migration("20240907140843_ChangingContractInfo")]
|
||||
partial class ChangingContractInfo
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "8.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("DSaC.Database.Models.Counterparty", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("ContractNumber")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("character varying(50)")
|
||||
.HasColumnName("contract_number");
|
||||
|
||||
b.Property<bool>("IsContractClosed")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_contract_closed");
|
||||
|
||||
b.Property<string>("ManagerName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("character varying(255)")
|
||||
.HasColumnName("manager_name");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("character varying(255)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("counterparty");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class ChangingContractInfo : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "is_contract_closed",
|
||||
table: "counterparty",
|
||||
type: "boolean",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "is_contract_closed",
|
||||
table: "counterparty");
|
||||
}
|
||||
}
|
||||
}
|
||||
63
kuzarin_maxim_lab_3/DSaC/Migrations/20240907141343_SmallHotfix.Designer.cs
generated
Normal file
63
kuzarin_maxim_lab_3/DSaC/Migrations/20240907141343_SmallHotfix.Designer.cs
generated
Normal file
@@ -0,0 +1,63 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using DSaC.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC.Migrations
|
||||
{
|
||||
[DbContext(typeof(DsacContext))]
|
||||
[Migration("20240907141343_SmallHotfix")]
|
||||
partial class SmallHotfix
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "8.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("DSaC.Database.Models.Counterparty", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("ContractNumber")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("character varying(50)")
|
||||
.HasColumnName("contract_number");
|
||||
|
||||
b.Property<bool>("IsContractClosed")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_contract_closed");
|
||||
|
||||
b.Property<string>("ManagerName")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("character varying(255)")
|
||||
.HasColumnName("manager_name");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("character varying(255)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("counterparty");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class SmallHotfix : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "manager_name",
|
||||
table: "counterparty",
|
||||
type: "character varying(255)",
|
||||
maxLength: 255,
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(255)",
|
||||
oldMaxLength: 255);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "manager_name",
|
||||
table: "counterparty",
|
||||
type: "character varying(255)",
|
||||
maxLength: 255,
|
||||
nullable: false,
|
||||
defaultValue: "",
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(255)",
|
||||
oldMaxLength: 255,
|
||||
oldNullable: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
48
kuzarin_maxim_lab_3/DSaC/Migrations/20240914065929_after-reconstruction.Designer.cs
generated
Normal file
48
kuzarin_maxim_lab_3/DSaC/Migrations/20240914065929_after-reconstruction.Designer.cs
generated
Normal file
@@ -0,0 +1,48 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using DSaC.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC.Migrations
|
||||
{
|
||||
[DbContext(typeof(DsacContext))]
|
||||
[Migration("20240914065929_after-reconstruction")]
|
||||
partial class afterreconstruction
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "8.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("DSaC.Database.Models.Counterparty", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("character varying(255)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("counterparty");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class afterreconstruction : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "contract_number",
|
||||
table: "counterparty");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "is_contract_closed",
|
||||
table: "counterparty");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "manager_name",
|
||||
table: "counterparty");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "contract_number",
|
||||
table: "counterparty",
|
||||
type: "character varying(50)",
|
||||
maxLength: 50,
|
||||
nullable: false,
|
||||
defaultValue: "");
|
||||
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "is_contract_closed",
|
||||
table: "counterparty",
|
||||
type: "boolean",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "manager_name",
|
||||
table: "counterparty",
|
||||
type: "character varying(255)",
|
||||
maxLength: 255,
|
||||
nullable: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using DSaC.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC.Migrations
|
||||
{
|
||||
[DbContext(typeof(DsacContext))]
|
||||
partial class DsacContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "8.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("DSaC.Database.Models.Counterparty", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("character varying(255)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("counterparty");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
17
kuzarin_maxim_lab_3/DSaC/Models/DTOs/ContractViewDto.cs
Normal file
17
kuzarin_maxim_lab_3/DSaC/Models/DTOs/ContractViewDto.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace DSaC.Models.DTOs
|
||||
{
|
||||
public class ContractViewDto
|
||||
{
|
||||
[Required(ErrorMessage = "Contract number must be present")]
|
||||
public string ContractNumber { get; set; } = null!;
|
||||
|
||||
[Required(ErrorMessage = "Manager name must be present")]
|
||||
public string ManagerName { get; set; } = null!;
|
||||
|
||||
public DateTime CreatinTime { get; set; }
|
||||
|
||||
public bool IsClosed { get; set; }
|
||||
}
|
||||
}
|
||||
13
kuzarin_maxim_lab_3/DSaC/Models/DTOs/CounterpartyBaseDto.cs
Normal file
13
kuzarin_maxim_lab_3/DSaC/Models/DTOs/CounterpartyBaseDto.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
|
||||
using AutoMapper;
|
||||
using DSaC.Database.Models;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace DSaC.Models.DTOs
|
||||
{
|
||||
public class CounterpartyBaseDto
|
||||
{
|
||||
[Required(ErrorMessage = "Cpty name must be present")]
|
||||
public string Name { get; set; } = null!;
|
||||
}
|
||||
}
|
||||
11
kuzarin_maxim_lab_3/DSaC/Models/DTOs/CounterpartyViewDto.cs
Normal file
11
kuzarin_maxim_lab_3/DSaC/Models/DTOs/CounterpartyViewDto.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using AutoMapper;
|
||||
using DSaC.Database.Models;
|
||||
|
||||
namespace DSaC.Models.DTOs
|
||||
{
|
||||
[AutoMap(typeof(Counterparty))]
|
||||
public class CounterpartyViewDto: CounterpartyBaseDto
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using DSaC.Models.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace DSaC.Models.Internal.Queries
|
||||
{
|
||||
public class GetCounterpartiesQuery: IRequest<ResponseModel<List<CounterpartyViewDto>>>
|
||||
{
|
||||
public List<Guid>? Ids { get; set; }
|
||||
|
||||
public int Page { get; set; }
|
||||
|
||||
public int PageSize { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using DSaC.Models.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace DSaC.Models.Internal.Queries
|
||||
{
|
||||
public class GetCounterpartyQuery: IRequest<ResponseModel<CounterpartyViewDto>>
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
}
|
||||
}
|
||||
30
kuzarin_maxim_lab_3/DSaC/Models/Internal/ResponseModel.cs
Normal file
30
kuzarin_maxim_lab_3/DSaC/Models/Internal/ResponseModel.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using System.Net;
|
||||
|
||||
namespace DSaC.Models.Internal
|
||||
{
|
||||
public class ResponseModel
|
||||
{
|
||||
public string? ErrorText;
|
||||
|
||||
public bool IsError => !string.IsNullOrEmpty(ErrorText);
|
||||
|
||||
private int? _errorCode = 200;
|
||||
|
||||
public int? ErrorCode
|
||||
{
|
||||
get => _errorCode;
|
||||
set => _errorCode = value;
|
||||
}
|
||||
|
||||
public HttpStatusCode? StatusCode
|
||||
{
|
||||
get => (HttpStatusCode?)_errorCode;
|
||||
set => _errorCode = (int?)value;
|
||||
}
|
||||
}
|
||||
|
||||
public class ResponseModel<T> : ResponseModel
|
||||
{
|
||||
public T? Value { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using DSaC.Models.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace DSaC.Models.Internal.Сommands
|
||||
{
|
||||
public class CreateCounterpartyCommand : IRequest<ResponseModel<CounterpartyViewDto>>
|
||||
{
|
||||
public CounterpartyBaseDto Model { get; set; } = null!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using MediatR;
|
||||
|
||||
namespace DSaC.Models.Internal.Сommands
|
||||
{
|
||||
public class DeleteCounterpartyCommand: IRequest<ResponseModel>
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using DSaC.Models.DTOs;
|
||||
using MediatR;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace DSaC.Models.Internal.Сommands
|
||||
{
|
||||
public class UpdateCounterpartyCommand: IRequest<ResponseModel<CounterpartyViewDto>>
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "UpdateMessageMust be present")]
|
||||
public CounterpartyViewDto Model { get; set; } = null!;
|
||||
}
|
||||
}
|
||||
128
kuzarin_maxim_lab_3/DSaC/Program.cs
Normal file
128
kuzarin_maxim_lab_3/DSaC/Program.cs
Normal file
@@ -0,0 +1,128 @@
|
||||
using DSaC.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using NLog.Config;
|
||||
using NLog.Extensions.Logging;
|
||||
using NLog.Targets;
|
||||
using PIHelperSh.Configuration;
|
||||
using PIHelperSh.Configuration.Attributes;
|
||||
using System.Reflection;
|
||||
using LogLevel = NLog.LogLevel;
|
||||
|
||||
[TrackedType]
|
||||
public class Program
|
||||
{
|
||||
private static WebApplication? app;
|
||||
|
||||
[Constant(BlockName = "Database")]
|
||||
private static string ConnectionString;
|
||||
|
||||
[Constant(BlockName = "GatewaySettings")]
|
||||
private static string AppPrefix;
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
ConfigureLogger(builder);
|
||||
|
||||
ConfigureServices(builder);
|
||||
|
||||
ConfigureDatabase(builder);
|
||||
|
||||
app = builder.Build();
|
||||
|
||||
var t = MigrateDatabase();
|
||||
|
||||
app.UseSwagger(c =>
|
||||
{
|
||||
if (!string.IsNullOrEmpty(AppPrefix))
|
||||
{
|
||||
//c.RouteTemplate = AppPrefix + "/swagger/{documentName}/swagger.json";
|
||||
|
||||
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
|
||||
{
|
||||
swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}/{AppPrefix}" } };
|
||||
});
|
||||
}
|
||||
});
|
||||
app.UseSwaggerUI(c =>
|
||||
{
|
||||
//if (!string.IsNullOrEmpty(AppPrefix))
|
||||
//{
|
||||
// c.SwaggerEndpoint($"/{AppPrefix}/swagger/v1/swagger.json", $"APP API");
|
||||
// c.RoutePrefix = $"{AppPrefix}/swagger";
|
||||
//}
|
||||
});
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
t.Wait();
|
||||
|
||||
app.Run();
|
||||
}
|
||||
|
||||
private static void ConfigureLogger(WebApplicationBuilder builder)
|
||||
{
|
||||
var nLogConfig = new LoggingConfiguration();
|
||||
var logConsole = new ConsoleTarget();
|
||||
var blackhole = new NullTarget();
|
||||
|
||||
var logFile = new FileTarget()
|
||||
{
|
||||
FileName = "${basedir}/logs/${shortdate}_logs.log"
|
||||
};
|
||||
|
||||
nLogConfig.AddRule(LogLevel.Trace, LogLevel.Trace, blackhole, "Microsoft.AspNetCore.*", true);
|
||||
nLogConfig.AddRule(LogLevel.Info, LogLevel.Warn, logFile, "Microsoft.EntityFrameworkCore.*", true);
|
||||
nLogConfig.AddRule(LogLevel.Info, LogLevel.Warn, logFile, "Microsoft.AspNetCore.*", true);
|
||||
nLogConfig.AddRule(LogLevel.Info, LogLevel.Warn, logFile, "System.Net.Http.HttpClient.Refit.*", true);
|
||||
nLogConfig.AddRule(LogLevel.Info, LogLevel.Error, logConsole);
|
||||
nLogConfig.AddRule(LogLevel.Debug, LogLevel.Error, logFile);
|
||||
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Services.AddLogging(m => m.AddNLog(nLogConfig));
|
||||
}
|
||||
|
||||
private static void ConfigureServices(WebApplicationBuilder builder)
|
||||
{
|
||||
builder.Services.AddConfigurations(builder.Configuration);
|
||||
builder.Configuration.AddConstants();
|
||||
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
|
||||
|
||||
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>());
|
||||
|
||||
builder.Services.AddControllers().AddNewtonsoftJson();
|
||||
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo
|
||||
{
|
||||
Title = "Distributed computing and applications",
|
||||
Version = "v1",
|
||||
Description = ""
|
||||
});
|
||||
|
||||
//c.EnableAnnotations();
|
||||
});
|
||||
}
|
||||
|
||||
private static void ConfigureDatabase(WebApplicationBuilder builder)
|
||||
{
|
||||
builder.Services.AddDbContext<DsacContext>(options =>
|
||||
{
|
||||
options.UseNpgsql(ConnectionString);
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task MigrateDatabase()
|
||||
{
|
||||
var context = app?.Services.CreateScope().ServiceProvider.GetService<DsacContext>();
|
||||
if(context != null)
|
||||
await context.Database.MigrateAsync();
|
||||
}
|
||||
}
|
||||
52
kuzarin_maxim_lab_3/DSaC/Properties/launchSettings.json
Normal file
52
kuzarin_maxim_lab_3/DSaC/Properties/launchSettings.json
Normal file
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "http://localhost:5062"
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "https://localhost:7219;http://localhost:5062"
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"Container (Dockerfile)": {
|
||||
"commandName": "Docker",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_HTTPS_PORTS": "8081",
|
||||
"ASPNETCORE_HTTP_PORTS": "8080"
|
||||
},
|
||||
"publishAllPorts": true,
|
||||
"useSSL": true
|
||||
}
|
||||
},
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:9154",
|
||||
"sslPort": 44381
|
||||
}
|
||||
}
|
||||
}
|
||||
14
kuzarin_maxim_lab_3/DSaC/appsettings.Development.json
Normal file
14
kuzarin_maxim_lab_3/DSaC/appsettings.Development.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Database": {
|
||||
"ConnectionString": "Host=db.dev-moio.online;Port=31153;Database=dsac_maxim;Username=postgres;Password=postgres_password"
|
||||
},
|
||||
"GatewaySettings": {
|
||||
"AppPrefix": ""
|
||||
}
|
||||
}
|
||||
9
kuzarin_maxim_lab_3/DSaC/appsettings.json
Normal file
9
kuzarin_maxim_lab_3/DSaC/appsettings.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using DSaC_second.Models.DTOs;
|
||||
using DSaC_second.Models.Internal.Queries;
|
||||
using DSaC_second.Models.Internal.Сommands;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Components.Forms;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace DSaC_second.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class ContractController : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public ContractController(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator;
|
||||
}
|
||||
|
||||
[HttpGet("")]
|
||||
public async Task<IActionResult> GetContracts(
|
||||
[FromQuery] int page = 0,
|
||||
[FromQuery] int pageSize = 10,
|
||||
[FromQuery] List<Guid>? ids = null
|
||||
)
|
||||
{
|
||||
var request = new GetContractsQuery
|
||||
{
|
||||
Page = page,
|
||||
PageSize = pageSize,
|
||||
Ids = ids
|
||||
};
|
||||
|
||||
var response = await _mediator.Send(request);
|
||||
|
||||
return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
|
||||
}
|
||||
|
||||
[HttpGet("{uuid:guid}")]
|
||||
public async Task<IActionResult> GetFullContract([FromRoute] Guid uuid)
|
||||
{
|
||||
var request = new GetContractQuery
|
||||
{
|
||||
Id = uuid
|
||||
};
|
||||
|
||||
var response = await _mediator.Send(request);
|
||||
|
||||
return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
|
||||
}
|
||||
|
||||
[HttpPost("")]
|
||||
public async Task<IActionResult> CreateContract([FromBody] ContractBaseDto dto)
|
||||
{
|
||||
var response = await _mediator.Send(new CreateContractCommand()
|
||||
{
|
||||
Model = dto
|
||||
});
|
||||
|
||||
return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
|
||||
}
|
||||
|
||||
[HttpPut("{uuid:guid}")]
|
||||
public async Task<IActionResult> UpdateContract([FromRoute] Guid uuid, [FromBody] ContractViewDto dto)
|
||||
{
|
||||
var response = await _mediator.Send(new UpdateContractCommand()
|
||||
{
|
||||
Id = uuid,
|
||||
Model = dto
|
||||
});
|
||||
|
||||
return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
|
||||
}
|
||||
|
||||
[HttpDelete("{uuid:guid}")]
|
||||
public async Task<IActionResult> DeleteContract([FromRoute] Guid uuid)
|
||||
{
|
||||
var response = await _mediator.Send(new DeleteContractCommand()
|
||||
{
|
||||
Id = uuid,
|
||||
});
|
||||
|
||||
return !response.IsError ? Ok() : StatusCode(response.ErrorCode!.Value, response.ErrorText);
|
||||
}
|
||||
}
|
||||
}
|
||||
27
kuzarin_maxim_lab_3/DSaC_second/DSaC_second.csproj
Normal file
27
kuzarin_maxim_lab_3/DSaC_second/DSaC_second.csproj
Normal file
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>39d29416-63e9-4884-9c5f-9d6ff461995f</UserSecretsId>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MediatR" Version="12.4.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.8">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.13" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.4" />
|
||||
<PackageReference Include="PIHelperSh.Configuration" Version="1.0.1" />
|
||||
<PackageReference Include="RestSharp" Version="112.0.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
15
kuzarin_maxim_lab_3/DSaC_second/Database/DsacContext.cs
Normal file
15
kuzarin_maxim_lab_3/DSaC_second/Database/DsacContext.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using DSaC_second.Database.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DSaC_second.Database
|
||||
{
|
||||
public class DsacContext : DbContext
|
||||
{
|
||||
public DsacContext(DbContextOptions options) : base(options)
|
||||
{
|
||||
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
|
||||
}
|
||||
|
||||
public DbSet<Contract> Contracts { get; set; }
|
||||
}
|
||||
}
|
||||
38
kuzarin_maxim_lab_3/DSaC_second/Database/Models/Contract.cs
Normal file
38
kuzarin_maxim_lab_3/DSaC_second/Database/Models/Contract.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using AutoMapper;
|
||||
using DSaC_second.Models.DTOs;
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace DSaC_second.Database.Models
|
||||
{
|
||||
[Table("contract")]
|
||||
[AutoMap(typeof(ContractBaseDto))]
|
||||
[AutoMap(typeof(ContractViewDto))]
|
||||
public class Contract
|
||||
{
|
||||
[Key]
|
||||
[Column("id")]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[Column("contract_number")]
|
||||
[Required]
|
||||
public string ContractNumber { get; set; }
|
||||
|
||||
[Column("manager_name")]
|
||||
[Required]
|
||||
public string ManagerName { get; set; }
|
||||
|
||||
[Column("counterparty_id")]
|
||||
[Required]
|
||||
public Guid CounterpartyId { get; set; }
|
||||
|
||||
[Column("creation_time")]
|
||||
[Required]
|
||||
public DateTime CreatinTime { get; set; } = DateTime.Now;
|
||||
|
||||
[Column("is_closed")]
|
||||
[DefaultValue(false)]
|
||||
public bool IsClosed { get; set; }
|
||||
}
|
||||
}
|
||||
24
kuzarin_maxim_lab_3/DSaC_second/Dockerfile
Normal file
24
kuzarin_maxim_lab_3/DSaC_second/Dockerfile
Normal file
@@ -0,0 +1,24 @@
|
||||
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
|
||||
WORKDIR /app
|
||||
EXPOSE 8080
|
||||
EXPOSE 8081
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
COPY ["DSaC_second.csproj", "DSaC_second/"]
|
||||
RUN dotnet restore "DSaC_second/DSaC_second.csproj"
|
||||
WORKDIR "/src/DSaC_second"
|
||||
COPY . .
|
||||
RUN dotnet build "DSaC_second.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "DSaC_second.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "DSaC_second.dll"]
|
||||
@@ -0,0 +1,76 @@
|
||||
using AutoMapper;
|
||||
using DSaC_second.Database;
|
||||
using DSaC_second.Database.Models;
|
||||
using DSaC_second.Logic.Handlers.Queries;
|
||||
using DSaC_second.Models.DTOs;
|
||||
using DSaC_second.Models.Internal;
|
||||
using DSaC_second.Models.Internal.Queries;
|
||||
using DSaC_second.Models.Internal.Сommands;
|
||||
using MediatR;
|
||||
|
||||
namespace DSaC_second.Logic.Handlers.Commands
|
||||
{
|
||||
public class CreateContractCommandHandler : IRequestHandler<CreateContractCommand, ResponseModel<ContractFullDto>>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public CreateContractCommandHandler(ILogger<CreateContractCommandHandler> logger, DsacContext context, IMapper mapper, IMediator mediator)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
_mediator = mediator;
|
||||
}
|
||||
|
||||
public async Task<ResponseModel<ContractFullDto>> Handle(CreateContractCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var counterparty = await _mediator.Send(new GetConunterpartyQuery()
|
||||
{
|
||||
Id = request.Model.CounterpartyId,
|
||||
}, cancellationToken: cancellationToken);
|
||||
|
||||
if (counterparty.IsError)
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = counterparty.ErrorText,
|
||||
};
|
||||
if (counterparty.Value == null)
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cpty with this id not found",
|
||||
};
|
||||
|
||||
var model = _mapper.Map<Contract>(request.Model);
|
||||
|
||||
var outModel = await _context.Contracts.AddAsync(model, cancellationToken: cancellationToken);
|
||||
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
var res = _mapper.Map<ContractFullDto>(model);
|
||||
res.Counterparty = counterparty.Value!;
|
||||
|
||||
return new()
|
||||
{
|
||||
Value = res,
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on creating record");
|
||||
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cannot create contract",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using AutoMapper;
|
||||
using DSaC_second.Database;
|
||||
using DSaC_second.Models.Internal;
|
||||
using DSaC_second.Models.Internal.Сommands;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DSaC_second.Logic.Handlers.Commands
|
||||
{
|
||||
public class DeleteContractCommandHandler: IRequestHandler<DeleteContractCommand, ResponseModel>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public DeleteContractCommandHandler(ILogger<DeleteContractCommandHandler> logger, DsacContext context, IMapper mapper)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<ResponseModel> Handle(DeleteContractCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _context.Contracts.Where(x => x.Id == request.Id).ExecuteDeleteAsync(cancellationToken);
|
||||
|
||||
return new();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on deleting record");
|
||||
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cannot delete contract by id",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using AutoMapper;
|
||||
using DSaC_second.Database;
|
||||
using DSaC_second.Database.Models;
|
||||
using DSaC_second.Models.DTOs;
|
||||
using DSaC_second.Models.Internal;
|
||||
using DSaC_second.Models.Internal.Queries;
|
||||
using DSaC_second.Models.Internal.Сommands;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DSaC_second.Logic.Handlers.Commands
|
||||
{
|
||||
public class UpdateContractCommandHandler : IRequestHandler<UpdateContractCommand, ResponseModel<ContractFullDto>>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public UpdateContractCommandHandler(ILogger<UpdateContractCommandHandler> logger, DsacContext context, IMapper mapper, IMediator mediator)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
_mediator = mediator;
|
||||
}
|
||||
|
||||
public async Task<ResponseModel<ContractFullDto>> Handle(UpdateContractCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var counterparty = await _mediator.Send(new GetConunterpartyQuery()
|
||||
{
|
||||
Id = request.Model.CounterpartyId,
|
||||
}, cancellationToken: cancellationToken);
|
||||
|
||||
if (counterparty.IsError)
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = counterparty.ErrorText,
|
||||
};
|
||||
if(counterparty.Value == null)
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cpty with this id not found",
|
||||
};
|
||||
|
||||
var model = _mapper.Map<Contract>(request.Model);
|
||||
|
||||
_context.Contracts.Update(model);
|
||||
|
||||
await _context.SaveChangesAsync(cancellationToken: cancellationToken);
|
||||
|
||||
var res = _mapper.Map<ContractFullDto>(model);
|
||||
|
||||
res.Counterparty = counterparty.Value!;
|
||||
|
||||
return new()
|
||||
{
|
||||
Value = res
|
||||
};
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on updating record");
|
||||
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cannot update contract by id",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using AutoMapper;
|
||||
using DSaC_second.Database;
|
||||
using DSaC_second.Models.DTOs;
|
||||
using DSaC_second.Models.Internal;
|
||||
using DSaC_second.Models.Internal.Queries;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DSaC_second.Logic.Handlers.Queries
|
||||
{
|
||||
public class GetContractQueryHandler : IRequestHandler<GetContractQuery, ResponseModel<ContractFullDto>>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public GetContractQueryHandler(ILogger<GetContractQueryHandler> logger, DsacContext context, IMapper mapper, IMediator mediator)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
_mediator = mediator;
|
||||
}
|
||||
|
||||
public async Task<ResponseModel<ContractFullDto>> Handle(GetContractQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var res = await _context.Contracts.FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken: cancellationToken);
|
||||
|
||||
if (res == null)
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Contract with whit Id is not exist"
|
||||
};
|
||||
var counterparty = await _mediator.Send(new GetConunterpartyQuery()
|
||||
{
|
||||
Id = res.CounterpartyId
|
||||
}, cancellationToken: cancellationToken);
|
||||
|
||||
if (counterparty.IsError)
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = counterparty.ErrorText
|
||||
};
|
||||
|
||||
var model = _mapper.Map<ContractFullDto>(res);
|
||||
model.Counterparty = counterparty.Value!;
|
||||
|
||||
return new()
|
||||
{
|
||||
Value = model,
|
||||
};
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on getting record");
|
||||
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cannot get contract by id",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using AutoMapper;
|
||||
using DSaC_second.Database;
|
||||
using DSaC_second.Models.DTOs;
|
||||
using DSaC_second.Models.Internal;
|
||||
using DSaC_second.Models.Internal.Queries;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DSaC_second.Logic.Handlers.Queries
|
||||
{
|
||||
public class GetContractsQueryHandler : IRequestHandler<GetContractsQuery, ResponseModel<List<ContractViewDto>>>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public GetContractsQueryHandler(ILogger<GetContractsQueryHandler> logger, DsacContext context, IMapper mapper)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<ResponseModel<List<ContractViewDto>>> Handle(GetContractsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var res = await _context.Contracts
|
||||
.Where(x=>request.Ids == null || request.Ids.Contains(x.Id))
|
||||
.Skip(request.Page * request.PageSize).Take(request.PageSize)
|
||||
.ToListAsync(cancellationToken: cancellationToken);
|
||||
|
||||
return new()
|
||||
{
|
||||
Value = res.Select(_mapper.Map<ContractViewDto>).ToList(),
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on getting records");
|
||||
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cannot get contracts",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using AutoMapper;
|
||||
using DSaC_second.Database;
|
||||
using DSaC_second.Logic.Handlers.Commands;
|
||||
using DSaC_second.Models.DTOs;
|
||||
using DSaC_second.Models.Internal;
|
||||
using DSaC_second.Models.Internal.Queries;
|
||||
using MediatR;
|
||||
using PIHelperSh.Configuration.Attributes;
|
||||
using RestSharp;
|
||||
|
||||
namespace DSaC_second.Logic.Handlers.Queries
|
||||
{
|
||||
[TrackedType]
|
||||
public class GetConunterpartyQueryHandler : IRequestHandler<GetConunterpartyQuery, ResponseModel<CounterpartyViewDto>>
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly DsacContext _context;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly RestClient _restClient;
|
||||
|
||||
[Constant(BlockName = "FirstService")]
|
||||
private static string BaseUrl;
|
||||
|
||||
[Constant(BlockName = "FirstService")]
|
||||
private static string GetCounterpartyPostfix;
|
||||
|
||||
public GetConunterpartyQueryHandler(ILogger<GetConunterpartyQueryHandler> logger, DsacContext context, IMapper mapper)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_mapper = mapper;
|
||||
_restClient = new RestClient(BaseUrl);
|
||||
}
|
||||
|
||||
~GetConunterpartyQueryHandler()
|
||||
{
|
||||
_restClient.Dispose();
|
||||
}
|
||||
|
||||
public async Task<ResponseModel<CounterpartyViewDto>> Handle(GetConunterpartyQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var rq = new RestRequest($"{GetCounterpartyPostfix}/{request.Id.ToString()}");
|
||||
|
||||
var res = await _restClient.ExecuteAsync<CounterpartyViewDto>(rq, cancellationToken:cancellationToken);
|
||||
|
||||
if (res.IsSuccessful)
|
||||
return new()
|
||||
{
|
||||
Value = res.Data
|
||||
};
|
||||
|
||||
return new()
|
||||
{
|
||||
StatusCode = res.StatusCode,
|
||||
ErrorText = res.ErrorMessage,
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error on getting record from first service");
|
||||
|
||||
return new()
|
||||
{
|
||||
StatusCode = System.Net.HttpStatusCode.NotFound,
|
||||
ErrorText = "Cannot get cpty from first service",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
64
kuzarin_maxim_lab_3/DSaC_second/Migrations/20240914152154_initial.Designer.cs
generated
Normal file
64
kuzarin_maxim_lab_3/DSaC_second/Migrations/20240914152154_initial.Designer.cs
generated
Normal file
@@ -0,0 +1,64 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using DSaC_second.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC_second.Migrations
|
||||
{
|
||||
[DbContext(typeof(DsacContext))]
|
||||
[Migration("20240914152154_initial")]
|
||||
partial class initial
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "8.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("DSaC_second.Database.Models.Contract", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("ContractNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("contract_number");
|
||||
|
||||
b.Property<Guid>("CounterpartyId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("counterparty_id");
|
||||
|
||||
b.Property<DateTime>("CreatinTime")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("creation_time");
|
||||
|
||||
b.Property<bool>("IsClosed")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_closed");
|
||||
|
||||
b.Property<string>("ManagerName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("manager_name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("contract");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC_second.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class initial : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "contract",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
contract_number = table.Column<string>(type: "text", nullable: false),
|
||||
manager_name = table.Column<string>(type: "text", nullable: false),
|
||||
counterparty_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
creation_time = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
is_closed = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_contract", x => x.id);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "contract");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using DSaC_second.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DSaC_second.Migrations
|
||||
{
|
||||
[DbContext(typeof(DsacContext))]
|
||||
partial class DsacContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "8.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("DSaC_second.Database.Models.Contract", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("ContractNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("contract_number");
|
||||
|
||||
b.Property<Guid>("CounterpartyId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("counterparty_id");
|
||||
|
||||
b.Property<DateTime>("CreatinTime")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("creation_time");
|
||||
|
||||
b.Property<bool>("IsClosed")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_closed");
|
||||
|
||||
b.Property<string>("ManagerName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("manager_name");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("contract");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using AutoMapper;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace DSaC_second.Models.DTOs
|
||||
{
|
||||
public class ContractBaseDto
|
||||
{
|
||||
[Required(ErrorMessage = "Contract number must be present")]
|
||||
public string ContractNumber { get; set; } = null!;
|
||||
|
||||
[Required(ErrorMessage = "Manager name must be present")]
|
||||
public string ManagerName { get; set; } = null!;
|
||||
|
||||
[Required(ErrorMessage = "Counterparty id must be present")]
|
||||
public Guid CounterpartyId { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using AutoMapper;
|
||||
using DSaC_second.Database.Models;
|
||||
|
||||
namespace DSaC_second.Models.DTOs
|
||||
{
|
||||
[AutoMap(typeof(Contract))]
|
||||
public class ContractFullDto: ContractViewDto
|
||||
{
|
||||
public CounterpartyViewDto Counterparty { get; set; } = new();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using AutoMapper;
|
||||
using DSaC_second.Database.Models;
|
||||
|
||||
namespace DSaC_second.Models.DTOs
|
||||
{
|
||||
[AutoMap(typeof(Contract))]
|
||||
public class ContractViewDto: ContractBaseDto
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public DateTime CreatinTime { get; set; }
|
||||
|
||||
public bool IsClosed { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace DSaC_second.Models.DTOs
|
||||
{
|
||||
public class CounterpartyViewDto
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "Cpty name must be present")]
|
||||
public string Name { get; set; } = null!;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user