Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 05/19/19 in Posts

  1. Hello everyone! Many of you have decided to use Entity Framework instead of raw SQL but failed somehow in the process (myself included)! This is why I am creating this quick guide with some examples on how to use Entity Framework Core with MySQL database in RAGEMP C# gamemode. It's not perfect, but it will work just fine. If you find a mistake or have a better way of doing something, please let me know! Let's start! Requirements: - Visual Studio 17 or better - Net Core 2.2 - RageMP C# 0.3.7 - MySQL database (I use XAMPP) 1. First, you will need some dependencies. Open up the nuget package manager and add these dependencies to your project: Microsoft.EntityFrameworkCore - Version 2.2.0 Microsoft.EntityFrameworkCore.Tools - Version 2.2.0 Pomelo.EntityFrameworkCore.MySql - Version 2.1.4 Pomelo.EntityFrameworkCore.MySql.Design - Version 1.1.2 Pomelo.EntityFrameworkCore.MySql is a MySQL provider. There are many more providers, but Pomelo's is just fine. How it looks when everything's added: NOTE: As of writing this, you have to use exactly those versions I had screenshot above! 2. Now we are ready to create a DbContext class. I will just copy and paste and explain needed with comments! using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; namespace EFCoreTutorial { public class DefaultDbContext : DbContext { // Connection string, more details below private const string connectionString = "Server=localhost;Database=efcoretutorial;Uid=root;Pwd="; // Initialize a new MySQL connection with the given connection parameters protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql(connectionString); } // Account model class created somewhere else public DbSet<Account> Accounts { get; set; } } } Server = the address of the server, in this case localhost Database = name of the database Uid = user accessing the database Pwd = database password, leave empty if none 3. Create a model class, in this case it's called Account using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace EFCoreTutorial { public class Account { [Key] public int Id { get; set; } public string Username { get; set; } public string Password { get; set; } } } 4. Let's make a simple registration command. using System; using System.Collections.Generic; using System.Linq; using System.Text; using GTANetworkAPI; namespace EFCoreTutorial { public class Commands : Script { [Command("register")] public void AccountCmdRegister(Client player, string username, string password) { RegisterAccount(player, username, password); NAPI.Chat.SendChatMessageToPlayer(player, "~g~Registration successful!"); } public static void RegisterAccount(Client client, string username, string password) { // create a new Account object var account = new Account { Username = username, Password = password }; // When created like this, the context will be immediately deleted AKA disposed. // This will make sure you don't have slowdowns with database calls if one day your server becomes popular using (var dbContext = new DefaultDbContext()) { // Add this account data to the current context dbContext.Accounts.Add(account); // And finally insert the data into the database dbContext.SaveChanges(); } } } } 4a. To check if you are properly connected to the database without going into the game, make a query when a resource starts, for example: using System; using System.Collections.Generic; using System.Linq; using System.Text; using GTANetworkAPI; namespace EFCoreTutorial { public class Main : Script { [ServerEvent(Event.ResourceStart)] public void OnResourceStart() { using (var dbContext = new DefaultDbContext()) { var playerCount = dbContext.Accounts.Count(); NAPI.Util.ConsoleOutput("Total players in the database: " + playerCount); } } } } 5. Before we can test the command or the above example, we need to make a migration. Manual migrations are the only way as of EF Core. To use them in our gamemodes which are most often only libraries (.dlls), we need to "trick the system" into thinking our gamemode is executable. The easiest way is to "create" a console application. First, open your project properties, ALT + F7. Change output type to "Console Application" Save with CTRL + S! Create a new class called Program.cs with the code below: using System; using System.Collections.Generic; using System.Text; namespace EFCoreTutorial { public class Program { public static void Main(string[] args) { } } } Yes, that's right. You only need the Main method. It's because the console app approach looks for "Main" as a starting point. Save and build the project! Now let's make the first migration. Open up the Package Manager Console and type "add-migration FirstMigration" (FirstMigration is only the name). After the migration class has been created, type once again into the console "update-database". The very first migration is now added and inside your database you will find Accounts table: Note: If there are any errors by this stage, then you are most likely not connected to your Database. This guide will not cover that! 6. We are almost done. For server to properly work, it will need runtime dlls. When you first start RAGEMP client, you will download some runtime files. Those are not enough and you have to take some extra steps. Go to the "RAGEMP" root folder, then "dotnet" folder and copy everything. Paste it inside the "runtime" folder (RAGEMP\server-files\bridge\runtime). When you build your project, it will also give you runtime files. Copy everything from bin/debug/netcoreapp2.2 (default build path) except Bootstrapper.dll , Newtonsoft.Json.dll and everything that starts with YourProjectName (EFCoreTutorial in my case). Paste it once again inside the "runtime" folder (RAGEMP\server-files\bridge\runtime). Finally, open YourProjectName.csproj with notepad and add this line <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> like so: Save and close. 7. You are all set up! From now on you don't have to worry about missing runtimes, errors and whatnot. This is everything Entity Framework Core requires to work properly in RAGEMP. Changelog: - Added appsettings.json, a better way of handling connection strings. Thanks @horseyhorsey! - Some clarification - Cleaned and updated the code per @Adam's suggestion This was my first tutorial/guide. Leave feedback and opinions. Thank you for reading! xForcer
    1 point
  2. A complete basic events template in C# for the total newbie, like the first SAMP's blank script .pawn. I just copy paste some codes from the wiki and guides and organised them a bit so it will look more clear, perhaps it can give a concept of script idea for the noob. Don't crack up if you're a pro. https://pastebin.com/bbffbXk4 * If you completely have no idea where to copy it msg me, for more info https://wiki.gtanet.work/ & Tutorials forum.
    1 point
  3. You need this resource I believe
    1 point
  4. modifie le raw input dans les paramètres
    1 point
  5. You would have each house teleport the player to whatever interior and then set the players for each house in their own Dimension. Then only the people that are in the specific house will see each other (as well as any elements created in the dimension) I think thats what you wanted to know?
    1 point
  6. Я в самп как игрок не играл уже несколько лет и не админил больше года, было время обдумать всё и абстрагироваться от сампа. Как по мне, так то что сейчас существует в сампе - это полное дно, направленное ТОЛЬКО на задротов, которые уже в этот самп играют годами. Все боятся сделать что-то кардинально новое, потому что боятся растерять игроков, но оставлять всё как есть сейчас - тоже путь в никуда. Простому игроку сложно прийти туда (в самп), да и вообще будет не интересно, можно засунуть в любую обложку это, но получится тот же редэйдж (самп в гта 5), 1 день я там побегал и полюбовался войс чатом и интерфейсом, на 2 день там делать уже было нечего. Нет желания искать лидеров, писать заявки на форум, играть пол года ради топ тачки. Работы где нужно бегать по чекпоинтам тоже не канают в 2019 году (какая бы обложка в конечном итоге не была у этой работы - инкассатор это или грузчик). У вас там может быть хоть 10 копий айфона на сервере, но это не добавит геймплея. Потыкать в телефон - развлечение на 5 минут. Чтобы в 2019 году можно было играть в РПГ игру, нужен действительно новый режим, новые занятия, новый геймплей, а не перенос сампа в пятерку
    1 point
  7. Du solltest erst einmal deine Rechtschreibung überarbeiten. Hilfe: https://www.spellboy.com/rechtschreibpruefung/
    1 point
×
×
  • Create New...