Skip to content

Commit

Permalink
DARKMILK-6: Реализовать EF и подключиться к бд
Browse files Browse the repository at this point in the history
  • Loading branch information
MilkRen committed Apr 29, 2024
1 parent 6d92f29 commit 8360f2d
Show file tree
Hide file tree
Showing 14 changed files with 159 additions and 46 deletions.
6 changes: 0 additions & 6 deletions LauncherDM.sln
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ServerTCP", "ServerTCP\Serv
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebAppDM", "WebAppDM\WebAppDM.csproj", "{C448F5B1-3C10-4BB7-89E8-9CE7BF5126CB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClientTCP", "ClientTCP\ClientTCP.csproj", "{FEB492ED-5E67-48DA-810B-4FDF1C32B44E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -29,10 +27,6 @@ Global
{C448F5B1-3C10-4BB7-89E8-9CE7BF5126CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C448F5B1-3C10-4BB7-89E8-9CE7BF5126CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C448F5B1-3C10-4BB7-89E8-9CE7BF5126CB}.Release|Any CPU.Build.0 = Release|Any CPU
{FEB492ED-5E67-48DA-810B-4FDF1C32B44E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FEB492ED-5E67-48DA-810B-4FDF1C32B44E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FEB492ED-5E67-48DA-810B-4FDF1C32B44E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FEB492ED-5E67-48DA-810B-4FDF1C32B44E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
4 changes: 2 additions & 2 deletions LauncherDM/LauncherDM.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<LangVersion>latest</LangVersion>
Expand Down Expand Up @@ -37,7 +37,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\ClientTCP\ClientTCP.csproj" />
<ProjectReference Include="..\ServerTCP\ServerTCP.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions LauncherDM/Services/Interfaces/ILoadingWindowService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ interface ILoadingWindowService
{
bool CheckRequestServer();

void GetTitle();
string GetTitle();

void DescInfoConnect();
string DescInfoConnect();
}
}
4 changes: 1 addition & 3 deletions LauncherDM/Services/Interfaces/IServerRequestService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ interface IServerRequestService
{
public MessageHeader SendMessageRequest(string data, MessageHeader.MessageType messageType, int length);

public MessageHeader SendMessageRequest(MessageHeader.MessageType messageType, int length);

//public string SendMessageRequestT<T>(T data, MessageHeader<T>.MessageType messageType, int length);
public MessageHeader SendMessageRequest(MessageHeader.MessageType messageType);
}
}
11 changes: 6 additions & 5 deletions LauncherDM/Services/LoadingWindowService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,27 @@ public bool CheckRequestServer()
if (serverRequest is null)
serverRequest = new ServerRequestService();

var requestMessageServer = serverRequest.SendMessageRequest(MessageHeader.MessageType.Check, 0);
var requestMessageServer = serverRequest.SendMessageRequest(MessageHeader.MessageType.Check);
return requestMessageServer.Message == "1";
}

public void GetTitle()
public string GetTitle()
{
if (serverRequest is null)
serverRequest = new ServerRequestService();

var requestMessageServer = serverRequest.SendMessageRequest(string.Empty,
MessageHeader.MessageType.Check, string.Empty.Length);
var requestMessageServer = serverRequest.SendMessageRequest(MessageHeader.MessageType.TitleLoading);
return requestMessageServer.Message;
}

public void DescInfoConnect()
public string DescInfoConnect()
{
if (serverRequest is null)
serverRequest = new ServerRequestService();

var requestMessageServer = serverRequest.SendMessageRequest(string.Empty,
MessageHeader.MessageType.Check, string.Empty.Length);
return requestMessageServer.Message;
}
}
}
23 changes: 10 additions & 13 deletions LauncherDM/Services/ServerRequestService.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using LauncherDM.Services.Interfaces;
using ServerTCP;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Windows.Markup;
using ServerTCP;

