Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions CourseApp.Tests/UnitTest5.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Xunit;
using System;
using CourseApp;

namespace CourseApp.Tests
{
public class UnitTest5
{
[Fact]
public void UnitTest17()
{
GetAge newAge = new GetAge();
DateTime dateBorn = new DateTime(1997, 02, 08);
DateTime dateToday = new DateTime(2019, 03, 18);
Assert.Equal("Возраст: 22, 1, 10", newAge.Get(dateBorn, dateToday));
}
[Fact]
public void UnitTest18()
{
GetAge newAge = new GetAge();
DateTime dateBorn = new DateTime(2019, 03, 18);
DateTime dateToday = new DateTime(2019, 03, 18);
Assert.Equal("Это сегодняшняя дата", newAge.Get(dateBorn, dateToday));
}
[Fact]
public void UnitTest19()
{
GetAge newAge = new GetAge();
DateTime dateBorn = new DateTime(2020, 02, 08);
DateTime dateToday = new DateTime(2019, 03, 18);
Assert.Equal("Дата ещё не наступила", newAge.Get(dateBorn, dateToday));
}
}
}

30 changes: 30 additions & 0 deletions CourseApp.Tests/UnitTest6.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using Xunit;
using System;
using CourseApp;

namespace CourseApp.Tests
{
public class UnitTest6
{
public Fox one = new Fox();

[Fact]
public void UnitTest20()
{
Assert.Equal("Лиса сделала КУСЬ!", one.Kus());
}

[Fact]
public void UnitTest21()
{
Fox one = new Fox();
Fox two = new Fox("Вторая", "Черная");
Fox[] fox = new Fox[] { one, two };
Array.Sort(fox);
Assert.Equal(one.Name, fox[1].Name);
Assert.Equal(one.Age, fox[1].Age);
Assert.Equal(two.Name, fox[0].Name);
Assert.Equal(two.Age, fox[0].Age);
}
}
}
20 changes: 19 additions & 1 deletion CourseApp/Fox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace CourseApp
{
public class Fox : Animals
public class Fox : Animals, IKus, IComparable
{
public Fox()
: base()
Expand All @@ -22,6 +22,24 @@ public Fox(string name, string color, int age)
Age = age;
} // 3 конструктор

public string Kus()
{
return "Лиса сделала КУСЬ!";
}

public int CompareTo(object o)
{
Fox f = o as Fox;
if (f != null)
{
return this.Name.CompareTo(f.Name);
}
else
{
throw new Exception("Невозможно сравнить два объекта");
}
}

public override void GetInfo()
{
Console.WriteLine($"Имя: {Name} Цвет: {Color} Возраст: {Age}");
Expand Down
28 changes: 28 additions & 0 deletions CourseApp/GetAge.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace CourseApp
{
public class GetAge
{
public string Get(DateTime dateBorn, DateTime dateToday)
{
if (dateBorn == dateToday)
{
return "Это сегодняшняя дата";
}

if (dateToday < dateBorn)
{
return $"Дата ещё не наступила";
}

dateToday = dateToday.AddYears(-dateBorn.Year);
dateToday = dateToday.AddMonths(-dateBorn.Month);
dateToday = dateToday.AddDays(-dateBorn.Day);

return $"Возраст: {dateToday.Year}, {dateToday.Month}, {dateToday.Day}";
}
}
}
11 changes: 11 additions & 0 deletions CourseApp/IKus.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace CourseApp
{
public interface IKus
{
string Kus();
}
}
16 changes: 16 additions & 0 deletions CourseApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,22 @@ private static void Main()
i.GetInfo();
}

Console.WriteLine(one.Kus());

Fox[] fox = new Fox[] { one, two };
Array.Sort(fox);

foreach (Fox f in fox)
{
Console.WriteLine("{0} - {1}", f.Name, f.Age);
}

GetAge date = new GetAge();
DateTime dateBorn = new DateTime(1997, 02, 08);
DateTime dateToday = new DateTime(2019, 03, 18);
Console.WriteLine();
Console.WriteLine(date.Get(dateBorn, dateToday));

Console.Read();
}
}
Expand Down
25 changes: 25 additions & 0 deletions FoxApp/FoxApp.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.438
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EFDataApp", "EFDataApp\EFDataApp.csproj", "{76EB5314-1ECF-4F1C-9FED-99A678DFBD3F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{76EB5314-1ECF-4F1C-9FED-99A678DFBD3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{76EB5314-1ECF-4F1C-9FED-99A678DFBD3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{76EB5314-1ECF-4F1C-9FED-99A678DFBD3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{76EB5314-1ECF-4F1C-9FED-99A678DFBD3F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {413E653D-4A18-4903-B166-B1302D73F53C}
EndGlobalSection
EndGlobal
92 changes: 92 additions & 0 deletions FoxApp/FoxApp/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using FoxApp.Models;

namespace FoxApp.Controllers
{
public class HomeController : Controller
{
private FoxxContext db; //Для взаимодействия с базой данных в контроллере определяется переменная контекст
//данных FoxxContext db. Причем поскольку в классе Startup в методе ConfigureServices
//контекст данных устанавливается как сервис, то в конструкторе контроллера мы можем
//получить переданный контекст данных.
public HomeController(FoxxContext context)
{
db = context;
}
//Создание
public async Task<IActionResult> Index()
{
return View(await db.Foxes.ToListAsync()); // Получаем объекты из бд, создаём из них список и передаём в представление.
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Create(Fox fox)
{
db.Foxes.Add(fox);
await db.SaveChangesAsync(); //Добавление данных в базу
return RedirectToAction("Index");
}
//Детали
public async Task<IActionResult> Details(int? id)
{
if (id != null)
{
Fox fox = await db.Foxes.FirstOrDefaultAsync(p => p.Id == id); //Метод получает id объекта,
//о котором надо вывести информацию.
//Затем найденный объект передается в представление.
if (fox != null)
return View(fox);
}
return NotFound();
}
//Редактирование
public async Task<IActionResult> Edit(int? id)
{
if (id != null)
{
Fox fox = await db.Foxes.FirstOrDefaultAsync(p => p.Id == id);
if (fox != null)
return View(fox);
}
return NotFound();
}
[HttpPost]
public async Task<IActionResult> Edit(Fox fox)
{
db.Foxes.Update(fox);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
//Удаление
[HttpGet]
[ActionName("Delete")] //Данный атрибут указывает, что этот метод также относится к действию Delete
public async Task<IActionResult> ConfirmDelete(int? id)
{
if (id != null)
{
Fox fox = await db.Foxes.FirstOrDefaultAsync(p => p.Id == id);
if (fox != null)
return View(fox);
}
return NotFound();
}
[HttpPost]
public async Task<IActionResult> Delete(int? id)
{
if (id != null)
{
Fox fox = new Fox { Id = id.Value };
db.Entry(fox).State = EntityState.Deleted;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return NotFound();
}
}
}
15 changes: 15 additions & 0 deletions FoxApp/FoxApp/FoxApp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>


<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />
</ItemGroup>

</Project>
11 changes: 11 additions & 0 deletions FoxApp/FoxApp/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;

namespace FoxApp.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
16 changes: 16 additions & 0 deletions FoxApp/FoxApp/Models/Fox.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FoxApp.Models
{
public class Fox //Модель, представляющая объекты, которые будут храниться в базе данных.
{
public int Id { get; set; }
public string Name { get; set; } // имя
public string Breed { get; set; } // вид
public string Description { get; set; } // описание
public int Age { get; set; } //возраст
}
}
20 changes: 20 additions & 0 deletions FoxApp/FoxApp/Models/FoxxContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Microsoft.EntityFrameworkCore;
//Чтобы взаимодействовать с базой данных через Entity Framework нам нужен контекст данных - класс,
//унаследованный от класса Microsoft.EntityFrameworkCore.DbContext.

namespace FoxApp.Models
{
public class FoxxContext : DbContext
{
public DbSet<Fox> Foxes { get; set; } //Свойство DbSet представляет собой коллекцию объектов,
//которая сопоставляется с определенной таблицей в базе данных.
//При этом по умолчанию название свойства должно соответствовать множественному числу
//названию модели в соответствии с правилами английского языка.
public FoxxContext(DbContextOptions<FoxxContext> options)
: base(options) //Через параметр options в конструктор контекста данных будут передаваться настройки контекста.
{
Database.EnsureCreated(); //В конструкторе с помощью вызова Database.EnsureCreated()
//по определению моделей будет создаваться база данных
}
}
}
24 changes: 24 additions & 0 deletions FoxApp/FoxApp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace FoxApp
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
Loading