Leaderboard
Popular Content
Showing content with the highest reputation on 05/19/19 in all areas
-
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! xForcer1 point
-
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
-
Version 0.2.0
730 downloads
RAGE Editor is a resource that allows you to write, test, and save JavaScript code without leaving the game. Features Derived from VS Code. RAGE Editor is built on top of Monaco Editor, which is the same text editor that powers VS Code. This means you can use familiar keybindings and color schemes when editing your code for maximum productivity. Multiple tabs and file management. You can create as many simultaneous tabs as you want in order to switch between testing environments. Tabs can be persisted to your local storage by any name and restored at any time, even through game restarts. Execute code on multiple environments. Run code dynamically on your local client, the server, or all other clients. You can also highlight a specific section of code and right click to run only that selection on any environment. Built-in up-to-date RAGE API typings w/ context switching. Typings for server-side and client-side RAGE APIs are fetched directly from GitHub to ensure you get the most up-to-date auto-complete and IntelliSense features without installing or setting up TypeScript. Local recently updated typing backups are also bundled with RAGE Editor in the event you're trying to work offline. You can switch between server-side and client-side typings with the click of a button. Configurable key binding. You can set the key binds to be any key you want for your server. Customizable user authentication using custom logic or built-in IP whitelisting. Without modification, you can specify a whitelist of IP addresses that will be able to access the editor in order to prevent anyone from running code on your server or other players, or you can omit whitelisting altogether to allow anyone to run code anywhere (not recommended, though). For more control, you can override this method by specifying your own logic to control who can access the editor, and which features they can use. See below. Dynamically move and resize the editor to your liking. In order to accommodate testing different UI components and optimizing for performance, you can drag/resize the editor to be any place and shape on your screen. Access convenient libraries such as rage-rpc. RAGE Editor uses rage-rpc under the hood to route code for remote execution. The editor also exposes a global rpc variable for you to use in your scripts for easy client<->server communication and testing! Installation Extract the provided rage-editor.zip file into your servers root. Installation is the same as any other resource. Don't forget to include the client_package in your client-side index.js: require('./rage-editor/index.js'); 3. When in game, simply press the key binding (default is F8) in order to toggle the editor view. Configuration RAGE Editor gives you some flexibility in order to make it work smoothly in your environment. There is a config.json file located in packages/rage-editor/config.json. The default version of this file should look like something like this once you open it in a text editor: { "key": 119, // F8 "port": 8083, "whitelistIPs": [], "useNgrok": true } Options: key: The key that the player will press in-game to toggle the editor. This defaults to F8. You must use the decimal representation of the key for now. Check this link for keys: https://docs.microsoft.com/en-us/windows/desktop/inputdev/virtual-key-codes port: The port that the built-in web server will serve the editor from. Monaco Editor requires web workers to function, and Chromium won't load web workers unless they are over HTTP/HTTPS. It's recommended that you open this port and disable useNgrok for the best performance and reliability. More on this below. whitelistIPs: This is an array of IPv4 strings that you want to allow to use RAGE Editor. If the list is empty, anyone will be allowed to use it without restrictions. If the list is not empty, only players whose IPs are in the list will be able to open the editor. This means you can use it in a production environment if you really want to. Be careful who you give access as they will have the ability to execute any code they want on the server or other users. useNgrok: ngrok is a utility that can open an HTTP tunnel to your server without you having to open a port (similar to Hamachi), and it comes with RAGE Editor by default. With this option enabled, you do not have to open the port specified above. However, anonymous ngrok tunnels have a maximum life-span of ~8 hours and have a limit on concurrent open connections. It's recommended that you disable this and open the port specified above yourself. This way, traffic can directly talk to your server without going through a middleman. It will increase load-time as well as reliability. Ngrok is a good way to get started and is perfectly acceptable if you have a small number of people using RAGE Editor, or you don't use it often. Connections from the same computer will always be served from localhost, whether this option is enabled or not. Usage The UI for RAGE Editor is pretty straight-forward. The top left toolbar has a few buttons that do different things regarding tab and file management: New: Opens a blank new tab. Open: Opens a previously saved file. You can only open files that aren't already open in any other tab. Save: Saves the current tab. It will prompt you for a file name of your choice if the tab is fresh. It'll overwrite the existing data if it's not a fresh tab. Save As: Saves the current tab as a different file name, but does not change this tab to reference that new file. This is useful for saving different variations of the same file. The top right section of the toolbar has some buttons that relate to executing code and switching typing contexts: L: Run the current tab locally on the current user's client. S: Run the current tab on the server. C :Run the current tab on all clients, including the current user. Server-side/Client-side: This button swaps out the built-in typings for the RAGE API. If it says Server-side, server-side IntelliSense will be available in the editor. If it says Client-side, client-side API typings will be available in the editor. This doesn't alter your code in any way other than swapping out the TypeScript definitions. You can drag the editor around by clicking and holding the top toolbar where the buttons are. You can resize the editor by clicking and holding on the handle on the lower right of the screen. The bottom right of the editor shows the status of the editor. It'll tell you when it's loading type definitions, or when it's in the middle of executing code. Currently there is no way to view execution results or errors. This will change in the future! Customization / Interoperability Access Control RAGE Editor has a built-in IP whitelist solution for controlling who can access the editor when in-game. This is great for most users, however, other users might want more flexibility and control over who can access what, and when. Since the editor uses rage-rpc under the hood to ask the server if a certain user can use the editor, this functionality can easily be overridden by any resource developer by simply re-registering the procedure on the server, making the calculation however you wish, and replying to the client if they can access the editor. You can also configure which features of the editor they are able to use. This is called every time a player presses the key bind to open the editor. Here's an example: const rpc = require('rage-rpc'); // Allow players with the name "micaww" to open the editor and execute code on all contexts rpc.register('reditor:canPlayerUse', (_, { player }) => player.name === 'micaww'); // Allow players whose name starts with "Admin" to open the editor and execute on all contexts, but only allow other players to execute code locally rpc.register('reditor:canPlayerUse', (_, { player }) => { if(player.name.startsWith("Admin")) return true; return { l: true, c: false, s: false }; }); You can either return a boolean or an object with the properties l, c, and s. If you return true, the player will be able to open the editor and execute on all contexts. If you return false, the player won't be able to open the editor at all. The key bind will do nothing. If you return an object, the editor will open, but you will need to specify which contexts they are allowed to execute on. l: Local client c: All clients s: The server This gives you unlimited control over which players can access the editor and what they are able to access. Events There are a few events that RAGE Editor exposes for you to hook into: reditor:shown (Client-side): The editor has been shown. reditor:hidden (Client-side): The editor has been hidden. Here's an example usage to disable some custom chat. // client-side const chat = require('./my-juicy-package/customchat.js'); mp.events.add('reditor:shown', () => { chat.setActive(false); }); mp.events.add('reditor:hidden', () => { chat.setActive(true); }); Examples Server-side Execution: https://streamable.com/c432b Client-side Execution: https://streamable.com/oomuq Add me on Discord micaww#3032, or message me here on the forums for any help. Here is the GitHub if you would like to contribute or have an issue: https://github.com/micaww/rage-editor1 point -
1 point
-
1 point
-
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
-
Я в самп как игрок не играл уже несколько лет и не админил больше года, было время обдумать всё и абстрагироваться от сампа. Как по мне, так то что сейчас существует в сампе - это полное дно, направленное ТОЛЬКО на задротов, которые уже в этот самп играют годами. Все боятся сделать что-то кардинально новое, потому что боятся растерять игроков, но оставлять всё как есть сейчас - тоже путь в никуда. Простому игроку сложно прийти туда (в самп), да и вообще будет не интересно, можно засунуть в любую обложку это, но получится тот же редэйдж (самп в гта 5), 1 день я там побегал и полюбовался войс чатом и интерфейсом, на 2 день там делать уже было нечего. Нет желания искать лидеров, писать заявки на форум, играть пол года ради топ тачки. Работы где нужно бегать по чекпоинтам тоже не канают в 2019 году (какая бы обложка в конечном итоге не была у этой работы - инкассатор это или грузчик). У вас там может быть хоть 10 копий айфона на сервере, но это не добавит геймплея. Потыкать в телефон - развлечение на 5 минут. Чтобы в 2019 году можно было играть в РПГ игру, нужен действительно новый режим, новые занятия, новый геймплей, а не перенос сампа в пятерку1 point
-
Du solltest erst einmal deine Rechtschreibung überarbeiten. Hilfe: https://www.spellboy.com/rechtschreibpruefung/1 point
