Kaynağa Gözat

Added Entity Framework Database support

Veloe 4 yıl önce
ebeveyn
işleme
23eecdb7ef

+ 4 - 4
MafiaTelegramBot/Controllers/RoomController.cs

@@ -13,7 +13,7 @@ namespace MafiaTelegramBot.Controllers
     {
         private static readonly Dictionary<string, GameRoom> OpenedGames = new();
 
-        public static async Task<ResultCode> CreateNewGame(User owner, string roomName, bool extended, string secretPhrase = null)
+        public static async Task<ResultCode> CreateNewGame(UserEntity owner, string roomName, bool extended, string secretPhrase = null)
         {
             return await Task.Run(async () =>
             {
@@ -30,7 +30,7 @@ namespace MafiaTelegramBot.Controllers
             });
         }
 
-        public static async Task<ResultCode> ConnectToGame(User player, string roomKey)
+        public static async Task<ResultCode> ConnectToGame(UserEntity player, string roomKey)
         {
             return await Task.Run(async () =>
             {
@@ -43,7 +43,7 @@ namespace MafiaTelegramBot.Controllers
             });
         }
 
-        public static async Task<List<User>> GetPlayers(string roomKey)
+        public static async Task<List<UserEntity>> GetPlayers(string roomKey)
         {
             return await Task.Run( ()=>
             {
@@ -53,7 +53,7 @@ namespace MafiaTelegramBot.Controllers
             });
         }
         
-        public static async Task<ResultCode> LeaveFromGame(User player)
+        public static async Task<ResultCode> LeaveFromGame(UserEntity player)
         {
             return await Task.Run(async () =>
             {

+ 20 - 0
MafiaTelegramBot/DataBase/Mafia.cs

@@ -0,0 +1,20 @@
+using System.ComponentModel.DataAnnotations.Schema;
+using Microsoft.EntityFrameworkCore;
+
+namespace MafiaTelegramBot.DataBase
+{
+    public class Mafia : DbContext
+    {
+        public DbSet<UserEntity> Users { get; set; }
+        //public DbSet<StatisticsEntity> Statistics { get; set; }
+        
+        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
+        {
+            //#warning To protect potentially sensitive information in your connection string, 
+            //you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 
+            //for guidance on storing connection strings.
+     
+            optionsBuilder.UseMySQL("server=192.168.2.2;port=3306;database=mafia;uid=mafia_bot; pwd=73*MYSQLpassword73*");
+        }
+    }
+}

+ 23 - 9
MafiaTelegramBot/DataBase/UserDao.cs

@@ -1,17 +1,20 @@
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
+using Microsoft.EntityFrameworkCore;
 
 namespace MafiaTelegramBot.DataBase
 {
     public static class UserDao
     {
-        private static readonly List<UserEntity> DataBase = new();
+        //private static readonly List<UserEntity> DataBase = new();
+        private static Mafia DataBase = new Mafia();
+        
         private static readonly Dictionary<long,UserEntity> ActiveUsers = new();
         public static async Task<UserEntity> GetUserById(long id)
         {
             if (ActiveUsers.ContainsKey(id)) return ActiveUsers[id];
-            var user = await Task.Run(()=> DataBase.First(user1 => user1.Id == id));
+            var user = await Task.Run(()=> DataBase.Users.First(user1 => user1.Id == id));
             ActiveUsers.Add(user.Id, user);
             return user;
         }
@@ -23,17 +26,28 @@ namespace MafiaTelegramBot.DataBase
         
         public static async Task Update(UserEntity userEntity)
         {
-            var updateIndex = await Task.Run(() => DataBase.FindIndex(user1 => user1.Id == userEntity.Id));
-            if (updateIndex != -1) DataBase[updateIndex] = userEntity;
-            else DataBase.Add(userEntity);
+            if (await DataBase.Users.AnyAsync(user => user.Id == userEntity.Id))
+            {
+                DataBase.Update(userEntity);
+            }
+            else
+            {
+                DataBase.Add(userEntity);
+            }
+            await DataBase.SaveChangesAsync();
         }
 
         public static async Task<bool> UserExists(long id)
         {
-            return await Task.Run(() =>
-            {
-                return ActiveUsers.ContainsKey(id) || DataBase.Exists(user => user.Id == id);
-            });
+            if (ActiveUsers.ContainsKey(id))
+                return true;
+            return await DataBase.Users.AnyAsync(user => user.Id == id);
+                /*
+                 return await Task.Run(() =>
+                {
+                    return ActiveUsers.ContainsKey(id) || DataBase.Users.AnyAsync(user => user.Id == id);
+                });
+                */
         }
     }
 }

+ 16 - 6
MafiaTelegramBot/DataBase/UserEntity.cs

@@ -1,17 +1,25 @@
 #nullable enable
 using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.Resources;
 
 namespace MafiaTelegramBot.DataBase
 {
-    public class UserEntity
+    [Table("users")]
+    public class  UserEntity
     {
+        [Key]
+        [DatabaseGenerated(DatabaseGeneratedOption.None)]
+        [Column("id")]
         public long Id { get; init; }
+        [Column("chat_id")]
         public long ChatId { get; init; }
-        
+        [NotMapped]
         private string _username = strings.no_name;
+        [Column("username")]
         public string Username
         {
             get => _username;
@@ -21,8 +29,9 @@ namespace MafiaTelegramBot.DataBase
                 _username = value;
             }
         }
-
+        [NotMapped]
         private string _nickName = "";
+        [Column("nickname")]
         public string NickName
         {
             get => _nickName;
@@ -32,14 +41,15 @@ namespace MafiaTelegramBot.DataBase
                 _nickName = value;
             }
         }
-        
+        [NotMapped]
         public Dictionary<Roles, StatisticsEntity> Statistics = new();
-
+        [NotMapped]
         private Roles _currentRole = Roles.None;
+        [NotMapped]
         public int TurnOrder = -1;
+        [NotMapped]
         private string _roomKey = "";
         
-
         public async Task UpdateName(string name)
         {
             NickName = name;

+ 1 - 1
MafiaTelegramBot/Game/GameRoles/CopRole.cs

@@ -3,7 +3,7 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using User = MafiaTelegramBot.DataBase.User;
+using User = MafiaTelegramBot.DataBase.UserEntity;
 
 namespace MafiaTelegramBot.Game.GameRoles
 {

+ 1 - 1
MafiaTelegramBot/Game/GameRoles/DoctorRole.cs

@@ -3,7 +3,7 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using User = MafiaTelegramBot.DataBase.User;
+using User = MafiaTelegramBot.DataBase.UserEntity;
 
 namespace MafiaTelegramBot.Game.GameRoles
 {

+ 1 - 1
MafiaTelegramBot/Game/GameRoles/DonRole.cs

@@ -3,7 +3,7 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using User = MafiaTelegramBot.DataBase.User;
+using User = MafiaTelegramBot.DataBase.UserEntity;
 
 namespace MafiaTelegramBot.Game.GameRoles
 {

+ 1 - 1
MafiaTelegramBot/Game/GameRoles/HookerRole.cs

@@ -3,7 +3,7 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using User = MafiaTelegramBot.DataBase.User;
+using User = MafiaTelegramBot.DataBase.UserEntity;
 
 namespace MafiaTelegramBot.Game.GameRoles
 {

+ 1 - 1
MafiaTelegramBot/Game/GameRoles/MafiaRole.cs

@@ -3,7 +3,7 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using User = MafiaTelegramBot.DataBase.User;
+using User = MafiaTelegramBot.DataBase.UserEntity;
 
 namespace MafiaTelegramBot.Game.GameRoles
 {

+ 1 - 1
MafiaTelegramBot/Game/GameRoles/Role.cs

@@ -3,7 +3,7 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using User = MafiaTelegramBot.DataBase.User;
+using User = MafiaTelegramBot.DataBase.UserEntity;
 
 namespace MafiaTelegramBot.Game.GameRoles
 {

+ 1 - 1
MafiaTelegramBot/Game/GameRoles/VillagerRole.cs

@@ -3,7 +3,7 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using User = MafiaTelegramBot.DataBase.User;
+using User = MafiaTelegramBot.DataBase.UserEntity;
 
 namespace MafiaTelegramBot.Game.GameRoles
 {

+ 4 - 4
MafiaTelegramBot/Game/GameRoom.cs

@@ -22,11 +22,11 @@ namespace MafiaTelegramBot.Game
         public bool IsExtended { get; init; }
         public bool TimerEnabled { get; set; } = true;
         public string RoomName { get; init; } = "NoNameRoom";
-        public User Owner { get; init; } = new();
+        public UserEntity Owner { get; init; } = new();
 
-        private readonly Queue<User> _turnOrder = new();
+        private readonly Queue<UserEntity> _turnOrder = new();
 
-        public readonly Dictionary<long, User> Players = new();
+        public readonly Dictionary<long, UserEntity> Players = new();
 
         public readonly Dictionary<Roles, int> Settings = new()
         {
@@ -132,7 +132,7 @@ namespace MafiaTelegramBot.Game
             });
         }
 
-        public async Task<List<User>> GetPlayers()
+        public async Task<List<UserEntity>> GetPlayers()
         {
             return await Task.Run(() =>
             {

+ 2 - 0
MafiaTelegramBot/MafiaTelegramBot.csproj

@@ -7,7 +7,9 @@
     </PropertyGroup>
 
     <ItemGroup>
+      <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.7" />
       <PackageReference Include="MySql.Data" Version="8.0.25" />
+      <PackageReference Include="MySql.EntityFrameworkCore" Version="5.0.3.1" />
       <PackageReference Include="Telegram.Bot" Version="16.0.0" />
       <PackageReference Include="Telegram.Bot.Extensions.Polling" Version="0.2.0" />
     </ItemGroup>

+ 5 - 3
MafiaTelegramBot/Models/Commands/ShowProfileCommand.cs

@@ -11,15 +11,17 @@ namespace MafiaTelegramBot.Models.Commands
         protected override string Name => keyboard.show_profile;
 
         protected override async Task<Message> Execute(Update update)
-        {
+        { /*
             var user = await UserDao.GetUserById(UserId);
-            var winRate = user.Games < 1 ? 0.0 : Convert.ToDouble(user.Wins) / Convert.ToDouble(user.Games);
+            var winRate = user < 1 ? 0.0 : Convert.ToDouble(user.Wins) / Convert.ToDouble(user.Games);
             var message =
                 $"__*{strings.statistics_for} _{user.NickName}_*__\n" +
                 $"{strings.games_count} {user.Games}\n" +
                 $"{strings.wins_count} {user.Wins}\n" +
                 $"{strings.winrate} {winRate}%\n";
-            return await Bot.SendWithMarkdown2(ChatId, message, Keyboards.ProfileKeyboard(UserId));
+                */
+            return await Bot.SendWithMarkdown2(ChatId, "message", Keyboards.ProfileKeyboard(UserId));
+            
         }
     }
 }

+ 1 - 1
MafiaTelegramBot/Models/Commands/StartCommand.cs

@@ -21,7 +21,7 @@ namespace MafiaTelegramBot.Models.Commands
             var username = await Utilities.EscapeSpecific(update.Message.From.Username);
             var firstName = await Utilities.EscapeSpecific(update.Message.From.FirstName);
             var lastName = await Utilities.EscapeSpecific(update.Message.From.LastName);
-            var user = new DataBase.User
+            var user = new DataBase.UserEntity
             {
                 Id = UserId, ChatId = ChatId, Username = username, NickName =  $"{firstName} {lastName}"
             };

+ 1 - 1
MafiaTelegramBot/Resources/AppSettings.cs

@@ -4,6 +4,6 @@ namespace MafiaTelegramBot.Resources
     {
         //public static string Url { get; set; } = ""; //TODO use this if need html tg api to get message updates
         public static string Name { get; set; } = ""; //TODO paste your bot name here if need using full commands like /start@mafiabot, if value "", triggers to all /start commands
-        public static string Token { get; set; } = ""; //TODO paste your bot token here
+        public static string Token { get; set; } = "1729356281:AAG8D_hO9b2WIS19doTVrPiPW3q7GFwAX2w"; //TODO paste your bot token here
     }
 }

+ 1 - 1
MafiaTelegramBot/Resources/Keyboards.cs

@@ -115,7 +115,7 @@ namespace MafiaTelegramBot.Resources
             return new InlineKeyboardMarkup(inlineButtons);
         }
 
-        public static InlineKeyboardMarkup KickKeyboard(List<User> users)
+        public static InlineKeyboardMarkup KickKeyboard(List<UserEntity> users)
         {
             var inlineButtons = new InlineKeyboardButton[users.Count][];
             for (var i = 0; i < users.Count; ++i)