Цель: создание консольного приложение .NET Core, которое умеет реагировать на команды пользователя и выполнять две команды - exit и help.
Все изменения (commits) должны храниться в ветке step1-add-file-cabinet-app, а после окончания работы должны быть слиты в ветку main.
Перед выполнением задания проверьте, что Вы:
- Умеете создавать консольные приложения .NET Core.
- Умеете работать к консольным приложением dotnet.
- Понимаете назначение файлов csproj и sln.
- Знаете основы работы с git и умеете работать с командной строкой (команды status, add, checkout, merge).
- Знаете, для чего нужен статический анализатор кода.
Проработайте дополнительные материалы, чтобы получить недостающие знания и умения.
Внимание! Использование внешних пакетов nuget допускается только в случае, если это предусмотрено руководством, или по согласованию с тренером или ментором.
Перед началом выполнения проверьте, что установлен .NET 6 SDK.
$ dotnet --list-sdks
6.0.100 [C:\Program Files\dotnet\sdk]
- Создайте новый private репозиторий и клонируйте его на локальный диск. Настройка .gitignore - VisualStudio.
- Создайте в клонированном репозитории новую ветку step1-add-file-cabinet-app и переключитесь на нее.
$ git checkout -B step1-add-file-cabinet-app
Switched to a new branch 'step1-add-file-cabinet-app'
- Создайте в каталоге клонированного репозитория новый проект .NET Core FileCabinetApp.
$ dotnet new console --name FileCabinetApp
The template "Console App" was created successfully.
Processing post-creation actions...
Running 'dotnet restore' on D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj...
Determining projects to restore...
Restored D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj (in 80 ms).
Restore succeeded.
- Создайте новый solution FileCabinet и добавьте в него проект FileCabinetApp.
$ dotnet new sln --name FileCabinet
The template "Solution File" was created successfully.
$ dotnet sln FileCabinet.sln add FileCabinetApp\FileCabinetApp.csproj
Project `FileCabinetApp\FileCabinetApp.csproj` added to the solution.
Внимание! Системы Windows используют "backslash" в файловых путях, а системы Linux и Mac - "slash". Поэтому для корректной работы командной строки в cmd.exe нужно использовать backslash. Однако, при работе в Windows через Bash Shell (mingw64) нужно использовать "slash".
- Соберите проект.
$ cd FileCabinetApp\
$ dotnet build
Microsoft (R) Build Engine version 17.0.0+c9eb9dd64 for .NET
Copyright (C) Microsoft Corporation. All rights reserved.
Determining projects to restore...
All projects are up-to-date for restore.
FileCabinetApp -> D:\file-cabinet-task\FileCabinetApp\bin\Debug\net6.0\FileCabinetApp.dll
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:02.31
- Прочтите руководство по установке StyleCop (копия страницы). Добавьте пакет StyleCop.Analyzers в проект FileCabinetApp.
$ dotnet add package StyleCop.Analyzers
Writing C:\Users\Aliaksandr_Rykau\AppData\Local\Temp\tmp8C24.tmp
info : Adding PackageReference for package 'StyleCop.Analyzers' into project 'D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj'.
info : Restoring packages for D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj...
info : GET https://api.nuget.org/v3-flatcontainer/stylecop.analyzers/index.json
info : OK https://api.nuget.org/v3-flatcontainer/stylecop.analyzers/index.json 469ms
info : Package 'StyleCop.Analyzers' is compatible with all the specified frameworks in project 'D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj'.
info : PackageReference for package 'StyleCop.Analyzers' version '1.1.118' added to file 'D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj'.
info : Committing restore...
info : Generating MSBuild file D:\file-cabinet-task\FileCabinetApp\obj\FileCabinetApp.csproj.nuget.g.props.
info : Writing assets file to disk. Path: D:\file-cabinet-task\FileCabinetApp\obj\project.assets.json
log : Restore completed in 1.03 sec for D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj.
Determining projects to restore...
Writing C:\Users\Aliaksandr_Rykau\AppData\Local\Temp\tmpE94B.tmp
info : Adding PackageReference for package 'StyleCop.Analyzers' into project 'D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj'.
info : GET https://api.nuget.org/v3/registration5-gz-semver2/stylecop.analyzers/index.json
info : OK https://api.nuget.org/v3/registration5-gz-semver2/stylecop.analyzers/index.json 1389ms
info : Restoring packages for D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj...
info : Package 'StyleCop.Analyzers' is compatible with all the specified frameworks in project 'D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj'.
info : PackageReference for package 'StyleCop.Analyzers' version '1.1.118' added to file 'D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj'.
info : Committing restore...
info : Generating MSBuild file D:\file-cabinet-task\FileCabinetApp\obj\FileCabinetApp.csproj.nuget.g.props.
info : Writing assets file to disk. Path: D:\file-cabinet-task\FileCabinetApp\obj\project.assets.json
log : Restored D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj (in 70 ms).
Внимание! В руководстве (см. выше) также используется пакет FxCopAnalyzers, однако в .NET есть встроенные анализаторы кода, поэтому необходимости в установке пакета FxCopAnalyzers нет.
- Снова соберите проект.
Microsoft (R) Build Engine version 17.0.0+c9eb9dd64 for .NET
Copyright (C) Microsoft Corporation. All rights reserved.
Determining projects to restore...
Restored D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj (in 204 ms).
D:\file-cabinet-task\FileCabinetApp\Program.cs(1,1): warning SA1633: The file header XML is invalid. [D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj]
CSC : warning SA0001: XML comment analysis is disabled due to project configuration [D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj]
FileCabinetApp -> D:\file-cabinet-task\FileCabinetApp\bin\Debug\net6.0\FileCabinetApp.dll
Build succeeded.
D:\file-cabinet-task\FileCabinetApp\Program.cs(1,1): warning SA1633: The file header XML is invalid. [D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj]
CSC : warning SA0001: XML comment analysis is disabled due to project configuration [D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj]
2 Warning(s)
0 Error(s)
Time Elapsed 00:00:01.42
Обратите внимание, что компилятор при сборке стал выдавать больше предупреждений. Эти предупреждения - результат работы StyleCop.
- Скопируйте файл code-analysis.ruleset в каталог проекта FileCabinetApp.
- Отредактируйте файл проекта FileCabinetApp.csproj и добавьте у него настройки для StyleCop.
<CodeAnalysisRuleSet>code-analysis.ruleset</CodeAnalysisRuleSet>
Файл проекта должен выглядеть следующим образом (примерно):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<CodeAnalysisRuleSet>code-analysis.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
</Project>
- Добавьте дополнительные настройки.
<DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>
<NoWarn>$(NoWarn),1573,1591,1712</NoWarn>
Файл проекта должен выглядеть следующим образом (примерно):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<CodeAnalysisRuleSet>code-analysis.ruleset</CodeAnalysisRuleSet>
<DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>
<NoWarn>$(NoWarn),1573,1591,1712</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
</Project>
- Снова соберите проект.
Microsoft (R) Build Engine version 17.0.0+c9eb9dd64 for .NET
Copyright (C) Microsoft Corporation. All rights reserved.
Determining projects to restore...
Restored D:\file-cabinet-task\FileCabinetApp\FileCabinetApp\FileCabinetApp.csproj (in 166 ms).
FileCabinetApp -> D:\file-cabinet-task\FileCabinetApp\FileCabinetApp\bin\Debug\net6.0\FileCabinetApp.dll
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:01.17
Обратите внимание, что пред упреждения, которые компилятор выводил на экран в прошлый раз, исчезли.Это произошло из-за того, что вы изменили настройки StyleCop через файл code-analysis.ruleset.
- Включите настройки встроенного анализатора кода .NET 6:
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors>
Файл проекта должен выглядеть следующим образом (примерно) - FileCabinetApp.csproj
- Снова соберите проект.
- Проверьте список измененных файлов в репозитории и просмотрите изменения.
$ cd ..
$ git status
On branch step1-add-file-cabinet-app
Untracked files:
(use "git add <file>..." to include in what will be committed)
FileCabinet.sln
FileCabinetApp/
$ git diff
...
- Добавьте изменения в файлах в stage.
$ git add *.cs *.csproj *.sln *.xml *.ruleset
$ git status
On branch step1-add-file-cabinet-app
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: FileCabinet.sln
new file: FileCabinetApp/FileCabinetApp.csproj
new file: FileCabinetApp/FileCabinetApp.xml
new file: FileCabinetApp/Program.cs
new file: FileCabinetApp/code-analysis.ruleset
- Просмотрите изменения в stage - всегда просматривайте ваши изменения перед тем как сделать commit.
$ git diff --staged
- Сделайте commit.
$ git commit -m "Add initial version of FileCabinetApp."
- Замените файл Program.cs в каталоге приложения на Program.cs.
- Соберите проект.
$ dotnet build
Microsoft (R) Build Engine version 16.2.32702+c4012a063 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.
Restore completed in 32.04 ms for D:\file-cabinet-task\FileCabinetApp\FileCabinetApp.csproj.
FileCabinetApp -> D:\file-cabinet-task\FileCabinetApp\bin\Debug\netcoreapp2.2\FileCabinetApp.dll
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:02.20
Ошибок при сборке быть не должно.
- Проверьте список измененных файлов в репозитории и добавьте их в stage. Сделайте commit.
$ git status
$ git add *.cs
$ git diff --staged
$ git commit -m "Add FileCabinetApp skeleton."
- В Program.cs исправьте значение DeveloperName - поставьте Ваше имя и фамилию.
private const string DeveloperName = "Vasili Vasilyev";
- Сделайте commit.
$ git status
$ git add *.cs
$ git commit -m "Change DeveloperName to Vasili Vasilyev."
- Сделайте push локальной ветки в удаленную ветку.
$ git push --set-upstream origin step1-add-file-cabinet-app
- Переключитесь на ветку main и сделайте fast-forward merge изменений из ветки step1-add-file-cabinet-app.
$ git checkout main
$ git merge step1-add-file-cabinet-app --ff
- Сделайте push изменений из локальной ветки main в удаленную ветку.
$ git push
- Проверьте работоспособность приложения.
$ cd FileCabinetApp
$ dotnet run
File Cabinet Application, developed by Vasili Vasilyev
Enter your command, or enter 'help' to get help.
> help
Available commands:
help - prints the help screen
exit - exits the application
> exit
Exiting an application...
- История репозитория должна выглядеть следующим образом:
$ git log --oneline
5e24f45 (HEAD -> main, origin/step1-add-file-cabinet-app, origin/main, origin/HEAD, step1-add-file-cabinet-app) Change DeveloperName to Vasil Vasilyev.
93f9f64 Add FileCabinetApp skeleton.
97e9145 Add initial version of FileCabinetApp.
227f3b7 Initial commit
- Репозиторий должен выглядеть как образец - file-cabinet-task-example.