namespace LauncherDM.Services
{
Expand All @@ -28,11 +28,12 @@ public ServerRequestService()

public MessageHeader SendMessageRequest(string data, MessageHeader.MessageType messageType, int length)
{
TcpClient tcpClient = null;
try
{
while (true)
{
var tcpClient = new TcpClient();
tcpClient = new TcpClient();
tcpClient.Connect(endPoint);

var messageHeader = new MessageHeader(data, messageType, length + MessageHeader.LengthAndDataType);
Expand All @@ -52,26 +53,22 @@ public MessageHeader SendMessageRequest(string data, MessageHeader.MessageType m
getBytes = getBytes.Take(size + MessageHeader.LengthAndDataType).ToArray();
return MessageHeader.FromArray(getBytes);
} while (tcpStream.DataAvailable);

//WriteColorTextCmd("Получил сообщение: ");
//Console.Write(returnDataStrBuild);
tcpClient.Close();
//return string.Empty;
}

}
catch (Exception e)
{
IDialogMessageBoxService dialogMessageBox = new DialogMessageBoxService();
dialogMessageBox.DialogShow("Error Server Reques", "Error Server Reques");
//return string.Empty;
return null;
}
finally
{
tcpClient?.Close();
}


return null;
}

public MessageHeader SendMessageRequest(MessageHeader.MessageType messageType, int length)
public MessageHeader SendMessageRequest(MessageHeader.MessageType messageType)
{
TcpClient tcpClient = null;
try
Expand All @@ -81,7 +78,7 @@ public MessageHeader SendMessageRequest(MessageHeader.MessageType messageType, i
tcpClient = new TcpClient();
tcpClient.Connect(endPoint);

var messageHeader = new MessageHeader(messageType, length);
var messageHeader = new MessageHeader(messageType, 0);
byte[] headerBytes = messageHeader.MessageToArray();

NetworkStream tcpStream = tcpClient.GetStream();
Expand Down
6 changes: 3 additions & 3 deletions LauncherDM/ViewModels/LoadingWindowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,15 @@ public LoadingWindowViewModel()
private void Load()
{
ICheckNetworkService checkNetwork = new CheckNetworkService();
ILoadingWindowService ServerCheck = new LoadingWindowService();
ILoadingWindowService Server = new LoadingWindowService();

Task.Run(() =>
{
if (checkNetwork.CheckingNetworkConnection())
{
if (ServerCheck.CheckRequestServer())
if (Server.CheckRequestServer())
{
DescInfoConnect = "sd";
DescInfoConnect = Server.GetTitle();

Thread.Sleep(5000);
_loadingWindow.Dispatcher.Invoke(() =>
Expand Down
21 changes: 21 additions & 0 deletions ServerTCP/ConsoleExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace ServerTCP
{
public static class ConsoleExtension
{
public static void WriteLineColor(string text, ConsoleColor foregroundColor = System.ConsoleColor.Gray, ConsoleColor backgroundColor = System.ConsoleColor.Black)
{
Console.ForegroundColor = foregroundColor;
Console.BackgroundColor = backgroundColor;
Console.WriteLine(text);
Console.ResetColor();
}

public static void WriteColor(string text, ConsoleColor foregroundColor = System.ConsoleColor.Gray, ConsoleColor backgroundColor = System.ConsoleColor.Black)
{
Console.ForegroundColor = foregroundColor;
Console.BackgroundColor = backgroundColor;
Console.Write(text);
Console.ResetColor();
}
}
}
30 changes: 30 additions & 0 deletions ServerTCP/DataBase/DataBaseCommands.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Threading.Channels;
using ServerTCP.Models;
using ServerTCP.Models.Data;

namespace ServerTCP.DataBase
{
internal class DataBaseCommands
{
public static void Insert(object table, MessageHeader.MessageType messageType)
{
using (var db = new ApplicationContext())
{
if (db.Database.CanConnect())
ConsoleExtension.WriteLineColor("База данных доступна.", ConsoleColor.DarkGreen);
else
ConsoleExtension.WriteLineColor("База данных не доступна!", ConsoleColor.DarkRed);

switch (messageType)
{
case MessageHeader.MessageType.Registration:
if (table is User user)
db.users.Add(user);
break;
}
db.SaveChanges();
}
}

}
}
1 change: 1 addition & 0 deletions ServerTCP/MessageHeader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public enum MessageType : byte
Data,
Check,
Title,
TitleLoading,
}

public MessageHeader(MessageType type, int length)
Expand Down
21 changes: 21 additions & 0 deletions ServerTCP/Models/Data/ApplicationContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System.Collections.Generic;

namespace ServerTCP.Models.Data
{
internal class ApplicationContext : DbContext
{
public DbSet<User> users { get; set; }

public ApplicationContext()
{
//Database.EnsureCreated(); // гарантирует, что БД существует или создаст её и таблицы там
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) // подключение к бд
{
optionsBuilder.UseNpgsql("Host=81.31.246.203;Port=5432;Database=DarkMilkBD;Username=gen_user;Password=lY8\\b@slc^g\\xJ");
}
}
}
16 changes: 16 additions & 0 deletions ServerTCP/Models/User.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace ServerTCP.Models
{
internal class User
{
public int id { get; set; }
public string username { get; set; }
public string login { get; set; }
public string email { get; set; }
public string password { get; set; }

public User()
{

}
}
}
50 changes: 40 additions & 10 deletions ServerTCP/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using ServerTCP.DataBase;
using ServerTCP.Models;

namespace ServerTCP
{
Expand Down Expand Up @@ -34,20 +35,49 @@ static void Main(string[] args)
size = listener.Receive(buffer); // получение данных, количество, значение
//buffer = buffer.Where(x => x != 0).ToArray();
var header = MessageHeader.FromArray(buffer);

MessageHeader headerRequest = null;
byte[] headerRequestBytes;
switch (header.Type)
{
case MessageHeader.MessageType.Check:
var headerRequest = new MessageHeader("1", MessageHeader.MessageType.Check, 1);
byte[] headerBytes = headerRequest.MessageToArray();
listener.Send(headerBytes);
headerRequest = new MessageHeader("1", MessageHeader.MessageType.Check, 1);
headerRequestBytes = headerRequest.MessageToArray();
listener.Send(headerRequestBytes);
break;
case MessageHeader.MessageType.Session:
break;
case MessageHeader.MessageType.Token:
break;
case MessageHeader.MessageType.Registration:
var user = new User
{
id = 1, login = "Gustaf", email = "[email protected]", username = "Gustavo", password = "sjafhfjhlkj12pje12j31kl23j1l123j"
};
DataBaseCommands.Insert(user, MessageHeader.MessageType.Registration);
break;
case MessageHeader.MessageType.Log:
break;
case MessageHeader.MessageType.File:
break;
case MessageHeader.MessageType.Photo:
break;
case MessageHeader.MessageType.Data:
break;
case MessageHeader.MessageType.Title:
break;
case MessageHeader.MessageType.TitleLoading:
headerRequest = new MessageHeader("1", MessageHeader.MessageType.TitleLoading, 1);
headerRequestBytes = headerRequest.MessageToArray();
listener.Send(headerRequestBytes);
break;

//case MessageHeader<string>.MessageType.Title:
// string messageRequest = "Привет, пупс!";
// var header1 = new MessageHeader<string>(messageRequest, MessageHeader<string>.MessageType.Check, Encoding.UTF8.GetBytes(messageRequest).Length);
// byte[] headerBytes = header1.MessageToArray();
// listener.Send(headerBytes);
// break;
//case MessageHeader<string>.MessageType.Title:
// string messageRequest = "Привет, пупс!";
// var header1 = new MessageHeader<string>(messageRequest, MessageHeader<string>.MessageType.Check, Encoding.UTF8.GetBytes(messageRequest).Length);
// byte[] headerBytes = header1.MessageToArray();
// listener.Send(headerBytes);
// break;
}
//data.Append(Encoding.UTF8.GetString(buffer, 0, size)); // сохраняем, добавляем данные. Данные передаются в кодированном формате, будем использовать кодировку UTF8, раскодируем байты
}
Expand Down
8 changes: 6 additions & 2 deletions ServerTCP/ServerTCP.csproj
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.2" />
</ItemGroup>

</Project>

0 comments on commit 8360f2d

Please sign in to comment.