Compare commits

...

No commits in common. "main" and "master" have entirely different histories.
main ... master

158 changed files with 79211 additions and 42 deletions

63
.gitattributes vendored Normal file
View 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

43
.gitignore vendored
View File

@ -1,8 +1,7 @@
# ---> VisualStudio
## 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/main/VisualStudio.gitignore
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
@ -30,6 +29,7 @@ x86/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
@ -91,7 +91,6 @@ StyleCopReport.xml
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
@ -295,17 +294,6 @@ node_modules/
# 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
@ -362,9 +350,6 @@ ASALocalRun/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
@ -375,26 +360,4 @@ MigrationBackup/
.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
FodyWeavers.xsd

73
Forum.sln Normal file
View File

@ -0,0 +1,73 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32825.248
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ForumView", "ForumView\ForumView.csproj", "{79DC3161-0FFB-4832-B2DC-DB5AE48DA9AB}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ForumDataModels", "ForumDataModels\ForumDataModels.csproj", "{B2D1577A-49BC-4D1B-A8A0-029BB21EEC5B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ForumContracts", "ForumContracts\ForumContracts.csproj", "{41257133-A3B7-497B-B615-AEFB2305E7F6}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ForumDatabaseImplement", "ForumDatabaseImplement\ForumDatabaseImplement.csproj", "{2C535F67-58F0-4098-99D8-9AF46BAC8605}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ForumBusinessLogic", "ForumBusinessLogic\ForumBusinessLogic.csproj", "{70B2DA03-F38D-42B0-81AC-13CD959750DD}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ForumRestApi", "ForumRestApi\ForumRestApi.csproj", "{53155982-EDFA-4038-87DF-5A99E6D8C758}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ForumUserApp", "ForumUserApp\ForumUserApp.csproj", "{CDAB926A-2C76-427D-A1D4-76A3E3092A4A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ForumMongoDataBase", "ForumMongoDataBase\ForumMongoDataBase.csproj", "{C8AA8117-89C1-4B41-91D0-B9CD248EA08F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ToMongoDB", "ToMongoDB\ToMongoDB.csproj", "{1C827109-83C3-4DDE-8DF2-30DF9631E984}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{79DC3161-0FFB-4832-B2DC-DB5AE48DA9AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{79DC3161-0FFB-4832-B2DC-DB5AE48DA9AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{79DC3161-0FFB-4832-B2DC-DB5AE48DA9AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{79DC3161-0FFB-4832-B2DC-DB5AE48DA9AB}.Release|Any CPU.Build.0 = Release|Any CPU
{B2D1577A-49BC-4D1B-A8A0-029BB21EEC5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B2D1577A-49BC-4D1B-A8A0-029BB21EEC5B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B2D1577A-49BC-4D1B-A8A0-029BB21EEC5B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B2D1577A-49BC-4D1B-A8A0-029BB21EEC5B}.Release|Any CPU.Build.0 = Release|Any CPU
{41257133-A3B7-497B-B615-AEFB2305E7F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{41257133-A3B7-497B-B615-AEFB2305E7F6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{41257133-A3B7-497B-B615-AEFB2305E7F6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{41257133-A3B7-497B-B615-AEFB2305E7F6}.Release|Any CPU.Build.0 = Release|Any CPU
{2C535F67-58F0-4098-99D8-9AF46BAC8605}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2C535F67-58F0-4098-99D8-9AF46BAC8605}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2C535F67-58F0-4098-99D8-9AF46BAC8605}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2C535F67-58F0-4098-99D8-9AF46BAC8605}.Release|Any CPU.Build.0 = Release|Any CPU
{70B2DA03-F38D-42B0-81AC-13CD959750DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{70B2DA03-F38D-42B0-81AC-13CD959750DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{70B2DA03-F38D-42B0-81AC-13CD959750DD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{70B2DA03-F38D-42B0-81AC-13CD959750DD}.Release|Any CPU.Build.0 = Release|Any CPU
{53155982-EDFA-4038-87DF-5A99E6D8C758}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{53155982-EDFA-4038-87DF-5A99E6D8C758}.Debug|Any CPU.Build.0 = Debug|Any CPU
{53155982-EDFA-4038-87DF-5A99E6D8C758}.Release|Any CPU.ActiveCfg = Release|Any CPU
{53155982-EDFA-4038-87DF-5A99E6D8C758}.Release|Any CPU.Build.0 = Release|Any CPU
{CDAB926A-2C76-427D-A1D4-76A3E3092A4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CDAB926A-2C76-427D-A1D4-76A3E3092A4A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CDAB926A-2C76-427D-A1D4-76A3E3092A4A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CDAB926A-2C76-427D-A1D4-76A3E3092A4A}.Release|Any CPU.Build.0 = Release|Any CPU
{C8AA8117-89C1-4B41-91D0-B9CD248EA08F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C8AA8117-89C1-4B41-91D0-B9CD248EA08F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C8AA8117-89C1-4B41-91D0-B9CD248EA08F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C8AA8117-89C1-4B41-91D0-B9CD248EA08F}.Release|Any CPU.Build.0 = Release|Any CPU
{1C827109-83C3-4DDE-8DF2-30DF9631E984}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1C827109-83C3-4DDE-8DF2-30DF9631E984}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1C827109-83C3-4DDE-8DF2-30DF9631E984}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1C827109-83C3-4DDE-8DF2-30DF9631E984}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {877C9F0F-56FC-4459-BABB-6548C0024653}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,127 @@
using ForumContracts.BindingModels;
using ForumContracts.BusinessLogicContracts;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumBusinessLogic.BusinessLogic
{
public class AnswerLogic : IAnswerLogic
{
private readonly ILogger _logger;
private readonly IAnswerStorage _answerStorage;
public AnswerLogic(ILogger<AnswerLogic> logger, IAnswerStorage answerStorage)
{
_logger = logger;
_answerStorage = answerStorage;
}
public bool Create(AnswerBindingModel model)
{
CheckModel(model);
if (_answerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(AnswerBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_answerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public AnswerViewModel? ReadElement(AnswerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. AnswerDes:{AnswerDes}.Id:{ Id}", model.AnswerDes, model.Id);
var element = _answerStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<AnswerViewModel>? ReadList(AnswerSearchModel? model)
{
_logger.LogInformation("ReadList. AnswerDes:{AnswerDes}.Id:{ Id}", model?.AnswerDes, model?.Id);
var list = model == null ? _answerStorage.GetFullList() : _answerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(AnswerBindingModel model)
{
CheckModel(model);
if (_answerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(AnswerBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.AnswerDes))
{
throw new ArgumentNullException("Нет ответа", nameof(model.AnswerDes));
}
_logger.LogInformation("Answer. AnswerDes:{AnswerDes}.ResponseDate:{ ResponseDate}. Id: { Id}", model.AnswerDes, model.ResponseDate, model.Id);
}
}
}

View File

@ -0,0 +1,121 @@
using ForumContracts.BindingModels;
using ForumContracts.BusinessLogicContracts;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumBusinessLogic.BusinessLogic
{
public class CategoryLogic : ICategoryLogic
{
private readonly ILogger _logger;
private readonly ICategoryStorage _categoryStorage;
public CategoryLogic(ILogger<CategoryLogic> logger, ICategoryStorage categoryStorage)
{
_logger = logger;
_categoryStorage = categoryStorage;
}
public bool Create(CategoryBindingModel model)
{
CheckModel(model);
if (_categoryStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(CategoryBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_categoryStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public CategoryViewModel? ReadElement(CategorySearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Name:{FIO}.Id:{ Id}",
model.Name, model.Id);
var element = _categoryStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<CategoryViewModel>? ReadList(CategorySearchModel? model)
{
_logger.LogInformation("ReadList. Name:{Name}.Id:{ Id} ", model?.Name, model?.Id);
var list = (model == null) ? _categoryStorage.GetFullList() :
_categoryStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(CategoryBindingModel model)
{
CheckModel(model);
if (_categoryStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(CategoryBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет названия категории", nameof(model.Name));
}
if (string.IsNullOrEmpty(model.Description))
{
throw new ArgumentNullException("Нет описания категории", nameof(model.Description));
}
_logger.LogInformation("Caregory. Id: {Id}, Name: {Name}", model.Id, model.Name);
var element = _categoryStorage.GetElement(new CategorySearchModel
{
Name = model.Name,
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Категория с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,143 @@
using ForumContracts.BindingModels;
using ForumContracts.BusinessLogicContracts;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumBusinessLogic.BusinessLogic
{
public class QuestionLogic : IQuestionLogic
{
private readonly ILogger _logger;
private readonly IQuestionStorage _questionStorage;
public QuestionLogic(ILogger<QuestionLogic> logger, IQuestionStorage questionStorage)
{
_logger = logger;
_questionStorage = questionStorage;
}
public bool Create(QuestionBindingModel model)
{
CheckModel(model);
if (_questionStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(QuestionBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_questionStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public QuestionViewModel? ReadElement(QuestionSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. QuestionDes:{QuestionDes}.Id:{ Id}", model.QuestionDes, model.Id);
var element = _questionStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<QuestionViewModel>? ReadList(QuestionSearchModel? model)
{
_logger.LogInformation("ReadList. QuestionDes:{QuestionDes}.Id:{ Id}", model?.QuestionDes, model?.Id);
var list = model == null ? _questionStorage.GetFullList() : _questionStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public List<QuestionViewModel>? HardRequest(QuestionSearchModel? model)
{
return _questionStorage.HardRequest(new QuestionSearchModel
{
DateFrom = model.DateFrom,
DateTo = model.DateTo
})
.Select(x => new QuestionViewModel
{
CreateDate = x.CreateDate,
QuestionDes = x.QuestionDes,
UserName = x.UserName,
CategoryName = x.CategoryName
})
.ToList();
}
public bool Update(QuestionBindingModel model)
{
CheckModel(model);
if (_questionStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(QuestionBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.QuestionDes))
{
throw new ArgumentNullException("Нет вопроса", nameof(model.QuestionDes));
}
_logger.LogInformation("Question. QuestionDes:{QuestionDes}.CreateDate:{ CreateDate}. Id: { Id}", model.QuestionDes, model.CreateDate, model.Id);
}
}
}

View File

@ -0,0 +1,133 @@
using ForumContracts.BindingModels;
using ForumContracts.StorageContracts;
using ForumContracts.BusinessLogicContracts;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ForumBusinessLogic.BusinessLogic
{
public class UserLogic : IUserLogic
{
private readonly ILogger _logger;
private readonly IUserStorage _userStorage;
public UserLogic(ILogger<UserLogic> logger, IUserStorage userStorage)
{
_logger = logger;
_userStorage = userStorage;
}
public bool Create(UserBindingModel model)
{
CheckModel(model);
if (_userStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
private void CheckModel(UserBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Nickname))
{
throw new ArgumentNullException("Нет ника пользователя", nameof(model.Nickname));
}
if (string.IsNullOrEmpty(model.Email))
{
throw new ArgumentNullException("Нет почты пользователя", nameof(model.Email));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля пользователя", nameof(model.Password));
}
_logger.LogInformation("User. Nickname: {Nickname}. Email: {Email}. Id: {Id}", model.Nickname, model.Email, model.Id);
var element = _userStorage.GetElement(new UserSearchModel
{
Nickname = model.Nickname,
Email = model.Email
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Пользователь с такой почтой и ником уже есть");
}
}
public bool Delete(UserBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id: {Id}", model.Id);
if (_userStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public UserViewModel? ReadElement(UserSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Nickname: {Nickname}. Email: {Email}. Id: {Id}.", model.Nickname, model.Email, model.Id);
var element = _userStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id: {Id}", element.Id);
return element;
}
public List<UserViewModel>? ReadList(UserSearchModel? model)
{
_logger.LogInformation("ReadList. Nickname: {Nickname}. Email: {Email}. Id: {Id}.", model?.Nickname, model?.Email, model?.Id);
var list = model == null ? _userStorage.GetFullList() : _userStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
public bool Update(UserBindingModel model)
{
CheckModel(model);
if (_userStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ForumContracts\ForumContracts.csproj" />
<ProjectReference Include="..\ForumDatabaseImplement\ForumDatabaseImplement.csproj" />
<ProjectReference Include="..\ForumMongoDataBase\ForumMongoDataBase.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,22 @@
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.BindingModels
{
public class AnswerBindingModel : IAnswerModel
{
public string AnswerDes { get; set; } = string.Empty;
public DateTime ResponseDate { get; set; } = DateTime.Now;
public int QuestionId { get; set; }
public int UserId { get; set; }
public int Id { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.BindingModels
{
public class CategoryBindingModel : ICategoryModel
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public int Id { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.BindingModels
{
public class QuestionBindingModel : IQuestionModel
{
public string QuestionDes { get; set; } = string.Empty;
public DateTime CreateDate { get; set; } = DateTime.Now;
public int UserId { get; set; }
public int CategoryId { get; set; }
public int Id { get; set; }
}
}

View File

@ -0,0 +1,24 @@
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.BindingModels
{
public class UserBindingModel : IUserModel
{
public string Nickname { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public DateTime RegistrationDate { get; set; } = DateTime.Now;
public DateTime ActivityDate { get; set; } = DateTime.Now;
public int Id { get; set; }
}
}

View File

@ -0,0 +1,20 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.BusinessLogicContracts
{
public interface IAnswerLogic
{
List<AnswerViewModel>? ReadList(AnswerSearchModel? model);
AnswerViewModel? ReadElement(AnswerSearchModel model);
bool Create(AnswerBindingModel model);
bool Update(AnswerBindingModel model);
bool Delete(AnswerBindingModel model);
}
}

View File

@ -0,0 +1,20 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.BusinessLogicContracts
{
public interface ICategoryLogic
{
List<CategoryViewModel>? ReadList(CategorySearchModel? model);
CategoryViewModel? ReadElement(CategorySearchModel model);
bool Create(CategoryBindingModel model);
bool Update(CategoryBindingModel model);
bool Delete(CategoryBindingModel model);
}
}

View File

@ -0,0 +1,21 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.BusinessLogicContracts
{
public interface IQuestionLogic
{
List<QuestionViewModel>? ReadList(QuestionSearchModel? model);
QuestionViewModel? ReadElement(QuestionSearchModel model);
List<QuestionViewModel>? HardRequest(QuestionSearchModel? model);
bool Create(QuestionBindingModel model);
bool Update(QuestionBindingModel model);
bool Delete(QuestionBindingModel model);
}
}

View File

@ -0,0 +1,20 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.BusinessLogicContracts
{
public interface IUserLogic
{
List<UserViewModel>? ReadList(UserSearchModel? model);
UserViewModel? ReadElement(UserSearchModel model);
bool Create(UserBindingModel model);
bool Update(UserBindingModel model);
bool Delete(UserBindingModel model);
}
}

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ForumDataModels\ForumDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.SearchModels
{
public class AnswerSearchModel
{
public string? AnswerDes { get; set; }
public DateTime? ResponseDate { get; set; }
public int? QuestionId { get; set; }
public int? UserId { get; set; }
public int? Id { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.SearchModels
{
public class CategorySearchModel
{
public string? Name { get; set; }
public string? Description { get; set; }
public int? Id { get; set; }
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.SearchModels
{
public class QuestionSearchModel
{
public string? QuestionDes { get; set; }
public DateTime? CreateDate { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? UserId { get; set; }
public int? CategoryId { get; set; }
public int? Id { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.SearchModels
{
public class UserSearchModel
{
public int? Id { get; set; }
public string? Nickname { get; set; }
public string? Password { get; set; }
public string? Email { get; set; }
public DateTime? RegistrationDate { get; set; }
public DateTime? ActivityDate { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.StorageContracts
{
public interface IAnswerStorage
{
List<AnswerViewModel> GetFullList();
List<AnswerViewModel> GetFilteredList(AnswerSearchModel model);
AnswerViewModel? GetElement(AnswerSearchModel model);
AnswerViewModel? Insert(AnswerBindingModel model);
AnswerViewModel? Update(AnswerBindingModel model);
AnswerViewModel? Delete(AnswerBindingModel model);
}
}

View File

@ -0,0 +1,21 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.StorageContracts
{
public interface ICategoryStorage
{
List<CategoryViewModel> GetFullList();
List<CategoryViewModel> GetFilteredList(CategorySearchModel model);
CategoryViewModel? GetElement(CategorySearchModel model);
CategoryViewModel? Insert(CategoryBindingModel model);
CategoryViewModel? Update(CategoryBindingModel model);
CategoryViewModel? Delete(CategoryBindingModel model);
}
}

View File

@ -0,0 +1,22 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.StorageContracts
{
public interface IQuestionStorage
{
List<QuestionViewModel> GetFullList();
List<QuestionViewModel> GetFilteredList(QuestionSearchModel model);
List<QuestionViewModel> HardRequest(QuestionSearchModel model);
QuestionViewModel? GetElement(QuestionSearchModel model);
QuestionViewModel? Insert(QuestionBindingModel model);
QuestionViewModel? Update(QuestionBindingModel model);
QuestionViewModel? Delete(QuestionBindingModel model);
}
}

View File

@ -0,0 +1,21 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.StorageContracts
{
public interface IUserStorage
{
List<UserViewModel> GetFullList();
List<UserViewModel> GetFilteredList(UserSearchModel model);
UserViewModel? GetElement(UserSearchModel model);
UserViewModel? Insert(UserBindingModel model);
UserViewModel? Update(UserBindingModel model);
UserViewModel? Delete(UserBindingModel model);
}
}

View File

@ -0,0 +1,34 @@
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.ViewModels
{
public class AnswerViewModel : IAnswerModel
{
[DisplayName("Ответ на вопрос")]
public string AnswerDes { get; set; } = string.Empty;
[DisplayName("Дата ответа")]
public DateTime ResponseDate { get; set; } = DateTime.Now;
[DisplayName("Автор ответа")]
public string AuthorAnswer { get; set; } = string.Empty;
[DisplayName("Содержание вопроса")]
public string QuestionText { get; set; } = string.Empty;
[DisplayName("Дата создания вопроса")]
public DateTime QuestionCreateDate { get; set; } = DateTime.Now;
public int QuestionId { get; set; }
public int UserId { get; set; }
public int Id { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.ViewModels
{
public class CategoryViewModel : ICategoryModel
{
[DisplayName("Название категории")]
public string Name { get; set; } = string.Empty;
[DisplayName("Описание категории")]
public string Description { get; set; } = string.Empty;
public int Id { get; set; }
}
}

View File

@ -0,0 +1,31 @@
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.ViewModels
{
public class QuestionViewModel : IQuestionModel
{
[DisplayName("Содержание вопроса")]
public string QuestionDes { get; set; } = string.Empty;
[DisplayName("Дата создания вопроса")]
public DateTime CreateDate { get; set; } = DateTime.Now;
[DisplayName("Имя пользователя")]
public string UserName { get; set; } = string.Empty;
[DisplayName("Название категории")]
public string CategoryName { get; set; } = string.Empty;
public int UserId { get; set; }
public int CategoryId { get; set; }
public int Id { get; set; }
}
}

View File

@ -0,0 +1,30 @@
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumContracts.ViewModels
{
public class UserViewModel : IUserModel
{
[DisplayName("Никнейм")]
public string Nickname { get; set; } = string.Empty;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
[DisplayName("Эл. почта")]
public string Email { get; set; } = string.Empty;
[DisplayName("Дата регистрации")]
public DateTime RegistrationDate { get; set; } = DateTime.Now;
[DisplayName("Дата активности")]
public DateTime ActivityDate { get; set; } = DateTime.Now;
public int Id { get; set; }
}
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

7
ForumDataModels/IId.cs Normal file
View File

@ -0,0 +1,7 @@
namespace ForumDataModels
{
public interface IId
{
int Id { get; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDataModels.Models
{
public interface IAnswerModel : IId
{
string AnswerDes { get; }
DateTime ResponseDate { get; }
int QuestionId { get; }
int UserId { get; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDataModels.Models
{
public interface ICategoryModel : IId
{
string Name { get; }
string Description { get; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDataModels.Models
{
public interface IQuestionModel : IId
{
string QuestionDes { get; }
DateTime CreateDate { get; }
int UserId { get; }
int CategoryId { get; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDataModels.Models
{
public interface IUserModel : IId
{
string Nickname { get; }
string Password { get; }
string Email { get; }
DateTime RegistrationDate { get; }
DateTime ActivityDate { get; }
}
}

View File

@ -0,0 +1,26 @@
using ForumDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace ForumDatabaseImplement
{
public class ForumDataBase : DbContext
{
public ForumDataBase()
{
}
public ForumDataBase(DbContextOptions<ForumDataBase> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseNpgsql("Host=192.168.56.101;Port=5432;Database=Forum;Username=ggg;Password=ankavanka27022003");
public virtual DbSet<User> Users { set; get; }
public virtual DbSet<Answer> Answers { set; get; }
public virtual DbSet<Question> Questions { set; get; }
public virtual DbSet<Category> Categories { set; get; }
}
}

View File

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EntityFramework" Version="6.4.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ForumContracts\ForumContracts.csproj" />
<ProjectReference Include="..\ForumDataModels\ForumDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,131 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using ForumDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Implements
{
public class AnswerStorage : IAnswerStorage
{
public AnswerViewModel? Delete(AnswerBindingModel model)
{
using var context = new ForumDataBase();
var element = context.Answers
.Include(x => x.User)
.Include(x => x.Question)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Answers.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public AnswerViewModel? GetElement(AnswerSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new ForumDataBase();
return context.Answers
.Include(x => x.User)
.Include(x => x.Question)
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public List<AnswerViewModel> GetFilteredList(AnswerSearchModel model)
{
if (model.Id.HasValue)
{
var result = GetElement(model);
return result != null ? new() { result } : new();
}
using var context = new ForumDataBase();
IQueryable<Answer>? queryWhere = null;
if (model.QuestionId.HasValue)
{
queryWhere = context.Answers.Where(x => x.QuestionId == model.QuestionId);
}
else
{
return new();
}
return queryWhere
.Include(x => x.Question)
.Include(x => x.User)
.Select(x => x.GetViewModel)
.ToList();
}
public List<AnswerViewModel> GetFullList()
{
using var context = new ForumDataBase();
return context.Answers
.Include(x => x.User)
.Include(x => x.Question)
.Select(x => x.GetViewModel).ToList();
}
public AnswerViewModel? Insert(AnswerBindingModel model)
{
var newAnswer = Answer.Create(model);
if (newAnswer == null)
{
return null;
}
using var context = new ForumDataBase();
context.Answers.Add(newAnswer);
context.SaveChanges();
return context.Answers
.Include(x => x.Question)
.Include(x => x.User)
.FirstOrDefault(x => x.Id == newAnswer.Id)
?.GetViewModel;
}
public AnswerViewModel? Update(AnswerBindingModel model)
{
using var context = new ForumDataBase();
var answer = context.Answers
.Include(x => x.Question)
.Include(x => x.User)
.FirstOrDefault(x => x.Id == model.Id);
if (answer == null)
{
return null;
}
answer.Update(model);
context.SaveChanges();
return answer.GetViewModel;
}
}
}

View File

@ -0,0 +1,111 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using ForumDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Implements
{
public class CategoryStorage : ICategoryStorage
{
public CategoryViewModel? Delete(CategoryBindingModel model)
{
using var context = new ForumDataBase();
var res = context.Categories
.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
context.Categories.Remove(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
public CategoryViewModel? GetElement(CategorySearchModel model)
{
using var context = new ForumDataBase();
if (model.Id.HasValue)
return context.Categories
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
return null;
}
public List<CategoryViewModel> GetFilteredList(CategorySearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.Name != null)
{
using var context = new ForumDataBase();
return context.Categories
.Where(x => x.Name.Equals(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public List<CategoryViewModel> GetFullList()
{
using var context = new ForumDataBase();
return context.Categories
.Select(x => x.GetViewModel)
.ToList();
}
public CategoryViewModel? Insert(CategoryBindingModel model)
{
using var context = new ForumDataBase();
var res = Category.Create(model);
if (res != null)
{
context.Categories.Add(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
public CategoryViewModel? Update(CategoryBindingModel model)
{
using var context = new ForumDataBase();
var res = context.Categories
.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
context.SaveChanges();
}
return res?.GetViewModel;
}
}
}

View File

@ -0,0 +1,148 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using ForumDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Implements
{
public class QuestionStorage : IQuestionStorage
{
public QuestionViewModel? Delete(QuestionBindingModel model)
{
using var context = new ForumDataBase();
var element = context.Questions
.Include(x => x.User)
.Include(x => x.Category)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Questions.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public QuestionViewModel? GetElement(QuestionSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new ForumDataBase();
return context.Questions
.Include(x => x.User)
.Include(x => x.Category)
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public List<QuestionViewModel> GetFilteredList(QuestionSearchModel model)
{
if (model.Id.HasValue)
{
var result = GetElement(model);
return result != null ? new() { result } : new();
}
using var context = new ForumDataBase();
IQueryable<Question>? queryWhere = null;
if (model.CategoryId.HasValue)
{
queryWhere = context.Questions.Where(x => x.CategoryId == model.CategoryId);
}
else if (model.UserId.HasValue)
{
queryWhere = context.Questions.Where(x => x.UserId == model.UserId);
}
else
{
return new();
}
return queryWhere
.Include(x => x.Category)
.Include(x => x.User)
.Select(x => x.GetViewModel)
.ToList();
}
public List<QuestionViewModel> HardRequest(QuestionSearchModel model)
{
using var context = new ForumDataBase();
return context.Questions.
OrderBy(x => x.CreateDate)
.Include(x => x.Category)
.Include(x => x.User)
.Where(x => x.CreateDate.Date >= model.DateFrom.Value.Date && x.CreateDate.Date <= model.DateTo.Value.Date)
.Select(x=>x.GetViewModel)
.ToList();
}
public List<QuestionViewModel> GetFullList()
{
using var context = new ForumDataBase();
return context.Questions
.Include(x => x.User)
.Include(x => x.Category)
.Select(x => x.GetViewModel).ToList();
}
public QuestionViewModel? Insert(QuestionBindingModel model)
{
var newQuestion = Question.Create(model);
if (newQuestion == null)
{
return null;
}
using var context = new ForumDataBase();
context.Questions.Add(newQuestion);
context.SaveChanges();
return context.Questions
.Include(x => x.Category)
.Include(x => x.User)
.FirstOrDefault(x => x.Id == newQuestion.Id)
?.GetViewModel;
}
public QuestionViewModel? Update(QuestionBindingModel model)
{
using var context = new ForumDataBase();
var question = context.Questions
.Include(x => x.Category)
.Include(x => x.User)
.FirstOrDefault(x => x.Id == model.Id);
if (question == null)
{
return null;
}
question.Update(model);
context.SaveChanges();
return question.GetViewModel;
}
}
}

View File

@ -0,0 +1,83 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using ForumDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Implements
{
public class UserStorage : IUserStorage
{
public UserViewModel? Delete(UserBindingModel model)
{
using var context = new ForumDataBase();
var element = context.Users.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Users.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public UserViewModel? GetElement(UserSearchModel model)
{
using var context = new ForumDataBase();
if (model.Id.HasValue)
return context.Users.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (!string.IsNullOrEmpty(model.Nickname) && !string.IsNullOrEmpty(model.Password))
return context.Users.FirstOrDefault(x => x.Nickname.Equals(model.Nickname) && x.Password.Equals(model.Password))?.GetViewModel;
if (!string.IsNullOrEmpty(model.Email))
return context.Users.FirstOrDefault(x => x.Email.Equals(model.Email))?.GetViewModel;
return null;
}
public List<UserViewModel> GetFilteredList(UserSearchModel model)
{
if (string.IsNullOrEmpty(model.Nickname))
{
return new();
}
using var context = new ForumDataBase();
return context.Users.Where(x => x.Nickname.Contains(model.Nickname)).Select(x => x.GetViewModel).ToList();
}
public List<UserViewModel> GetFullList()
{
using var context = new ForumDataBase();
return context.Users.Select(x => x.GetViewModel).ToList();
}
public UserViewModel? Insert(UserBindingModel model)
{
var newUser = User.Create(model);
if (newUser == null)
{
return null;
}
using var context = new ForumDataBase();
context.Users.Add(newUser);
context.SaveChanges();
return newUser.GetViewModel;
}
public UserViewModel? Update(UserBindingModel model)
{
using var context = new ForumDataBase();
var user = context.Users.FirstOrDefault(x => x.Id == model.Id);
if (user == null)
{
return null;
}
user.Update(model);
context.SaveChanges();
return user.GetViewModel;
}
}
}

View File

@ -0,0 +1,197 @@
// <auto-generated />
using System;
using ForumDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ForumDatabaseImplement.Migrations
{
[DbContext(typeof(ForumDataBase))]
[Migration("20230430154303_InitDb")]
partial class InitDb
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ForumDatabaseImplement.Models.Answer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("AnswerDes")
.IsRequired()
.HasColumnType("text");
b.Property<int>("QuestionId")
.HasColumnType("integer");
b.Property<DateTime>("ResponseDate")
.HasColumnType("timestamp with time zone");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("QuestionId");
b.HasIndex("UserId");
b.ToTable("Answers");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Categories");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Question", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CategoryId")
.HasColumnType("integer");
b.Property<DateTime>("CreateDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("QuestionDes")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("UserId");
b.ToTable("Questions");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("ActivityDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Nickname")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("RegistrationDate")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Answer", b =>
{
b.HasOne("ForumDatabaseImplement.Models.Question", "Question")
.WithMany("Answers")
.HasForeignKey("QuestionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ForumDatabaseImplement.Models.User", "User")
.WithMany("Answers")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Question");
b.Navigation("User");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Question", b =>
{
b.HasOne("ForumDatabaseImplement.Models.Category", "Category")
.WithMany("Questions")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ForumDatabaseImplement.Models.User", "User")
.WithMany("Questions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
b.Navigation("User");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Category", b =>
{
b.Navigation("Questions");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Question", b =>
{
b.Navigation("Answers");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.User", b =>
{
b.Navigation("Answers");
b.Navigation("Questions");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,139 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ForumDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitDb : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false),
Description = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Nickname = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
RegistrationDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
ActivityDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Questions",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
CreateDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: false),
CategoryId = table.Column<int>(type: "integer", nullable: false),
QuestionDes = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Questions", x => x.Id);
table.ForeignKey(
name: "FK_Questions_Categories_CategoryId",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Questions_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Answers",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ResponseDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
QuestionId = table.Column<int>(type: "integer", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: false),
AnswerDes = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Answers", x => x.Id);
table.ForeignKey(
name: "FK_Answers_Questions_QuestionId",
column: x => x.QuestionId,
principalTable: "Questions",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Answers_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Answers_QuestionId",
table: "Answers",
column: "QuestionId");
migrationBuilder.CreateIndex(
name: "IX_Answers_UserId",
table: "Answers",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Questions_CategoryId",
table: "Questions",
column: "CategoryId");
migrationBuilder.CreateIndex(
name: "IX_Questions_UserId",
table: "Questions",
column: "UserId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Answers");
migrationBuilder.DropTable(
name: "Questions");
migrationBuilder.DropTable(
name: "Categories");
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@ -0,0 +1,194 @@
// <auto-generated />
using System;
using ForumDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ForumDatabaseImplement.Migrations
{
[DbContext(typeof(ForumDataBase))]
partial class ForumDataBaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ForumDatabaseImplement.Models.Answer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("AnswerDes")
.IsRequired()
.HasColumnType("text");
b.Property<int>("QuestionId")
.HasColumnType("integer");
b.Property<DateTime>("ResponseDate")
.HasColumnType("timestamp with time zone");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("QuestionId");
b.HasIndex("UserId");
b.ToTable("Answers");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Categories");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Question", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CategoryId")
.HasColumnType("integer");
b.Property<DateTime>("CreateDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("QuestionDes")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("UserId");
b.ToTable("Questions");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("ActivityDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Nickname")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("RegistrationDate")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Answer", b =>
{
b.HasOne("ForumDatabaseImplement.Models.Question", "Question")
.WithMany("Answers")
.HasForeignKey("QuestionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ForumDatabaseImplement.Models.User", "User")
.WithMany("Answers")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Question");
b.Navigation("User");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Question", b =>
{
b.HasOne("ForumDatabaseImplement.Models.Category", "Category")
.WithMany("Questions")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ForumDatabaseImplement.Models.User", "User")
.WithMany("Questions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
b.Navigation("User");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Category", b =>
{
b.Navigation("Questions");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.Question", b =>
{
b.Navigation("Answers");
});
modelBuilder.Entity("ForumDatabaseImplement.Models.User", b =>
{
b.Navigation("Answers");
b.Navigation("Questions");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,81 @@
using ForumContracts.BindingModels;
using ForumContracts.ViewModels;
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Models
{
public class Answer : IAnswerModel
{
[Required]
public DateTime ResponseDate { get; set; } = DateTime.Now;
public int QuestionId { get; set; }
public int UserId { get; set; }
public int Id { get; set; }
[Required]
public string AnswerDes { get; set; } = string.Empty;
public virtual User User { get; set; }
public virtual Question Question { get; set; }
public static Answer? Create(AnswerBindingModel model)
{
if (model == null)
{
return null;
}
return new Answer()
{
Id = model.Id,
ResponseDate = model.ResponseDate,
UserId = model.UserId,
QuestionId = model.QuestionId,
AnswerDes = model.AnswerDes
};
}
public static Answer Create(AnswerViewModel model)
{
return new Answer
{
Id = model.Id,
UserId = model.UserId,
QuestionId = model.QuestionId,
ResponseDate = model.ResponseDate,
AnswerDes = model.AnswerDes
};
}
public void Update(AnswerBindingModel model)
{
if (model == null)
{
return;
}
UserId = model.UserId;
QuestionId = model.QuestionId;
ResponseDate = model.ResponseDate;
AnswerDes = model.AnswerDes;
}
public AnswerViewModel GetViewModel => new()
{
AuthorAnswer= User?.Nickname ?? string.Empty,
QuestionCreateDate =Question?.CreateDate ?? DateTime.Now,
QuestionText = Question?.QuestionDes ?? string.Empty,
Id = Id,
ResponseDate = ResponseDate,
UserId = UserId,
QuestionId = QuestionId,
AnswerDes = AnswerDes
};
}
}

View File

@ -0,0 +1,66 @@
using ForumContracts.BindingModels;
using ForumContracts.ViewModels;
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Models
{
public class Category : ICategoryModel
{
[Required]
public string Name { get; set; } = string.Empty;
[Required]
public string Description { get; set; } = string.Empty;
public int Id { get; set; }
[ForeignKey("CategoryId")]
public virtual List<Question> Questions { get; set; } = new();
public static Category? Create(CategoryBindingModel model)
{
if (model == null)
{
return null;
}
return new Category()
{
Id = model.Id,
Name = model.Name,
Description = model.Description
};
}
public static Category Create(CategoryViewModel model)
{
return new Category
{
Id = model.Id,
Name = model.Name,
Description = model.Description
};
}
public void Update(CategoryBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
Description = model.Description;
}
public CategoryViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Description = Description
};
}
}

View File

@ -0,0 +1,84 @@
using ForumContracts.BindingModels;
using ForumContracts.ViewModels;
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Models
{
public class Question : IQuestionModel
{
[Required]
public DateTime CreateDate { get; set; } = DateTime.Now;
public int UserId { get; set; }
public int CategoryId { get; set; }
public int Id { get; set; }
[Required]
public string QuestionDes { get; set; } = string.Empty;
public virtual User User { get; set; }
public virtual Category Category { get; set; }
[ForeignKey("QuestionId")]
public virtual List<Answer> Answers { get; set; } = new();
public static Question? Create(QuestionBindingModel model)
{
if (model == null)
{
return null;
}
return new Question()
{
Id = model.Id,
CreateDate = model.CreateDate,
UserId = model.UserId,
CategoryId = model.CategoryId,
QuestionDes = model.QuestionDes
};
}
public static Question Create(QuestionViewModel model)
{
return new Question
{
Id = model.Id,
UserId = model.UserId,
CategoryId = model.CategoryId,
CreateDate = model.CreateDate,
QuestionDes = model.QuestionDes
};
}
public void Update(QuestionBindingModel model)
{
if (model == null)
{
return;
}
UserId = model.UserId;
CategoryId = model.CategoryId;
CreateDate = model.CreateDate;
QuestionDes = model.QuestionDes;
}
public QuestionViewModel GetViewModel => new()
{
Id = Id,
UserId = UserId,
UserName = User?.Nickname ?? string.Empty,
CategoryId = CategoryId,
CreateDate = CreateDate,
QuestionDes = QuestionDes,
CategoryName=Category?.Name
};
}
}

View File

@ -0,0 +1,89 @@
using ForumContracts.BindingModels;
using ForumContracts.ViewModels;
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Models
{
public class User : IUserModel
{
[Required]
public string Nickname { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
[Required]
public string Email { get; set; } = string.Empty;
[Required]
public DateTime RegistrationDate { get; set; } = DateTime.Now;
[Required]
public DateTime ActivityDate { get; set; } = DateTime.Now;
public int Id { get; set; }
[ForeignKey("UserId")]
public virtual List<Answer> Answers { get; set; } = new();
[ForeignKey("UserId")]
public virtual List<Question> Questions { get; set; } = new();
public static User? Create(UserBindingModel model)
{
if (model == null)
{
return null;
}
return new User()
{
Id = model.Id,
Nickname = model.Nickname,
Password = model.Password,
Email = model.Email,
RegistrationDate = model.RegistrationDate,
ActivityDate = model.ActivityDate
};
}
public static User Create(UserViewModel model)
{
return new User
{
Id = model.Id,
Nickname = model.Nickname,
Password = model.Password,
Email = model.Email,
RegistrationDate = model.RegistrationDate,
ActivityDate = model.ActivityDate
};
}
public void Update(UserBindingModel model)
{
if (model == null)
{
return;
}
Nickname = model.Nickname;
Password = model.Password;
Email = model.Email;
RegistrationDate = model.RegistrationDate;
ActivityDate = model.ActivityDate;
}
public UserViewModel GetViewModel => new()
{
Id = Id,
Nickname = Nickname,
Password = Password,
Email = Email,
RegistrationDate = RegistrationDate,
ActivityDate = ActivityDate
};
}
}

View File

@ -0,0 +1,19 @@
using MongoDB.Driver;
namespace ForumMongoDataBase
{
public class ForumMongoDataBase
{
private static ForumMongoDataBase instance;
public MongoClient client;
private ForumMongoDataBase()
{ client = new MongoClient("mongodb://localhost:27017"); }
public static ForumMongoDataBase getInstance()
{
if (instance == null)
instance = new ForumMongoDataBase();
return instance;
}
}
}

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MongoDB.Driver" Version="2.19.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ForumContracts\ForumContracts.csproj" />
<ProjectReference Include="..\ForumDataModels\ForumDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,120 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using ForumDatabaseImplement.Models;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumMongoDataBase.Implements
{
public class AnswerStorage : IAnswerStorage
{
private readonly IMongoCollection<Answer> _collection;
public MongoClient context;
public AnswerStorage()
{
context = ForumMongoDataBase.getInstance().client;
_collection = context.GetDatabase("forum").GetCollection<Answer>("answers");
}
public AnswerViewModel? Delete(AnswerBindingModel model)
{
var filter = Builders<Answer>.Filter.Eq(a => a.Id, model.Id);
var answer = _collection.FindOneAndDelete(filter);
if (answer == null)
{
return null;
}
return answer.GetViewModel();
}
public AnswerViewModel? GetElement(AnswerSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
var answer = _collection.Find(a => a.Id == model.Id.Value)
.FirstOrDefault();
if (answer == null)
{
return null;
}
return answer.GetViewModel();
}
public List<AnswerViewModel> GetFilteredList(AnswerSearchModel model)
{
var filter = Builders<Answer>.Filter.Empty;
if (model.Id.HasValue)
{
filter &= Builders<Answer>.Filter.Eq(a => a.Id, model.Id.Value);
}
if (model.QuestionId.HasValue)
{
filter &= Builders<Answer>.Filter.Eq(a => a.QuestionId, model.QuestionId.Value);
}
else
{
return new List<AnswerViewModel>();
}
var answers = _collection.Find(filter)
.ToList()
.Select(a => a.GetViewModel())
.ToList();
return answers;
}
public List<AnswerViewModel> GetFullList()
{
var answers = _collection.Find(_ => true)
.ToList()
.Select(a => a.GetViewModel())
.ToList();
return answers;
}
public AnswerViewModel? Insert(AnswerBindingModel model)
{
var answer = Answer.Create(model);
if (answer == null)
{
return null;
}
_collection.InsertOne(answer);
return answer.GetViewModel();
}
public AnswerViewModel? Update(AnswerBindingModel model)
{
var filter = Builders<Answer>.Filter.Eq(a => a.Id, model.Id);
var answer = _collection.Find(filter).FirstOrDefault();
answer.Update(model);
_collection.ReplaceOne(filter, answer);
return answer.GetViewModel();
}
}
}

View File

@ -0,0 +1,119 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ForumDatabaseImplement.Models;
namespace ForumMongoDataBase.Implements
{
public class CategoryStorage : ICategoryStorage
{
private readonly IMongoCollection<Category> _collection;
public MongoClient context;
public CategoryStorage()
{
context = ForumMongoDataBase.getInstance().client;
_collection = context.GetDatabase("forum").GetCollection<Category>("categories");
}
public CategoryViewModel? Delete(CategoryBindingModel model)
{
var filter = Builders<Category>.Filter.Eq(c => c.Id, model.Id);
var category = _collection.FindOneAndDelete(filter);
if (category == null)
{
return null;
}
return category.GetViewModel();
}
public CategoryViewModel? GetElement(CategorySearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
var category = _collection.Find(c => c.Id == model.Id.Value)
.FirstOrDefault();
if (category == null)
{
return null;
}
return category.GetViewModel();
}
public List<CategoryViewModel> GetFilteredList(CategorySearchModel model)
{
var filter = Builders<Category>.Filter.Empty;
if (model.Id.HasValue)
{
filter &= Builders<Category>.Filter.Eq(c => c.Id, model.Id.Value);
}
if (model.Name != null)
{
filter &= Builders<Category>.Filter.Eq(c => c.Name, model.Name);
}
var categories = _collection.Find(filter)
.ToList()
.Select(c => c.GetViewModel())
.ToList();
return categories;
}
public List<CategoryViewModel> GetFullList()
{
var categories = _collection.Find(_ => true)
.ToList()
.Select(c => c.GetViewModel())
.ToList();
return categories;
}
public CategoryViewModel? Insert(CategoryBindingModel model)
{
var category = Category.Create(model);
if (category == null)
{
return null;
}
_collection.InsertOne(category);
return category.GetViewModel();
}
public CategoryViewModel? Update(CategoryBindingModel model)
{
var filter = Builders<Category>.Filter.Eq(c => c.Id, model.Id);
var category = _collection.Find(filter).FirstOrDefault();
if (category == null)
{
return null;
}
category.Update(model);
_collection.ReplaceOne(filter, category);
return category.GetViewModel();
}
}
}

View File

@ -0,0 +1,141 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using ForumDatabaseImplement.Models;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumMongoDataBase.Implements
{
public class QuestionStorage : IQuestionStorage
{
public MongoClient context;
private readonly IMongoCollection<Question> _collection;
public QuestionStorage()
{
context = ForumMongoDataBase.getInstance().client;
_collection = context.GetDatabase("forum").GetCollection<Question>("questions");
}
public QuestionViewModel? Delete(QuestionBindingModel model)
{
var filter = Builders<Question>.Filter.Eq(q => q.Id, model.Id);
var question = _collection.FindOneAndDelete(filter);
if (question == null)
{
return null;
}
return question.GetViewModel();
}
public QuestionViewModel? GetElement(QuestionSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
var question = _collection.Find(q => q.Id == model.Id.Value)
.FirstOrDefault();
if (question == null)
{
return null;
}
return question.GetViewModel();
}
public List<QuestionViewModel> GetFilteredList(QuestionSearchModel model)
{
var filter = Builders<Question>.Filter.Empty;
if (model.Id.HasValue)
{
filter &= Builders<Question>.Filter.Eq(q => q.Id, model.Id.Value);
}
if (model.CategoryId.HasValue)
{
filter &= Builders<Question>.Filter.Eq(q => q.CategoryId, model.CategoryId.Value);
}
if (model.UserId.HasValue)
{
filter &= Builders<Question>.Filter.Eq(q => q.UserId, model.UserId.Value);
}
var questions = _collection.Find(filter)
.ToList()
.Select(q => q.GetViewModel())
.ToList();
return questions;
}
public List<QuestionViewModel> HardRequest(QuestionSearchModel model)
{
var filter = Builders<Question>.Filter.And(
Builders<Question>.Filter.Gte(q => q.CreateDate, model.DateFrom),
Builders<Question>.Filter.Lte(q => q.CreateDate, model.DateTo));
var questions = _collection.Find(filter)
.SortBy(q => q.CreateDate)
.ToList()
.Select(q => q.GetViewModel())
.ToList();
return questions;
}
public List<QuestionViewModel> GetFullList()
{
var questions = _collection.Find(_ => true)
.ToList()
.Select(q => q.GetViewModel())
.ToList();
return questions;
}
public QuestionViewModel? Insert(QuestionBindingModel model)
{
var question = Question.Create(model);
if (question == null)
{
return null;
}
_collection.InsertOne(question);
return question.GetViewModel();
}
public QuestionViewModel? Update(QuestionBindingModel model)
{
var filter = Builders<Question>.Filter.Eq(q => q.Id, model.Id);
var question = _collection.Find(filter).FirstOrDefault();
if (question == null)
{
return null;
}
question.Update(model);
_collection.ReplaceOne(filter, question);
return question.GetViewModel();
}
}
}

View File

@ -0,0 +1,128 @@
using ForumContracts.BindingModels;
using ForumContracts.SearchModels;
using ForumContracts.StorageContracts;
using ForumContracts.ViewModels;
using ForumDatabaseImplement.Models;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumMongoDataBase.Implements
{
public class UserStorage : IUserStorage
{
private readonly IMongoCollection<User> _collection;
public MongoClient context;
public UserStorage()
{
context = ForumMongoDataBase.getInstance().client;
_collection = context.GetDatabase("forum").GetCollection<User>("users");
}
public UserViewModel? Delete(UserBindingModel model)
{
var filter = Builders<User>.Filter.Eq(u => u.Id, model.Id);
var user = _collection.FindOneAndDelete(filter);
if (user == null)
{
return null;
}
return user.GetViewModel();
}
public UserViewModel? GetElement(UserSearchModel model)
{
var filter = Builders<User>.Filter.Empty;
if (model.Id.HasValue)
{
filter &= Builders<User>.Filter.Eq(u => u.Id, model.Id.Value);
}
if (!string.IsNullOrEmpty(model.Nickname) && !string.IsNullOrEmpty(model.Password))
{
filter &= Builders<User>.Filter.Eq(u => u.Nickname, model.Nickname)
& Builders<User>.Filter.Eq(u => u.Password, model.Password);
}
if (!string.IsNullOrEmpty(model.Email))
{
filter &= Builders<User>.Filter.Eq(u => u.Email, model.Email);
}
var user = _collection.Find(filter)
.FirstOrDefault();
if (user == null)
{
return null;
}
return user.GetViewModel();
}
public List<UserViewModel> GetFilteredList(UserSearchModel model)
{
if (string.IsNullOrEmpty(model.Nickname))
{
return new List<UserViewModel>();
}
var filter = Builders<User>.Filter.Regex(u => u.Nickname, new BsonRegularExpression(model.Nickname, "i"));
var users = _collection.Find(filter)
.ToList()
.Select(u => u.GetViewModel())
.ToList();
return users;
}
public List<UserViewModel> GetFullList()
{
var users = _collection.Find(_ => true)
.ToList()
.Select(u => u.GetViewModel())
.ToList();
return users;
}
public UserViewModel? Insert(UserBindingModel model)
{
var user = User.Create(model);
if (user == null)
{
return null;
}
_collection.InsertOne(user);
return user.GetViewModel();
}
public UserViewModel? Update(UserBindingModel model)
{
var filter = Builders<User>.Filter.Eq(u => u.Id, model.Id);
var user = _collection.Find(filter).FirstOrDefault();
if (user == null)
{
return null;
}
user.Update(model);
_collection.ReplaceOne(filter, user);
return user.GetViewModel();
}
}
}

View File

@ -0,0 +1,85 @@
using ForumContracts.BindingModels;
using ForumContracts.ViewModels;
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Models
{
public class Answer : IAnswerModel
{
[Required]
public DateTime ResponseDate { get; set; } = DateTime.Now;
public int QuestionId { get; set; }
public int UserId { get; set; }
public int Id { get; set; }
[Required]
public string AnswerDes { get; set; } = string.Empty;
public virtual User User { get; set; }
public virtual Question Question { get; set; }
public static Answer? Create(AnswerBindingModel model)
{
if (model == null)
{
return null;
}
return new Answer()
{
Id = model.Id,
ResponseDate = model.ResponseDate,
UserId = model.UserId,
QuestionId = model.QuestionId,
AnswerDes = model.AnswerDes
};
}
public static Answer Create(AnswerViewModel model)
{
return new Answer
{
Id = model.Id,
UserId = model.UserId,
QuestionId = model.QuestionId,
ResponseDate = model.ResponseDate,
AnswerDes = model.AnswerDes
};
}
public void Update(AnswerBindingModel model)
{
if (model == null)
{
return;
}
UserId = model.UserId;
QuestionId = model.QuestionId;
ResponseDate = model.ResponseDate;
AnswerDes = model.AnswerDes;
}
public AnswerViewModel? GetViewModel()
{
return new()
{
AuthorAnswer = User?.Nickname ?? string.Empty,
QuestionCreateDate = Question?.CreateDate ?? DateTime.Now,
QuestionText = Question?.QuestionDes ?? string.Empty,
Id = Id,
ResponseDate = ResponseDate,
UserId = UserId,
QuestionId = QuestionId,
AnswerDes = AnswerDes
};
}
}
}

View File

@ -0,0 +1,70 @@
using ForumContracts.BindingModels;
using ForumContracts.ViewModels;
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Models
{
public class Category : ICategoryModel
{
[Required]
public string Name { get; set; } = string.Empty;
[Required]
public string Description { get; set; } = string.Empty;
public int Id { get; set; }
[ForeignKey("CategoryId")]
public virtual List<Question> Questions { get; set; } = new();
public static Category? Create(CategoryBindingModel model)
{
if (model == null)
{
return null;
}
return new Category()
{
Id = model.Id,
Name = model.Name,
Description = model.Description
};
}
public static Category Create(CategoryViewModel model)
{
return new Category
{
Id = model.Id,
Name = model.Name,
Description = model.Description
};
}
public void Update(CategoryBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
Description = model.Description;
}
public CategoryViewModel? GetViewModel()
{
return new()
{
Id = Id,
Name = Name,
Description = Description
};
}
}
}

View File

@ -0,0 +1,87 @@
using ForumContracts.BindingModels;
using ForumContracts.ViewModels;
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Models
{
public class Question : IQuestionModel
{
[Required]
public DateTime CreateDate { get; set; } = DateTime.Now;
public int UserId { get; set; }
public int CategoryId { get; set; }
public int Id { get; set; }
[Required]
public string QuestionDes { get; set; } = string.Empty;
public virtual User User { get; set; }
public virtual Category Category { get; set; }
[ForeignKey("QuestionId")]
public virtual List<Answer> Answers { get; set; } = new();
public static Question? Create(QuestionBindingModel model)
{
if (model == null)
{
return null;
}
return new Question()
{
Id = model.Id,
CreateDate = model.CreateDate,
UserId = model.UserId,
CategoryId = model.CategoryId,
QuestionDes = model.QuestionDes
};
}
public static Question Create(QuestionViewModel model)
{
return new Question
{
Id = model.Id,
UserId = model.UserId,
CategoryId = model.CategoryId,
CreateDate = model.CreateDate,
QuestionDes = model.QuestionDes
};
}
public void Update(QuestionBindingModel model)
{
if (model == null)
{
return;
}
UserId = model.UserId;
CategoryId = model.CategoryId;
CreateDate = model.CreateDate;
QuestionDes = model.QuestionDes;
}
public QuestionViewModel GetViewModel()
{
return new()
{
Id = Id,
UserId = UserId,
UserName = User?.Nickname ?? string.Empty,
CategoryId = CategoryId,
CreateDate = CreateDate,
QuestionDes = QuestionDes,
CategoryName = Category?.Name
};
}
}
}

View File

@ -0,0 +1,92 @@
using ForumContracts.BindingModels;
using ForumContracts.ViewModels;
using ForumDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDatabaseImplement.Models
{
public class User : IUserModel
{
[Required]
public string Nickname { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
[Required]
public string Email { get; set; } = string.Empty;
[Required]
public DateTime RegistrationDate { get; set; } = DateTime.Now;
[Required]
public DateTime ActivityDate { get; set; } = DateTime.Now;
public int Id { get; set; }
[ForeignKey("UserId")]
public virtual List<Answer> Answers { get; set; } = new();
[ForeignKey("UserId")]
public virtual List<Question> Questions { get; set; } = new();
public static User? Create(UserBindingModel model)
{
if (model == null)
{
return null;
}
return new User()
{
Id = model.Id,
Nickname = model.Nickname,
Password = model.Password,
Email = model.Email,
RegistrationDate = model.RegistrationDate,
ActivityDate = model.ActivityDate
};
}
public static User Create(UserViewModel model)
{
return new User
{
Id = model.Id,
Nickname = model.Nickname,
Password = model.Password,
Email = model.Email,
RegistrationDate = model.RegistrationDate,
ActivityDate = model.ActivityDate
};
}
public void Update(UserBindingModel model)
{
if (model == null)
{
return;
}
Nickname = model.Nickname;
Password = model.Password;
Email = model.Email;
RegistrationDate = model.RegistrationDate;
ActivityDate = model.ActivityDate;
}
public UserViewModel GetViewModel()
{
return new()
{
Id = Id,
Nickname = Nickname,
Password = Password,
Email = Email,
RegistrationDate = RegistrationDate,
ActivityDate = ActivityDate
};
}
}
}

View File

@ -0,0 +1,198 @@
using ForumContracts.BindingModels;
using ForumContracts.BusinessLogicContracts;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using ForumDatabaseImplement.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ForumRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class MainController : Controller
{
private readonly ILogger _logger;
private readonly IAnswerLogic _answer;
private readonly IQuestionLogic _question;
private readonly ICategoryLogic _category;
public MainController(ILogger<MainController> logger, IAnswerLogic answer, IQuestionLogic question, ICategoryLogic category)
{
_logger = logger;
_answer = answer;
_question = question;
_category = category;
}
[HttpGet]
public List<CategoryViewModel>? GetCategoryList()
{
try
{
return _category.ReadList(null);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка категорий");
throw;
}
}
[HttpGet]
public List<AnswerViewModel>? GetAnswersByQuestion(int questionId)
{
try
{
return _answer.ReadList(new AnswerSearchModel
{
QuestionId = questionId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка ответов вопроса id ={ questionId}", questionId);
throw;
}
}
[HttpGet]
public CategoryViewModel? GetCategory(int categoryId)
{
try
{
return _category.ReadElement(new CategorySearchModel
{
Id = categoryId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения категории по id={categoryId}", categoryId);
throw;
}
}
[HttpGet]
public List<QuestionViewModel>? GetQuestionsByUser(int userId)
{
try
{
return _question.ReadList(new QuestionSearchModel
{
UserId = userId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка вопросов пользователя id ={ userId}", userId);
throw;
}
}
[HttpGet]
public List<QuestionViewModel>? HardRequest(DateTime dateFrom,DateTime dateTo)
{
try
{
return _question.HardRequest(new QuestionSearchModel
{
DateFrom=dateFrom,
DateTo=dateTo
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка вопросов");
throw;
}
}
[HttpGet]
public List<QuestionViewModel>? GetQuestionsByCategory(int categoryId)
{
try
{
return _question.ReadList(new QuestionSearchModel
{
CategoryId = categoryId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка вопросов категории id ={ categoryId}", categoryId);
throw;
}
}
[HttpPost]
public void DeleteQuestion(QuestionBindingModel model)
{
try
{
_question.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления вопроса");
throw;
}
}
[HttpPost]
public void DeleteAnswer(AnswerBindingModel model)
{
try
{
_answer.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления ответа");
throw;
}
}
[HttpPost]
public void CreateCategory(CategoryBindingModel model)
{
try
{
_category.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания категории");
throw;
}
}
[HttpPost]
public void CreateAnswer(AnswerBindingModel model)
{
try
{
_answer.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания ответа");
throw;
}
}
[HttpPost]
public void CreateQuestion(QuestionBindingModel model)
{
try
{
_question.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания вопроса");
throw;
}
}
}
}

View File

@ -0,0 +1,70 @@
using ForumContracts.BindingModels;
using ForumContracts.BusinessLogicContracts;
using ForumContracts.SearchModels;
using ForumContracts.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace ForumRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class UserController : Controller
{
private readonly ILogger _logger;
private readonly IUserLogic _logic;
public UserController(IUserLogic logic, ILogger<UserController> logger)
{
_logger = logger;
_logic = logic;
}
[HttpGet]
public UserViewModel? Login(string login, string password)
{
try
{
return _logic.ReadElement(new UserSearchModel
{
Email = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка входа в систему");
throw;
}
}
[HttpPost]
public void Register(UserBindingModel model)
{
try
{
_logic.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка регистрации");
throw;
}
}
[HttpPost]
public void UpdateData(UserBindingModel model)
{
try
{
_logic.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных");
throw;
}
}
}
}

View File

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="log4net" Version="2.0.15" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ForumBusinessLogic\ForumBusinessLogic.csproj" />
<ProjectReference Include="..\ForumContracts\ForumContracts.csproj" />
<ProjectReference Include="..\ForumDatabaseImplement\ForumDatabaseImplement.csproj" />
<ProjectReference Include="..\ForumMongoDataBase\ForumMongoDataBase.csproj" />
</ItemGroup>
</Project>

51
ForumRestApi/Program.cs Normal file
View File

@ -0,0 +1,51 @@
using ForumBusinessLogic.BusinessLogic;
using ForumContracts.BusinessLogicContracts;
using ForumContracts.StorageContracts;
using ForumMongoDataBase.Implements;
using Microsoft.OpenApi.Models;
using NLog.Extensions.Logging;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.Logging.AddNLog("log4net.config");
// Add services to the container.
builder.Services.AddTransient<IAnswerStorage, AnswerStorage>();
builder.Services.AddTransient<IQuestionStorage, QuestionStorage>();
builder.Services.AddTransient<IUserStorage, UserStorage>();
builder.Services.AddTransient<ICategoryStorage, CategoryStorage>();
builder.Services.AddTransient<IAnswerLogic, AnswerLogic>();
builder.Services.AddTransient<IQuestionLogic, QuestionLogic>();
builder.Services.AddTransient<IUserLogic, UserLogic>();
builder.Services.AddTransient<ICategoryLogic, CategoryLogic>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "ForumRestApi",
Version = "v1"
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ForumRestApi v1"));
}
app.UseHttpsRedirection();
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:27698",
"sslPort": 44340
}
},
"profiles": {
"ForumRestApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7124;http://localhost:5124",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

49
ForumUserApp/APIClient.cs Normal file
View File

@ -0,0 +1,49 @@
using ForumContracts.ViewModels;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace ForumUserApp
{
public class APIClient
{
private static readonly HttpClient _client = new();
public static UserViewModel? User { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -0,0 +1,239 @@
using ForumContracts.BindingModels;
using ForumContracts.ViewModels;
using ForumUserApp.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using static System.Formats.Asn1.AsnWriter;
namespace ForumUserApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult CreateCategory()
{
return View();
}
[HttpPost]
public void CreateCategory(string name, string des)
{
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(des))
{
throw new Exception("Введите название");
}
if (string.IsNullOrEmpty(des))
{
throw new Exception("Введите описание");
}
APIClient.PostRequest("api/main/createcategory", new CategoryBindingModel
{
Name = name,
Description = des
});
Response.Redirect("Index");
}
public IActionResult CreateQuestion()
{
ViewBag.Categories = APIClient.GetRequest<List<CategoryViewModel>>("api/main/getcategorylist");
return View();
}
[HttpPost]
public void CreateQuestion(string questionDes, int categoryId)
{
if (string.IsNullOrEmpty(questionDes))
{
throw new Exception("Введите вопрос");
}
APIClient.PostRequest("api/main/createquestion", new QuestionBindingModel
{
UserId = APIClient.User.Id,
CategoryId=categoryId,
QuestionDes = questionDes,
CreateDate = DateTime.Now
});
Response.Redirect("Index");
}
[HttpPost]
public void DeleteQuestion(int questionId)
{
APIClient.PostRequest("api/main/deletequestion", new QuestionBindingModel
{
Id = questionId
});
Response.Redirect("Index");
}
[HttpPost]
public void DeleteAnswer(int answerId)
{
APIClient.PostRequest("api/main/deleteanswer", new AnswerBindingModel
{
Id = answerId
});
Response.Redirect("Index");
}
public IActionResult Index()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<CategoryViewModel>>($"api/main/getcategorylist"));
}
public IActionResult Questions(int categoryId)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<QuestionViewModel>>($"api/main/getquestionsbycategory?categoryId={categoryId}"));
}
public IActionResult UserQuestions()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<QuestionViewModel>>($"api/main/getquestionsbyuser?userId={APIClient.User.Id}"));
}
public IActionResult HardRequest(DateTime dateFrom,DateTime dateTo)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<QuestionViewModel>>($"api/main/hardrequest?dateFrom={dateFrom}&dateTo={dateTo}"));
}
public IActionResult CreateAnswer()
{
return View();
}
[HttpPost]
public void CreateAnswer(string answerDes, int questionId)
{
if (string.IsNullOrEmpty(answerDes))
{
throw new Exception("Введите ответ");
}
APIClient.PostRequest("api/main/createanswer", new AnswerBindingModel
{
UserId = APIClient.User.Id,
QuestionId = questionId,
AnswerDes = answerDes,
ResponseDate = DateTime.Now
});
Response.Redirect("Index");
}
public IActionResult Answers(int questionId)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<AnswerViewModel>>($"api/main/getanswersbyquestion?questionId={questionId}"));
}
[HttpGet]
public IActionResult Privacy()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.User);
}
[HttpPost]
public void Privacy(string login, string password, string nick)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(nick))
{
throw new Exception("Введите логин, пароль и никнейм");
}
APIClient.PostRequest("api/user/updatedata", new UserBindingModel
{
Id = APIClient.User.Id,
Nickname= nick,
Email = login,
Password = password
});
APIClient.User.Nickname = nick;
APIClient.User.Email = login;
APIClient.User.Password = password;
Response.Redirect("Index");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
APIClient.User = APIClient.GetRequest<UserViewModel>($"api/user/login?login={login}&password={password}");
if (APIClient.User == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string login, string password, string nick)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(nick))
{
throw new Exception("Введите логин, пароль и ник");
}
APIClient.PostRequest("api/user/register", new UserBindingModel
{
Nickname = nick,
Email = login,
Password = password
});
Response.Redirect("Enter");
return;
}
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ForumContracts\ForumContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,9 @@
namespace ForumUserApp.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}

30
ForumUserApp/Program.cs Normal file
View File

@ -0,0 +1,30 @@
using ForumUserApp;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

View File

@ -0,0 +1,28 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:24810",
"sslPort": 44336
}
},
"profiles": {
"ForumUserApp": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7110;http://localhost:5110",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,62 @@
@using ForumContracts.ViewModels
@model List<AnswerViewModel>
@{
ViewData["Title"] = "Answer Page";
}
<div class="text-center">
<p>
@if(Model.Count > 0){
<h1>@Model[0].QuestionText</h1>
<h5>@Model[0].QuestionCreateDate</h5>
}
</p>
<h1 class="display-4">Ответы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Дата ответа
</th>
<th>
Ответ
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.ResponseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.AnswerDes)
</td>
<td>
@if (APIClient.User.Id == item.UserId)
{
<form action="DeleteAnswer" method="post">
<input type="hidden" name="answerId" value="@item.Id"/>
<button type="submit" class="btn btn-danger">Удалить</button>
</form>
}</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,16 @@
@{
ViewData["Title"] = "CreateAnswer";
}
<div class="text-center">
<h2 class="display-4">Создание ответа</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Ответ:</div>
<div class="col-8"><input type="text" name="answerDes" id="answerDes" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Создать" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,20 @@
@{
ViewData["Title"] = "CreateCategory";
}
<div class="text-center">
<h2 class="display-4">Создание категории</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Название:</div>
<div class="col-8"><input type="text" name="name" id="name" /></div>
</div>
<div class="row">
<div class="col-4">Описание:</div>
<div class="col-8"><input type="text" id="des" name="des" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Создать" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,22 @@
@{
ViewData["Title"] = "CreateQuestion";
}
<div class="text-center">
<h2 class="display-4">Создание вопроса</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Выберите категорию вопроса:</div>
<div class="col-8">
<select id="categoryId" name="categoryId" class="form-control" asp-items="@(new SelectList(@ViewBag.Categories,"Id", "Name"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Содержание вопроса:</div>
<div class="col-8"><input type="text" name="questionDes" id="questionDes" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Создать" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,21 @@
@{
ViewData["Title"] = "Enter";
}
<div class="text-center">
<h2 class="display-4">Добро пожаловать на форум!</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Вход" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,69 @@
@using ForumContracts.ViewModels
@model List<QuestionViewModel>
@{
ViewData["Title"] = "HardRequest Page";
}
<div class="text-center">
<h1 class="display-4">Выборка вопросов</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<form method="post">
<div class="row">
<div class="col-4">С:</div>
<div class="col-8"><input type="date" name="dateFrom" /></div>
</div>
<div class="row">
<div class="col-4">По:</div>
<div class="col-8"><input type="date" name="dateTo" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Показать" class="btn btn-primary" /></div>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
Дата создания
</th>
<th>
Категория вопроса
</th>
<th>
Вопрос
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CreateDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.CategoryName)
</td>
<td>
@Html.DisplayFor(modelItem => item.QuestionDes)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,59 @@
@using ForumContracts.ViewModels
@model List<CategoryViewModel>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Главная страница</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a asp-action="CreateCategory">Создать категорию</a>
<a asp-action="CreateQuestion">Задать вопрос</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Имя категории
</th>
<th>
Описание категории
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<form asp-action="Questions" method="post">
<input type="hidden" name="categoryId" value="@item.Id"/>
<button type="submit" class="btn btn-primary">Выбрать</button>
</form>
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,28 @@
@using ForumContracts.ViewModels
@model UserViewModel
@{
ViewData["Title"] = "Privacy Policy";
}
<div class="text-center">
<h2 class="display-4">Личные данные</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" value="@Model.Email"/></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" value="@Model.Password"/></div>
</div>
<div class="row">
<div class="col-4">Ник:</div>
<div class="col-8"><input type="text" name="nick" value="@Model.Nickname"/></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Сохранить" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,75 @@
@using ForumContracts.ViewModels
@model List<QuestionViewModel>
@{
ViewData["Title"] = "Question Page";
}
<div class="text-center">
<h1 class="display-4">Вопросы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Дата создания
</th>
<th>
Вопрос
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CreateDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.QuestionDes)
</td>
<td>
<div class="container">
<div class="row">
<div class="col">
<form asp-action="CreateAnswer" method="get">
<input type="hidden" name="questionId" value="@item.Id" />
<button type="submit" class="btn btn-success">Ответить</button>
</form>
</div>
<div class="col">
<form action="Answers" method="post">
<input type="hidden" name="questionId" value="@item.Id"/>
<button type="submit" class="btn btn-primary">Выбрать</button>
</form>
</div>
<div class="col">
@if (APIClient.User.Id == item.UserId)
{
<form action="DeleteQuestion" method="post">
<input type="hidden" name="questionId" value="@item.Id"/>
<button type="submit" class="btn btn-danger">Удалить</button>
</form>
}
</div>
</div>
</div>
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,25 @@
@{
ViewData["Title"] = "Register";
}
<div class="text-center">
<h2 class="display-4">Регистрация</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-4">Ник:</div>
<div class="col-8"><input type="text" name="nick" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Регистрация" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,75 @@
@using ForumContracts.ViewModels
@model List<QuestionViewModel>
@{
ViewData["Title"] = "UserQuestions Page";
}
<div class="text-center">
<h1 class="display-4">Мои вопросы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Дата создания
</th>
<th>
Вопрос
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CreateDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.QuestionDes)
</td>
<td>
<div class="container">
<div class="row">
<div class="col">
<form asp-action="CreateAnswer" method="get">
<input type="hidden" name="questionId" value="@item.Id" />
<button type="submit" class="btn btn-success">Ответить</button>
</form>
</div>
<div class="col">
<form action="Answers" method="post">
<input type="hidden" name="questionId" value="@item.Id"/>
<button type="submit" class="btn btn-primary">Выбрать</button>
</form>
</div>
<div class="col">
@if (APIClient.User.Id == item.UserId)
{
<form action="DeleteQuestion" method="post">
<input type="hidden" name="questionId" value="@item.Id"/>
<button type="submit" class="btn btn-danger">Удалить</button>
</form>
}
</div>
</div>
</div>
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

View File

@ -0,0 +1,65 @@

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - ForumUserApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/ForumUserApp.styles.css" asp-append-version="true" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Форум</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Главная страница</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="CreateQuestion">Задать вопрос</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="UserQuestions">Мои вопросы</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="HardRequest">Выборка вопросов</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2023 - ForumUserApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@ -0,0 +1,49 @@
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
a {
color: #0077cc;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px;
}

View File

@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

View File

@ -0,0 +1,3 @@
@using ForumUserApp
@using ForumUserApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@ -0,0 +1,9 @@
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"IPAddress": "http://localhost:5124/"
}

View File

@ -0,0 +1,18 @@
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

View File

@ -0,0 +1,4 @@
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.

View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2011-2021 Twitter, Inc.
Copyright (c) 2011-2021 The Bootstrap Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More