yakovleva_yulia_lab_2 #20

Merged
Alexey merged 4 commits from yakovleva_yulia_lab_2 into main 2024-09-26 08:45:10 +04:00
17 changed files with 866 additions and 0 deletions

View 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/**

484
yakovleva_yulia_lab_2/.gitignore vendored Normal file
View File

@ -0,0 +1,484 @@
## 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

View File

@ -0,0 +1,19 @@
<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.19.6" />
</ItemGroup>
<!-- <ItemGroup>
<ProjectReference Include="..\FileGeneration\FileGeneration.csproj" />
</ItemGroup> -->
</Project>

View 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 ["App1.csproj", "App1/"]
RUN dotnet restore "App1/App1.csproj"
WORKDIR "/src/App1"
COPY . .
RUN dotnet build "App1.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "App1.csproj" -c $BUILD_CONFIGURATION -o /app/publish --self-contained false --no-restore
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "App1.dll"]

View File

@ -0,0 +1,31 @@
using System;
using System.IO;
class Program
{
static void Main()
{
string inputPath = Environment.GetEnvironmentVariable("DATA_PATH") ?? ".\\data";
string outputPath = Environment.GetEnvironmentVariable("RESULT_PATH") ?? ".\\result";
try
{
string[] files = Directory.GetFiles(inputPath);
using (StreamWriter writer = new StreamWriter(Path.Combine(outputPath, "data.txt")))
{
foreach (string file in files)
{
int lineCount = File.ReadAllLines(file).Length;
writer.WriteLine(lineCount);
}
}
Console.WriteLine("Файл data.txt успешно создан");
}
catch (Exception ex)
{
Console.WriteLine("Произошла ошибка: " + ex.Message);
}
}
}

View File

@ -0,0 +1,10 @@
{
"profiles": {
"App1": {
"commandName": "Project"
},
"Container (Dockerfile)": {
"commandName": "Docker"
}
}
}

View 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.19.6" />
</ItemGroup>
</Project>

View 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 ["App2.csproj", "App2/"]
RUN dotnet restore "App2/App2.csproj"
WORKDIR "/src/App2"
COPY . .
RUN dotnet build "App2.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "App2.csproj" -c $BUILD_CONFIGURATION -o /app/publish --self-contained false --no-restore
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "App2.dll"]

View File

@ -0,0 +1,35 @@
using System;
using System.IO;
using System.Linq;
class Program
{
static void Main()
{
string inputPath = Environment.GetEnvironmentVariable("DATA_PATH") ?? ".\\data";
string outputPath = Environment.GetEnvironmentVariable("RESULT_PATH") ?? ".\\result";
try
{
string dataFilePath = Path.Combine(inputPath, "data.txt");
// Чтение всех строк из файла
string[] lines = File.ReadAllLines(dataFilePath);
int[] numbers = lines.Select(int.Parse).ToArray();
// Поиск наибольшего числа
int maxNumber = numbers.Max();
// Подсчет количества таких чисел
int maxCount = numbers.Count(n => n == maxNumber);
File.WriteAllText(Path.Combine(outputPath, "result.txt"), maxCount.ToString());
Console.WriteLine($"Количество наибольших чисел: {maxCount}");
}
catch (Exception ex)
{
Console.WriteLine("Произошла ошибка: " + ex.Message);
}
}
}

View File

@ -0,0 +1,10 @@
{
"profiles": {
"App2": {
"commandName": "Project"
},
"Container (Dockerfile)": {
"commandName": "Docker"
}
}
}

View File

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34728.123
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "App2", "App2\App2.csproj", "{D03073B1-0CB3-4CA9-A9D8-F1FB804F92D1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "App1", "App1\App1.csproj", "{729837A1-27A7-4D48-BBB2-21F68E5F7766}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileGeneration", "FileGeneration\FileGeneration.csproj", "{E7AD8A8C-C957-41FF-B92A-924465D73DDB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D03073B1-0CB3-4CA9-A9D8-F1FB804F92D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D03073B1-0CB3-4CA9-A9D8-F1FB804F92D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D03073B1-0CB3-4CA9-A9D8-F1FB804F92D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D03073B1-0CB3-4CA9-A9D8-F1FB804F92D1}.Release|Any CPU.Build.0 = Release|Any CPU
{729837A1-27A7-4D48-BBB2-21F68E5F7766}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{729837A1-27A7-4D48-BBB2-21F68E5F7766}.Debug|Any CPU.Build.0 = Debug|Any CPU
{729837A1-27A7-4D48-BBB2-21F68E5F7766}.Release|Any CPU.ActiveCfg = Release|Any CPU
{729837A1-27A7-4D48-BBB2-21F68E5F7766}.Release|Any CPU.Build.0 = Release|Any CPU
{E7AD8A8C-C957-41FF-B92A-924465D73DDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E7AD8A8C-C957-41FF-B92A-924465D73DDB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E7AD8A8C-C957-41FF-B92A-924465D73DDB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E7AD8A8C-C957-41FF-B92A-924465D73DDB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {36392E9A-B3A7-4CFF-B577-B2A3146B3007}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,22 @@
#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/runtime:8.0 AS base
WORKDIR /app
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["FileGeneration.csproj", "FileGeneration/"]
RUN dotnet restore "FileGeneration/FileGeneration.csproj"
WORKDIR "/src/FileGeneration"
COPY . .
RUN dotnet build "FileGeneration.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "FileGeneration.csproj" -c $BUILD_CONFIGURATION -o /app/publish --self-contained false --no-restore
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "FileGeneration.dll"]

View 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.19.6" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,41 @@
using System;
using System.IO;
class Program
{
static void Main()
{
string directoryPath = Environment.GetEnvironmentVariable("DATA_PATH") ?? ".\\data";
Random random = new Random();
try
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
for (int i = 1; i <= 100; i++)
{
int lineCount = random.Next(1, 101);
string filePath = Path.Combine(directoryPath, $"file_{i}.txt");
using (StreamWriter writer = new StreamWriter(filePath))
{
for (int j = 0; j < lineCount; j++)
{
writer.WriteLine($"{j + 1}");
}
}
Console.WriteLine($"Файл {filePath} успешно создан с {lineCount} строками.");
}
}
catch (Exception ex)
{
Console.WriteLine("Произошла ошибка: " + ex.Message);
}
}
}

View File

@ -0,0 +1,10 @@
{
"profiles": {
"FileGeneration": {
"commandName": "Project"
},
"Container (Dockerfile)": {
"commandName": "Docker"
}
}
}

View File

@ -0,0 +1,34 @@
# Лабораторная работа 2
## Описание
В данной лабораторной работе были изучены файлы сборки образов и создание их для приложений. Сборки образов необходимы для контейниризации созданных приложений. В файле сборки мы указываем папку из которой копируем в контейнер и собираем проект.
## Описание работы
Были выбраны варианты для первого приложения - 3 вариант и для второго 3 вариант.
В первом приложении мы ищем все файлы из папки output и записываем количество строк каждого файла в файл data.txt. Затем второе приложение ищет в data.txt наибольшее значения и записывает количество наибольших значений в файл result.txt.
## Запуск
1. Для начала необходимо запустить Docker
2. Открыть консоль, перейти в папку с docker-compose.yml
3. Ввести команду:
```
docker compose up --build
```
`--build` необходим для принудительной сборки контейнеров, даже если они уже запущены.
## Результат
В результате в логах видим, что приложения успешно отработали:
```
app2-1 | Количество наибольших чисел: 1
app1-1 exited with code 0
app2-1 exited with code 0
```
И также видим в папке Files две созданные папки: data и result. В data находятся сгенерированные файлы, а в result - файл с результатом.
## Описание docker-compose.yml
В docker-compose.yml запускаются 3 сервиса: первый генерирует файлы с рандомным набором строк, второй сервис записывает количество строк каждого файла в data.txt, а третий сервис определяет количество наибольших чисел из файла data.txt и записывает результат в файл result.txt. Также используются зависимости `depends_on`, второй сервис зависит от запуска первого, и третий севрис зависит от запуска второго.
С помощью `volumes` создаем буферную область, которая позволяет использовать двум севрисам одну папку. `build` позволяет использовать только что собранный образ в момент запуска.
## Видеоотчёт
[Видеоотчёт](https://disk.yandex.ru/i/Ds2f4xO8vQ8XPA)

View File

@ -0,0 +1,33 @@
services:
generatefiles:
build: ./FileGeneration/
volumes:
- ./Files/data:/var/data
- buffer:/var/result
environment:
DATA_PATH: "/var/data"
RESULT_PATH: "/var/result"
app1:
build: ./App1/
depends_on:
- generatefiles
volumes:
- ./Files/data:/var/data
- buffer:/var/result
environment:
DATA_PATH: "/var/data"
RESULT_PATH: "/var/result"
app2:
build: ./App2/
depends_on:
- app1
volumes:
- buffer:/var/data
- ./Files/result:/var/result
environment:
DATA_PATH: "/var/data"
RESULT_PATH: "/var/result"
volumes:
buffer: