From 1cbc3e4c44b412c512fbad8ae07f6661e6dbfe78 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 5 Oct 2018 09:43:16 +0300 Subject: [PATCH 01/22] not ready --- FifthLesson/readme.md | 2 +- FirstLesson/readme.md | 2 +- ForthLesson/readme.md | 2 +- SecondLesson/readme.md | 2 +- SixthLesson/readme.md | 2 +- ThirdLesson/readme.md | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/FifthLesson/readme.md b/FifthLesson/readme.md index 1db0aa3..89916d2 100644 --- a/FifthLesson/readme.md +++ b/FifthLesson/readme.md @@ -1 +1 @@ -Fifth lesson of Margelov Vitaly \ No newline at end of file +Fifth lesson of Kuznetsova Tatiana \ No newline at end of file diff --git a/FirstLesson/readme.md b/FirstLesson/readme.md index d135227..e7ef770 100644 --- a/FirstLesson/readme.md +++ b/FirstLesson/readme.md @@ -1 +1 @@ -First lesson of Margelov Vitaly \ No newline at end of file +First lesson of Kuznetsova Tatiana \ No newline at end of file diff --git a/ForthLesson/readme.md b/ForthLesson/readme.md index 4681cff..d9bf578 100644 --- a/ForthLesson/readme.md +++ b/ForthLesson/readme.md @@ -1 +1 @@ -Forth lesson of Margelov Vitaly \ No newline at end of file +Forth lesson of Kuznetsova Tatiana \ No newline at end of file diff --git a/SecondLesson/readme.md b/SecondLesson/readme.md index c420268..08d2a4a 100644 --- a/SecondLesson/readme.md +++ b/SecondLesson/readme.md @@ -1 +1 @@ -Second lesson of Margelov Vitaly \ No newline at end of file +Second lesson of Kuznetsova Tatiana \ No newline at end of file diff --git a/SixthLesson/readme.md b/SixthLesson/readme.md index dd112f1..181322d 100644 --- a/SixthLesson/readme.md +++ b/SixthLesson/readme.md @@ -1 +1 @@ -Sixth lesson of Margelov Vitaly \ No newline at end of file +Sixth lesson of Kuznetsova Tatiana \ No newline at end of file diff --git a/ThirdLesson/readme.md b/ThirdLesson/readme.md index 681ccfd..c29839c 100644 --- a/ThirdLesson/readme.md +++ b/ThirdLesson/readme.md @@ -1 +1 @@ -Third lesson of Margelov Vitaly \ No newline at end of file +Third lesson of Kuznetsova Tatiana \ No newline at end of file From 8e61ae09a1e10a9d72bc158106d4c03f226dda40 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 5 Oct 2018 09:54:50 +0300 Subject: [PATCH 02/22] not ready --- FirstLesson/ConsoleApp16/ConsoleApp16.sln | 25 ++ .../ConsoleApp16/ConsoleApp16/App.config | 6 + .../ConsoleApp16/ConsoleApp16/Class1.cs | 34 +++ .../ConsoleApp16/ConsoleApp16.csproj | 54 ++++ .../ConsoleApp16/ConsoleApp16/Program.cs | 68 +++++ .../ConsoleApp16/Properties/AssemblyInfo.cs | 36 +++ FirstLesson/ConsoleApp17/.gitattributes | 63 +++++ FirstLesson/ConsoleApp17/.gitignore | 261 ++++++++++++++++++ FirstLesson/ConsoleApp17/ConsoleApp17.sln | 25 ++ .../ConsoleApp17/ConsoleApp17/App.config | 6 + .../ConsoleApp17/ConsoleApp17/Class1.cs | 20 ++ .../ConsoleApp17/ConsoleApp17.csproj | 57 ++++ .../ConsoleApp17/ConsoleApp17/Program.cs | 70 +++++ .../ConsoleApp17/Properties/AssemblyInfo.cs | 36 +++ .../ConsoleApp17/ConsoleApp17/text.txt | 6 + 15 files changed, 767 insertions(+) create mode 100644 FirstLesson/ConsoleApp16/ConsoleApp16.sln create mode 100644 FirstLesson/ConsoleApp16/ConsoleApp16/App.config create mode 100644 FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs create mode 100644 FirstLesson/ConsoleApp16/ConsoleApp16/ConsoleApp16.csproj create mode 100644 FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs create mode 100644 FirstLesson/ConsoleApp16/ConsoleApp16/Properties/AssemblyInfo.cs create mode 100644 FirstLesson/ConsoleApp17/.gitattributes create mode 100644 FirstLesson/ConsoleApp17/.gitignore create mode 100644 FirstLesson/ConsoleApp17/ConsoleApp17.sln create mode 100644 FirstLesson/ConsoleApp17/ConsoleApp17/App.config create mode 100644 FirstLesson/ConsoleApp17/ConsoleApp17/Class1.cs create mode 100644 FirstLesson/ConsoleApp17/ConsoleApp17/ConsoleApp17.csproj create mode 100644 FirstLesson/ConsoleApp17/ConsoleApp17/Program.cs create mode 100644 FirstLesson/ConsoleApp17/ConsoleApp17/Properties/AssemblyInfo.cs create mode 100644 FirstLesson/ConsoleApp17/ConsoleApp17/text.txt diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16.sln b/FirstLesson/ConsoleApp16/ConsoleApp16.sln new file mode 100644 index 0000000..ed1935f --- /dev/null +++ b/FirstLesson/ConsoleApp16/ConsoleApp16.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2036 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp16", "ConsoleApp16\ConsoleApp16.csproj", "{98F93A01-4F0F-477D-8D1E-A01381617D75}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {98F93A01-4F0F-477D-8D1E-A01381617D75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {98F93A01-4F0F-477D-8D1E-A01381617D75}.Debug|Any CPU.Build.0 = Debug|Any CPU + {98F93A01-4F0F-477D-8D1E-A01381617D75}.Release|Any CPU.ActiveCfg = Release|Any CPU + {98F93A01-4F0F-477D-8D1E-A01381617D75}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F99AE804-D6B4-4029-B20C-45E21DD9DCA3} + EndGlobalSection +EndGlobal diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/App.config b/FirstLesson/ConsoleApp16/ConsoleApp16/App.config new file mode 100644 index 0000000..731f6de --- /dev/null +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs b/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs new file mode 100644 index 0000000..694da0b --- /dev/null +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConsoleApp16 +{ + class Student + { + string time; + public string fio; + public int course; + string institut; + public bool dorm; + public Student(string time, string fio, int course, string institut, bool dorm) + { + this.time = time; + this.fio = fio; + this.course = course; + this.institut = institut; + this.dorm = dorm; + } + public Student(string time, string fio, string course, string institut, string dorm) + { + this.time = time; + this.fio = fio; + this.course = (int)course[0]; + this.institut = institut; + this.dorm = dorm.Equals("Да"); ; + + } + } +} diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/ConsoleApp16.csproj b/FirstLesson/ConsoleApp16/ConsoleApp16/ConsoleApp16.csproj new file mode 100644 index 0000000..0a2c880 --- /dev/null +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/ConsoleApp16.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {98F93A01-4F0F-477D-8D1E-A01381617D75} + Exe + ConsoleApp16 + ConsoleApp16 + v4.6.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs b/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs new file mode 100644 index 0000000..7c621b0 --- /dev/null +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConsoleApp16 +{ + class Program + { + static void Main(string[] args) + { + string s = Console.ReadLine(); + string func=Console.ReadLine(); + string[] lines = File.ReadAllLines(s, System.Text.Encoding.Default); + string[] b; + List ab = new List(); + foreach(string a in lines) + { + b = a.Split(';'); + ab.Add(new Student(b[0], b[1], b[2], b[3], b[4])); + } + ab.RemoveAt(0); + switch (func) + { + case "count": + count(ab); + break; + case "dorm": + dorm(ab); + break; + case "course": + course(ab); + break; + } + + + } + + private static int count(List ab) + { + return ab.Count(); + } + + private static void dorm(List ab) + { + List q = new List(); + foreach (Student a in ab) + { + if(a.dorm) + { + q.Add(a.fio); + } + + } + } + + private static void course(List ab) + { + int[] c = new int[] { 0,0,0,0}; + foreach (Student a in ab) + { + c[a.course - 1]++; + } + } + } +} diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/Properties/AssemblyInfo.cs b/FirstLesson/ConsoleApp16/ConsoleApp16/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c5b26e3 --- /dev/null +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Общие сведения об этой сборке предоставляются следующим набором +// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, +// связанные со сборкой. +[assembly: AssemblyTitle("ConsoleApp16")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ConsoleApp16")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми +// для компонентов COM. Если необходимо обратиться к типу в этой сборке через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(false)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("98f93a01-4f0f-477d-8d1e-a01381617d75")] + +// Сведения о версии сборки состоят из следующих четырех значений: +// +// Основной номер версии +// Дополнительный номер версии +// Номер сборки +// Редакция +// +// Можно задать все значения или принять номер сборки и номер редакции по умолчанию. +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/FirstLesson/ConsoleApp17/.gitattributes b/FirstLesson/ConsoleApp17/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/FirstLesson/ConsoleApp17/.gitattributes @@ -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 diff --git a/FirstLesson/ConsoleApp17/.gitignore b/FirstLesson/ConsoleApp17/.gitignore new file mode 100644 index 0000000..3c4efe2 --- /dev/null +++ b/FirstLesson/ConsoleApp17/.gitignore @@ -0,0 +1,261 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +#*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc \ No newline at end of file diff --git a/FirstLesson/ConsoleApp17/ConsoleApp17.sln b/FirstLesson/ConsoleApp17/ConsoleApp17.sln new file mode 100644 index 0000000..f8fcc87 --- /dev/null +++ b/FirstLesson/ConsoleApp17/ConsoleApp17.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2036 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp17", "ConsoleApp17\ConsoleApp17.csproj", "{F2541835-6D26-4BC0-99DE-ECDF4ECE209B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F2541835-6D26-4BC0-99DE-ECDF4ECE209B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F2541835-6D26-4BC0-99DE-ECDF4ECE209B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F2541835-6D26-4BC0-99DE-ECDF4ECE209B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F2541835-6D26-4BC0-99DE-ECDF4ECE209B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {68BBE75E-1DDD-4F20-A9C2-B520871AC971} + EndGlobalSection +EndGlobal diff --git a/FirstLesson/ConsoleApp17/ConsoleApp17/App.config b/FirstLesson/ConsoleApp17/ConsoleApp17/App.config new file mode 100644 index 0000000..731f6de --- /dev/null +++ b/FirstLesson/ConsoleApp17/ConsoleApp17/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/FirstLesson/ConsoleApp17/ConsoleApp17/Class1.cs b/FirstLesson/ConsoleApp17/ConsoleApp17/Class1.cs new file mode 100644 index 0000000..13d3983 --- /dev/null +++ b/FirstLesson/ConsoleApp17/ConsoleApp17/Class1.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConsoleApp17 +{ + class Competition + { + public string name; + public List list; + public Competition(string name, List list) + { + this.name = name; + this.list = list; + + } + } +} diff --git a/FirstLesson/ConsoleApp17/ConsoleApp17/ConsoleApp17.csproj b/FirstLesson/ConsoleApp17/ConsoleApp17/ConsoleApp17.csproj new file mode 100644 index 0000000..bd0400f --- /dev/null +++ b/FirstLesson/ConsoleApp17/ConsoleApp17/ConsoleApp17.csproj @@ -0,0 +1,57 @@ + + + + + Debug + AnyCPU + {F2541835-6D26-4BC0-99DE-ECDF4ECE209B} + Exe + ConsoleApp17 + ConsoleApp17 + v4.6.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FirstLesson/ConsoleApp17/ConsoleApp17/Program.cs b/FirstLesson/ConsoleApp17/ConsoleApp17/Program.cs new file mode 100644 index 0000000..1457cf6 --- /dev/null +++ b/FirstLesson/ConsoleApp17/ConsoleApp17/Program.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace ConsoleApp17 +{ + class Program + { + static void Main(string[] args) + { + List t=new List(); + A: + string fun = Console.ReadLine(); + string name = Console.ReadLine(); + string second_atr = Console.ReadLine(); + + Competition test; + switch (fun) + { + case "create": + t.Add(create(name, second_atr)); + File.Create(name+".txt"); + + goto A; + + case "winner": + test = findtour(name, t); + test.list.RemoveAt(test.list.IndexOf(second_atr)); + goto A; + default: + break; + + + } + + } + + private static Competition findtour(string name, List t) + { + + foreach (Competition a in t) + { + if (a.name.Equals(name)) + { + return a; + } + + } + return null; + } + + + private static Competition create(string name, string fileway) + { + List list = Parse(fileway); + Competition c = new Competition(name, list); + return c; + + } + + private static List Parse(string fileway) + { + List a = File.ReadAllLines(fileway).ToList(); + return a; + } + + + } +} diff --git a/FirstLesson/ConsoleApp17/ConsoleApp17/Properties/AssemblyInfo.cs b/FirstLesson/ConsoleApp17/ConsoleApp17/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..6989a91 --- /dev/null +++ b/FirstLesson/ConsoleApp17/ConsoleApp17/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Общие сведения об этой сборке предоставляются следующим набором +// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, +// связанные со сборкой. +[assembly: AssemblyTitle("ConsoleApp17")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ConsoleApp17")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми +// для компонентов COM. Если необходимо обратиться к типу в этой сборке через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(false)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("f2541835-6d26-4bc0-99de-ecdf4ece209b")] + +// Сведения о версии сборки состоят из следующих четырех значений: +// +// Основной номер версии +// Дополнительный номер версии +// Номер сборки +// Редакция +// +// Можно задать все значения или принять номер сборки и номер редакции по умолчанию. +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/FirstLesson/ConsoleApp17/ConsoleApp17/text.txt b/FirstLesson/ConsoleApp17/ConsoleApp17/text.txt new file mode 100644 index 0000000..fa10b15 --- /dev/null +++ b/FirstLesson/ConsoleApp17/ConsoleApp17/text.txt @@ -0,0 +1,6 @@ +Horvatia +Russia +Spain +Italy +USA +Canada \ No newline at end of file From 22deea6b9cede7e98f4a6f130cf852e1e6dfe134 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 5 Oct 2018 11:30:39 +0300 Subject: [PATCH 03/22] close code --- .../ConsoleApp16/ConsoleApp16/Class1.cs | 23 +++-- .../ConsoleApp16/ConsoleApp16/Program.cs | 84 ++++++++++++++----- 2 files changed, 81 insertions(+), 26 deletions(-) diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs b/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs index 694da0b..7df3da2 100644 --- a/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs @@ -7,12 +7,25 @@ namespace ConsoleApp16 { class Student - { + { string time; - public string fio; - public int course; + string fio; + int course; string institut; - public bool dorm; + bool dorm; + public string FIO + { + get {return fio; } + } + public int Course + { + get { return course; } + } + public bool Dorm + { + get { return dorm; } + } + public Student(string time, string fio, int course, string institut, bool dorm) { this.time = time; @@ -25,7 +38,7 @@ public Student(string time, string fio, string course, string institut, string d { this.time = time; this.fio = fio; - this.course = (int)course[0]; + this.course = course[0] - '0'; this.institut = institut; this.dorm = dorm.Equals("Да"); ; diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs b/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs index 7c621b0..67af08c 100644 --- a/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs @@ -2,8 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; + namespace ConsoleApp16 { @@ -11,31 +10,72 @@ class Program { static void Main(string[] args) { - string s = Console.ReadLine(); - string func=Console.ReadLine(); - string[] lines = File.ReadAllLines(s, System.Text.Encoding.Default); - string[] b; - List ab = new List(); - foreach(string a in lines) + string func=args[0]; + string file_path = args[1]; + + if (!File.Exists(file_path)) { - b = a.Split(';'); - ab.Add(new Student(b[0], b[1], b[2], b[3], b[4])); + Print("ERROR"); + return; } - ab.RemoveAt(0); - switch (func) + + string[] data = File.ReadAllLines(file_path, System.Text.Encoding.Default); + + List abitur = CreateList(data); + + if (abitur.Count > 0) + {abitur.RemoveAt(0);} + switch (args[0]) { case "count": - count(ab); + Print(count(abitur)); break; case "dorm": - dorm(ab); + PrintList(dorm(abitur)); break; case "course": - course(ab); + PrintArray(course(abitur)); break; + default: + Print("ERROR"); + return; + } + Console.ReadKey(); + + + } + + private static List CreateList(string[] data) + { + List abitur = new List(); + string[] b; + foreach (string a in data) + { + b = a.Split(';'); + abitur.Add(new Student(b[0], b[1], b[2], b[3], b[4])); + } + return abitur; + } + + private static void PrintArray(int[] v) + { + for(int i=0;i list) + { + foreach (string a in list) + { + Console.WriteLine(a); + } + } + private static void Print(object obj) + { + Console.WriteLine(obj.ToString()); } private static int count(List ab) @@ -43,26 +83,28 @@ private static int count(List ab) return ab.Count(); } - private static void dorm(List ab) + private static List dorm(List ab) { List q = new List(); foreach (Student a in ab) { - if(a.dorm) + if(a.Dorm) { - q.Add(a.fio); + q.Add(a.FIO); } } + return q; } - private static void course(List ab) + private static int[] course(List ab) { - int[] c = new int[] { 0,0,0,0}; + int[] c = new int[] {0,0,0,0}; foreach (Student a in ab) { - c[a.course - 1]++; + c[a.Course - 1]++; } + return c; } } } From d7d79ab2aa5d1109be601d67d1d0cfb1a1fcc285 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 5 Oct 2018 15:40:27 +0300 Subject: [PATCH 04/22] beggining of the UnitTests --- FirstLesson/ConsoleApp16/ConsoleApp16.sln | 6 ++ .../ConsoleApp16/ConsoleApp16/Class1.cs | 2 +- .../ConsoleApp16/ConsoleApp16/Program.cs | 49 ++++++++---- .../Properties/AssemblyInfo.cs | 20 +++++ .../ConsoleApp16/UnitTestAbitura/UnitTest1.cs | 20 +++++ .../UnitTestAbitura/UnitTestAbitura.csproj | 74 +++++++++++++++++++ .../UnitTestAbitura/packages.config | 5 ++ 7 files changed, 159 insertions(+), 17 deletions(-) create mode 100644 FirstLesson/ConsoleApp16/UnitTestAbitura/Properties/AssemblyInfo.cs create mode 100644 FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs create mode 100644 FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTestAbitura.csproj create mode 100644 FirstLesson/ConsoleApp16/UnitTestAbitura/packages.config diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16.sln b/FirstLesson/ConsoleApp16/ConsoleApp16.sln index ed1935f..e8af7b6 100644 --- a/FirstLesson/ConsoleApp16/ConsoleApp16.sln +++ b/FirstLesson/ConsoleApp16/ConsoleApp16.sln @@ -5,6 +5,8 @@ VisualStudioVersion = 15.0.28010.2036 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp16", "ConsoleApp16\ConsoleApp16.csproj", "{98F93A01-4F0F-477D-8D1E-A01381617D75}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTestAbitura", "UnitTestAbitura\UnitTestAbitura.csproj", "{2B8DA9A3-CD1A-45F3-9D65-B3E279D48FA6}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +17,10 @@ Global {98F93A01-4F0F-477D-8D1E-A01381617D75}.Debug|Any CPU.Build.0 = Debug|Any CPU {98F93A01-4F0F-477D-8D1E-A01381617D75}.Release|Any CPU.ActiveCfg = Release|Any CPU {98F93A01-4F0F-477D-8D1E-A01381617D75}.Release|Any CPU.Build.0 = Release|Any CPU + {2B8DA9A3-CD1A-45F3-9D65-B3E279D48FA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2B8DA9A3-CD1A-45F3-9D65-B3E279D48FA6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2B8DA9A3-CD1A-45F3-9D65-B3E279D48FA6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2B8DA9A3-CD1A-45F3-9D65-B3E279D48FA6}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs b/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs index 7df3da2..3557ce2 100644 --- a/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs @@ -34,7 +34,7 @@ public Student(string time, string fio, int course, string institut, bool dorm) this.institut = institut; this.dorm = dorm; } - public Student(string time, string fio, string course, string institut, string dorm) + public Student(string time, string fio, string course, string institut, string dorm)//тест сюда { this.time = time; this.fio = fio; diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs b/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs index 67af08c..b56724b 100644 --- a/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs @@ -6,26 +6,25 @@ namespace ConsoleApp16 { - class Program + public class Program { static void Main(string[] args) { string func=args[0]; string file_path = args[1]; - - if (!File.Exists(file_path)) + + if (!isOkay(file_path)) { - Print("ERROR"); - return; - } + return; } string[] data = File.ReadAllLines(file_path, System.Text.Encoding.Default); - List abitur = CreateList(data); + if (abitur.Count > 0) - {abitur.RemoveAt(0);} - switch (args[0]) + { abitur.RemoveAt(0);} + + switch (args[0])//4 теста сюда { case "count": Print(count(abitur)); @@ -45,7 +44,25 @@ static void Main(string[] args) } - private static List CreateList(string[] data) + private static bool isOkay(string file_path)//тест сюда + { + return File.Exists(file_path) && CorrectExtention(file_path); + + } + + private static bool CorrectExtention(string file_path)//тест сюда + { + string exp = "csv"; + return exp.Equals(getFileExtension(file_path)); + } + + public static string getFileExtension(string fileName)//тест сюда + { + return fileName.Substring(fileName.LastIndexOf(".") + 1); + } + + + private static List CreateList(string[] data)//тест сюда { List abitur = new List(); string[] b; @@ -57,7 +74,7 @@ private static List CreateList(string[] data) return abitur; } - private static void PrintArray(int[] v) + private static void PrintArray(int[] v)//тест сюда { for(int i=0;i list) + private static void PrintList(List list)//тест сюда { foreach (string a in list) { @@ -73,17 +90,17 @@ private static void PrintList(List list) } } - private static void Print(object obj) + private static void Print(object obj)//тест сюда { Console.WriteLine(obj.ToString()); } - private static int count(List ab) + private static int count(List ab)//тест сюда { return ab.Count(); } - private static List dorm(List ab) + private static List dorm(List ab)//тест сюда { List q = new List(); foreach (Student a in ab) @@ -97,7 +114,7 @@ private static List dorm(List ab) return q; } - private static int[] course(List ab) + private static int[] course(List ab)//тест сюда { int[] c = new int[] {0,0,0,0}; foreach (Student a in ab) diff --git a/FirstLesson/ConsoleApp16/UnitTestAbitura/Properties/AssemblyInfo.cs b/FirstLesson/ConsoleApp16/UnitTestAbitura/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0eabbd5 --- /dev/null +++ b/FirstLesson/ConsoleApp16/UnitTestAbitura/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("UnitTestAbitura")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("UnitTestAbitura")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: ComVisible(false)] + +[assembly: Guid("2b8da9a3-cd1a-45f3-9d65-b3e279d48fa6")] + +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs b/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs new file mode 100644 index 0000000..89b8f3b --- /dev/null +++ b/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs @@ -0,0 +1,20 @@ +using System; +using System.IO; +using Microsoft.VisualStudio.TestTools.UnitTesting; + + +namespace UnitTestAbitura +{ + [TestClass] + public class UnitTest1 + { + [TestMethod] + public void FilePathThatExist_true() + { + File.Create("test.txt"); + + Assert.IsTrue(Program.isOkay("test.txt")); + + } + } +} diff --git a/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTestAbitura.csproj b/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTestAbitura.csproj new file mode 100644 index 0000000..027b232 --- /dev/null +++ b/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTestAbitura.csproj @@ -0,0 +1,74 @@ + + + + + + Debug + AnyCPU + {2B8DA9A3-CD1A-45F3-9D65-B3E279D48FA6} + Library + Properties + UnitTestAbitura + UnitTestAbitura + v4.6.1 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 15.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages + False + UnitTest + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll + + + ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll + + + + + + + + + + + + + + {98f93a01-4f0f-477d-8d1e-a01381617d75} + ConsoleApp16 + + + + + + + Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}. + + + + + + \ No newline at end of file diff --git a/FirstLesson/ConsoleApp16/UnitTestAbitura/packages.config b/FirstLesson/ConsoleApp16/UnitTestAbitura/packages.config new file mode 100644 index 0000000..102a45c --- /dev/null +++ b/FirstLesson/ConsoleApp16/UnitTestAbitura/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file From a47010b3cba86c13945b5312dcf7259d8ac93e08 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 5 Oct 2018 17:17:39 +0300 Subject: [PATCH 05/22] few UnitTests --- .../ConsoleApp16/ConsoleApp16/Class1.cs | 2 +- .../ConsoleApp16/ConsoleApp16/Program.cs | 22 ++--- .../ConsoleApp16/UnitTestAbitura/UnitTest1.cs | 89 ++++++++++++++++++- 3 files changed, 97 insertions(+), 16 deletions(-) diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs b/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs index 3557ce2..174c7e0 100644 --- a/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/Class1.cs @@ -6,7 +6,7 @@ namespace ConsoleApp16 { - class Student + public class Student { string time; string fio; diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs b/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs index b56724b..839c7d0 100644 --- a/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs @@ -8,7 +8,7 @@ namespace ConsoleApp16 { public class Program { - static void Main(string[] args) + public static void Main(string[] args) { string func=args[0]; string file_path = args[1]; @@ -44,13 +44,13 @@ static void Main(string[] args) } - private static bool isOkay(string file_path)//тест сюда + public static bool isOkay(string file_path)//тест сюда { return File.Exists(file_path) && CorrectExtention(file_path); } - private static bool CorrectExtention(string file_path)//тест сюда + public static bool CorrectExtention(string file_path)//тест сюда { string exp = "csv"; return exp.Equals(getFileExtension(file_path)); @@ -62,7 +62,7 @@ public static string getFileExtension(string fileName)//тест сюда } - private static List CreateList(string[] data)//тест сюда + public static List CreateList(string[] data)//тест сюда { List abitur = new List(); string[] b; @@ -74,7 +74,7 @@ private static List CreateList(string[] data)//тест сюда return abitur; } - private static void PrintArray(int[] v)//тест сюда + public static void PrintArray(int[] v)//тест сюда { for(int i=0;i list)//тест сюда + public static void PrintList(List list)//тест сюда { foreach (string a in list) { @@ -90,19 +90,19 @@ private static void PrintList(List list)//тест сюда } } - private static void Print(object obj)//тест сюда + public static void Print(object obj)//тест сюда { Console.WriteLine(obj.ToString()); } - private static int count(List ab)//тест сюда + public static int count(List ab)//тест сюда { return ab.Count(); } - private static List dorm(List ab)//тест сюда + public static List dorm(List ab)//тест сюда { - List q = new List(); + List q = new List(); foreach (Student a in ab) { if(a.Dorm) @@ -114,7 +114,7 @@ private static List dorm(List ab)//тест сюда return q; } - private static int[] course(List ab)//тест сюда + public static int[] course(List ab)//тест сюда { int[] c = new int[] {0,0,0,0}; foreach (Student a in ab) diff --git a/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs b/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs index 89b8f3b..450d5e1 100644 --- a/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs +++ b/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs @@ -1,20 +1,101 @@ using System; +using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace UnitTestAbitura +namespace ConsoleApp16 { [TestClass] public class UnitTest1 { [TestMethod] - public void FilePathThatExist_true() + public void FileRightExtention_false() { - File.Create("test.txt"); + //arrange + var file_path = "test.txt";//не должен пройти + File.Create(file_path); + + //act + var res = Program.CorrectExtention(file_path); + //assert + Assert.IsFalse(res); + - Assert.IsTrue(Program.isOkay("test.txt")); } + [TestMethod] + public void FilePathThatExist_false() + { + //arrange + var file_path = "test.txt"; + + //act + var res = Program.isOkay(file_path); + //assert + Assert.IsFalse(res); + + + } + + [TestMethod] + public void GetFileExtention_PointAndCSV() + { + //arrange + var file_path = "test.txt.csv"; + + //act + var res = Program.getFileExtension(file_path); + //assert + Assert.AreEqual(res, "csv"); + + } + [TestMethod] + public void GetCountOfList_IntCount() + { + //arrange + List list = new List() { new Student("9", "Sasha", 1, "ITASY", true) }; + var Rcount = 1; + //act + var res = Program.count(list); + //assert + Assert.AreEqual(res, Rcount); + + } + [TestMethod] + public void GetListStudentsInDormitory_CorrectList() + { + //arrange + List list = new List() { new Student("9", "Sasha", 1, "ITASY", true), new Student("8", "Dasha", 2, "ITASY", false) }; + var Rname = "Sasha"; + //act + var res = Program.dorm(list); + //assert + Assert.AreEqual(res[0], Rname); + + } + [TestMethod] + public void GetStatisticOfStudentsCourse_ArrayWithЬStatistic() + { + //arrange + List list = new List() { new Student("9", "Sasha", 1, "ITASY", true), new Student("8", "Dasha", 2, "ITASY", false) }; + int[] Rarray = new int[] { 1, 1, 0, 0 }; + //act + var res = Program.course(list); + //assert + for(int i=0;i<4;i++) + { + Assert.AreEqual(res[i], Rarray[i]); + + } + + + } + + + + + + } } From 8f8949eade798c3db29cf3d05ea3a953d23ca6e8 Mon Sep 17 00:00:00 2001 From: LavanderSea <43253286+LavanderSea@users.noreply.github.com> Date: Fri, 5 Oct 2018 17:19:57 +0300 Subject: [PATCH 06/22] Update readme.md --- FirstLesson/readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/FirstLesson/readme.md b/FirstLesson/readme.md index e7ef770..dd44f2a 100644 --- a/FirstLesson/readme.md +++ b/FirstLesson/readme.md @@ -1 +1,3 @@ -First lesson of Kuznetsova Tatiana \ No newline at end of file +First lesson of Kuznetsova Tatiana +First task in first folder +Second task in second folder From 252a96e5d71b58aa0895396d39c05586f778ff4e Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 5 Oct 2018 17:49:32 +0300 Subject: [PATCH 07/22] Error update --- FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs b/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs index 839c7d0..65a777a 100644 --- a/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs +++ b/FirstLesson/ConsoleApp16/ConsoleApp16/Program.cs @@ -15,6 +15,7 @@ public static void Main(string[] args) if (!isOkay(file_path)) { + Print("Неверный путь к файлу или разрешение"); return; } string[] data = File.ReadAllLines(file_path, System.Text.Encoding.Default); @@ -36,7 +37,7 @@ public static void Main(string[] args) PrintArray(course(abitur)); break; default: - Print("ERROR"); + Print("Неверная функция"); return; } Console.ReadKey(); From 7f3a89a72992b1cb9b3abf1a2db9211019fb6427 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 5 Oct 2018 20:24:56 +0300 Subject: [PATCH 08/22] new tests --- .../ConsoleApp16/UnitTestAbitura/UnitTest1.cs | 30 ++++++++++++++++++- .../ConsoleApp17/ConsoleApp17/Program.cs | 14 ++++++--- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs b/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs index 450d5e1..f8dce33 100644 --- a/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs +++ b/FirstLesson/ConsoleApp16/UnitTestAbitura/UnitTest1.cs @@ -22,13 +22,41 @@ public void FileRightExtention_false() Assert.IsFalse(res); + } + [TestMethod] + public void FileRightExtention_true() + { + //arrange + var file_path = "test.csv";//должен пройти + File.Create(file_path); + + //act + var res = Program.CorrectExtention(file_path); + //assert + Assert.IsTrue(res); + } [TestMethod] public void FilePathThatExist_false() { //arrange - var file_path = "test.txt"; + var file_path = "test.txt"; + File.Create(file_path); + + + //act + var res = Program.isOkay(file_path); + //assert + Assert.IsFalse(res); + + + } + [TestMethod] + public void FilePathThatExist_екгу() + { + //arrange + var file_path = "test.txt"; //act var res = Program.isOkay(file_path); diff --git a/FirstLesson/ConsoleApp17/ConsoleApp17/Program.cs b/FirstLesson/ConsoleApp17/ConsoleApp17/Program.cs index 1457cf6..1975499 100644 --- a/FirstLesson/ConsoleApp17/ConsoleApp17/Program.cs +++ b/FirstLesson/ConsoleApp17/ConsoleApp17/Program.cs @@ -11,9 +11,9 @@ static void Main(string[] args) { List t=new List(); A: - string fun = Console.ReadLine(); - string name = Console.ReadLine(); - string second_atr = Console.ReadLine(); + string fun = args[0]; + string name = args[1]; + string second_atr = args[2]; Competition test; switch (fun) @@ -29,13 +29,19 @@ static void Main(string[] args) test.list.RemoveAt(test.list.IndexOf(second_atr)); goto A; default: - break; + Print("Enter correct atribute"); + goto A; } } + private static void Print(string v) + { + Console.WriteLine(v); + } + private static Competition findtour(string name, List t) { From 54911186217eb5426016a35f3064287ea278a933 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Tue, 9 Oct 2018 15:08:39 +0300 Subject: [PATCH 09/22] create necessary classes and methods: adding car in car park, rent car(without check), getting user history of rent) --- SecondLesson/CarRent/CarRent.sln | 25 ++++++++ SecondLesson/CarRent/CarRent/App.config | 6 ++ SecondLesson/CarRent/CarRent/Car.cs | 19 ++++++ SecondLesson/CarRent/CarRent/CarRent.cs | 18 ++++++ SecondLesson/CarRent/CarRent/CarRent.csproj | 58 +++++++++++++++++++ SecondLesson/CarRent/CarRent/Cars.cs | 16 +++++ SecondLesson/CarRent/CarRent/Program.cs | 15 +++++ .../CarRent/Properties/AssemblyInfo.cs | 36 ++++++++++++ SecondLesson/CarRent/CarRent/User.cs | 24 ++++++++ SecondLesson/CarRent/CarRent/UserRent.cs | 12 ++++ 10 files changed, 229 insertions(+) create mode 100644 SecondLesson/CarRent/CarRent.sln create mode 100644 SecondLesson/CarRent/CarRent/App.config create mode 100644 SecondLesson/CarRent/CarRent/Car.cs create mode 100644 SecondLesson/CarRent/CarRent/CarRent.cs create mode 100644 SecondLesson/CarRent/CarRent/CarRent.csproj create mode 100644 SecondLesson/CarRent/CarRent/Cars.cs create mode 100644 SecondLesson/CarRent/CarRent/Program.cs create mode 100644 SecondLesson/CarRent/CarRent/Properties/AssemblyInfo.cs create mode 100644 SecondLesson/CarRent/CarRent/User.cs create mode 100644 SecondLesson/CarRent/CarRent/UserRent.cs diff --git a/SecondLesson/CarRent/CarRent.sln b/SecondLesson/CarRent/CarRent.sln new file mode 100644 index 0000000..8e76391 --- /dev/null +++ b/SecondLesson/CarRent/CarRent.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2036 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CarRent", "CarRent\CarRent.csproj", "{02D4419C-B448-46C3-AD91-8EA37C3FEECF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {02D4419C-B448-46C3-AD91-8EA37C3FEECF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {02D4419C-B448-46C3-AD91-8EA37C3FEECF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {02D4419C-B448-46C3-AD91-8EA37C3FEECF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {02D4419C-B448-46C3-AD91-8EA37C3FEECF}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2E517628-A2D2-410C-9256-2CB4AE9BFA69} + EndGlobalSection +EndGlobal diff --git a/SecondLesson/CarRent/CarRent/App.config b/SecondLesson/CarRent/CarRent/App.config new file mode 100644 index 0000000..731f6de --- /dev/null +++ b/SecondLesson/CarRent/CarRent/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/SecondLesson/CarRent/CarRent/Car.cs b/SecondLesson/CarRent/CarRent/Car.cs new file mode 100644 index 0000000..8a2b567 --- /dev/null +++ b/SecondLesson/CarRent/CarRent/Car.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using System; + + +namespace CarRent +{ + class Car + { + List _tenants_list; + int _number; + + public void RentCar(User tenant, DateTimeOffset date_of_begining, DateTimeOffset date_of_ending ) + { + _tenants_list.Add(new CarRent(tenant._id, date_of_begining, date_of_ending)); + } + + + } +} diff --git a/SecondLesson/CarRent/CarRent/CarRent.cs b/SecondLesson/CarRent/CarRent/CarRent.cs new file mode 100644 index 0000000..28f8de6 --- /dev/null +++ b/SecondLesson/CarRent/CarRent/CarRent.cs @@ -0,0 +1,18 @@ +using System; + +namespace CarRent +{ + public class CarRent + { + Guid _tenant; + DateTimeOffset _date_of_begining; + DateTimeOffset _date_of_ending; + + public CarRent(Guid tenant, DateTimeOffset date_of_begining, DateTimeOffset date_of_ending) + { + _tenant = tenant; + _date_of_begining = date_of_begining; + _date_of_ending = date_of_ending; + } + } +} \ No newline at end of file diff --git a/SecondLesson/CarRent/CarRent/CarRent.csproj b/SecondLesson/CarRent/CarRent/CarRent.csproj new file mode 100644 index 0000000..b44a10c --- /dev/null +++ b/SecondLesson/CarRent/CarRent/CarRent.csproj @@ -0,0 +1,58 @@ + + + + + Debug + AnyCPU + {02D4419C-B448-46C3-AD91-8EA37C3FEECF} + Exe + CarRent + CarRent + v4.6.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SecondLesson/CarRent/CarRent/Cars.cs b/SecondLesson/CarRent/CarRent/Cars.cs new file mode 100644 index 0000000..3cff62d --- /dev/null +++ b/SecondLesson/CarRent/CarRent/Cars.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + + +namespace CarRent +{ + class Cars + { + public List _list { private set; get; } + + public void AddNewCarInCarPark(Car adding_car) + { + _list.Add(adding_car); + } + + } +} diff --git a/SecondLesson/CarRent/CarRent/Program.cs b/SecondLesson/CarRent/CarRent/Program.cs new file mode 100644 index 0000000..64761cb --- /dev/null +++ b/SecondLesson/CarRent/CarRent/Program.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarRent +{ + class Program + { + static void Main(string[] args) + { + } + } +} diff --git a/SecondLesson/CarRent/CarRent/Properties/AssemblyInfo.cs b/SecondLesson/CarRent/CarRent/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d400cd5 --- /dev/null +++ b/SecondLesson/CarRent/CarRent/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Общие сведения об этой сборке предоставляются следующим набором +// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, +// связанные со сборкой. +[assembly: AssemblyTitle("CarRent")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CarRent")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми +// для компонентов COM. Если необходимо обратиться к типу в этой сборке через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(false)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("02d4419c-b448-46c3-ad91-8ea37c3feecf")] + +// Сведения о версии сборки состоят из следующих четырех значений: +// +// Основной номер версии +// Дополнительный номер версии +// Номер сборки +// Редакция +// +// Можно задать все значения или принять номер сборки и номер редакции по умолчанию. +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SecondLesson/CarRent/CarRent/User.cs b/SecondLesson/CarRent/CarRent/User.cs new file mode 100644 index 0000000..96f4171 --- /dev/null +++ b/SecondLesson/CarRent/CarRent/User.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using System; + +namespace CarRent +{ + public class User + { + List _list_of_rental_cars; + string _first_name { get; } + string _second_name; + public Guid _id; + + public User(List list_of_rental_cars, string first_name, string second_name) + { + _list_of_rental_cars = list_of_rental_cars; + _first_name = first_name; + _second_name = second_name; + } + public List GetRentalHistory() + { + return _list_of_rental_cars; + } + } +} \ No newline at end of file diff --git a/SecondLesson/CarRent/CarRent/UserRent.cs b/SecondLesson/CarRent/CarRent/UserRent.cs new file mode 100644 index 0000000..ce07f59 --- /dev/null +++ b/SecondLesson/CarRent/CarRent/UserRent.cs @@ -0,0 +1,12 @@ +using System; + +namespace CarRent +{ + public class UserRent + { + Car _rental_car; + DateTimeOffset _date_of_begining; + DateTimeOffset _date_of_ending; + + } +} \ No newline at end of file From b5b545a8a342b0469eb697b530ffeb2d2e9e20d6 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 12 Oct 2018 19:40:07 +0300 Subject: [PATCH 10/22] adding UnitTests, adding scenary maintanance, united UserRent and CarRent, rename Cars -> Car_park --- SecondLesson/CarRent/CarRent.sln | 6 + SecondLesson/CarRent/CarRent/Car.cs | 17 +- SecondLesson/CarRent/CarRent/CarRent.cs | 18 -- SecondLesson/CarRent/CarRent/CarRent.csproj | 5 +- SecondLesson/CarRent/CarRent/Cars.cs | 144 ++++++++++++++- SecondLesson/CarRent/CarRent/IRepository.cs | 15 ++ SecondLesson/CarRent/CarRent/Maintenance.cs | 18 ++ SecondLesson/CarRent/CarRent/Program.cs | 8 +- SecondLesson/CarRent/CarRent/Rent.cs | 24 +++ SecondLesson/CarRent/CarRent/User.cs | 12 +- SecondLesson/CarRent/CarRent/UserRent.cs | 12 -- .../CarRentUnitTests/CarRentUnitTests.csproj | 74 ++++++++ .../Properties/AssemblyInfo.cs | 20 +++ .../CarRent/CarRentUnitTests/UnitTest1.cs | 168 ++++++++++++++++++ .../CarRent/CarRentUnitTests/packages.config | 5 + 15 files changed, 494 insertions(+), 52 deletions(-) delete mode 100644 SecondLesson/CarRent/CarRent/CarRent.cs create mode 100644 SecondLesson/CarRent/CarRent/IRepository.cs create mode 100644 SecondLesson/CarRent/CarRent/Maintenance.cs create mode 100644 SecondLesson/CarRent/CarRent/Rent.cs delete mode 100644 SecondLesson/CarRent/CarRent/UserRent.cs create mode 100644 SecondLesson/CarRent/CarRentUnitTests/CarRentUnitTests.csproj create mode 100644 SecondLesson/CarRent/CarRentUnitTests/Properties/AssemblyInfo.cs create mode 100644 SecondLesson/CarRent/CarRentUnitTests/UnitTest1.cs create mode 100644 SecondLesson/CarRent/CarRentUnitTests/packages.config diff --git a/SecondLesson/CarRent/CarRent.sln b/SecondLesson/CarRent/CarRent.sln index 8e76391..b7a0d1e 100644 --- a/SecondLesson/CarRent/CarRent.sln +++ b/SecondLesson/CarRent/CarRent.sln @@ -5,6 +5,8 @@ VisualStudioVersion = 15.0.28010.2036 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CarRent", "CarRent\CarRent.csproj", "{02D4419C-B448-46C3-AD91-8EA37C3FEECF}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CarRentUnitTests", "CarRentUnitTests\CarRentUnitTests.csproj", "{0BD1AF88-D8B4-4930-94E9-4FB52A242FC7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +17,10 @@ Global {02D4419C-B448-46C3-AD91-8EA37C3FEECF}.Debug|Any CPU.Build.0 = Debug|Any CPU {02D4419C-B448-46C3-AD91-8EA37C3FEECF}.Release|Any CPU.ActiveCfg = Release|Any CPU {02D4419C-B448-46C3-AD91-8EA37C3FEECF}.Release|Any CPU.Build.0 = Release|Any CPU + {0BD1AF88-D8B4-4930-94E9-4FB52A242FC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0BD1AF88-D8B4-4930-94E9-4FB52A242FC7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0BD1AF88-D8B4-4930-94E9-4FB52A242FC7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0BD1AF88-D8B4-4930-94E9-4FB52A242FC7}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/SecondLesson/CarRent/CarRent/Car.cs b/SecondLesson/CarRent/CarRent/Car.cs index 8a2b567..e506790 100644 --- a/SecondLesson/CarRent/CarRent/Car.cs +++ b/SecondLesson/CarRent/CarRent/Car.cs @@ -4,16 +4,17 @@ namespace CarRent { - class Car - { - List _tenants_list; - int _number; + public class Car + { + public int _number; + public Guid _id; + public DateTimeOffset _end_date_of_last_maintenance; - public void RentCar(User tenant, DateTimeOffset date_of_begining, DateTimeOffset date_of_ending ) + public Car(int number, Guid id, DateTimeOffset first_possible_rentdate) { - _tenants_list.Add(new CarRent(tenant._id, date_of_begining, date_of_ending)); + _number = number; + _id = id; + _end_date_of_last_maintenance = first_possible_rentdate; } - - } } diff --git a/SecondLesson/CarRent/CarRent/CarRent.cs b/SecondLesson/CarRent/CarRent/CarRent.cs deleted file mode 100644 index 28f8de6..0000000 --- a/SecondLesson/CarRent/CarRent/CarRent.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace CarRent -{ - public class CarRent - { - Guid _tenant; - DateTimeOffset _date_of_begining; - DateTimeOffset _date_of_ending; - - public CarRent(Guid tenant, DateTimeOffset date_of_begining, DateTimeOffset date_of_ending) - { - _tenant = tenant; - _date_of_begining = date_of_begining; - _date_of_ending = date_of_ending; - } - } -} \ No newline at end of file diff --git a/SecondLesson/CarRent/CarRent/CarRent.csproj b/SecondLesson/CarRent/CarRent/CarRent.csproj index b44a10c..71574a5 100644 --- a/SecondLesson/CarRent/CarRent/CarRent.csproj +++ b/SecondLesson/CarRent/CarRent/CarRent.csproj @@ -45,11 +45,12 @@ + + + - - diff --git a/SecondLesson/CarRent/CarRent/Cars.cs b/SecondLesson/CarRent/CarRent/Cars.cs index 3cff62d..79c3e07 100644 --- a/SecondLesson/CarRent/CarRent/Cars.cs +++ b/SecondLesson/CarRent/CarRent/Cars.cs @@ -1,16 +1,154 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; namespace CarRent { - class Cars + public class Car_park//: IRepository { - public List _list { private set; get; } + private List _list; + public List _list_of_rents { private set; get; } + private List _list_of_time_maintensnce; + private TimeSpan _maintenance_duration; + private int _amount_of_rent_without_maintenance; + public Car_park(List list, List list_of_rents, List list_of_time_maintensnce, TimeSpan maintenance_duration, int amount_of_rent_without_maintenance) + { + _list = list; + _list_of_rents = list_of_rents; + _list_of_time_maintensnce = list_of_time_maintensnce; + _maintenance_duration = maintenance_duration; + _amount_of_rent_without_maintenance = amount_of_rent_without_maintenance; + } + + public Car FindCarByID(Guid id) + { + foreach (Car car in _list) + { + if(car._id == id) + { + return car; + } + } + return null; + } public void AddNewCarInCarPark(Car adding_car) { _list.Add(adding_car); } + public void RentCar(User tenant, Car rental_car, DateTimeOffset date_of_begining, DateTimeOffset date_of_ending) + { + if (CheckIsCarFree(rental_car, date_of_begining.Date, date_of_ending.Date) && CheckIsTenantFree(tenant, date_of_begining.Date, date_of_ending.Date)&&(rental_car._end_date_of_last_maintenance.Date<=date_of_begining.Date)) + { + _list_of_rents.Add(new Rent(tenant, rental_car, date_of_begining, date_of_ending)); + if (CheckItIsTimeRorMaintenance(rental_car)) + { + SendCarForMaintenance(rental_car, GetEndDateOfLestRent(rental_car)); + } + } + else Print("Error"); + + } + + private DateTimeOffset GetEndDateOfLestRent(Car rental_car) + { + DateTimeOffset end_date_of_last_rent = DateTimeOffset.MinValue; + foreach (Rent rent in _list_of_rents) + { + if ((rent._car == rental_car) && (rent._begining_date.Date >= rental_car._end_date_of_last_maintenance.Date)) + { + if (rent._ending_date > end_date_of_last_rent) + { + end_date_of_last_rent = rent._ending_date; + } + } + } + return end_date_of_last_rent; + + } + private int GetAmountOfRentAfterLastMaintenance(Car rental_car) + { + int this_car_amount_of_rent = 0; + + foreach (Rent rent in _list_of_rents) + { + if ((rent._car == rental_car) && (rent._begining_date.Date >= rental_car._end_date_of_last_maintenance.Date)) + { + this_car_amount_of_rent++; + } + } + return this_car_amount_of_rent; + } + private bool CheckItIsTimeRorMaintenance(Car rental_car) + { + if (_amount_of_rent_without_maintenance == GetAmountOfRentAfterLastMaintenance(rental_car)) + { + return true; + } + return false; + } + private void SendCarForMaintenance(Car rental_car, DateTimeOffset end_date_of_last_rent) + { + _list_of_time_maintensnce.Add(new Maintenance(rental_car, end_date_of_last_rent, end_date_of_last_rent + _maintenance_duration)); + rental_car._end_date_of_last_maintenance = end_date_of_last_rent + _maintenance_duration; + } + + public List ViewListFreeCars(DateTimeOffset date_of_begining, DateTimeOffset date_of_ending) + { + List freecars = new List(); + foreach (Rent i in _list_of_rents) + { + if (CheckIsCarFree(i._car, date_of_begining, date_of_ending)&&(i._car._end_date_of_last_maintenance.Date<=date_of_begining.Date)) + { + freecars.Add(i._car); + } + } + return freecars; + } + public List ViewUserRentalHistory(User tenant) + { + List rent_list = new List(); + foreach (Rent i in _list_of_rents) + { + if (i._tenant == tenant) + { + rent_list.Add(i); + } + } + return rent_list; + } + + private bool CheckIsTenantFree(User tenant, DateTimeOffset date_of_begining, DateTimeOffset date_of_ending) + { + foreach (Rent i in _list_of_rents) + { + if ((i._tenant == tenant) && !(date_of_begining.Date > i._ending_date.Date || date_of_ending.Date < i._begining_date.Date)) + { + return false; + } + } + return true; + } + private bool CheckIsCarFree(Car rental_car, DateTimeOffset date_of_begining, DateTimeOffset date_of_ending) + { + foreach (Rent i in _list_of_rents) + { + if ((i._car == rental_car) && !(date_of_begining.Date > i._ending_date.Date || date_of_ending.Date < i._begining_date.Date)) + { + return false; + } + } + return true; + } + + public void Print(string text) + { + Console.WriteLine(text); + } + + + + } } diff --git a/SecondLesson/CarRent/CarRent/IRepository.cs b/SecondLesson/CarRent/CarRent/IRepository.cs new file mode 100644 index 0000000..b977634 --- /dev/null +++ b/SecondLesson/CarRent/CarRent/IRepository.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; + +namespace CarRent +{ + interface IRepository : IDisposable + where T : class + { + IEnumerable GetAll(); // получение всех объектов + void Create(T item); // создание объекта + void Update(T item); // обновление объекта + void Delete(int id); // удаление объекта по id + void Save(); // сохранение изменений + } +} diff --git a/SecondLesson/CarRent/CarRent/Maintenance.cs b/SecondLesson/CarRent/CarRent/Maintenance.cs new file mode 100644 index 0000000..9e233f4 --- /dev/null +++ b/SecondLesson/CarRent/CarRent/Maintenance.cs @@ -0,0 +1,18 @@ +using System; + +namespace CarRent +{ + public class Maintenance + { + public Car _car; + public DateTimeOffset _date_of_begining; + public DateTimeOffset _date_of_ending; + + public Maintenance(Car car, DateTimeOffset date_of_begining, DateTimeOffset date_of_ending) + { + _car = car; + _date_of_begining = date_of_begining; + _date_of_ending = date_of_ending; + } + } +} diff --git a/SecondLesson/CarRent/CarRent/Program.cs b/SecondLesson/CarRent/CarRent/Program.cs index 64761cb..1ce4ee1 100644 --- a/SecondLesson/CarRent/CarRent/Program.cs +++ b/SecondLesson/CarRent/CarRent/Program.cs @@ -6,10 +6,16 @@ namespace CarRent { - class Program + public class Program { static void Main(string[] args) { + + //Для сохранения сущностей пользуйтесь паттерном Repository. + //В качестве программного эндпоинта для приложения используйте паттерн Facade. + } + + } } diff --git a/SecondLesson/CarRent/CarRent/Rent.cs b/SecondLesson/CarRent/CarRent/Rent.cs new file mode 100644 index 0000000..82563fe --- /dev/null +++ b/SecondLesson/CarRent/CarRent/Rent.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarRent +{ + public class Rent + { + public User _tenant; + public Car _car; + public DateTimeOffset _begining_date; + public DateTimeOffset _ending_date; + + public Rent(User tenant, Car car, DateTimeOffset begining_date, DateTimeOffset ending_date) + { + _tenant = tenant; + _car = car; + _begining_date = begining_date; + _ending_date = ending_date; + } + } +} diff --git a/SecondLesson/CarRent/CarRent/User.cs b/SecondLesson/CarRent/CarRent/User.cs index 96f4171..287e104 100644 --- a/SecondLesson/CarRent/CarRent/User.cs +++ b/SecondLesson/CarRent/CarRent/User.cs @@ -4,21 +4,17 @@ namespace CarRent { public class User - { - List _list_of_rental_cars; + { string _first_name { get; } string _second_name; public Guid _id; - public User(List list_of_rental_cars, string first_name, string second_name) + public User(string first_name, string second_name, Guid id) { - _list_of_rental_cars = list_of_rental_cars; _first_name = first_name; _second_name = second_name; + _id = id; } - public List GetRentalHistory() - { - return _list_of_rental_cars; - } + } } \ No newline at end of file diff --git a/SecondLesson/CarRent/CarRent/UserRent.cs b/SecondLesson/CarRent/CarRent/UserRent.cs deleted file mode 100644 index ce07f59..0000000 --- a/SecondLesson/CarRent/CarRent/UserRent.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace CarRent -{ - public class UserRent - { - Car _rental_car; - DateTimeOffset _date_of_begining; - DateTimeOffset _date_of_ending; - - } -} \ No newline at end of file diff --git a/SecondLesson/CarRent/CarRentUnitTests/CarRentUnitTests.csproj b/SecondLesson/CarRent/CarRentUnitTests/CarRentUnitTests.csproj new file mode 100644 index 0000000..b35bfd7 --- /dev/null +++ b/SecondLesson/CarRent/CarRentUnitTests/CarRentUnitTests.csproj @@ -0,0 +1,74 @@ + + + + + + Debug + AnyCPU + {0BD1AF88-D8B4-4930-94E9-4FB52A242FC7} + Library + Properties + CarRentUnitTests + CarRentUnitTests + v4.6.1 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 15.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages + False + UnitTest + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll + + + ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll + + + + + + + + + + + + + + {02d4419c-b448-46c3-ad91-8ea37c3feecf} + CarRent + + + + + + + Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}. + + + + + + \ No newline at end of file diff --git a/SecondLesson/CarRent/CarRentUnitTests/Properties/AssemblyInfo.cs b/SecondLesson/CarRent/CarRentUnitTests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..71efb96 --- /dev/null +++ b/SecondLesson/CarRent/CarRentUnitTests/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("CarRentUnitTests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CarRentUnitTests")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: ComVisible(false)] + +[assembly: Guid("0bd1af88-d8b4-4930-94e9-4fb52a242fc7")] + +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SecondLesson/CarRent/CarRentUnitTests/UnitTest1.cs b/SecondLesson/CarRent/CarRentUnitTests/UnitTest1.cs new file mode 100644 index 0000000..8c30f13 --- /dev/null +++ b/SecondLesson/CarRent/CarRentUnitTests/UnitTest1.cs @@ -0,0 +1,168 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; + + +namespace CarRent +{ + [TestClass] + public class CarRentTest + { + [TestMethod] + public void RentCarForValuableTime_AddingRecordInRentList() + { + User tenant = new User("Ivan", "Dobry", Guid.NewGuid()); + var car_id = Guid.NewGuid(); + var cars_list = new List { new Car(123, car_id, DateTimeOffset.Now) }; + var rents_list = new List { + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 10, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 11, 23, 59, 59, TimeSpan.Zero)) }; + + Car_park park = new Car_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); + + var exating_rent_list = new List { + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 10, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 11, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 5, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 7, 0, 0, 0, TimeSpan.Zero))}; + + + park.RentCar(tenant, cars_list[0], new DateTimeOffset(2019, 5, 5, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 7, 0, 0, 0, TimeSpan.Zero)); + + + CollectionAssert.ReferenceEquals(park._list_of_rents, exating_rent_list); + + } + [TestMethod] + public void RentCarWhenItNotFree_RentListWithoutChanging() + { + var first_tenant = new User("Ivan", "Dobry", Guid.NewGuid()); + var second_tenant = new User("Roman", "Oganesson", Guid.NewGuid()); + var car_id = Guid.NewGuid(); + var cars_list = new List { new Car(123, car_id, DateTimeOffset.Now) }; + var rents_list = new List { new Rent(second_tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 10, 23, 59, 59, TimeSpan.Zero)) }; + var park = new Car_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); + + var exiting_rent_list = rents_list; + park.RentCar(first_tenant, park.FindCarByID(car_id), new DateTimeOffset(2018, 5, 3, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2018, 5, 12, 23, 59, 59, TimeSpan.Zero)); + + CollectionAssert.ReferenceEquals(exiting_rent_list, park._list_of_rents); + + } + + [TestMethod] + public void RentCarWhenUserAlreadyRentAnotherCar_RentListWithoutChanging() + { + User tenant = new User("Ivan", "Dobry", Guid.NewGuid()); + var car_id = Guid.NewGuid(); + var cars_list = new List { new Car(123, car_id, DateTimeOffset.Now), new Car(146, Guid.NewGuid(), DateTimeOffset.Now) }; + var rents_list = new List { + new Rent(tenant, cars_list[1], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 9, 23, 59, 59, TimeSpan.Zero))}; + + Car_park park = new Car_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); + + var exiting_rent_list = rents_list; + park.RentCar(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 7, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 11, 23, 59, 59, TimeSpan.Zero)); + + + CollectionAssert.ReferenceEquals(exiting_rent_list, park._list_of_rents); + + + } + + [TestMethod] + public void ViewFreeCarForRent_ListWithCarsThatHaveNotRentInThisPeriod() + { + User tenant = new User("Ivan", "Dobry", Guid.NewGuid()); + var car_id = Guid.NewGuid(); + var cars_list = new List { new Car(123, car_id, DateTimeOffset.Now), new Car(145, Guid.NewGuid(), DateTimeOffset.Now), new Car(189, Guid.NewGuid(), DateTimeOffset.Now) }; + var rents_list = new List { + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[1], new DateTimeOffset(2019, 5, 10, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 11, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[2], new DateTimeOffset(2019, 5, 20, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 25, 23, 59, 59, TimeSpan.Zero)) }; + Car_park park = new Car_park(new List(), new List(), new List(), TimeSpan.FromDays(7), 10); + + var exated_list_of_free_cars = new List { cars_list[0], cars_list[2] }; + var list_free_cars = park.ViewListFreeCars(new DateTimeOffset(2019, 5, 10, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 12, 0, 0, 0, TimeSpan.Zero)); + + CollectionAssert.ReferenceEquals(exated_list_of_free_cars, list_free_cars); + } + + + [TestMethod] + public void ViewUserRentalHistory_ListWithCarsThatUserRented() + { + var tenant = new User("Ivan", "Dobry", Guid.NewGuid()); + var second_tenant = new User("Ivan", "Oganesson", Guid.NewGuid()); + Car_park park = new Car_park(new List(), new List(), new List(), TimeSpan.FromDays(7), 10); + var cars_list = new List { new Car(123, Guid.NewGuid(), DateTimeOffset.Now) }; + var rents_list = new List { + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), + new Rent(second_tenant, cars_list[0], new DateTimeOffset(2019, 5, 10, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 11, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 20, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 25, 23, 59, 59, TimeSpan.Zero)) }; + + var expected_user_rent_history_list = new List { rents_list[0], rents_list[2] }; + var tenant_rental_list = park.ViewUserRentalHistory(tenant); + + CollectionAssert.ReferenceEquals(expected_user_rent_history_list, tenant_rental_list); + } + + + + [TestMethod] + public void TryToRentCarWhileItInMaintenance_ListWithoutChange() + { + User tenant = new User("Ivan", "Dobry", Guid.NewGuid()); + var car_id = Guid.NewGuid(); + var cars_list = new List { new Car(123, car_id, DateTimeOffset.Now) }; + var rents_list = new List { new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 1, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 2, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 3, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 5, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 6, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 7, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 8, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 11, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 12, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 13, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 14, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 15, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 16, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 17, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 18, 23, 59, 59, TimeSpan.Zero)), + }; + + Car_park park = new Car_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); + park.RentCar(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 21, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 22, 23, 59, 59, TimeSpan.Zero)); + + park.RentCar(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 23, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 24, 23, 59, 59, TimeSpan.Zero)); + + var expected_rent_list = rents_list; + expected_rent_list.Add(new Rent(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 21, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 22, 23, 59, 59, TimeSpan.Zero))); + + CollectionAssert.ReferenceEquals(park._list_of_rents, expected_rent_list); + } + [TestMethod] + public void TryToRentCarBeforePlanningMaintenance_ListWithoutChange() + { + User tenant = new User("Ivan", "Dobry", Guid.NewGuid()); + var car_id = Guid.NewGuid(); + var cars_list = new List { new Car(123, car_id, DateTimeOffset.Now) }; + var rents_list = new List { new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 1, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 2, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 3, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 5, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 6, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 7, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 8, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 11, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 12, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 13, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 14, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 15, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 16, 23, 59, 59, TimeSpan.Zero)), + new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 17, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 18, 23, 59, 59, TimeSpan.Zero)), + }; + + Car_park park = new Car_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); + park.RentCar(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 21, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 22, 23, 59, 59, TimeSpan.Zero)); + + park.RentCar(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 19, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 20, 23, 59, 59, TimeSpan.Zero)); + + var expected_rent_list = rents_list; + expected_rent_list.Add(new Rent(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 21, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 22, 23, 59, 59, TimeSpan.Zero))); + + CollectionAssert.ReferenceEquals(park._list_of_rents, expected_rent_list); + } + + } + +} diff --git a/SecondLesson/CarRent/CarRentUnitTests/packages.config b/SecondLesson/CarRent/CarRentUnitTests/packages.config new file mode 100644 index 0000000..102a45c --- /dev/null +++ b/SecondLesson/CarRent/CarRentUnitTests/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file From 43aedebf0edaa90d12d45fdddbe8779afab786b7 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 12 Oct 2018 19:47:26 +0300 Subject: [PATCH 11/22] rename Unit tests --- .../CarRent/CarRentUnitTests/{UnitTest1.cs => CarRentTest.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename SecondLesson/CarRent/CarRentUnitTests/{UnitTest1.cs => CarRentTest.cs} (100%) diff --git a/SecondLesson/CarRent/CarRentUnitTests/UnitTest1.cs b/SecondLesson/CarRent/CarRentUnitTests/CarRentTest.cs similarity index 100% rename from SecondLesson/CarRent/CarRentUnitTests/UnitTest1.cs rename to SecondLesson/CarRent/CarRentUnitTests/CarRentTest.cs From 3fd9860e7909e938bc116e1d86ad747c05700edf Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 12 Oct 2018 20:28:40 +0300 Subject: [PATCH 12/22] adding repository, return Cars_park name --- SecondLesson/CarRent/CarRent/CarRent.csproj | 4 +- .../CarRent/CarRent/Cars_ParkRepository.cs | 39 +++++++++++++++++++ .../CarRent/CarRent/{Cars.cs => Cars_park.cs} | 4 +- SecondLesson/CarRent/CarRent/IRepository.cs | 7 ++-- .../CarRent/CarRent/UserRepository.cs | 35 +++++++++++++++++ .../CarRent/CarRentUnitTests/CarRentTest.cs | 30 +++++++------- .../CarRentUnitTests/CarRentUnitTests.csproj | 2 +- 7 files changed, 98 insertions(+), 23 deletions(-) create mode 100644 SecondLesson/CarRent/CarRent/Cars_ParkRepository.cs rename SecondLesson/CarRent/CarRent/{Cars.cs => Cars_park.cs} (95%) create mode 100644 SecondLesson/CarRent/CarRent/UserRepository.cs diff --git a/SecondLesson/CarRent/CarRent/CarRent.csproj b/SecondLesson/CarRent/CarRent/CarRent.csproj index 71574a5..0d18969 100644 --- a/SecondLesson/CarRent/CarRent/CarRent.csproj +++ b/SecondLesson/CarRent/CarRent/CarRent.csproj @@ -44,13 +44,15 @@ - + + + diff --git a/SecondLesson/CarRent/CarRent/Cars_ParkRepository.cs b/SecondLesson/CarRent/CarRent/Cars_ParkRepository.cs new file mode 100644 index 0000000..3a5a397 --- /dev/null +++ b/SecondLesson/CarRent/CarRent/Cars_ParkRepository.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarRent +{ + class Cars_ParkRepository : IRepository + { + private List _cars_list; + public Cars_ParkRepository() + { + _cars_list = new List(); + } + + public Cars_ParkRepository(List cars_list) + { + _cars_list = cars_list; + } + + public void Create(Cars_park park) + { + _cars_list.Add(park); + } + + public void Delete(int id) + { + _cars_list.RemoveAt(id); + } + + + public IEnumerable GetAll() + { + return _cars_list; + } + + } +} diff --git a/SecondLesson/CarRent/CarRent/Cars.cs b/SecondLesson/CarRent/CarRent/Cars_park.cs similarity index 95% rename from SecondLesson/CarRent/CarRent/Cars.cs rename to SecondLesson/CarRent/CarRent/Cars_park.cs index 79c3e07..f871490 100644 --- a/SecondLesson/CarRent/CarRent/Cars.cs +++ b/SecondLesson/CarRent/CarRent/Cars_park.cs @@ -4,7 +4,7 @@ namespace CarRent { - public class Car_park//: IRepository + public class Cars_park { private List _list; public List _list_of_rents { private set; get; } @@ -12,7 +12,7 @@ public class Car_park//: IRepository private TimeSpan _maintenance_duration; private int _amount_of_rent_without_maintenance; - public Car_park(List list, List list_of_rents, List list_of_time_maintensnce, TimeSpan maintenance_duration, int amount_of_rent_without_maintenance) + public Cars_park(List list, List list_of_rents, List list_of_time_maintensnce, TimeSpan maintenance_duration, int amount_of_rent_without_maintenance) { _list = list; _list_of_rents = list_of_rents; diff --git a/SecondLesson/CarRent/CarRent/IRepository.cs b/SecondLesson/CarRent/CarRent/IRepository.cs index b977634..48f343f 100644 --- a/SecondLesson/CarRent/CarRent/IRepository.cs +++ b/SecondLesson/CarRent/CarRent/IRepository.cs @@ -3,13 +3,12 @@ namespace CarRent { - interface IRepository : IDisposable + interface IRepository where T : class { IEnumerable GetAll(); // получение всех объектов - void Create(T item); // создание объекта - void Update(T item); // обновление объекта + void Create(T item); // создание объекта void Delete(int id); // удаление объекта по id - void Save(); // сохранение изменений + } } diff --git a/SecondLesson/CarRent/CarRent/UserRepository.cs b/SecondLesson/CarRent/CarRent/UserRepository.cs new file mode 100644 index 0000000..fbc5bac --- /dev/null +++ b/SecondLesson/CarRent/CarRent/UserRepository.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; + +namespace CarRent +{ + class UserRepository : IRepository + { + private List _user_list; + + public UserRepository() + { + _user_list = new List(); + } + + public UserRepository(List user_list) + { + _user_list = user_list; + } + + public void Create(User user) + { + _user_list.Add(user); + + } + + public void Delete(int id) + { + _user_list.RemoveAt(id); + } + + public IEnumerable GetAll() + { + return _user_list; + } + } +} diff --git a/SecondLesson/CarRent/CarRentUnitTests/CarRentTest.cs b/SecondLesson/CarRent/CarRentUnitTests/CarRentTest.cs index 8c30f13..23590e9 100644 --- a/SecondLesson/CarRent/CarRentUnitTests/CarRentTest.cs +++ b/SecondLesson/CarRent/CarRentUnitTests/CarRentTest.cs @@ -18,9 +18,9 @@ public void RentCarForValuableTime_AddingRecordInRentList() new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 10, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 11, 23, 59, 59, TimeSpan.Zero)) }; - Car_park park = new Car_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); + Cars_park park = new Cars_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); - var exating_rent_list = new List { + var expected_rent_list = new List { new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 10, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 11, 23, 59, 59, TimeSpan.Zero)), new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 5, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 7, 0, 0, 0, TimeSpan.Zero))}; @@ -29,7 +29,7 @@ public void RentCarForValuableTime_AddingRecordInRentList() park.RentCar(tenant, cars_list[0], new DateTimeOffset(2019, 5, 5, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 7, 0, 0, 0, TimeSpan.Zero)); - CollectionAssert.ReferenceEquals(park._list_of_rents, exating_rent_list); + CollectionAssert.ReferenceEquals(park._list_of_rents, expected_rent_list); } [TestMethod] @@ -40,12 +40,12 @@ public void RentCarWhenItNotFree_RentListWithoutChanging() var car_id = Guid.NewGuid(); var cars_list = new List { new Car(123, car_id, DateTimeOffset.Now) }; var rents_list = new List { new Rent(second_tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 10, 23, 59, 59, TimeSpan.Zero)) }; - var park = new Car_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); + var park = new Cars_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); - var exiting_rent_list = rents_list; + var expected_rent_list = rents_list; park.RentCar(first_tenant, park.FindCarByID(car_id), new DateTimeOffset(2018, 5, 3, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2018, 5, 12, 23, 59, 59, TimeSpan.Zero)); - CollectionAssert.ReferenceEquals(exiting_rent_list, park._list_of_rents); + CollectionAssert.ReferenceEquals( expected_rent_list, park._list_of_rents); } @@ -58,13 +58,13 @@ public void RentCarWhenUserAlreadyRentAnotherCar_RentListWithoutChanging() var rents_list = new List { new Rent(tenant, cars_list[1], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 9, 23, 59, 59, TimeSpan.Zero))}; - Car_park park = new Car_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); + Cars_park park = new Cars_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); - var exiting_rent_list = rents_list; + var expected_rent_list = rents_list; park.RentCar(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 7, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 11, 23, 59, 59, TimeSpan.Zero)); - CollectionAssert.ReferenceEquals(exiting_rent_list, park._list_of_rents); + CollectionAssert.ReferenceEquals( expected_rent_list, park._list_of_rents); } @@ -79,12 +79,12 @@ public void ViewFreeCarForRent_ListWithCarsThatHaveNotRentInThisPeriod() new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), new Rent(tenant, cars_list[1], new DateTimeOffset(2019, 5, 10, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 11, 23, 59, 59, TimeSpan.Zero)), new Rent(tenant, cars_list[2], new DateTimeOffset(2019, 5, 20, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 25, 23, 59, 59, TimeSpan.Zero)) }; - Car_park park = new Car_park(new List(), new List(), new List(), TimeSpan.FromDays(7), 10); + Cars_park park = new Cars_park(new List(), new List(), new List(), TimeSpan.FromDays(7), 10); - var exated_list_of_free_cars = new List { cars_list[0], cars_list[2] }; + var expected_list_of_free_cars = new List { cars_list[0], cars_list[2] }; var list_free_cars = park.ViewListFreeCars(new DateTimeOffset(2019, 5, 10, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 12, 0, 0, 0, TimeSpan.Zero)); - CollectionAssert.ReferenceEquals(exated_list_of_free_cars, list_free_cars); + CollectionAssert.ReferenceEquals( expected_list_of_free_cars, list_free_cars); } @@ -93,7 +93,7 @@ public void ViewUserRentalHistory_ListWithCarsThatUserRented() { var tenant = new User("Ivan", "Dobry", Guid.NewGuid()); var second_tenant = new User("Ivan", "Oganesson", Guid.NewGuid()); - Car_park park = new Car_park(new List(), new List(), new List(), TimeSpan.FromDays(7), 10); + Cars_park park = new Cars_park(new List(), new List(), new List(), TimeSpan.FromDays(7), 10); var cars_list = new List { new Car(123, Guid.NewGuid(), DateTimeOffset.Now) }; var rents_list = new List { new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 2, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 4, 23, 59, 59, TimeSpan.Zero)), @@ -125,7 +125,7 @@ public void TryToRentCarWhileItInMaintenance_ListWithoutChange() new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 17, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 18, 23, 59, 59, TimeSpan.Zero)), }; - Car_park park = new Car_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); + Cars_park park = new Cars_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); park.RentCar(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 21, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 22, 23, 59, 59, TimeSpan.Zero)); park.RentCar(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 23, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 24, 23, 59, 59, TimeSpan.Zero)); @@ -152,7 +152,7 @@ public void TryToRentCarBeforePlanningMaintenance_ListWithoutChange() new Rent(tenant, cars_list[0], new DateTimeOffset(2019, 5, 17, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 18, 23, 59, 59, TimeSpan.Zero)), }; - Car_park park = new Car_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); + Cars_park park = new Cars_park(cars_list, rents_list, new List(), TimeSpan.FromDays(7), 10); park.RentCar(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 21, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 22, 23, 59, 59, TimeSpan.Zero)); park.RentCar(tenant, park.FindCarByID(car_id), new DateTimeOffset(2019, 5, 19, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2019, 5, 20, 23, 59, 59, TimeSpan.Zero)); diff --git a/SecondLesson/CarRent/CarRentUnitTests/CarRentUnitTests.csproj b/SecondLesson/CarRent/CarRentUnitTests/CarRentUnitTests.csproj index b35bfd7..cb61522 100644 --- a/SecondLesson/CarRent/CarRentUnitTests/CarRentUnitTests.csproj +++ b/SecondLesson/CarRent/CarRentUnitTests/CarRentUnitTests.csproj @@ -49,7 +49,7 @@ - + From 81f54c43b33743c5698b63775ac941ac277016ad Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 12 Oct 2018 20:59:33 +0300 Subject: [PATCH 13/22] Adding Facade --- SecondLesson/CarRent/CarRent/CarRent.csproj | 1 + .../CarRent/CarRent/Car_ParkFacade.cs | 32 +++++++++++++++++++ SecondLesson/CarRent/CarRent/Cars_park.cs | 8 +++-- SecondLesson/CarRent/CarRent/User.cs | 4 +-- 4 files changed, 40 insertions(+), 5 deletions(-) create mode 100644 SecondLesson/CarRent/CarRent/Car_ParkFacade.cs diff --git a/SecondLesson/CarRent/CarRent/CarRent.csproj b/SecondLesson/CarRent/CarRent/CarRent.csproj index 0d18969..7b3e63d 100644 --- a/SecondLesson/CarRent/CarRent/CarRent.csproj +++ b/SecondLesson/CarRent/CarRent/CarRent.csproj @@ -46,6 +46,7 @@ + diff --git a/SecondLesson/CarRent/CarRent/Car_ParkFacade.cs b/SecondLesson/CarRent/CarRent/Car_ParkFacade.cs new file mode 100644 index 0000000..ff7257f --- /dev/null +++ b/SecondLesson/CarRent/CarRent/Car_ParkFacade.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; + +namespace CarRent +{ + class Car_ParkFacade + { + public Cars_park _cars_park; + + public Car_ParkFacade(Cars_park cars_park) + { + _cars_park = cars_park; + } + public void AddNewCarInCarPark(Car adding_car) + { + _cars_park.AddNewCarInCarPark(adding_car); + } + public void RentCar(User tenant, Guid id, DateTimeOffset date_of_begining, DateTimeOffset date_of_ending) + { + _cars_park.RentCar(tenant, _cars_park.FindCarByID(id), date_of_begining, date_of_ending); + } + + public List ViewListFreeCars(DateTimeOffset date_of_begining, DateTimeOffset date_of_ending) + { + return _cars_park.ViewListFreeCars(date_of_begining, date_of_ending); + } + public List ViewUserRentalHistory(User tenant) + { + return _cars_park.ViewUserRentalHistory(tenant); + } + } +} diff --git a/SecondLesson/CarRent/CarRent/Cars_park.cs b/SecondLesson/CarRent/CarRent/Cars_park.cs index f871490..41c8800 100644 --- a/SecondLesson/CarRent/CarRent/Cars_park.cs +++ b/SecondLesson/CarRent/CarRent/Cars_park.cs @@ -23,14 +23,16 @@ public Cars_park(List list, List list_of_rents, List lis public Car FindCarByID(Guid id) { + Car finded_car = null; foreach (Car car in _list) { if(car._id == id) { - return car; + finded_car = car; + return finded_car; } } - return null; + throw new ArgumentNullException("There are no car with that id", nameof(finded_car)); } public void AddNewCarInCarPark(Car adding_car) { @@ -142,7 +144,7 @@ private bool CheckIsCarFree(Car rental_car, DateTimeOffset date_of_begining, Dat return true; } - public void Print(string text) + private void Print(string text) { Console.WriteLine(text); } diff --git a/SecondLesson/CarRent/CarRent/User.cs b/SecondLesson/CarRent/CarRent/User.cs index 287e104..806b490 100644 --- a/SecondLesson/CarRent/CarRent/User.cs +++ b/SecondLesson/CarRent/CarRent/User.cs @@ -5,8 +5,8 @@ namespace CarRent { public class User { - string _first_name { get; } - string _second_name; + public string _first_name { get; private set; } + public string _second_name { get; private set; } public Guid _id; public User(string first_name, string second_name, Guid id) From d543044d09eef98326771c90722830e71e6267bc Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 19 Oct 2018 21:39:01 +0300 Subject: [PATCH 14/22] completed task --- ThirdLesson/Messenger/Messenger.sln | 31 +++ ThirdLesson/Messenger/Messenger/App.config | 6 + .../Messenger/Facades/UserService.cs | 99 ++++++++++ .../Messenger/Messenger/Intefaces/IChat.cs | 17 ++ .../Messenger/Messenger/Intefaces/IMessage.cs | 11 ++ .../Messenger/Intefaces/IRepository.cs | 12 ++ .../Messenger/Messenger/Intefaces/IUser.cs | 10 + .../Messenger/Intefaces/IUserService.cs | 16 ++ .../Messenger/Messenger/Messenger.csproj | 67 +++++++ .../Messenger/Messenger/Objects/Channel.cs | 140 ++++++++++++++ .../Messenger/Objects/Conversation.cs | 127 +++++++++++++ .../Messenger/Messenger/Objects/Dialogue.cs | 107 +++++++++++ .../Messenger/Messenger/Objects/Message.cs | 42 ++++ .../Messenger/Messenger/Objects/User.cs | 33 ++++ ThirdLesson/Messenger/Messenger/Program.cs | 15 ++ .../Messenger/Properties/AssemblyInfo.cs | 36 ++++ .../Messenger/Repositories/ChatRepository.cs | 47 +++++ .../Messenger/Repositories/UserRepository.cs | 48 +++++ .../Messenger/MessengerTests/ChannelTest.cs | 71 +++++++ .../MessengerTests/ConversationTest.cs | 63 ++++++ .../MessengerTests/MessengerTests.csproj | 76 ++++++++ .../MessengerTests/Properties/AssemblyInfo.cs | 20 ++ .../MessengerTests/WorkinWithMessageTest.cs | 179 ++++++++++++++++++ .../Messenger/MessengerTests/packages.config | 5 + 24 files changed, 1278 insertions(+) create mode 100644 ThirdLesson/Messenger/Messenger.sln create mode 100644 ThirdLesson/Messenger/Messenger/App.config create mode 100644 ThirdLesson/Messenger/Messenger/Facades/UserService.cs create mode 100644 ThirdLesson/Messenger/Messenger/Intefaces/IChat.cs create mode 100644 ThirdLesson/Messenger/Messenger/Intefaces/IMessage.cs create mode 100644 ThirdLesson/Messenger/Messenger/Intefaces/IRepository.cs create mode 100644 ThirdLesson/Messenger/Messenger/Intefaces/IUser.cs create mode 100644 ThirdLesson/Messenger/Messenger/Intefaces/IUserService.cs create mode 100644 ThirdLesson/Messenger/Messenger/Messenger.csproj create mode 100644 ThirdLesson/Messenger/Messenger/Objects/Channel.cs create mode 100644 ThirdLesson/Messenger/Messenger/Objects/Conversation.cs create mode 100644 ThirdLesson/Messenger/Messenger/Objects/Dialogue.cs create mode 100644 ThirdLesson/Messenger/Messenger/Objects/Message.cs create mode 100644 ThirdLesson/Messenger/Messenger/Objects/User.cs create mode 100644 ThirdLesson/Messenger/Messenger/Program.cs create mode 100644 ThirdLesson/Messenger/Messenger/Properties/AssemblyInfo.cs create mode 100644 ThirdLesson/Messenger/Messenger/Repositories/ChatRepository.cs create mode 100644 ThirdLesson/Messenger/Messenger/Repositories/UserRepository.cs create mode 100644 ThirdLesson/Messenger/MessengerTests/ChannelTest.cs create mode 100644 ThirdLesson/Messenger/MessengerTests/ConversationTest.cs create mode 100644 ThirdLesson/Messenger/MessengerTests/MessengerTests.csproj create mode 100644 ThirdLesson/Messenger/MessengerTests/Properties/AssemblyInfo.cs create mode 100644 ThirdLesson/Messenger/MessengerTests/WorkinWithMessageTest.cs create mode 100644 ThirdLesson/Messenger/MessengerTests/packages.config diff --git a/ThirdLesson/Messenger/Messenger.sln b/ThirdLesson/Messenger/Messenger.sln new file mode 100644 index 0000000..4d85d85 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2036 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Messenger", "Messenger\Messenger.csproj", "{C9592618-8C23-44A9-A466-F62A05D0DA2F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MessengerTests", "MessengerTests\MessengerTests.csproj", "{B890DC96-3384-4170-929B-7C6190B68520}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C9592618-8C23-44A9-A466-F62A05D0DA2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C9592618-8C23-44A9-A466-F62A05D0DA2F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C9592618-8C23-44A9-A466-F62A05D0DA2F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C9592618-8C23-44A9-A466-F62A05D0DA2F}.Release|Any CPU.Build.0 = Release|Any CPU + {B890DC96-3384-4170-929B-7C6190B68520}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B890DC96-3384-4170-929B-7C6190B68520}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B890DC96-3384-4170-929B-7C6190B68520}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B890DC96-3384-4170-929B-7C6190B68520}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B73E9C4E-5D05-4E7C-8778-7C6644434CC0} + EndGlobalSection +EndGlobal diff --git a/ThirdLesson/Messenger/Messenger/App.config b/ThirdLesson/Messenger/Messenger/App.config new file mode 100644 index 0000000..731f6de --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/ThirdLesson/Messenger/Messenger/Facades/UserService.cs b/ThirdLesson/Messenger/Messenger/Facades/UserService.cs new file mode 100644 index 0000000..380afaf --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Facades/UserService.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; + +namespace Messenger +{ + internal class UserService : IUserService + { + private UserRepository userRepository; + private ChatRepository chatRepository; + private IUser this_user; + + public UserService(UserRepository userRepository, ChatRepository chatRepository) + { + this.userRepository = userRepository; + this.chatRepository = chatRepository; + } + + public void Identification(Guid user_id) + { + this_user = userRepository.Get(user_id); + } + + public void ChangeMessage(string changed_message, Guid message_id, IChat chat) + { + chat.ChangeMessage(changed_message, message_id, this_user._id); + } + public void RemoveMessage(Guid message_id, IChat chat) + { + chat.RemoveMessage(message_id, this_user._id); + } + public void SendMessage(IMessage message, IChat chat) + { + chat.SendMessage(message, this_user._id); + } + + public void AddAdminInChannel(Channel channel, IUser new_admin) + { + channel.AddNewAdmin(new_admin, this_user._id); + } + public void InvateUserInConversation(Conversation conversation, IUser new_interviewer) + { + conversation.AddNewUser(new_interviewer, this_user); + } + + public void ChangeChannelName(Channel channel, string new_name) + { + channel.ChangeName(new_name, this_user._id); + } + public void ChangeConversationName(Conversation conversation, string new_name) + { + conversation.ChangeName(new_name, this_user._id); + } + + public IChat CreateChannel(string name) + { + var channel_id = Guid.NewGuid(); + var admins = new Dictionary() { { this_user._id, this_user } }; + var followers = admins; + var new_channel = new Channel(channel_id, name, admins, followers, new Dictionary()); + chatRepository.Create(new_channel); + return new_channel; + } + public IChat CreateDialogue(IUser interlocutor) + { + var dialogue_id = Guid.NewGuid(); + var new_dialogue = new Dialogue(dialogue_id, this_user, interlocutor, new Dictionary()); + chatRepository.Create(new_dialogue); + return new_dialogue; + } + public IChat CreateConversation(List users, string name) + { + var conversation_id = Guid.NewGuid(); + var interviewers = new Dictionary(); + foreach (IUser user in users) + { + interviewers.Add(user._id, user); + } + var new_conversation = new Conversation(interviewers, new Dictionary(), name, conversation_id); + chatRepository.Create(new_conversation); + return new_conversation; + } + + public void JoinChannel(Channel chanel) + { + chanel.Join(this_user); + } + public List GetMessages(IChat chat) + { + return chat.GetMessages(this_user); + } + + public IMessage GetLastMessages(IChat chat) + { + return chat.GetLastMessages(this_user); + } + + + } +} \ No newline at end of file diff --git a/ThirdLesson/Messenger/Messenger/Intefaces/IChat.cs b/ThirdLesson/Messenger/Messenger/Intefaces/IChat.cs new file mode 100644 index 0000000..37749aa --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Intefaces/IChat.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; + +namespace Messenger +{ + public interface IChat + { + Guid _id { get; } + + void ChangeMessage(string changed_message, Guid message_id, Guid user_id); + void RemoveMessage(Guid message_id, Guid user_id); + void SendMessage(IMessage message, Guid user_id); + List GetMessages(IUser user); + IMessage GetLastMessages(IUser user); + + } +} diff --git a/ThirdLesson/Messenger/Messenger/Intefaces/IMessage.cs b/ThirdLesson/Messenger/Messenger/Intefaces/IMessage.cs new file mode 100644 index 0000000..949bb6c --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Intefaces/IMessage.cs @@ -0,0 +1,11 @@ +using System; + +namespace Messenger +{ + public interface IMessage + { + Guid _id { get; } + IUser _author { get; } + DateTimeOffset _departure_time { get; } + } +} diff --git a/ThirdLesson/Messenger/Messenger/Intefaces/IRepository.cs b/ThirdLesson/Messenger/Messenger/Intefaces/IRepository.cs new file mode 100644 index 0000000..de78e39 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Intefaces/IRepository.cs @@ -0,0 +1,12 @@ +using System; + +namespace Messenger +{ + interface IRepository where T : class + { + void Create(T item); + T Get(Guid id); + void Remove(Guid id); + void Save(T item); + } +} diff --git a/ThirdLesson/Messenger/Messenger/Intefaces/IUser.cs b/ThirdLesson/Messenger/Messenger/Intefaces/IUser.cs new file mode 100644 index 0000000..70f1754 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Intefaces/IUser.cs @@ -0,0 +1,10 @@ +using System; + +namespace Messenger +{ + public interface IUser + { + Guid _id { get; } + string nickname { get; } + } +} diff --git a/ThirdLesson/Messenger/Messenger/Intefaces/IUserService.cs b/ThirdLesson/Messenger/Messenger/Intefaces/IUserService.cs new file mode 100644 index 0000000..d277ca6 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Intefaces/IUserService.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; + +namespace Messenger +{ + public interface IUserService + { + void Identification(Guid user_id); + + void ChangeMessage(string changed_message, Guid message_id, IChat chat); + void RemoveMessage(Guid message_id, IChat chat); + void SendMessage(IMessage message, IChat chat); + List GetMessages(IChat chat); + IMessage GetLastMessages(IChat chat); + } +} \ No newline at end of file diff --git a/ThirdLesson/Messenger/Messenger/Messenger.csproj b/ThirdLesson/Messenger/Messenger/Messenger.csproj new file mode 100644 index 0000000..ed7d212 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Messenger.csproj @@ -0,0 +1,67 @@ + + + + + Debug + AnyCPU + {C9592618-8C23-44A9-A466-F62A05D0DA2F} + Exe + Messenger + Messenger + v4.6.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ThirdLesson/Messenger/Messenger/Objects/Channel.cs b/ThirdLesson/Messenger/Messenger/Objects/Channel.cs new file mode 100644 index 0000000..93138a3 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Objects/Channel.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Messenger +{ + public class Channel : IChat + { + public Guid _id { get; } + public string _name { private set; get; } //not null + + private Dictionary admins; + private Dictionary followers; + private Dictionary messages; + + public Channel(Guid id, string name, Dictionary admins, Dictionary followers, Dictionary messages) + { + _id = id; + _name = name ?? throw new ArgumentNullException(nameof(name)); + this.admins = admins ?? throw new ArgumentNullException(nameof(admins));//не пустая коллекция + this.followers = followers; + this.messages = messages; + } + + public void AddNewAdmin(IUser new_admin, Guid old_admin_id) + { + if (admins.ContainsKey(old_admin_id)) + { + admins.Add(new_admin._id, new_admin); + followers.Add(new_admin._id, new_admin); + } + else throw new InvalidOperationException($"You are not admin"); + } + + + public void ChangeName(string new_name, Guid user_id) + { + if (admins.ContainsKey(user_id)) + { + _name = new_name; + } + else throw new InvalidOperationException($"You are not admin"); + } + + public void ChangeMessage(string changed_message, Guid message_id, Guid user_id) + { + if (messages.TryGetValue(message_id, out IMessage finded_message) && followers.TryGetValue(user_id, out IUser finded_user)) + { + if (finded_message._author == finded_user) + { + messages[message_id] = new Message(changed_message, finded_message._id, finded_message._author, finded_message._departure_time); + } + else throw new InvalidOperationException($"This message not your"); + } + else throw new InvalidOperationException($"Message or user does not exist"); + + } + + public void RemoveMessage(Guid message_id, Guid user_id) + { + if (followers.TryGetValue(user_id, out IUser finded_user) && messages.TryGetValue(message_id, out IMessage finded_message)) + { + if (finded_message._author == finded_user || admins.ContainsKey(user_id)) + { + messages.Remove(message_id); + } + } + else throw new InvalidOperationException($"Message or user does not exist"); + + } + + public void SendMessage(IMessage message, Guid user_id) + { + if (followers.ContainsKey(user_id)) + { + messages.Add(message._id, message); + } + else throw new InvalidOperationException($"Firstly join the channel"); + } + + public void Join(IUser follower) + { + followers.Add(follower._id, follower); + } + + public List GetMessages(IUser user) + { + if (followers.ContainsKey(user._id)) + { + return messages.Values.ToList(); + } + throw new InvalidOperationException($"Firstly join the channel"); + + } + + public IMessage GetLastMessages(IUser user) + { + var min_time = DateTimeOffset.MinValue; + var empty_user = new User(string.Empty, Guid.Empty); + var last_message = new Message(string.Empty, Guid.Empty, empty_user, min_time); + + if (followers.ContainsKey(user._id)) + { + foreach (Message message in messages.Values) + { + if (min_time > message._departure_time) + { + min_time = message._departure_time; + last_message = message; + } + + } + return last_message; + } + throw new InvalidOperationException($"Firstly join the channel"); + } + + public override bool Equals(object obj) + { + var channel = obj as Channel; + return channel != null && + _id.Equals(channel._id) && + _name.Equals(channel._name) && + EqualityComparer>.Default.Equals(admins, channel.admins) && + EqualityComparer>.Default.Equals(followers, channel.followers) && + EqualityComparer>.Default.Equals(messages, channel.messages); + } + + public override int GetHashCode() + { + var hashCode = -1020551394; + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_id); + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_name); + hashCode = hashCode * -1521134295 + EqualityComparer>.Default.GetHashCode(admins); + hashCode = hashCode * -1521134295 + EqualityComparer>.Default.GetHashCode(followers); + hashCode = hashCode * -1521134295 + EqualityComparer>.Default.GetHashCode(messages); + return hashCode; + } + } +} \ No newline at end of file diff --git a/ThirdLesson/Messenger/Messenger/Objects/Conversation.cs b/ThirdLesson/Messenger/Messenger/Objects/Conversation.cs new file mode 100644 index 0000000..b6be015 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Objects/Conversation.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Messenger +{ + public class Conversation : IChat + { + private Dictionary interviewers; + private Dictionary messages; + + public string _name; + + public Conversation(Dictionary interviewers, Dictionary messages, string name, Guid id) + { + this.interviewers = interviewers ?? throw new ArgumentNullException(nameof(interviewers)); + this.messages = messages ?? throw new ArgumentNullException(nameof(messages)); + _name = name ?? throw new ArgumentNullException(nameof(name)); + _id = id; + } + + public Guid _id { get; } + + public void AddNewUser(IUser user, IUser interviewer) + { + if (interviewers.ContainsKey(interviewer._id)) + { + interviewers.Add(user._id, user); + } + else throw new InvalidOperationException($"Firstly join the conversation"); + + } + public void ChangeName(string new_name, Guid user_id) + { + if (interviewers.ContainsKey(user_id)) + { + _name = new_name; + } + else throw new InvalidOperationException($"Firstly join the conversation"); + } + + public void ChangeMessage(string changed_message, Guid message_id, Guid user_id) + { + if (messages.TryGetValue(message_id, out IMessage finded_message) && interviewers.TryGetValue(user_id, out IUser finded_user)) + { + if (finded_message._author == finded_user) + { + messages[message_id] = new Message(changed_message, finded_message._id, finded_message._author, finded_message._departure_time); + } + else throw new InvalidOperationException($"This message not your"); + } + else throw new InvalidOperationException($"Message or user does not exist"); + } + public void RemoveMessage(Guid message_id, Guid user_id) + { + if (messages.TryGetValue(message_id, out IMessage finded_message) && interviewers.TryGetValue(user_id, out IUser finded_user)) + { + if (finded_message._author == finded_user) + { + messages.Remove(message_id); + } + else throw new InvalidOperationException($"This message not your"); + } + else throw new InvalidOperationException($"No message or user does not exist"); + } + public void SendMessage(IMessage message, Guid user_id) + { + if (interviewers.ContainsKey(user_id)) + { + messages.Add(message._id, message); + } + else throw new InvalidOperationException($"Firstly join the conversation"); + } + + public List GetMessages(IUser user) + { + if (interviewers.ContainsKey(user._id)) + { + return messages.Values.ToList(); + } + throw new InvalidOperationException($"Firstly join the conversation"); + + } + + public IMessage GetLastMessages(IUser user) + { + var min_time = DateTimeOffset.MinValue; + var empty_user = new User(string.Empty, Guid.Empty); + var last_message = new Message(string.Empty, Guid.Empty, empty_user, min_time); + + if (interviewers.ContainsKey(user._id)) + { + foreach (Message message in messages.Values) + { + if (min_time > message._departure_time) + { + min_time = message._departure_time; + last_message = message; + } + + } + return last_message; + } + throw new InvalidOperationException($"Firstly join the conversation"); + } + + public override bool Equals(object obj) + { + var conversation = obj as Conversation; + return conversation != null && + EqualityComparer>.Default.Equals(interviewers, conversation.interviewers) && + EqualityComparer>.Default.Equals(messages, conversation.messages) && + _name.Equals(conversation._name) && + _id.Equals(conversation._id); + } + + public override int GetHashCode() + { + var hashCode = -2106479715; + hashCode = hashCode * -1521134295 + EqualityComparer>.Default.GetHashCode(interviewers); + hashCode = hashCode * -1521134295 + EqualityComparer>.Default.GetHashCode(messages); + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_name); + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_id); + return hashCode; + } + } +} diff --git a/ThirdLesson/Messenger/Messenger/Objects/Dialogue.cs b/ThirdLesson/Messenger/Messenger/Objects/Dialogue.cs new file mode 100644 index 0000000..8fc258a --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Objects/Dialogue.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Messenger +{ + public class Dialogue : IChat + { + public Guid _id { get; } + + public IUser first_user { private set; get; } + public IUser second_user { private set; get; } + private Dictionary messages; + + public Dialogue(Guid id, IUser first_user, IUser second_user, Dictionary messages) + { + _id = id; + this.first_user = first_user ?? throw new ArgumentNullException(nameof(first_user)); + this.second_user = second_user ?? throw new ArgumentNullException(nameof(second_user)); + this.messages = messages; + } + + public void ChangeMessage(string changed_message, Guid message_id, Guid user_id) + { + if (messages.ContainsKey(message_id)) + { + if (messages[message_id]._author._id == user_id) + { + messages[message_id] = new Message(changed_message, messages[message_id]._id, messages[message_id]._author, messages[message_id]._departure_time); + } + else throw new InvalidOperationException($"This message not yours"); + } + else throw new InvalidOperationException($"Message does not found"); + } + public void RemoveMessage(Guid message_id, Guid user_id) + { + if (messages.ContainsKey(message_id)) + { + if (messages[message_id]._author._id == user_id) + { + messages.Remove(message_id); + } + else throw new InvalidOperationException($"This message not yours"); + } + else throw new InvalidOperationException($"Message does not found"); + } + public void SendMessage(IMessage message, Guid user_id) + { + if (first_user._id == user_id || second_user._id == user_id) + { + messages.Add(message._id, message); + } + else throw new InvalidOperationException($"This is not your dialogue"); + + } + + public List GetMessages(IUser user) + { + if (first_user == user || second_user == user) + { + return messages.Values.ToList(); + } + throw new InvalidOperationException($"You have not root to to this operation"); + } + public IMessage GetLastMessages(IUser user) + { + var min_time = DateTimeOffset.MinValue; + var empty_user = new User(string.Empty, Guid.Empty); + var last_message = new Message(string.Empty, Guid.Empty, empty_user, min_time); + + if (first_user == user || second_user == user) + { + foreach (Message message in messages.Values) + { + if (min_time > message._departure_time) + { + min_time = message._departure_time; + last_message = message; + } + + } + return last_message; + } + throw new InvalidOperationException($"You have not root to to this operation"); + } + + public override bool Equals(object obj) + { + var dialogue = obj as Dialogue; + return dialogue != null && + _id.Equals(dialogue._id) && + EqualityComparer.Default.Equals(first_user, dialogue.first_user) && + EqualityComparer.Default.Equals(second_user, dialogue.second_user) && + EqualityComparer>.Default.Equals(messages, dialogue.messages); + } + + public override int GetHashCode() + { + var hashCode = -1217293218; + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_id); + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(first_user); + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(second_user); + hashCode = hashCode * -1521134295 + EqualityComparer>.Default.GetHashCode(messages); + return hashCode; + } + } +} diff --git a/ThirdLesson/Messenger/Messenger/Objects/Message.cs b/ThirdLesson/Messenger/Messenger/Objects/Message.cs new file mode 100644 index 0000000..4af1bcd --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Objects/Message.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; + +namespace Messenger +{ + public class Message : IMessage + { + public string _text; + + public Message(string text, Guid id, IUser author, DateTimeOffset departure_time) + { + _text = text ?? throw new ArgumentNullException(nameof(text)); + _id = id; + _author = author ?? throw new ArgumentNullException(nameof(author)); + _departure_time = departure_time; + } + + public Guid _id { get; } + public IUser _author { get; } + public DateTimeOffset _departure_time { get; } + + public override bool Equals(object obj) + { + var message = obj as Message; + return message != null && + _text.Equals(message._text) && + _id.Equals(message._id) && + EqualityComparer.Default.Equals(_author, message._author) && + _departure_time.Equals(message._departure_time); + } + + public override int GetHashCode() + { + var hashCode = -419153245; + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_text); + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_id); + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_author); + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_departure_time); + return hashCode; + } + } +} diff --git a/ThirdLesson/Messenger/Messenger/Objects/User.cs b/ThirdLesson/Messenger/Messenger/Objects/User.cs new file mode 100644 index 0000000..2c12921 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Objects/User.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; + +namespace Messenger +{ + public class User : IUser + { + public User(string nickname, Guid id) + { + this.nickname = nickname ?? throw new ArgumentNullException(nameof(nickname)); + _id = id; + } + + public string nickname { private set; get; } + public Guid _id { get; } + + public override bool Equals(object obj) + { + var user = obj as User; + return user != null && + nickname.Equals(user.nickname) && + _id.Equals(user._id); + } + + public override int GetHashCode() + { + var hashCode = -647874936; + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(nickname); + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_id); + return hashCode; + } + } +} diff --git a/ThirdLesson/Messenger/Messenger/Program.cs b/ThirdLesson/Messenger/Messenger/Program.cs new file mode 100644 index 0000000..14c2b52 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Program.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Messenger +{ + class Program + { + static void Main(string[] args) + { + } + } +} diff --git a/ThirdLesson/Messenger/Messenger/Properties/AssemblyInfo.cs b/ThirdLesson/Messenger/Messenger/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d89e5ca --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Общие сведения об этой сборке предоставляются следующим набором +// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, +// связанные со сборкой. +[assembly: AssemblyTitle("Messenger")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Messenger")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми +// для компонентов COM. Если необходимо обратиться к типу в этой сборке через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(false)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("c9592618-8c23-44a9-a466-f62a05d0da2f")] + +// Сведения о версии сборки состоят из следующих четырех значений: +// +// Основной номер версии +// Дополнительный номер версии +// Номер сборки +// Редакция +// +// Можно задать все значения или принять номер сборки и номер редакции по умолчанию. +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ThirdLesson/Messenger/Messenger/Repositories/ChatRepository.cs b/ThirdLesson/Messenger/Messenger/Repositories/ChatRepository.cs new file mode 100644 index 0000000..c7b5087 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Repositories/ChatRepository.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; + +namespace Messenger +{ + public class ChatRepository : IRepository + { + private Dictionary chats; + + public ChatRepository(Dictionary chats) + { + this.chats = chats; + } + + public void Create(IChat chat) + { + chats.Add(chat._id, chat); + } + + public IChat Get(Guid chat_id) + { + if (chats.TryGetValue(chat_id, out IChat chat)) + { + return chat; + } + throw new InvalidOperationException($"Chat with id {chat_id} not found"); + } + + + public void Remove(Guid id) + { + throw new InvalidOperationException($"You can not remove chat"); + } + + + public void Save(IChat chat) + { + if (chats.TryGetValue(chat._id, out IChat existantChat)) + { + chats.Remove(chat._id); + } + + chats.Add(chat._id, chat); + } + + } +} diff --git a/ThirdLesson/Messenger/Messenger/Repositories/UserRepository.cs b/ThirdLesson/Messenger/Messenger/Repositories/UserRepository.cs new file mode 100644 index 0000000..7e16f91 --- /dev/null +++ b/ThirdLesson/Messenger/Messenger/Repositories/UserRepository.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; + +namespace Messenger +{ + public class UserRepository : IRepository + { + Dictionary users; + + public UserRepository(Dictionary users) + { + this.users = users; + } + + public void Create(IUser user) + { + users.Add(user._id, user); + } + + public IUser Get(Guid id) + { + if (users.TryGetValue(id, out IUser user)) + { + return user; + } + throw new InvalidOperationException($"User with id {id} not found"); + } + + public void Remove(Guid id) + { + if (users.ContainsKey(id)) + { + users.Remove(id); + } + throw new InvalidOperationException($"User with id {id} already removed"); + } + + public void Save(IUser user) + { + if (users.TryGetValue(user._id, out IUser existantUser)) + { + users.Remove(user._id); + } + + users.Add(user._id, user); + } + } +} diff --git a/ThirdLesson/Messenger/MessengerTests/ChannelTest.cs b/ThirdLesson/Messenger/MessengerTests/ChannelTest.cs new file mode 100644 index 0000000..3a369a9 --- /dev/null +++ b/ThirdLesson/Messenger/MessengerTests/ChannelTest.cs @@ -0,0 +1,71 @@ +using Messenger; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; + +namespace MessengerTests +{ + [TestClass] + public class ChannelTest + { + private Channel CreateChannelWithOneAdmin() + { + Guid admin_id = Guid.Empty; + User admin = new User("admin", admin_id); + Guid channel_id = Guid.Empty; + Channel testChannel = new Channel(channel_id, "test", new Dictionary() { { admin_id, admin } }, new Dictionary() { { admin_id, admin } }, new Dictionary()); + return testChannel; + } + + [TestMethod] + public void AdminAddNewAdmin_NewAdminInAdminDictionary() + { + var admin_id = Guid.Empty; + var admin = new User("admin", admin_id); + var channel = CreateChannelWithOneAdmin(); + + var new_admin_id = Guid.NewGuid(); + var new_admin = new User("new admin", new_admin_id); + + channel.AddNewAdmin(new_admin, admin_id); + var ex_channel = new Channel(Guid.Empty, "test", new Dictionary() { { admin_id, admin }, { new_admin_id, new_admin } }, new Dictionary() { { admin_id, admin }, { new_admin_id, new_admin } }, new Dictionary()); + Assert.ReferenceEquals(channel, ex_channel); + } + + [TestMethod] + public void NotAdminAddNewAdmin_WithoutChanging() + { + var admin_id = Guid.Empty; + var admin = new User("admin", admin_id); + var channel = CreateChannelWithOneAdmin(); + var new_admin_id = Guid.NewGuid(); + var new_admin = new User("new admin", new_admin_id); + + var current_user = new User("user", Guid.NewGuid()); + + Assert.ThrowsException(() => channel.AddNewAdmin(new_admin, current_user._id)); + } + [TestMethod] + public void AdminChangeChannelName_NewChannelName() + { + var admin = new User("admin", Guid.Empty); + var channel = CreateChannelWithOneAdmin(); + + channel.ChangeName("new name", admin._id); + var ex_channel = new Channel(Guid.Empty, "new name", new Dictionary() { { admin._id, admin } }, new Dictionary() { { admin._id, admin } }, new Dictionary()); + + Assert.ReferenceEquals(channel, ex_channel); + } + [TestMethod] + public void NotAdminChangeChannelName_ReturnInvalidOperationException() + { + var admin = new User("admin", Guid.Empty); + var channel = CreateChannelWithOneAdmin(); + var current_user = new User("user", Guid.NewGuid()); + + Assert.ThrowsException(() => channel.ChangeName("new name", current_user._id)); + } + + + } +} diff --git a/ThirdLesson/Messenger/MessengerTests/ConversationTest.cs b/ThirdLesson/Messenger/MessengerTests/ConversationTest.cs new file mode 100644 index 0000000..031fdfa --- /dev/null +++ b/ThirdLesson/Messenger/MessengerTests/ConversationTest.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using Messenger; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MessengerTests +{ + [TestClass] + public class ConversationTest + { + private Conversation CreateChannelWithOneInterviewer() + { + var interviewer = new User("igor", Guid.Empty); + var testСonversation = new Conversation(new Dictionary() { { interviewer._id, interviewer } }, new Dictionary(), "test", Guid.Empty); ; + return testСonversation; + } + + + [TestMethod] + public void InterviewerChangeName_NewConversationName() + { + var interviewer = new User("igor", Guid.Empty); + var conversation = CreateChannelWithOneInterviewer(); + + conversation.ChangeName("new name", interviewer._id); + var expected_name = "new name"; + + Assert.AreEqual(conversation._name, expected_name); + } + [TestMethod] + public void NotInterviewerChangeName_Exception() + { + var not_interviewer = new User("igor", Guid.NewGuid()); + var conversation = CreateChannelWithOneInterviewer(); + + Assert.ThrowsException(() => conversation.ChangeName("new name", not_interviewer._id)); + } + + [TestMethod] + public void NotInterviewerAddingNewUser_Exception() + { + var not_interviewer = new User("igor", Guid.NewGuid()); + var adding_user = new User("ivan", Guid.NewGuid()); + var conversation = CreateChannelWithOneInterviewer(); + + Assert.ThrowsException(() => conversation.AddNewUser(adding_user, not_interviewer)); + } + [TestMethod] + public void InterviewerAddingNewUser_NewUserInConversation() + { + var interviewer = new User("igor", Guid.Empty); + var adding_user = new User("ivan", Guid.NewGuid()); + var conversation = CreateChannelWithOneInterviewer(); + var expected_conversation = new Conversation(new Dictionary() { { interviewer._id, interviewer }, { adding_user._id, adding_user} }, new Dictionary(), "test", Guid.Empty); ; + + Assert.ReferenceEquals(conversation, expected_conversation); + } + + + + + } +} diff --git a/ThirdLesson/Messenger/MessengerTests/MessengerTests.csproj b/ThirdLesson/Messenger/MessengerTests/MessengerTests.csproj new file mode 100644 index 0000000..20ca48e --- /dev/null +++ b/ThirdLesson/Messenger/MessengerTests/MessengerTests.csproj @@ -0,0 +1,76 @@ + + + + + + Debug + AnyCPU + {B890DC96-3384-4170-929B-7C6190B68520} + Library + Properties + MessengerTests + MessengerTests + v4.6.1 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 15.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages + False + UnitTest + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll + + + ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll + + + + + + + + + + + + + + + + {c9592618-8c23-44a9-a466-f62a05d0da2f} + Messenger + + + + + + + Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}. + + + + + + \ No newline at end of file diff --git a/ThirdLesson/Messenger/MessengerTests/Properties/AssemblyInfo.cs b/ThirdLesson/Messenger/MessengerTests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..36a4fe0 --- /dev/null +++ b/ThirdLesson/Messenger/MessengerTests/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("MessengerTests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MessengerTests")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: ComVisible(false)] + +[assembly: Guid("b890dc96-3384-4170-929b-7c6190b68520")] + +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ThirdLesson/Messenger/MessengerTests/WorkinWithMessageTest.cs b/ThirdLesson/Messenger/MessengerTests/WorkinWithMessageTest.cs new file mode 100644 index 0000000..49471f0 --- /dev/null +++ b/ThirdLesson/Messenger/MessengerTests/WorkinWithMessageTest.cs @@ -0,0 +1,179 @@ +using System; +using System.Collections.Generic; +using Messenger; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MessengerTests +{ + [TestClass] + public class WorkinWithMessageTest + { + private Dialogue CreateDialogue() + { + User user_1 = new User("igor", Guid.NewGuid()); + User user_2 = new User("ivan", Guid.NewGuid()); + var message = new Message("text",Guid.Empty, user_1, DateTimeOffset.MinValue); + var testDialogue = new Dialogue(Guid.Empty, user_1, user_2, new Dictionary() { { message._id, message } }); + return testDialogue; + } + private Channel CreateChannelWithOneAdmin() + { + User admin = new User("admin", Guid.Empty); + var message = new Message("text", Guid.Empty, admin, DateTimeOffset.MinValue); + Channel testChannel = new Channel(Guid.Empty, "test", new Dictionary() { { admin._id, admin } }, new Dictionary() { { admin._id, admin } }, new Dictionary() { { message._id, message } }); + return testChannel; + } + private Conversation CreateConversationWithOneInterviewer() + { + var interviewer = new User("igor", Guid.Empty); + var message = new Message("text", Guid.Empty, interviewer, DateTimeOffset.Now); + var testСonversation = new Conversation(new Dictionary() { { interviewer._id, interviewer } }, new Dictionary() { { message._id, message} }, "test", Guid.Empty); ; + return testСonversation; + } + + [TestMethod] + public void UserTryToChangeMessageAnotherUserInDialogue_Exception() + { + var dialogue = CreateDialogue(); + var new_message = "new_text"; + + Assert.ThrowsException(() => dialogue.ChangeMessage(new_message, Guid.Empty,dialogue.second_user._id )); + + + } + [TestMethod] + public void UserTryToChangeMessageAdminInChannel_Exception() + { + var admin = new User("admin", Guid.Empty); + var channel = CreateChannelWithOneAdmin(); + var current_user = new User("sasha", Guid.NewGuid()); + var new_message = "new_text"; + + Assert.ThrowsException(() => channel.ChangeMessage(new_message, Guid.Empty, current_user._id)); + + + } + [TestMethod] + public void UserTryToChangeMessageAnotherUserInConversation_Exception() + { + var interviewer = new User("igor", Guid.Empty); + var conversation = CreateConversationWithOneInterviewer(); + var current_user = new User("sasha", Guid.NewGuid()); + var new_message = "new_text"; + + Assert.ThrowsException(() => conversation.ChangeMessage(new_message, Guid.Empty, current_user._id)); + + + } + + [TestMethod] + public void UserTryToChangeOwnMessageInDialogue_ChangedMessage() + { + var dialogue = CreateDialogue(); + var new_message = new Message("new_text", Guid.Empty, dialogue.first_user, DateTimeOffset.MinValue); + + var expected_dialogue = new Dialogue(Guid.Empty,new User("igor", Guid.NewGuid()), new User("ivan", Guid.NewGuid()), new Dictionary() { { Guid.Empty, new_message } }); + + Assert.ReferenceEquals(dialogue, expected_dialogue); + + } + [TestMethod] + public void UserTryToChangeOwnMessageInСhannel_ChangedMessage() + { + var admin = new User("admin", Guid.Empty); + var channel = CreateChannelWithOneAdmin(); + var new_message = "new_text"; + channel.ChangeMessage(new_message, Guid.Empty, admin._id); + + var expected_channel = new Channel(Guid.Empty, "test", new Dictionary() { { admin._id, admin } }, new Dictionary() { { admin._id, admin } }, new Dictionary() { { Guid.Empty, new Message("new text", Guid.Empty, admin, DateTimeOffset.MinValue) } }); + + Assert.ReferenceEquals(channel, expected_channel) ; + + } + [TestMethod] + public void UserTryToChangeOwnMessageInConversation_ChangedMessage() + { + var interviewer = new User("igor", Guid.Empty); + var conversation = CreateConversationWithOneInterviewer(); + var new_message = "new_text"; + + conversation.ChangeMessage(new_message, Guid.Empty, interviewer._id); + + var expected_conversation = new Conversation(new Dictionary() { { interviewer._id, interviewer } }, new Dictionary() { { Guid.Empty, new Message(new_message, Guid.Empty, interviewer, DateTimeOffset.MinValue) } }, "test", Guid.Empty); + + + Assert.ReferenceEquals(conversation, expected_conversation); + + } + [TestMethod] + public void UserTryToRemoveMessageAnotherUserInDialogue_Exception() + { + var dialogue = CreateDialogue(); + + Assert.ThrowsException(() => dialogue.RemoveMessage(Guid.Empty, dialogue.second_user._id)); + + + } + [TestMethod] + public void UserTryToRemoveMessageAdminInChannel_Exception() + { + var admin = new User("admin", Guid.Empty); + var channel = CreateChannelWithOneAdmin(); + var current_user = new User("sasha", Guid.NewGuid()); + + Assert.ThrowsException(() => channel.RemoveMessage(Guid.Empty, current_user._id)); + + + } + [TestMethod] + public void UserTryToRemoveMessageAnotherUserInConversation_Exception() + { + var interviewer = new User("igor", Guid.Empty); + var conversation = CreateConversationWithOneInterviewer(); + var current_user = new User("sasha", Guid.NewGuid()); + + Assert.ThrowsException(() => conversation.RemoveMessage(Guid.Empty, current_user._id)); + + + } + + [TestMethod] + public void UserTryToRemoveOwnMessageInDialogue_RemovedMessage() + { + var dialogue = CreateDialogue(); + dialogue.RemoveMessage(Guid.Empty, dialogue.first_user._id); + + var expected_dialogue = new Dialogue(Guid.Empty, new User("igor", Guid.NewGuid()), new User("ivan", Guid.NewGuid()), new Dictionary()); + + Assert.ReferenceEquals(dialogue, expected_dialogue); + + } + [TestMethod] + public void AdminTryToRemoveOwnMessageInСhannel_RemovedMessage() + { + var admin = new User("admin", Guid.Empty); + var channel = CreateChannelWithOneAdmin(); + channel.RemoveMessage(Guid.Empty, admin._id); + + var expected_channel = new Channel(Guid.Empty, "test", new Dictionary() { { admin._id, admin } }, new Dictionary() { { admin._id, admin } }, new Dictionary()); + + Assert.ReferenceEquals(channel, expected_channel); + + } + [TestMethod] + public void UserTryToRemoveOwnMessageInConversation_RemovedMessage() + { + var interviewer = new User("igor", Guid.Empty); + var conversation = CreateConversationWithOneInterviewer(); + + conversation.RemoveMessage(Guid.Empty, interviewer._id); + + var expected_conversation = new Conversation(new Dictionary() { { interviewer._id, interviewer } }, new Dictionary(), "test", Guid.Empty); + + + Assert.ReferenceEquals(conversation, expected_conversation); + + } + + } +} diff --git a/ThirdLesson/Messenger/MessengerTests/packages.config b/ThirdLesson/Messenger/MessengerTests/packages.config new file mode 100644 index 0000000..102a45c --- /dev/null +++ b/ThirdLesson/Messenger/MessengerTests/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file From f60297f86d687c0b094022b2be2d562eeab2e690 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 19 Oct 2018 21:56:17 +0300 Subject: [PATCH 15/22] new tests --- ThirdLesson/Messenger/Messenger/Objects/Channel.cs | 5 +++-- .../MessengerTests/WorkinWithMessageTest.cs | 13 +++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/ThirdLesson/Messenger/Messenger/Objects/Channel.cs b/ThirdLesson/Messenger/Messenger/Objects/Channel.cs index 93138a3..b1cb612 100644 --- a/ThirdLesson/Messenger/Messenger/Objects/Channel.cs +++ b/ThirdLesson/Messenger/Messenger/Objects/Channel.cs @@ -58,12 +58,13 @@ public void ChangeMessage(string changed_message, Guid message_id, Guid user_id) public void RemoveMessage(Guid message_id, Guid user_id) { - if (followers.TryGetValue(user_id, out IUser finded_user) && messages.TryGetValue(message_id, out IMessage finded_message)) + if (followers.ContainsKey(user_id) && messages.ContainsKey(message_id)) { - if (finded_message._author == finded_user || admins.ContainsKey(user_id)) + if (admins.ContainsKey(user_id)) { messages.Remove(message_id); } + else throw new InvalidOperationException($"You are not admin"); } else throw new InvalidOperationException($"Message or user does not exist"); diff --git a/ThirdLesson/Messenger/MessengerTests/WorkinWithMessageTest.cs b/ThirdLesson/Messenger/MessengerTests/WorkinWithMessageTest.cs index 49471f0..f424738 100644 --- a/ThirdLesson/Messenger/MessengerTests/WorkinWithMessageTest.cs +++ b/ThirdLesson/Messenger/MessengerTests/WorkinWithMessageTest.cs @@ -53,6 +53,7 @@ public void UserTryToChangeMessageAdminInChannel_Exception() } + [TestMethod] public void UserTryToChangeMessageAnotherUserInConversation_Exception() { @@ -159,6 +160,18 @@ public void AdminTryToRemoveOwnMessageInСhannel_RemovedMessage() Assert.ReferenceEquals(channel, expected_channel); + } + + [TestMethod] + public void UserTryToRemoveOwnMessageInСhannel_Excaption() + { + var current_user = new User("ivan", Guid.NewGuid()); + var message = new Message("text", Guid.NewGuid(), current_user, DateTimeOffset.MinValue); + var channel = new Channel(Guid.Empty, "test", new Dictionary(), new Dictionary() { {current_user._id, current_user } }, new Dictionary() { { message._id, message } }); + + Assert.ThrowsException(() => channel.RemoveMessage( message._id, current_user._id)); + + } [TestMethod] public void UserTryToRemoveOwnMessageInConversation_RemovedMessage() From 452751237db6177d0c6c302a61ccb9018be816f5 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Tue, 30 Oct 2018 18:24:11 +0300 Subject: [PATCH 16/22] 4 lesson without tests --- ForthLesson/Leo-sprint/Leo-sprint.sln | 25 ++++ ForthLesson/Leo-sprint/Leo-sprint/App.config | 6 + .../Leo-sprint/Leo-sprint/Class/Session.cs | 133 ++++++++++++++++++ .../Leo-sprint/Leo-sprint/Class/User.cs | 65 +++++++++ .../Leo-sprint/Leo-sprint/Class/Word.cs | 40 ++++++ .../Leo-sprint/Client/UserClient.cs | 31 ++++ .../Leo-sprint/Leo-sprint/Interfaces/IUser.cs | 10 ++ .../Leo-sprint/Leo-sprint/Leo-sprint.csproj | 64 +++++++++ ForthLesson/Leo-sprint/Leo-sprint/Program.cs | 15 ++ .../Leo-sprint/Properties/AssemblyInfo.cs | 36 +++++ .../Leo-sprint/Repository/UserRepository.cs | 23 +++ .../Leo-sprint/Leo-sprint/packages.config | 4 + .../SessionTest/Properties/AssemblyInfo.cs | 20 +++ .../Leo-sprint/SessionTest/SessionTest.csproj | 68 +++++++++ .../Leo-sprint/SessionTest/packages.config | 5 + 15 files changed, 545 insertions(+) create mode 100644 ForthLesson/Leo-sprint/Leo-sprint.sln create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/App.config create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Class/Word.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Client/UserClient.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Program.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Properties/AssemblyInfo.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/packages.config create mode 100644 ForthLesson/Leo-sprint/SessionTest/Properties/AssemblyInfo.cs create mode 100644 ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj create mode 100644 ForthLesson/Leo-sprint/SessionTest/packages.config diff --git a/ForthLesson/Leo-sprint/Leo-sprint.sln b/ForthLesson/Leo-sprint/Leo-sprint.sln new file mode 100644 index 0000000..7e97485 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2036 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leo-sprint", "Leo-sprint\Leo-sprint.csproj", "{5B0D4076-11AA-4C82-B4EE-4B682297E11B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5B0D4076-11AA-4C82-B4EE-4B682297E11B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5B0D4076-11AA-4C82-B4EE-4B682297E11B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5B0D4076-11AA-4C82-B4EE-4B682297E11B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5B0D4076-11AA-4C82-B4EE-4B682297E11B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {4458E466-2C46-4ABC-8F0F-96F1AD55B334} + EndGlobalSection +EndGlobal diff --git a/ForthLesson/Leo-sprint/Leo-sprint/App.config b/ForthLesson/Leo-sprint/Leo-sprint/App.config new file mode 100644 index 0000000..731f6de --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs new file mode 100644 index 0000000..2584b25 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; + +namespace Leo_sprint +{ + public class Session + { + private Word[] _words; + private Random randomizer; + + public Session(Word[] words, Random randomizer) + { + _words = words; + this.randomizer = randomizer; + } + + public static Session Create(Word[] words) + { + Word[] words_in_tasks = new Word[words.Length]; + var random = new Random(); + for (int i = 0; i < words.Length; i++) + { + if (random.Next(1) == 0) + { + words_in_tasks[i] = GetWordWithWrongTranslation(words, i, random); + } + } + + words_in_tasks = MixedWords(words_in_tasks, random); + return new Session(words_in_tasks, random); + + + + } + public void Show() + { + var user_answers = PrintWordsAndGetAnswers(_words); + var wrong_answers = CheckAnswers(user_answers, words, _words); + ShowWhatsWrongInAnswers(wrong_answers); + } + + private static Word[] MixedWords(Word[] words_in_tasks, Random random) + { + var new_words = words_in_tasks; + Word temp; + int random_index; + for (int i = words_in_tasks.Length; i > 2; i++) + { + random_index = random.Next(i) + 1; + if (random_index != i) + { + temp = new_words[i]; + new_words[i] = new_words[random_index]; + new_words[random_index] = temp; + } + } + return new_words; + } + + private void ShowWhatsWrongInAnswers(List wrong_answers) + { + foreach(var Word in wrong_answers) + { + Console.WriteLine("You answered wrong. Right translation is"+ Word._in_russian); + } + } + + private bool[] PrintWordsAndGetAnswers(Word[] _words) + { + var size = _words.Length; + var i = 0; + var answers = new bool[size]; + while (i < size) + { + PrintQuestion(_words[i]); + ConvertAnswer(GetAnswers()); + } + return answers; + + } + + private bool ConvertAnswer(string answer) + { + switch (answer) + { + case "Да": + return true; + case "Нет": + return false; + default: + return false; + } + } + + private string GetAnswers() + { + return Console.ReadLine(); + } + + + private void PrintQuestion(Word word) + { + Console.WriteLine(word._in_english + "-" + word._in_russian + "is right?"); + } + + private List CheckAnswers(bool[] user_answers, Word[] words, Word[] words_in_question)//неправильный алгоритм + { + + var wrong_answers = new List(); + for (int i = 0; i < words.Length; i++) + { + if (words[i].Equals(words_in_question[i]) != user_answers[i]) + { + wrong_answers.Add(words[i]); + } + } + return wrong_answers; + } + + private static Word GetWordWithWrongTranslation(Word[] words, int index, Random random) + { + var first_index = index; + var second_index = random.Next(0, words.Length); + while (first_index == second_index) + { + second_index = random.Next(0, words.Length); + } + return new Word(words[first_index]._in_english, words[second_index]._in_russian, 0); + + } + + } +} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs new file mode 100644 index 0000000..bd95f03 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Leo_sprint +{ + public class User : IUser + { + public string _nickname { get; } + public Guid _id { get; } + + private List learned_words; + private List words_in_process; + + public Session StartSession() + { + return Session.Create(words_in_process.ToArray()); + } + public void AddNewWordInDictionary(Word word) + { + if (!learned_words.Contains(word)) + { + words_in_process.Add(word); + } + + } + public IEnumerable ShowWordInProgress() + { + return words_in_process.AsEnumerable(); + } + public IEnumerable ShowLearnedWord() + { + return learned_words.AsEnumerable(); + } + + public List CheckAnswers(bool[] user_answers, Word[] words_in_question)//неправильный алгоритм + { + var answers = new Dictionary(); + for (int i=0;i(); + + foreach (var word in words_in_process) + { + if (!answers.ContainsKey(word)) + { + var checked_word = answers.Single(s => s.Key._in_english==word._in_english).Key; + if (answers[checked_word]==true) + { + wrong_answers.Add(word); + } + } + if (answers.ContainsKey(word) && answers[word] == false) + { + wrong_answers.Add(word); + } + + } + return wrong_answers; + } + + } +} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/Word.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/Word.cs new file mode 100644 index 0000000..d1a3919 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/Word.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leo_sprint +{ + public class Word + { + public string _in_english { get; } + public string _in_russian { get; } + + public Word(string in_english, string in_russian, int flag) + { + _in_english = in_english; + _in_russian = in_russian; + _flag = flag; + } + + public int _flag { private set; get; } + + public override bool Equals(object obj) + { + var word = obj as Word; + return word != null && + _in_english == word._in_english && + _in_russian == word._in_russian; + } + + public override int GetHashCode() + { + var hashCode = -1432052003; + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_in_english); + hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(_in_russian); + hashCode = hashCode * -1521134295 + _flag.GetHashCode(); + return hashCode; + } + } +} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Client/UserClient.cs b/ForthLesson/Leo-sprint/Leo-sprint/Client/UserClient.cs new file mode 100644 index 0000000..f1cb6a8 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Client/UserClient.cs @@ -0,0 +1,31 @@ +using System; + +namespace Leo_sprint.Client +{ + public class UserClient + { + private User this_user; + + public void StartSession() + { + var this_session = this_user.StartSession(); + this_session.Show(this_user); + } + + public void AddNewWordInDictionary(Word new_word) + { + this_user.AddNewWordInDictionary(new_word); + } + public void PrintWordInProcess() + { + var words_in_process = this_user.ShowWordInProgress(); + foreach (var word in words_in_process) + { + Console.WriteLine(word._in_english + "-" + word._in_russian); + } + } + + + + } +} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs b/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs new file mode 100644 index 0000000..aa3dd95 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs @@ -0,0 +1,10 @@ +using System; + +namespace Leo_sprint +{ + public interface IUser + { + Guid _id { get; } + string _nickname { get; } + } +} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj b/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj new file mode 100644 index 0000000..048e923 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj @@ -0,0 +1,64 @@ + + + + + Debug + AnyCPU + {5B0D4076-11AA-4C82-B4EE-4B682297E11B} + Exe + Leo_sprint + Leo-sprint + v4.6.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Program.cs b/ForthLesson/Leo-sprint/Leo-sprint/Program.cs new file mode 100644 index 0000000..260c51d --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Program.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leo_sprint +{ + class Program + { + static void Main(string[] args) + { + } + } +} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Properties/AssemblyInfo.cs b/ForthLesson/Leo-sprint/Leo-sprint/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e3e3b62 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Общие сведения об этой сборке предоставляются следующим набором +// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, +// связанные со сборкой. +[assembly: AssemblyTitle("Leo-sprint")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leo-sprint")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми +// для компонентов COM. Если необходимо обратиться к типу в этой сборке через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(false)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("5b0d4076-11aa-4c82-b4ee-4b682297e11b")] + +// Сведения о версии сборки состоят из следующих четырех значений: +// +// Основной номер версии +// Дополнительный номер версии +// Номер сборки +// Редакция +// +// Можно задать все значения или принять номер сборки и номер редакции по умолчанию. +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs b/ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs new file mode 100644 index 0000000..994304d --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs @@ -0,0 +1,23 @@ +using Newtonsoft.Json; +using System; +using System.IO; + +namespace Leo_sprint +{ + public class UserRepository + { + public void Create(Guid id) + { + File.Create(id.ToString() + ".txt"); + } + public void Update(User user) + { + File.WriteAllText(user._id.ToString() + ".txt", JsonConvert.SerializeObject(user)); + } + public IUser Get(Guid id)//Authentication + { + var json = File.ReadAllText(id.ToString() + ".txt"); + return JsonConvert.DeserializeObject(json); + } + } +} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/packages.config b/ForthLesson/Leo-sprint/Leo-sprint/packages.config new file mode 100644 index 0000000..5762754 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/ForthLesson/Leo-sprint/SessionTest/Properties/AssemblyInfo.cs b/ForthLesson/Leo-sprint/SessionTest/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0962139 --- /dev/null +++ b/ForthLesson/Leo-sprint/SessionTest/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("SessionTest")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SessionTest")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: ComVisible(false)] + +[assembly: Guid("bdf09280-e31f-451d-9eeb-8782872acf44")] + +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj b/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj new file mode 100644 index 0000000..615ce4e --- /dev/null +++ b/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj @@ -0,0 +1,68 @@ + + + + + + Debug + AnyCPU + {BDF09280-E31F-451D-9EEB-8782872ACF44} + Library + Properties + SessionTest + SessionTest + v4.6.1 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 15.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages + False + UnitTest + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll + + + ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll + + + + + + + + + + + + + + + + Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}. + + + + + + \ No newline at end of file diff --git a/ForthLesson/Leo-sprint/SessionTest/packages.config b/ForthLesson/Leo-sprint/SessionTest/packages.config new file mode 100644 index 0000000..102a45c --- /dev/null +++ b/ForthLesson/Leo-sprint/SessionTest/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file From 9b0badbdaadc1c3f6930b2565743c17f6962126f Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Tue, 30 Oct 2018 18:39:16 +0300 Subject: [PATCH 17/22] first test added --- ForthLesson/Leo-sprint/Leo-sprint.sln | 6 +++++ .../Leo-sprint/Leo-sprint/Class/Session.cs | 27 +++++-------------- .../Leo-sprint/Leo-sprint/Class/User.cs | 8 ++++++ .../Leo-sprint/SessionTest/SessionTest.csproj | 8 +++++- .../Leo-sprint/SessionTest/UserTest.cs | 23 ++++++++++++++++ 5 files changed, 50 insertions(+), 22 deletions(-) create mode 100644 ForthLesson/Leo-sprint/SessionTest/UserTest.cs diff --git a/ForthLesson/Leo-sprint/Leo-sprint.sln b/ForthLesson/Leo-sprint/Leo-sprint.sln index 7e97485..2f745ec 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint.sln +++ b/ForthLesson/Leo-sprint/Leo-sprint.sln @@ -5,6 +5,8 @@ VisualStudioVersion = 15.0.28010.2036 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leo-sprint", "Leo-sprint\Leo-sprint.csproj", "{5B0D4076-11AA-4C82-B4EE-4B682297E11B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SessionTest", "SessionTest\SessionTest.csproj", "{BDF09280-E31F-451D-9EEB-8782872ACF44}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +17,10 @@ Global {5B0D4076-11AA-4C82-B4EE-4B682297E11B}.Debug|Any CPU.Build.0 = Debug|Any CPU {5B0D4076-11AA-4C82-B4EE-4B682297E11B}.Release|Any CPU.ActiveCfg = Release|Any CPU {5B0D4076-11AA-4C82-B4EE-4B682297E11B}.Release|Any CPU.Build.0 = Release|Any CPU + {BDF09280-E31F-451D-9EEB-8782872ACF44}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BDF09280-E31F-451D-9EEB-8782872ACF44}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BDF09280-E31F-451D-9EEB-8782872ACF44}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BDF09280-E31F-451D-9EEB-8782872ACF44}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs index 2584b25..9295637 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs @@ -32,10 +32,10 @@ public static Session Create(Word[] words) } - public void Show() + public void Show(User user) { var user_answers = PrintWordsAndGetAnswers(_words); - var wrong_answers = CheckAnswers(user_answers, words, _words); + var wrong_answers = user.CheckAnswers(user_answers, _words); ShowWhatsWrongInAnswers(wrong_answers); } @@ -59,21 +59,20 @@ private static Word[] MixedWords(Word[] words_in_tasks, Random random) private void ShowWhatsWrongInAnswers(List wrong_answers) { - foreach(var Word in wrong_answers) + foreach (var Word in wrong_answers) { - Console.WriteLine("You answered wrong. Right translation is"+ Word._in_russian); + Console.WriteLine("You answered wrong. Right translation is" + Word._in_russian); } } private bool[] PrintWordsAndGetAnswers(Word[] _words) { var size = _words.Length; - var i = 0; var answers = new bool[size]; - while (i < size) + for (int i = 0; i < size; i++) { PrintQuestion(_words[i]); - ConvertAnswer(GetAnswers()); + answers[i] = ConvertAnswer(GetAnswers()); } return answers; @@ -103,20 +102,6 @@ private void PrintQuestion(Word word) Console.WriteLine(word._in_english + "-" + word._in_russian + "is right?"); } - private List CheckAnswers(bool[] user_answers, Word[] words, Word[] words_in_question)//неправильный алгоритм - { - - var wrong_answers = new List(); - for (int i = 0; i < words.Length; i++) - { - if (words[i].Equals(words_in_question[i]) != user_answers[i]) - { - wrong_answers.Add(words[i]); - } - } - return wrong_answers; - } - private static Word GetWordWithWrongTranslation(Word[] words, int index, Random random) { var first_index = index; diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs index bd95f03..ae706c0 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs @@ -12,6 +12,14 @@ public class User : IUser private List learned_words; private List words_in_process; + public User(string nickname, Guid id, List learned_words, List words_in_process) + { + _nickname = nickname; + _id = id; + this.learned_words = learned_words; + this.words_in_process = words_in_process; + } + public Session StartSession() { return Session.Create(words_in_process.ToArray()); diff --git a/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj b/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj index 615ce4e..6a73d60 100644 --- a/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj +++ b/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj @@ -49,12 +49,18 @@ - + + + + {5b0d4076-11aa-4c82-b4ee-4b682297e11b} + Leo-sprint + + diff --git a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs new file mode 100644 index 0000000..b020541 --- /dev/null +++ b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using Leo_sprint; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace SessionTest +{ + [TestClass] + public class UserTest + { + [TestMethod] + public void CheckRightAnswers_GetEmptyListOfWords() + { + var words_in_process = new List { new Word("eng", "rus", 0), new Word("eng1", "rus1", 0) }; + var test_user = new User(string.Empty, Guid.Empty, new List(),words_in_process ); + var answers = new bool[] { true, true }; + + var list = test_user.CheckAnswers(answers, words_in_process.ToArray()); + var expected_list = new List(); + CollectionAssert.ReferenceEquals(list, expected_list); + } + } +} From 35d9d6df6ed54217314c4314af02a98558f6a535 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Tue, 30 Oct 2018 18:41:14 +0300 Subject: [PATCH 18/22] second test --- ForthLesson/Leo-sprint/SessionTest/UserTest.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs index b020541..f45ef0a 100644 --- a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs +++ b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs @@ -19,5 +19,17 @@ public void CheckRightAnswers_GetEmptyListOfWords() var expected_list = new List(); CollectionAssert.ReferenceEquals(list, expected_list); } + [TestMethod] + public void CheckRightAnswersWithOneWrongAnswer_GetListWithOneWord() + { + var words_in_process = new List { new Word("eng", "rus", 0), new Word("eng1", "rus1", 0) }; + var test_words = new List { new Word("eng", "rus", 0), new Word("eng1", "rus2", 0) }; + var test_user = new User(string.Empty, Guid.Empty, new List(), words_in_process); + var answers = new bool[] { true, true }; + + var list = test_user.CheckAnswers(answers, words_in_process.ToArray()); + var expected_list = new List { new Word("eng1", "rus1", 0) }; + CollectionAssert.ReferenceEquals(list, expected_list); + } } } From 90d9aeedd5252336b45836e98907605eedaa1754 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Tue, 30 Oct 2018 18:43:47 +0300 Subject: [PATCH 19/22] third test --- ForthLesson/Leo-sprint/SessionTest/UserTest.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs index f45ef0a..d0eee61 100644 --- a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs +++ b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs @@ -31,5 +31,17 @@ public void CheckRightAnswersWithOneWrongAnswer_GetListWithOneWord() var expected_list = new List { new Word("eng1", "rus1", 0) }; CollectionAssert.ReferenceEquals(list, expected_list); } + [TestMethod] + public void SecondCheckRightAnswers_GetEmptyListOfWords() + { + var words_in_process = new List { new Word("eng", "rus", 0), new Word("eng1", "rus1", 0) }; + var test_words = new List { new Word("eng", "rus", 0), new Word("eng1", "rus2", 0) }; + var test_user = new User(string.Empty, Guid.Empty, new List(), words_in_process); + var answers = new bool[] { true, false }; + + var list = test_user.CheckAnswers(answers, words_in_process.ToArray()); + var expected_list = new List (); + CollectionAssert.ReferenceEquals(list, expected_list); + } } } From d6dd02faf841757fdbf704fd61556447d277659c Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Tue, 30 Oct 2018 18:45:11 +0300 Subject: [PATCH 20/22] forth test --- ForthLesson/Leo-sprint/SessionTest/UserTest.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs index d0eee61..84e7781 100644 --- a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs +++ b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs @@ -43,5 +43,17 @@ public void SecondCheckRightAnswers_GetEmptyListOfWords() var expected_list = new List (); CollectionAssert.ReferenceEquals(list, expected_list); } + [TestMethod] + public void SecondCheckRightAnswersWithOneWrongAnswer_GetListWithOneWord() + { + var words_in_process = new List { new Word("eng", "rus", 0), new Word("eng1", "rus1", 0) }; + var test_words = new List { new Word("eng", "rus", 0), new Word("eng1", "rus2", 0) }; + var test_user = new User(string.Empty, Guid.Empty, new List(), words_in_process); + var answers = new bool[] { false, false }; + + var list = test_user.CheckAnswers(answers, words_in_process.ToArray()); + var expected_list = new List { new Word("eng", "rus", 0) }; + CollectionAssert.ReferenceEquals(list, expected_list); + } } } From cd020b0e4a5858466f36d2b6b01065e52baa0934 Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 2 Nov 2018 22:36:55 +0300 Subject: [PATCH 21/22] Backend --- ForthLesson/Leo-sprint/Leo-sprint.sln | 6 ++ .../Leo-sprint/Leo-sprint/Class/Session.cs | 59 +++----------- .../Leo-sprint/Leo-sprint/Class/User.cs | 56 +++++++++---- .../Leo-sprint/Leo-sprint/Class/Word.cs | 5 ++ .../Leo-sprint/Client/UserClient.cs | 31 -------- .../Leo-sprint/Leo-sprint/Interfaces/IUser.cs | 4 + .../Leo-sprint/Leo-sprint/Leo-sprint.csproj | 1 - ForthLesson/Leo-sprint/Leo-sprint/Program.cs | 12 ++- .../Leo-sprint/Repository/UserRepository.cs | 39 ++++++++-- .../Leo-sprint/SessionTest/SessionTest.csproj | 3 + .../Leo-sprint/SessionTest/UserTest.cs | 1 + .../Leo-sprint/SessionTest/packages.config | 1 + .../Controllers/UserController.cs | 78 +++++++++++++++++++ .../Controllers/ValuesController.cs | 45 +++++++++++ .../WebApplication1/Leo-sprintAPI.csproj | 26 +++++++ .../WebApplication1/Models/UserModel.cs | 20 +++++ .../Leo-sprint/WebApplication1/Program.cs | 25 ++++++ .../Properties/launchSettings.json | 29 +++++++ .../Leo-sprint/WebApplication1/Startup.cs | 50 ++++++++++++ .../appsettings.Development.json | 10 +++ .../WebApplication1/appsettings.json | 15 ++++ 21 files changed, 411 insertions(+), 105 deletions(-) delete mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Client/UserClient.cs create mode 100644 ForthLesson/Leo-sprint/WebApplication1/Controllers/UserController.cs create mode 100644 ForthLesson/Leo-sprint/WebApplication1/Controllers/ValuesController.cs create mode 100644 ForthLesson/Leo-sprint/WebApplication1/Leo-sprintAPI.csproj create mode 100644 ForthLesson/Leo-sprint/WebApplication1/Models/UserModel.cs create mode 100644 ForthLesson/Leo-sprint/WebApplication1/Program.cs create mode 100644 ForthLesson/Leo-sprint/WebApplication1/Properties/launchSettings.json create mode 100644 ForthLesson/Leo-sprint/WebApplication1/Startup.cs create mode 100644 ForthLesson/Leo-sprint/WebApplication1/appsettings.Development.json create mode 100644 ForthLesson/Leo-sprint/WebApplication1/appsettings.json diff --git a/ForthLesson/Leo-sprint/Leo-sprint.sln b/ForthLesson/Leo-sprint/Leo-sprint.sln index 2f745ec..c9af128 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint.sln +++ b/ForthLesson/Leo-sprint/Leo-sprint.sln @@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leo-sprint", "Leo-sprint\Le EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SessionTest", "SessionTest\SessionTest.csproj", "{BDF09280-E31F-451D-9EEB-8782872ACF44}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leo-sprintAPI", "WebApplication1\Leo-sprintAPI.csproj", "{09F18761-E54A-45D1-B3AA-134404CC581A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -21,6 +23,10 @@ Global {BDF09280-E31F-451D-9EEB-8782872ACF44}.Debug|Any CPU.Build.0 = Debug|Any CPU {BDF09280-E31F-451D-9EEB-8782872ACF44}.Release|Any CPU.ActiveCfg = Release|Any CPU {BDF09280-E31F-451D-9EEB-8782872ACF44}.Release|Any CPU.Build.0 = Release|Any CPU + {09F18761-E54A-45D1-B3AA-134404CC581A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {09F18761-E54A-45D1-B3AA-134404CC581A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {09F18761-E54A-45D1-B3AA-134404CC581A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {09F18761-E54A-45D1-B3AA-134404CC581A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs index 9295637..2983b67 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs @@ -20,7 +20,7 @@ public static Session Create(Word[] words) var random = new Random(); for (int i = 0; i < words.Length; i++) { - if (random.Next(1) == 0) + if (random.Next(2) == 1) { words_in_tasks[i] = GetWordWithWrongTranslation(words, i, random); } @@ -28,16 +28,7 @@ public static Session Create(Word[] words) words_in_tasks = MixedWords(words_in_tasks, random); return new Session(words_in_tasks, random); - - - - } - public void Show(User user) - { - var user_answers = PrintWordsAndGetAnswers(_words); - var wrong_answers = user.CheckAnswers(user_answers, _words); - ShowWhatsWrongInAnswers(wrong_answers); - } + } private static Word[] MixedWords(Word[] words_in_tasks, Random random) { @@ -56,50 +47,24 @@ private static Word[] MixedWords(Word[] words_in_tasks, Random random) } return new_words; } - - private void ShowWhatsWrongInAnswers(List wrong_answers) - { - foreach (var Word in wrong_answers) - { - Console.WriteLine("You answered wrong. Right translation is" + Word._in_russian); - } - } - - private bool[] PrintWordsAndGetAnswers(Word[] _words) + public IEnumerable ShowTask() { - var size = _words.Length; - var answers = new bool[size]; - for (int i = 0; i < size; i++) + var task = new List(); + foreach (var word in _words) { - PrintQuestion(_words[i]); - answers[i] = ConvertAnswer(GetAnswers()); + task.Add(word._in_english + "-" + word._in_russian); } - return answers; - + return task; } - private bool ConvertAnswer(string answer) + public string ShowWhatsWrongInAnswers(List wrong_answers) { - switch (answer) + var words = $"You answered wrong. Right translations are\n"; + foreach (var Word in wrong_answers) { - case "Да": - return true; - case "Нет": - return false; - default: - return false; + words += Word._in_russian + "\n" ; } - } - - private string GetAnswers() - { - return Console.ReadLine(); - } - - - private void PrintQuestion(Word word) - { - Console.WriteLine(word._in_english + "-" + word._in_russian + "is right?"); + return words; } private static Word GetWordWithWrongTranslation(Word[] words, int index, Random random) diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs index ae706c0..99940ac 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs @@ -30,21 +30,29 @@ public void AddNewWordInDictionary(Word word) { words_in_process.Add(word); } - + + } + public void RemoveWordFromDictionary(Word word) + { + if (!learned_words.Contains(word)) + { + words_in_process.Remove(word); + } + } - public IEnumerable ShowWordInProgress() - { - return words_in_process.AsEnumerable(); - } - public IEnumerable ShowLearnedWord() - { - return learned_words.AsEnumerable(); - } - - public List CheckAnswers(bool[] user_answers, Word[] words_in_question)//неправильный алгоритм + public IEnumerable ShowWordInProgress() + { + return words_in_process.AsEnumerable(); + } + public IEnumerable ShowLearnedWord() + { + return learned_words.AsEnumerable(); + } + + public List CheckAnswers(bool[] user_answers, Word[] words_in_question) { var answers = new Dictionary(); - for (int i=0;i CheckAnswers(bool[] user_answers, Word[] words_in_question)// { if (!answers.ContainsKey(word)) { - var checked_word = answers.Single(s => s.Key._in_english==word._in_english).Key; - if (answers[checked_word]==true) + var checked_word = answers.Single(s => s.Key._in_english == word._in_english).Key; + if (answers[checked_word] == true) { wrong_answers.Add(word); } } - if (answers.ContainsKey(word) && answers[word] == false) + else if (answers.ContainsKey(word) && answers[word] == false) { wrong_answers.Add(word); } + else FlagGrowsOnePoint(word); } return wrong_answers; } + private void FlagGrowsOnePoint(Word word) + { + var new_word = new Word(word._in_english,word._in_russian,word._flag+1); + words_in_process.Remove(word); + if (!IsWordLearned(new_word)) + { + words_in_process.Add(new_word); + } + else + learned_words.Add(new_word); + } + + private bool IsWordLearned(Word new_word) + { + if (new_word._flag < 3) return false; + return true; + } } } diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/Word.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/Word.cs index d1a3919..a26d624 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Class/Word.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/Word.cs @@ -36,5 +36,10 @@ public override int GetHashCode() hashCode = hashCode * -1521134295 + _flag.GetHashCode(); return hashCode; } + + private void FlagGrowsOnePoint() + { + _flag++; + } } } diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Client/UserClient.cs b/ForthLesson/Leo-sprint/Leo-sprint/Client/UserClient.cs deleted file mode 100644 index f1cb6a8..0000000 --- a/ForthLesson/Leo-sprint/Leo-sprint/Client/UserClient.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; - -namespace Leo_sprint.Client -{ - public class UserClient - { - private User this_user; - - public void StartSession() - { - var this_session = this_user.StartSession(); - this_session.Show(this_user); - } - - public void AddNewWordInDictionary(Word new_word) - { - this_user.AddNewWordInDictionary(new_word); - } - public void PrintWordInProcess() - { - var words_in_process = this_user.ShowWordInProgress(); - foreach (var word in words_in_process) - { - Console.WriteLine(word._in_english + "-" + word._in_russian); - } - } - - - - } -} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs b/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs index aa3dd95..c62518f 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; namespace Leo_sprint { @@ -6,5 +7,8 @@ public interface IUser { Guid _id { get; } string _nickname { get; } + void AddNewWordInDictionary(Word word); + IEnumerable ShowWordInProgress(); + IEnumerable ShowLearnedWord(); } } diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj b/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj index 048e923..360a7f4 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj +++ b/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj @@ -49,7 +49,6 @@ - diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Program.cs b/ForthLesson/Leo-sprint/Leo-sprint/Program.cs index 260c51d..9033cf7 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Program.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Program.cs @@ -1,8 +1,7 @@ -using System; +using Newtonsoft.Json; +using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.IO; namespace Leo_sprint { @@ -10,6 +9,11 @@ class Program { static void Main(string[] args) { + var user = new User("sss", Guid.NewGuid(), new List(), new List()); + var a = JsonConvert.SerializeObject(user); + UserRepository.Create("foo"); + File.WriteAllLines("C:\\Users\\Татьяна\\Desktop\\i.txt", UserRepository.GetAllUsers()); + } } } diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs b/ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs index 994304d..d801826 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs @@ -1,23 +1,48 @@ using Newtonsoft.Json; using System; +using System.Collections.Generic; using System.IO; + namespace Leo_sprint { public class UserRepository { - public void Create(Guid id) + + public static IEnumerable GetAllUsers() { - File.Create(id.ToString() + ".txt"); + var json_users = new List(); + string[] users_paths; + if (File.Exists("users.txt")) + { + users_paths = File.ReadAllLines("users.txt"); + foreach (var path in users_paths) + { + var json = File.ReadAllText(path); + json_users.Add(json); + } + } + return json_users; + } - public void Update(User user) + + public static Guid Create(string nickname) { - File.WriteAllText(user._id.ToString() + ".txt", JsonConvert.SerializeObject(user)); + var id = Guid.NewGuid(); + var new_user = new User(nickname, id, new List(), new List()); + File.AppendAllText("users.txt", id.ToString() + ".txt\n"); + File.WriteAllText(new_user._id.ToString() + ".txt", JsonConvert.SerializeObject(new_user)); + return id; } - public IUser Get(Guid id)//Authentication + public static void Update(User user) { - var json = File.ReadAllText(id.ToString() + ".txt"); - return JsonConvert.DeserializeObject(json); + File.AppendAllText(user._id.ToString() + ".txt", JsonConvert.SerializeObject(user)); + } + + public static string GetJson(Guid id) + { + return File.ReadAllText(id.ToString() + ".txt"); + } } } diff --git a/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj b/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj index 6a73d60..835aca9 100644 --- a/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj +++ b/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj @@ -45,6 +45,9 @@ ..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll + + ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll + diff --git a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs index 84e7781..f916f9b 100644 --- a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs +++ b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs @@ -55,5 +55,6 @@ public void SecondCheckRightAnswersWithOneWrongAnswer_GetListWithOneWord() var expected_list = new List { new Word("eng", "rus", 0) }; CollectionAssert.ReferenceEquals(list, expected_list); } + } } diff --git a/ForthLesson/Leo-sprint/SessionTest/packages.config b/ForthLesson/Leo-sprint/SessionTest/packages.config index 102a45c..398c675 100644 --- a/ForthLesson/Leo-sprint/SessionTest/packages.config +++ b/ForthLesson/Leo-sprint/SessionTest/packages.config @@ -2,4 +2,5 @@ + \ No newline at end of file diff --git a/ForthLesson/Leo-sprint/WebApplication1/Controllers/UserController.cs b/ForthLesson/Leo-sprint/WebApplication1/Controllers/UserController.cs new file mode 100644 index 0000000..0715599 --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/Controllers/UserController.cs @@ -0,0 +1,78 @@ +using Leo_sprint; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; + +namespace Leo_sprintAPI.Controllers +{ + public class UsersController : Controller + { + + [HttpGet] + [Route("users/{id}")] + public string GetUserById(Guid id) + { + return UserRepository.GetJson(id); + } + [HttpGet] + [Route("users")] + public IEnumerable GetUsers(Guid id) + { + return UserRepository.GetAllUsers(); + } + [HttpGet] + [Route("users/{id}/word_in_process")] + public IEnumerable GetUsersWordsInProcess(Guid id) + { + var words = new List(); + var userPub = JsonConvert.DeserializeObject(UserRepository.GetJson(id)); + foreach (var word in userPub.words_in_process) + { + words.Add(word._in_english + "-" + word._in_russian); + } + return words; + } + [HttpGet] + [Route("users/{id}/learned_words")] + public IEnumerable GetUsersLearnedWords(Guid id) + { + var words = new List(); + var user = JsonConvert.DeserializeObject(UserRepository.GetJson(id)); + foreach (var word in user.learned_words) + { + words.Add(word._in_english + "-" + word._in_russian); + } + return words; + } + [HttpPost] + [Route("users")] + public string CreateUser([FromBody]string nickname) + { + var id = UserRepository.Create(nickname); + return $"User witn nickname {nickname} created with id {id}"; + } + [HttpPost] + [Route("users/{id}/word_in_process")] + public string AddWordToUsersWordsInProcess(Guid id, [FromBody] string in_english, [FromBody] string in_russian) + { + var userPub = JsonConvert.DeserializeObject(UserRepository.GetJson(id)); + var user = new User(userPub._nickname, userPub._id, userPub.learned_words, userPub.words_in_process); + user.AddNewWordInDictionary(new Word(in_english, in_russian, 0)); + return $"Word added"; + } + [HttpDelete] + [Route("users/{id}/word_in_process")] + public string RemoveWordFromDictionary(Guid id, [FromBody] string in_english, [FromBody] string in_russian) + { + var userPub = JsonConvert.DeserializeObject(UserRepository.GetJson(id)); + var user = new User(userPub._nickname, userPub._id, userPub.learned_words, userPub.words_in_process); + user.RemoveWordFromDictionary(new Word(in_english, in_russian, 0)); + return $"Word removed"; + } + + + + + } +} \ No newline at end of file diff --git a/ForthLesson/Leo-sprint/WebApplication1/Controllers/ValuesController.cs b/ForthLesson/Leo-sprint/WebApplication1/Controllers/ValuesController.cs new file mode 100644 index 0000000..84b486a --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/Controllers/ValuesController.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; + +namespace WebApplication1.Controllers +{ + [Route("api/[controller]")] + //http://localhost:50464/api/values + public class ValuesController : Controller + { + // GET api/values + [HttpGet] + public IEnumerable Get() + { + return new string[] { "value1", "value2" }; + } + + // GET api/values/5 + [HttpGet("{id}")] + public string Get(int id) + { + return "value"; + } + + // POST api/values + [HttpPost] + public void Post([FromBody]string value) + { + } + + // PUT api/values/5 + [HttpPut("{id}")] + public void Put(int id, [FromBody]string value) + { + } + + // DELETE api/values/5 + [HttpDelete("{id}")] + public void Delete(int id) + { + } + } +} diff --git a/ForthLesson/Leo-sprint/WebApplication1/Leo-sprintAPI.csproj b/ForthLesson/Leo-sprint/WebApplication1/Leo-sprintAPI.csproj new file mode 100644 index 0000000..f64aa4f --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/Leo-sprintAPI.csproj @@ -0,0 +1,26 @@ + + + + netcoreapp2.0 + + + + + + + + + + + + + + + + + + + + + + diff --git a/ForthLesson/Leo-sprint/WebApplication1/Models/UserModel.cs b/ForthLesson/Leo-sprint/WebApplication1/Models/UserModel.cs new file mode 100644 index 0000000..a04447d --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/Models/UserModel.cs @@ -0,0 +1,20 @@ +using Leo_sprint; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace Leo_sprintAPI +{ + public class UserModel + { + [Required] + [StringLength(50, MinimumLength = 8)] + public string _nickname { get; set; } + [Required] + public Guid _id { get; set; } + [Required] + public List words_in_process { get; set; } + [Required] + public List learned_words { get; set; } + } +} diff --git a/ForthLesson/Leo-sprint/WebApplication1/Program.cs b/ForthLesson/Leo-sprint/WebApplication1/Program.cs new file mode 100644 index 0000000..bdce207 --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/Program.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; + +namespace WebApplication1 +{ + public class Program + { + public static void Main(string[] args) + { + BuildWebHost(args).Run(); + } + + public static IWebHost BuildWebHost(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup() + .Build(); + } +} diff --git a/ForthLesson/Leo-sprint/WebApplication1/Properties/launchSettings.json b/ForthLesson/Leo-sprint/WebApplication1/Properties/launchSettings.json new file mode 100644 index 0000000..d27a5ee --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:50464/", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "api/values", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "WebApplication1": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "api/values", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:50465/" + } + } +} diff --git a/ForthLesson/Leo-sprint/WebApplication1/Startup.cs b/ForthLesson/Leo-sprint/WebApplication1/Startup.cs new file mode 100644 index 0000000..e26b8ac --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/Startup.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Swashbuckle.AspNetCore.Swagger; + +namespace WebApplication1 +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddMvc(); + services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", new Info { Title = "", Version = "v1" }); + }); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IHostingEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + app.UseSwagger(); + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "Leo-sprintAPI V1"); + }); + + app.UseMvc(); + } + } +} diff --git a/ForthLesson/Leo-sprint/WebApplication1/appsettings.Development.json b/ForthLesson/Leo-sprint/WebApplication1/appsettings.Development.json new file mode 100644 index 0000000..fa8ce71 --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/appsettings.Development.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "IncludeScopes": false, + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} diff --git a/ForthLesson/Leo-sprint/WebApplication1/appsettings.json b/ForthLesson/Leo-sprint/WebApplication1/appsettings.json new file mode 100644 index 0000000..26bb0ac --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/appsettings.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "IncludeScopes": false, + "Debug": { + "LogLevel": { + "Default": "Warning" + } + }, + "Console": { + "LogLevel": { + "Default": "Warning" + } + } + } +} From 847e13c5414e222047938d56e9fcb44f1f334bae Mon Sep 17 00:00:00 2001 From: LavanderSea Date: Fri, 9 Nov 2018 18:40:07 +0300 Subject: [PATCH 22/22] hometask backend --- ForthLesson/Leo-sprint/Leo-sprint.sln | 2 +- .../Leo-sprint/Leo-sprint/Class/Session.cs | 62 +++++----- .../Leo-sprint/Leo-sprint/Class/User.cs | 84 +++++++++---- .../Leo-sprint/Leo-sprint/Class/UserPub.cs | 58 +++++++++ .../Leo-sprint/Leo-sprint/Interfaces/IUser.cs | 3 - .../Leo-sprint/Leo-sprint/Leo-sprint.csproj | 23 +++- ForthLesson/Leo-sprint/Leo-sprint/Program.cs | 12 +- .../Leo-sprint/Repository/IUserRepository.cs | 12 ++ .../Repository/MongoUserRepository.cs | 53 ++++++++ .../Leo-sprint/Repository/UserRepository.cs | 48 -------- .../Leo-sprint/Leo-sprint/SessionClient.cs | 35 ++++++ .../Leo-sprint/Leo-sprint/packages.config | 7 ++ .../Leo-sprint/SessionTest/SessionTest.cs | 41 +++++++ .../Leo-sprint/SessionTest/SessionTest.csproj | 1 + .../Leo-sprint/SessionTest/UserTest.cs | 54 +++++++-- .../Controllers/UserController.cs | 113 +++++++++++------- .../WebApplication1/Leo-sprintAPI.csproj | 2 + .../WebApplication1/Models/AnswerModel.cs | 14 +++ .../Models/{UserModel.cs => NicknameModel.cs} | 14 +-- .../WebApplication1/Models/WordModel.cs | 17 +++ .../Leo-sprint/WebApplication1/Startup.cs | 10 +- .../appsettings.Development.json | 9 +- .../WebApplication1/appsettings.json | 16 +-- 23 files changed, 480 insertions(+), 210 deletions(-) create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Class/UserPub.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Repository/IUserRepository.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Repository/MongoUserRepository.cs delete mode 100644 ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs create mode 100644 ForthLesson/Leo-sprint/Leo-sprint/SessionClient.cs create mode 100644 ForthLesson/Leo-sprint/SessionTest/SessionTest.cs create mode 100644 ForthLesson/Leo-sprint/WebApplication1/Models/AnswerModel.cs rename ForthLesson/Leo-sprint/WebApplication1/Models/{UserModel.cs => NicknameModel.cs} (53%) create mode 100644 ForthLesson/Leo-sprint/WebApplication1/Models/WordModel.cs diff --git a/ForthLesson/Leo-sprint/Leo-sprint.sln b/ForthLesson/Leo-sprint/Leo-sprint.sln index c9af128..20308ea 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint.sln +++ b/ForthLesson/Leo-sprint/Leo-sprint.sln @@ -7,7 +7,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leo-sprint", "Leo-sprint\Le EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SessionTest", "SessionTest\SessionTest.csproj", "{BDF09280-E31F-451D-9EEB-8782872ACF44}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leo-sprintAPI", "WebApplication1\Leo-sprintAPI.csproj", "{09F18761-E54A-45D1-B3AA-134404CC581A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LEO-sprintAPI", "WebApplication1\LEO-sprintAPI.csproj", "{09F18761-E54A-45D1-B3AA-134404CC581A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs index 2983b67..49df2ef 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/Session.cs @@ -1,43 +1,47 @@ using System; using System.Collections.Generic; +using System.Linq; namespace Leo_sprint { public class Session { - private Word[] _words; + private Word[] words; private Random randomizer; + private bool[] answers; + public Guid _id { get; } - public Session(Word[] words, Random randomizer) + public Session(Word[] words, Random randomizer, Guid id) { - _words = words; + this.words = words; this.randomizer = randomizer; + _id = id; } public static Session Create(Word[] words) { - Word[] words_in_tasks = new Word[words.Length]; var random = new Random(); - for (int i = 0; i < words.Length; i++) + var id = Guid.NewGuid(); + var words_in_tasks = words.Select(word => { if (random.Next(2) == 1) { - words_in_tasks[i] = GetWordWithWrongTranslation(words, i, random); + word = GetWordWithWrongTranslation(words, word, random); } - } - + return word; + }).ToArray(); words_in_tasks = MixedWords(words_in_tasks, random); - return new Session(words_in_tasks, random); - } + return new Session(words_in_tasks, random,id); + } private static Word[] MixedWords(Word[] words_in_tasks, Random random) { var new_words = words_in_tasks; Word temp; int random_index; - for (int i = words_in_tasks.Length; i > 2; i++) + for (int i = words_in_tasks.Length - 1; i > 2; i--) { - random_index = random.Next(i) + 1; + random_index = random.Next(i); if (random_index != i) { temp = new_words[i]; @@ -45,39 +49,33 @@ private static Word[] MixedWords(Word[] words_in_tasks, Random random) new_words[random_index] = temp; } } + return new_words; } public IEnumerable ShowTask() { - var task = new List(); - foreach (var word in _words) - { - task.Add(word._in_english + "-" + word._in_russian); - } + var task = words.Select(word => word._in_english + "-" + word._in_russian); return task; } + public void GetAnswers(bool[] answers) + { + this.answers = answers; + } - public string ShowWhatsWrongInAnswers(List wrong_answers) + public List CheckAnswers(User user) { - var words = $"You answered wrong. Right translations are\n"; - foreach (var Word in wrong_answers) - { - words += Word._in_russian + "\n" ; - } - return words; + return user.CheckAnswers(answers, words); + } - private static Word GetWordWithWrongTranslation(Word[] words, int index, Random random) + private static Word GetWordWithWrongTranslation(Word[] words, Word word, Random random) { - var first_index = index; - var second_index = random.Next(0, words.Length); - while (first_index == second_index) + var index = random.Next(0, words.Length); + while (words[index]._in_russian == word._in_russian) { - second_index = random.Next(0, words.Length); + index = random.Next(0, words.Length); } - return new Word(words[first_index]._in_english, words[second_index]._in_russian, 0); - + return new Word(word._in_english, words[index]._in_russian, 0); } - } } diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs index 99940ac..29a7e8d 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/User.cs @@ -11,6 +11,19 @@ public class User : IUser private List learned_words; private List words_in_process; + public IEnumerator _learned_words => learned_words.GetEnumerator(); + public IEnumerator _words_in_process => words_in_process.GetEnumerator(); + + public UserPub ToUserPub() + { + var l_word = new List(); + var p_words = new List(); + if (learned_words != null) + l_word = learned_words.Select(m => m._in_english + "." + m._in_russian + "." + m._flag).ToList(); + if (words_in_process!=null) + p_words = words_in_process.Select(m => m._in_english + "." + m._in_russian + "." + m._flag).ToList(); + return new UserPub(_nickname, _id, l_word, p_words ); + } public User(string nickname, Guid id, List learned_words, List words_in_process) { @@ -20,10 +33,29 @@ public User(string nickname, Guid id, List learned_words, List words this.words_in_process = words_in_process; } - public Session StartSession() + public Session StartSession(int number_of_words) + { + var words = GetSomeWords(number_of_words); + return Session.Create(words); + } + + private Word[] GetSomeWords(int number_of_words) { - return Session.Create(words_in_process.ToArray()); + if (number_of_words > words_in_process.Count()) + { + return words_in_process.ToArray(); + } + var words = words_in_process; + var count = words.Count() - number_of_words; + var random = new Random(); + for (int i = 0; i < count; i++) + { + var random_index = random.Next(words.Count()); + words.RemoveAt(random_index); + } + return words.ToArray(); } + public void AddNewWordInDictionary(Word word) { if (!learned_words.Contains(word)) @@ -51,37 +83,31 @@ public IEnumerable ShowLearnedWord() public List CheckAnswers(bool[] user_answers, Word[] words_in_question) { - var answers = new Dictionary(); - for (int i = 0; i < user_answers.Count(); i++) - { - answers.Add(words_in_process[i], user_answers[i]); - } + var right_words = new List(); + var answers = words_in_question + .Zip(user_answers, (word, answer) => { return new KeyValuePair(word, answer); }) + .ToDictionary(item => item.Key, item => item.Value); var wrong_answers = new List(); - - foreach (var word in words_in_process) + foreach (var word in words_in_question) { - if (!answers.ContainsKey(word)) + if ( words_in_process.Contains(word) == !answers[word]) { - var checked_word = answers.Single(s => s.Key._in_english == word._in_english).Key; - if (answers[checked_word] == true) - { - wrong_answers.Add(word); - } - } - else if (answers.ContainsKey(word) && answers[word] == false) - { - wrong_answers.Add(word); - } - else FlagGrowsOnePoint(word); - + var right_word = words_in_process.First(this_word => word._in_english == this_word._in_english); + wrong_answers.Add(right_word); + } + else right_words.Add(word); + } + foreach (var word in right_words) + { + FlagGrowsOnePoint(word); } return wrong_answers; } private void FlagGrowsOnePoint(Word word) { - var new_word = new Word(word._in_english,word._in_russian,word._flag+1); - words_in_process.Remove(word); + var new_word = new Word(word._in_english, word._in_russian, word._flag + 1); + words_in_process.Remove(new_word); if (!IsWordLearned(new_word)) { words_in_process.Add(new_word); @@ -95,5 +121,15 @@ private bool IsWordLearned(Word new_word) if (new_word._flag < 3) return false; return true; } + + public override bool Equals(object obj) + { + var user = obj as User; + return user != null && + _nickname == user._nickname && + _id.Equals(user._id) && + EqualityComparer>.Default.Equals(learned_words, user.learned_words) && + EqualityComparer>.Default.Equals(words_in_process, user.words_in_process); + } } } diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Class/UserPub.cs b/ForthLesson/Leo-sprint/Leo-sprint/Class/UserPub.cs new file mode 100644 index 0000000..29e8848 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Class/UserPub.cs @@ -0,0 +1,58 @@ +using MongoDB.Bson.Serialization.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leo_sprint +{ + public class UserPub + { + public string _nickname; + public Guid _id; + public List learned_words; + public List words_in_process; + + public UserPub(string nickname, Guid id, List learned_words, List words_in_process) + { + _nickname = nickname; + _id = id; + this.learned_words = learned_words; + this.words_in_process = words_in_process; + } + + public override bool Equals(object obj) + { + var pub = obj as UserPub; + return pub != null && + _nickname == pub._nickname && + _id.Equals(pub._id) && + EqualityComparer>.Default.Equals(learned_words, pub.learned_words) && + EqualityComparer>.Default.Equals(words_in_process, pub.words_in_process); + } + + public User ToUser() + { + var l_words = new List(); + var p_words = new List(); + if (learned_words != null) + { + l_words = learned_words.Select(m => + { + var words_parts = m.Split('.'); + return new Word(words_parts[0], words_parts[1], int.Parse(words_parts[2])); + }).ToList(); + } + if (words_in_process != null) + { + p_words = words_in_process.Select(m => + { + var words_parts = m.Split('.'); + return new Word(words_parts[0], words_parts[1], int.Parse(words_parts[2])); + }).ToList(); + } + return new User(_nickname, _id, l_words, p_words); + } + } +} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs b/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs index c62518f..e7c93f2 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Interfaces/IUser.cs @@ -7,8 +7,5 @@ public interface IUser { Guid _id { get; } string _nickname { get; } - void AddNewWordInDictionary(Word word); - IEnumerable ShowWordInProgress(); - IEnumerable ShowLearnedWord(); } } diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj b/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj index 360a7f4..df5385a 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj +++ b/ForthLesson/Leo-sprint/Leo-sprint/Leo-sprint.csproj @@ -33,11 +33,29 @@ 4 + + ..\packages\DnsClient.1.0.7\lib\net45\DnsClient.dll + + + ..\packages\MongoDB.Bson.2.7.0\lib\net45\MongoDB.Bson.dll + + + ..\packages\MongoDB.Driver.2.7.0\lib\net45\MongoDB.Driver.dll + + + ..\packages\MongoDB.Driver.Core.2.7.0\lib\net45\MongoDB.Driver.Core.dll + ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll + + ..\packages\System.Buffers.4.3.0\lib\netstandard1.1\System.Buffers.dll + + + ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.0.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll + @@ -48,11 +66,14 @@ + - + + + diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Program.cs b/ForthLesson/Leo-sprint/Leo-sprint/Program.cs index 9033cf7..391abbf 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/Program.cs +++ b/ForthLesson/Leo-sprint/Leo-sprint/Program.cs @@ -1,19 +1,9 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.IO; - -namespace Leo_sprint +namespace Leo_sprint { class Program { static void Main(string[] args) { - var user = new User("sss", Guid.NewGuid(), new List(), new List()); - var a = JsonConvert.SerializeObject(user); - UserRepository.Create("foo"); - File.WriteAllLines("C:\\Users\\Татьяна\\Desktop\\i.txt", UserRepository.GetAllUsers()); - } } } diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Repository/IUserRepository.cs b/ForthLesson/Leo-sprint/Leo-sprint/Repository/IUserRepository.cs new file mode 100644 index 0000000..d63b195 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Repository/IUserRepository.cs @@ -0,0 +1,12 @@ +using MongoDB.Driver; +using System; + +namespace Leo_sprint +{ + public interface IUserRepository + { + User LaodUser(Guid id); + void SaveUser(User user); + Guid CreateUser(string nickname); + } +} \ No newline at end of file diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Repository/MongoUserRepository.cs b/ForthLesson/Leo-sprint/Leo-sprint/Repository/MongoUserRepository.cs new file mode 100644 index 0000000..4fd9c40 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/Repository/MongoUserRepository.cs @@ -0,0 +1,53 @@ +using MongoDB.Bson.Serialization; +using MongoDB.Driver; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Leo_sprint +{ + public class MongoUserRepository : IUserRepository + { + private readonly IMongoCollection users; + + public MongoUserRepository(string mongoConnection) + { + var mongoClient = new MongoClient(mongoConnection); + var DateBase = mongoClient.GetDatabase("TanyaDatabase"); + users = DateBase.GetCollection("UserPub"); + } + static MongoUserRepository() + { + BsonClassMap.RegisterClassMap(map => + { + map.AutoMap(); + map.MapIdMember(user => user._id); + map.MapMember(user => user._nickname); + map.MapMember(user => user.learned_words); + map.MapMember(user => user.words_in_process); + }); + + } + + public User LaodUser(Guid id) + { + try { return users.Find(user => user._id == id).First().ToUser(); } + catch { return new User(string.Empty, Guid.Empty, new List(), new List()); } + } + public Guid CreateUser(string nickname) + { + var id = Guid.NewGuid(); + var user = new UserPub(nickname, id, new List(), new List()); + users.InsertOne(user); + return id; + } + + + public void SaveUser(User user) + { + users.ReplaceOne(m => user._id == m._id, user.ToUserPub()); + } + } + +} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs b/ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs deleted file mode 100644 index d801826..0000000 --- a/ForthLesson/Leo-sprint/Leo-sprint/Repository/UserRepository.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.IO; - - -namespace Leo_sprint -{ - public class UserRepository - { - - public static IEnumerable GetAllUsers() - { - var json_users = new List(); - string[] users_paths; - if (File.Exists("users.txt")) - { - users_paths = File.ReadAllLines("users.txt"); - foreach (var path in users_paths) - { - var json = File.ReadAllText(path); - json_users.Add(json); - } - } - return json_users; - - } - - public static Guid Create(string nickname) - { - var id = Guid.NewGuid(); - var new_user = new User(nickname, id, new List(), new List()); - File.AppendAllText("users.txt", id.ToString() + ".txt\n"); - File.WriteAllText(new_user._id.ToString() + ".txt", JsonConvert.SerializeObject(new_user)); - return id; - } - public static void Update(User user) - { - File.AppendAllText(user._id.ToString() + ".txt", JsonConvert.SerializeObject(user)); - } - - public static string GetJson(Guid id) - { - return File.ReadAllText(id.ToString() + ".txt"); - - } - } -} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/SessionClient.cs b/ForthLesson/Leo-sprint/Leo-sprint/SessionClient.cs new file mode 100644 index 0000000..27873d0 --- /dev/null +++ b/ForthLesson/Leo-sprint/Leo-sprint/SessionClient.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leo_sprint +{ + public class SessionClient + { + private static Dictionary sessions = new Dictionary(); + + public static Guid StartSession(User user,int number_of_words) + { + var session= user.StartSession(number_of_words); + sessions.Add(session._id, session); + return session._id; + } + + public static IEnumerable ShowTask(Guid session_id) + { + return sessions[session_id].ShowTask(); + } + + public static void GetAnswers(bool[] answers, Guid session_id) + { + sessions[session_id].GetAnswers(answers); + } + + public static IEnumerable CheckAnswers(User user, Guid session_id) + { + return sessions[session_id].CheckAnswers(user); + } + } +} diff --git a/ForthLesson/Leo-sprint/Leo-sprint/packages.config b/ForthLesson/Leo-sprint/Leo-sprint/packages.config index 5762754..34896e4 100644 --- a/ForthLesson/Leo-sprint/Leo-sprint/packages.config +++ b/ForthLesson/Leo-sprint/Leo-sprint/packages.config @@ -1,4 +1,11 @@  + + + + + + + \ No newline at end of file diff --git a/ForthLesson/Leo-sprint/SessionTest/SessionTest.cs b/ForthLesson/Leo-sprint/SessionTest/SessionTest.cs new file mode 100644 index 0000000..13fe287 --- /dev/null +++ b/ForthLesson/Leo-sprint/SessionTest/SessionTest.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Leo_sprint; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace SessionTest +{ + [TestClass] + public class SessionTest + { + [TestMethod] + public void CreateSession_GetMixedListOfWord() + { + var words = new List { new Word("eng", "rus", 0), new Word("eng1", "rus1", 0), new Word("eng2", "rus2", 0), new Word("eng3", "rus3", 0) }; + var test_user = new User(string.Empty, Guid.Empty, new List(), words); + var session = Session.Create(words.ToArray()); + var task = words.Select(word => word._in_english + "-" + word._in_russian); + + CollectionAssert.AreNotEqual(session.ShowTask().ToList(), task.ToList()); + } + [TestMethod] + public void CreateSession_GetMixedListOf5Word() + { + var words = new List { + new Word("eng", "rus", 0), + new Word("eng1", "rus1", 0), + new Word("eng2", "rus2", 0), + new Word("eng3", "rus3", 0), + new Word("eng4", "rus4", 0), + new Word("eng5", "rus5", 0), + new Word("eng6", "rus6", 0), + new Word("eng7", "rus7", 0) + }; + var test_user = new User(string.Empty, Guid.Empty, new List(), words); + var session = test_user.StartSession(5); + Assert.IsTrue(session.ShowTask().Count() == 5); + } + + } +} diff --git a/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj b/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj index 835aca9..ed7d8e8 100644 --- a/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj +++ b/ForthLesson/Leo-sprint/SessionTest/SessionTest.csproj @@ -53,6 +53,7 @@ + diff --git a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs index f916f9b..6ec45e5 100644 --- a/ForthLesson/Leo-sprint/SessionTest/UserTest.cs +++ b/ForthLesson/Leo-sprint/SessionTest/UserTest.cs @@ -1,7 +1,8 @@ -using System; -using System.Collections.Generic; -using Leo_sprint; +using Leo_sprint; using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.Linq; namespace SessionTest { @@ -12,12 +13,38 @@ public class UserTest public void CheckRightAnswers_GetEmptyListOfWords() { var words_in_process = new List { new Word("eng", "rus", 0), new Word("eng1", "rus1", 0) }; - var test_user = new User(string.Empty, Guid.Empty, new List(),words_in_process ); + var test_user = new User(string.Empty, Guid.Empty, new List(), words_in_process); var answers = new bool[] { true, true }; var list = test_user.CheckAnswers(answers, words_in_process.ToArray()); var expected_list = new List(); - CollectionAssert.ReferenceEquals(list, expected_list); + CollectionAssert.AreEqual(list, expected_list); + } + [TestMethod] + public void CheckRightAnswersWordHaveFlagLessForOnePointUntillTheyBecameLearned_WordsBecameLearned() + { + var words_in_process = new List { new Word("eng", "rus", 2), new Word("eng1", "rus1", 2) }; + var test_user = new User(string.Empty, Guid.Empty, new List(), words_in_process); + var answers = new bool[] { true, true }; + + var list = test_user.CheckAnswers(answers, words_in_process.ToArray()); + var list_of_learned_words = test_user.ShowLearnedWord().ToList(); + var expected_list = new List { new Word("eng", "rus", 3), new Word("eng1", "rus1", 3) }; + + CollectionAssert.AreEqual(list_of_learned_words, expected_list); + } + [TestMethod] + public void CheckRightAnswersWordHaveFlagLessForOnePointUntillTheyBecameLearned_ListWordsInPocessIsEmpty() + { + var words_in_process = new List { new Word("eng", "rus", 2), new Word("eng1", "rus1", 2) }; + var test_user = new User(string.Empty, Guid.Empty, new List(), words_in_process); + var answers = new bool[] { true, true }; + + var list = test_user.CheckAnswers(answers, words_in_process.ToArray()); + var list_word_in_process = test_user.ShowWordInProgress().ToList(); + var expected_list = new List (); + + CollectionAssert.AreEqual(expected_list, list_word_in_process); } [TestMethod] public void CheckRightAnswersWithOneWrongAnswer_GetListWithOneWord() @@ -27,9 +54,9 @@ public void CheckRightAnswersWithOneWrongAnswer_GetListWithOneWord() var test_user = new User(string.Empty, Guid.Empty, new List(), words_in_process); var answers = new bool[] { true, true }; - var list = test_user.CheckAnswers(answers, words_in_process.ToArray()); + var list = test_user.CheckAnswers(answers, test_words.ToArray()); var expected_list = new List { new Word("eng1", "rus1", 0) }; - CollectionAssert.ReferenceEquals(list, expected_list); + CollectionAssert.AreEqual(list, expected_list); } [TestMethod] public void SecondCheckRightAnswers_GetEmptyListOfWords() @@ -39,9 +66,9 @@ public void SecondCheckRightAnswers_GetEmptyListOfWords() var test_user = new User(string.Empty, Guid.Empty, new List(), words_in_process); var answers = new bool[] { true, false }; - var list = test_user.CheckAnswers(answers, words_in_process.ToArray()); - var expected_list = new List (); - CollectionAssert.ReferenceEquals(list, expected_list); + var list = test_user.CheckAnswers(answers, test_words.ToArray()); + var expected_list = new List(); + CollectionAssert.AreEqual(list, expected_list); } [TestMethod] public void SecondCheckRightAnswersWithOneWrongAnswer_GetListWithOneWord() @@ -51,10 +78,11 @@ public void SecondCheckRightAnswersWithOneWrongAnswer_GetListWithOneWord() var test_user = new User(string.Empty, Guid.Empty, new List(), words_in_process); var answers = new bool[] { false, false }; - var list = test_user.CheckAnswers(answers, words_in_process.ToArray()); + var list = test_user.CheckAnswers(answers,test_words.ToArray()); var expected_list = new List { new Word("eng", "rus", 0) }; - CollectionAssert.ReferenceEquals(list, expected_list); + CollectionAssert.AreEqual(list, expected_list); } - + + } } diff --git a/ForthLesson/Leo-sprint/WebApplication1/Controllers/UserController.cs b/ForthLesson/Leo-sprint/WebApplication1/Controllers/UserController.cs index 0715599..5f325b4 100644 --- a/ForthLesson/Leo-sprint/WebApplication1/Controllers/UserController.cs +++ b/ForthLesson/Leo-sprint/WebApplication1/Controllers/UserController.cs @@ -1,78 +1,107 @@ using Leo_sprint; using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; using System; using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; namespace Leo_sprintAPI.Controllers { public class UsersController : Controller { + private readonly IUserRepository _userRepository; - [HttpGet] - [Route("users/{id}")] - public string GetUserById(Guid id) + public UsersController(IUserRepository userRepository) { - return UserRepository.GetJson(id); + _userRepository = userRepository; } - [HttpGet] + + [HttpPost] [Route("users")] - public IEnumerable GetUsers(Guid id) + public ActionResult CreateUser([FromBody] NicknameModel nickname) { - return UserRepository.GetAllUsers(); + var userId = _userRepository.CreateUser(nickname._nickname); + return Ok($"User witn nickname {nickname._nickname} created with id {userId}"); } + [HttpGet] - [Route("users/{id}/word_in_process")] - public IEnumerable GetUsersWordsInProcess(Guid id) + [Route("users/{id}")] + public ActionResult GetUser(Guid id) { - var words = new List(); - var userPub = JsonConvert.DeserializeObject(UserRepository.GetJson(id)); - foreach (var word in userPub.words_in_process) + var user = _userRepository.LaodUser(id); + if (user._nickname.Equals(string.Empty)) { - words.Add(word._in_english + "-" + word._in_russian); + return BadRequest($"This user does not exist"); } - return words; + return Ok(user); } + [HttpGet] - [Route("users/{id}/learned_words")] - public IEnumerable GetUsersLearnedWords(Guid id) + [Route("users/{id}/wordInProcess")] + public ActionResult GetUsersWordsInProcess(Guid id) { var words = new List(); - var user = JsonConvert.DeserializeObject(UserRepository.GetJson(id)); - foreach (var word in user.learned_words) - { - words.Add(word._in_english + "-" + word._in_russian); - } - return words; + var user = _userRepository.LaodUser(id); + return Ok(user.ShowWordInProgress()); } - [HttpPost] - [Route("users")] - public string CreateUser([FromBody]string nickname) + [HttpGet] + [Route("users/{id}/learnedWords")] + public ActionResult GetUsersLearnedWords(Guid id) { - var id = UserRepository.Create(nickname); - return $"User witn nickname {nickname} created with id {id}"; + var words = new List(); + var user = _userRepository.LaodUser(id); + return Ok(user.ShowLearnedWord()); } + [HttpPost] - [Route("users/{id}/word_in_process")] - public string AddWordToUsersWordsInProcess(Guid id, [FromBody] string in_english, [FromBody] string in_russian) + [Route("users/{id}/wordInProcess")] + public ActionResult AddWordToUsersWordsInProcess(Guid id, [FromBody] WordModel word) { - var userPub = JsonConvert.DeserializeObject(UserRepository.GetJson(id)); - var user = new User(userPub._nickname, userPub._id, userPub.learned_words, userPub.words_in_process); - user.AddNewWordInDictionary(new Word(in_english, in_russian, 0)); - return $"Word added"; + var user = _userRepository.LaodUser(id); + user.AddNewWordInDictionary(new Word(word.In_english, word.In_russian, 0)); + _userRepository.SaveUser(user); + return Ok($"Word added"); } [HttpDelete] - [Route("users/{id}/word_in_process")] - public string RemoveWordFromDictionary(Guid id, [FromBody] string in_english, [FromBody] string in_russian) + [Route("users/{id}/wordInProcess")] + public ActionResult RemoveWordFromDictionary(Guid id, [FromBody] WordModel word) { - var userPub = JsonConvert.DeserializeObject(UserRepository.GetJson(id)); - var user = new User(userPub._nickname, userPub._id, userPub.learned_words, userPub.words_in_process); - user.RemoveWordFromDictionary(new Word(in_english, in_russian, 0)); - return $"Word removed"; + var user = _userRepository.LaodUser(id); + user.RemoveWordFromDictionary(new Word(word.In_english, word.In_russian, 0)); + _userRepository.SaveUser(user); + return Ok($"Word removed"); + } + [HttpPost] + [Route("users/{id}/sessions")] + public ActionResult StartSession(Guid id, [FromBody] int number_of_words) + { + var user = _userRepository.LaodUser(id); + var session_id = SessionClient.StartSession(user, number_of_words); + return Ok($"Session created with id {session_id}"); } - + [HttpGet] + [Route("users/{id}/sessions/{session_id}/showTask")] + public ActionResult ShowTask(Guid session_id) + { + return Ok(SessionClient.ShowTask(session_id)); + } + [HttpPost] + [Route("users/{id}/sessions/{session_id}/sendAnswers")] + public ActionResult GetAnswers([FromBody] AnswerModel answers, Guid session_id) + { + SessionClient.GetAnswers(answers.Answers, session_id); + return Ok("Answers checked"); + } + [HttpGet] + [Route("users/{id}/sessions/{session_id}/showWrongAnswers")] + public ActionResult ShowWrongAnswers(Guid session_id, Guid id) + { + var user = _userRepository.LaodUser(id); + var wrong_answers = SessionClient.CheckAnswers(user, session_id); + _userRepository.SaveUser(user); + return Ok(wrong_answers); + } } -} \ No newline at end of file +} diff --git a/ForthLesson/Leo-sprint/WebApplication1/Leo-sprintAPI.csproj b/ForthLesson/Leo-sprint/WebApplication1/Leo-sprintAPI.csproj index f64aa4f..b41c6fa 100644 --- a/ForthLesson/Leo-sprint/WebApplication1/Leo-sprintAPI.csproj +++ b/ForthLesson/Leo-sprint/WebApplication1/Leo-sprintAPI.csproj @@ -11,6 +11,8 @@ + + diff --git a/ForthLesson/Leo-sprint/WebApplication1/Models/AnswerModel.cs b/ForthLesson/Leo-sprint/WebApplication1/Models/AnswerModel.cs new file mode 100644 index 0000000..a1ca31b --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/Models/AnswerModel.cs @@ -0,0 +1,14 @@ +using System.ComponentModel.DataAnnotations; + +namespace Leo_sprintAPI +{ + public class AnswerModel + { + public AnswerModel(bool[] answers) + { + Answers = answers; + } + [Required] + public bool[] Answers { get; set; } + } +} \ No newline at end of file diff --git a/ForthLesson/Leo-sprint/WebApplication1/Models/UserModel.cs b/ForthLesson/Leo-sprint/WebApplication1/Models/NicknameModel.cs similarity index 53% rename from ForthLesson/Leo-sprint/WebApplication1/Models/UserModel.cs rename to ForthLesson/Leo-sprint/WebApplication1/Models/NicknameModel.cs index a04447d..8780cad 100644 --- a/ForthLesson/Leo-sprint/WebApplication1/Models/UserModel.cs +++ b/ForthLesson/Leo-sprint/WebApplication1/Models/NicknameModel.cs @@ -5,16 +5,16 @@ namespace Leo_sprintAPI { - public class UserModel + public class NicknameModel { + public NicknameModel(string nickname) + { + _nickname = nickname; + } + [Required] [StringLength(50, MinimumLength = 8)] public string _nickname { get; set; } - [Required] - public Guid _id { get; set; } - [Required] - public List words_in_process { get; set; } - [Required] - public List learned_words { get; set; } + } } diff --git a/ForthLesson/Leo-sprint/WebApplication1/Models/WordModel.cs b/ForthLesson/Leo-sprint/WebApplication1/Models/WordModel.cs new file mode 100644 index 0000000..9647b8c --- /dev/null +++ b/ForthLesson/Leo-sprint/WebApplication1/Models/WordModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading.Tasks; +using Leo_sprint; + +namespace Leo_sprintAPI +{ + public class WordModel + { + [Required] + public string In_english { get; set; } + [Required] + public string In_russian { get; set; } + } +} diff --git a/ForthLesson/Leo-sprint/WebApplication1/Startup.cs b/ForthLesson/Leo-sprint/WebApplication1/Startup.cs index e26b8ac..824736c 100644 --- a/ForthLesson/Leo-sprint/WebApplication1/Startup.cs +++ b/ForthLesson/Leo-sprint/WebApplication1/Startup.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using Leo_sprint; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; using Swashbuckle.AspNetCore.Swagger; namespace WebApplication1 @@ -29,6 +24,9 @@ public void ConfigureServices(IServiceCollection services) { c.SwaggerDoc("v1", new Info { Title = "", Version = "v1" }); }); + var mongoConnectionString = Configuration.GetValue("mongoConnectionString"); + IUserRepository mongoUserRepository = new MongoUserRepository(mongoConnectionString); + services.AddSingleton(mongoUserRepository); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/ForthLesson/Leo-sprint/WebApplication1/appsettings.Development.json b/ForthLesson/Leo-sprint/WebApplication1/appsettings.Development.json index fa8ce71..b2802a8 100644 --- a/ForthLesson/Leo-sprint/WebApplication1/appsettings.Development.json +++ b/ForthLesson/Leo-sprint/WebApplication1/appsettings.Development.json @@ -1,10 +1,3 @@ { - "Logging": { - "IncludeScopes": false, - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } - } + "mongoconnectionstring": "mongodb+srv://dbAdmin:alLq0JUnZVtrPpK6@cluster0-wqq1j.mongodb.net/LOD?retryWrites=true" } diff --git a/ForthLesson/Leo-sprint/WebApplication1/appsettings.json b/ForthLesson/Leo-sprint/WebApplication1/appsettings.json index 26bb0ac..f09278e 100644 --- a/ForthLesson/Leo-sprint/WebApplication1/appsettings.json +++ b/ForthLesson/Leo-sprint/WebApplication1/appsettings.json @@ -1,15 +1,3 @@ { - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning" - } - } - } -} + "mongoConnectionString": "mongodb+srv://Admin:123456q@tanya-wyba6.mongodb.net/test?retryWrites=true" +} \ No newline at end of file