Jump to content

Search the Community

Showing results for tags 'Tutorial'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • RAGE Multiplayer
    • Announcements
    • Discussion
    • Suggestions
  • Scripting
    • Scripting
    • Resources
  • Community
    • Support
    • Servers
    • Media Gallery
  • Non-English
    • Русский - Russian
    • Français - French
    • Deutsch - German
    • Espanol - Spanish
    • Română - Romanian
    • Portuguesa - Portuguese
    • Polski - Polish

Categories

  • Scripts
  • Gamemodes
  • Libraries
  • Plugins
  • Maps
  • Tools

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Facebook


Youtube


Skype


Web


VK

Found 21 results

  1. Because I had a lot of issues with blocking ma topic on forum, I migrated tutorial on my github with some example for easy understanding. You can find tutorial HERE If you have any guestions, ask here on forum or discord.
  2. For those who face this error and cannot connect to public or personal servers, I have a solution for you. Follow the exact steps listed below: 1. Restart the PC or be sure that you closed every instance of GTA V & Rage MP. 2. Go to Documents(usually located in your Root disk, where the operating system is installed), find 'Rockstar Games', open it and delete the 'Social Club' folder. 3. Open updater.exe(located in the Rage MP folder) and connect to a server. 4. Rage will open the Rockstar Games Launcher and will ask you to connect to your Rockstar Games account, so do that. 5. After that, you'll notice that Rage MP has stopped, open Rage MP again and connect to a server. It took me a few days to solve this problem, leave a reply if it helped you somehow. - STKappa
  3. How to create a database and save a player's coordinates in it Hello. As a beginner I had lots of trouble finding a MySQL appropriate tutorial for beginners in development. I spent days learning how to create a basic table and save records in it. I decided to create this tutorial so that no one has to go throught what I went. This tutorial is divided in X parts. Feel free to jump ahead if you already to know how to do some. Index Downloading MySQL and MySQL Workbench Installing MySQL Driver Creating a database Connecting to the database and creating a table in it Manipulating the table 1- Installing MySQL and MySQL Workbench For you to be able to save databases and work with them you must first install MySQL and MySQL Workbench. Firstly, go to https://www.mysql.com/downloads/. Now, follow the steps on this video: https://www.youtube.com/watch?v=GIRcpjg-3Eg. I won't do a tutorial on how to install MySQL as it is to complex and very standart to everyone. 2- Installing MySQL Driver After installing MySQL we can access it by using Node.js. This tutorial will use the "mysql" module, downloaded from NPM. To download and install the "mysql" module, open the Command Terminal (go to your search bar and type 'cmd') and execute the following: C:\Users\Your Name>npm install mysql 3- Creating a database If you corretly followed the video above mentioned, you should have something like this once you open your MySQL Workbench: https://imgur.com/wSHrWr0 https://imgur.com/wSHrWr0 You want to press on Local instance MySQL80 or on any other connection you have. Once you do, the following page will open: https://imgur.com/vzSUhvS Right click on the left side box named Schemas and click 'Create Schema': https://imgur.com/rPg6RVi Name it 'rpg' (or whatever you want, just pay attention on the future steps) and click Apply twice and Finish. https://imgur.com/c1CrPwA Nice. Your database has been created. Now, we must connect to it. 4- Connecting to the database and creating a table in it To connect to a database, create a file on your server-files folder named connection.js. Once you create one go to your index.js and add in it the following: require('./connection.js') This will make your server know this file exists and run the code in it. Now, back to connection.js, type the following: var mysql = require('mysql'); With the first line, we are now importing the 'mysql' module to the file. Now, in the same file, type this: const con = mysql.createConnection({ host:'127.0.0.1', // host of server user:'user', // MySQL user password:'password', // MySQL password database: "rpg" }); With this code we are connecting to the database you host. Make sure to replace the user, the password and the database with whatever you had chosen in the previous steps. After connecting to the database, we can now manipulate it. Firstly, we'll create a table. The table can be created on MySQL Workbench or on the javascript file. If you create it on the file, it will try to create it everytime you open your ragemp-server, but it will return an innofensive error if it already exists. I'll create in on the file. Type the following: var sql = "CREATE TABLE players (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, scID int NOT NULL UNIQUE, posX int NOT NULL, posY int NOT NULL, posZ int NOT NULL)"; con.query(sql, function (err, result) { if (err) { console.log('The following error happened while creating [players]: ' + err); throw err; } console.log("[players] has been created"); }); With the code above we've just created a table called 'players' which has 5 columns: 'id', 'scID', 'posX', 'posY', 'posZ'. As you can see, all of them are integers, which means they only accept numbers. If you try to add 'banana' to 'posX', you'll get an error. Also, all of them are NOT NULL, which means that there must be a value in them, they can't be empty, or you'll also get an error. 'scID' is unique, which means that the same data can't be repeated twice. Finally, 'ID' is a Primary Key, which is a mix between NOT NULL and UNIQUE. It uniquely identifies each record in a table. It is also AUTO_INCREMENT, which means a new number will be automatically generated when a new record is inserted into a table. After typing it, open your console. You received the following log: "[players] has been created". It obviously confirms that the table has been created. If you close your console and open it again, you'll instead receive this log: "The following error happened while creating [players]: Error: ER_TABLE_EXISTS_ERROR: Table 'players' already exists". That means that the table couldn't be created because it already exists. There's nothing wrong with the error. You can change it so the server doesn't try to create a table if it already exists, but I'll just leave it be. Now that our table is created, we want to manipulate it, but first make sure you add the module below to the bottom of connection.js: exports.con = con This will make it so that the const 'con' can be used in any file that imports it, which will be necessary for the next step. 5- Manipulating the table Now that we've created the table, we wan't to manipulate it according to our needs. You can do this on the same file, but we'll create another one. On the server-files folder, create a file named database.js (or whatever you want). Once again, make sure to add the require module to index.js: require('./database.js') Now, back to database.js, add the following: const con = require('./connection').con; This will import the 'con' const from connection.js, so that we can use it on this file. Now, we want to add a player's Rockstar Games Social Services ID to our table once he joins for the first time. To do it, write the code above: mp.events.add('playerJoin', (player) => { const socialID = player.rgscId; console.log(`[SERVER]: ${player.name} [SCID: ${player.rgscId}, ID: ${player.id}] entrou no servidor.`); con.query('INSERT INTO players (scID, posX, posY, posZ) VALUES ('+socialID+', 174, -919, 30.687)', function (err, result) { if (err) { console.log('The following error happened while inserting a new record to [players]: ' + err) throw err; } else { console.log(`New player: ${player.name}`); }; player.spawn(new mp.Vector3(174, -919, 30.687)); }); }); With this code, once a player join's we'll get is Social ID, send a log to the console informing us about his connection, insert his Social ID into our database (so that we can identify him later) and spawning him on X: 174, Y: -919, Z: 30.687. Now, as we made it so that the scID (Social ID) was UNIQUE, if a player is already in the database we can't add him again, and if we try to it will return an error. So, if you connect to your server for the first time, you'll get the log: "New player: [Your Name]". If you connect again, you'll get the log: 'The following error happened while inserting a new record to [players]: Error: ER_DUP_ENTRY: Duplicate entry '12345678' for key 'players.scID'. This means it detected that the scID you tried to insert already existed and, because the column is unique, we can't insert a similar one. Now, we can use this error to our advantage, as we don't need to check if a value already exists, because the error already tells us if it does or not. So, replace the code above with the one below: mp.events.add('playerJoin', (player) => { const socialID = player.rgscId; console.log(`[SERVER]: ${player.name} [SCID: ${player.rgscId}, ID: ${player.id}] entrou no servidor.`); con.query('INSERT INTO players (scID, posX, posY, posZ) VALUES ('+socialID+', 174, -919, 30.687)', function (err, result) { if (err) { switch(err.code) { case "ER_DUP_ENTRY": console.log("The following error happened while inserting a new record to [players]: " + err); con.query('SELECT posX, posY, posZ FROM players WHERE scID = '+socialID+'', function (err, result) { if (err) { console.log('The following error happened while selecting scID from [players]: ' + err); throw err; } else { player.spawn(new mp.Vector3(result[0].posX, result[0].posY, result[0].posZ)); } }); break; default: console.log('The following error happened while inserting a new record to [players]: ' + err) throw err; } } else { console.log(`Novo jogador: ${player.name}`); }; player.spawn(new mp.Vector3(174, -919, 30.687)); }); }); With this code, if there's an rror we'll check if the error is "ER_DUP_ENTRY" (if the value is duplicated). If it is, we will stop trying to insert it and actually use the coordinates assigned to a Social ID to spawn the player with that Social ID on those coordinates. We select 'posX', 'posY' and 'posZ' from the row where the 'scID' value is equal to the Social ID of the player that joined the server and spawn that player in those positions. If there's an error while selecting the values, we'll make sure that it is logged. Also, as we don't know for sure that the only error that we will face is "ER_DUP_ENTRY", we make sure to add a switch statement. If the error is the mention, we'll try to spawn the player and if it isn't we'll log it. Now, we made it so that a player spawns in the coordinates associated to him, but we need to actually made those coordinates change whenever he leaves. For this, add this code to the same file: mp.events.add('playerQuit', (player, exitType, reason) => { const socialID = player.rgscId; pos = player.position console.log(`[SERVER]: ${player.name} [SCID: ${player.rgscId}, ID: ${player.id}] left the server.`); con.query('UPDATE players SET posX = '+pos.x+', posY = '+pos.y+', posZ = '+pos.z+' WHERE scID = '+socialID+'', function (err, result) { if (err) { console.log(err); throw err; } else { console.log("Coordinates added") } }); }); This code means that once a player quits the server, we'll log the console of his disconnect and update the 'players' table with the coordinates where he left the server. We search for the row where his Social ID equals 'scID' and change his coordinates to the ones we obtained with the 'pos' var. If we do it successfuly, we'll log to the console: "Coordinates added". If there's an error, we'll log it. This is it. Thank you very much. If you know of anyway I can make my code better, let me know.
  4. Using Microsoft Dependency Injection in RAGE:MP I used # instead of dot, cause security reasons of page. Intro After some time of researching how to implement dependency injection in RAGE MP C sharp script, I finally found correct way to use it.I didnt find any good solution on Discord or forum, so I wanted to share with you this knowledge, so you dont need to waste your time if you choose to use it in your project. I will not upload it on github but I will try to explain every part of code to details. If you guys have any question, ask I will help back. Concept of Dependency Injection Concept of dependency injection may be little bit complicated for beginners so I will paste some documents from WEB so you get basic idea of using this. If you understand concept skip this part. In object-oriented programming (OOP) software design, dependency injection (DI) is the process of supplying a resource that a given piece of code requires. The required resource, which is often a component of the application itself, is called a dependency. Dependency injection can be useful when working with large applications because it relieves various code modules from the task of instantiating references to resources and allows dependencies -- even mock dependencies -- to be swapped out easily, which can make unit testing easier. -https://www.techtarget.com/searchapparchitecture/definition/dependency-injection Like I sad for beginners it may be complicated, I copied this text just so you know basics of DI. What is DI and why its useful. In my example I will have script with WorldWeather service implemented inside DI in different ways. In couple of examples I will show you what is Transient, Scoped, Singleton services in DI concept. Script structure ServiceContainer#cs Starting#cs Services - FOLDER App#cs App2#cs WorldWeather#cs Add this elements to your empty project. Be careful, all Services must be inside folder ( It doesn't matter how folder is called ), while Starting#cs, ServiceContainer#cs should be in ROOT folder of your project. Just like this on image... ServiceContainer.cs - file Create ServiceContainer#cs class and copy next code inside: public static class ServicesContainer { public static ServiceProvider serviceProvider; public static IServiceScopeFactory serviceScopeFactory; public static void Init() { var services = ConfigureServices(); serviceProvider = services.BuildServiceProvider(); serviceScopeFactory = serviceProvider.GetService<IServiceScopeFactory>(); } public static IServiceCollection ConfigureServices() { IServiceCollection services = new ServiceCollection(); var config = LoadConfiguration(); services.AddSingleton(config); services.AddScoped<WorldWeather>(); return services; } public static IConfiguration LoadConfiguration() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); return builder.Build(); } } Starting.cs - file Create Starting#cs class and copy next code inside. public class Starting : Script { public Starting() : base() { ServicesContainer.Init(); } } WorldWeather.cs Create WorldWeather#cs class inside Services folder and copy next code inside. public class WorldWeather : Script { public Guid _Id { get; set; } private string CurrentWeather { get; set; } = string.Empty; private string[] Weathers = { "\x1b[92m Sunny", "\x1b[95m Rainy", "\x1b[96m Windy", "\x1b[94m Freezing cold", "\x1b[91m Boiling hot", "Cloudy" }; public WorldWeather() { _Id = Guid.NewGuid(); Random rnd = new Random(); CurrentWeather = Weathers[rnd.Next(Weathers.Length)]; } public string GetWeather() { return $"\x1b[39m Weather Service - with ID: {_Id} is saying... Outside is {CurrentWeather}"; } } App.cs - file Create App#cs class inside Services folder and copy next code inside. public class App : Script, IDisposable { private IServiceScopeFactory scopeFactory = ServicesContainer.serviceScopeFactory; private IServiceScope _scope; public App() { _scope = scopeFactory.CreateScope(); } public void Dispose() { _scope.Dispose(); } [ServerEvent(Event.PlayerConnected)] public void OnPlayerConnected(Player player) { var Weather = _scope.ServiceProvider.GetService<WorldWeather>(); var Weather2 = _scope.ServiceProvider.GetService<WorldWeather>(); NAPI.Util.ConsoleOutput(Weather.GetWeather()); NAPI.Util.ConsoleOutput(Weather2.GetWeather()); } } App2.cs - file Create App2#cs class inside Services folder and copy next code inside. Code is same as App#cs but different class and constructor name. public class App2 : Script, IDisposable { private IServiceScopeFactory scopeFactory = ServicesContainer.serviceScopeFactory; private IServiceScope _scope; public App2() { _scope = scopeFactory.CreateScope(); } public void Dispose() { _scope.Dispose(); } [ServerEvent(Event.PlayerConnected)] public void OnPlayerConnected(Player player) { var Weather = _scope.ServiceProvider.GetService<WorldWeather>(); var Weather2 = _scope.ServiceProvider.GetService<WorldWeather>(); NAPI.Util.ConsoleOutput(Weather.GetWeather()); NAPI.Util.ConsoleOutput(Weather2.GetWeather()); } } Result - WorldWeather is Scoped service in DI In this example I have scoped my WorldWeather service in dependency injection. We can se how 2 instances of WorldWeather is created. This is because we have created 2 scopes (App and App2). Every scope is creating one instance of WorldWeather and printing 2 times weather. Also with ID we can see only 2 different IDs. Result - WorldWeather is Transient service in DI In this example we can see that not even 1 message is same. This is why every time we call WorldWeather service, DI will create new instance of it, no matter in which scope it is... Result - World Weather is Singleton service in DI In this example we can se how every single message is the same, IDs and weathers are same in all 4 messages. This is because our DI created just one instance of WorldWeather service and every time we call it, DI will return same instance. Conclusion We saw how different types of services are acting in our script. We have scoped which return same instance inside the scope, Transient which return different instance per service request and Singleton which returns same instance every per service request. var Weather = _scope.ServiceProvider.GetService<WorldWeather>(); This is called injection, where we inject our class. In ASP.NET applications ... We are injecting services with constructor, but in case of RAGE:MP its not possible ( or maybe is, but I didnt find easy and working way) Dependency injection is great for managing your code and building your script, also for testing entire application or easy switching between services. In my tutorial I didnt use Interfaces ( wanted to keep it simple ). This is not 100% proper way of implementing DI in applications. Dont use DI if you find it complicated, first google more information about this concept, and use my example for implementing it to your script. Dont forget that ServiceContainer#cs and Staring#cs should be in root component without any other classes. This is because when you start rage mp server there is not correct way of loading classes, it is loaded randomly so it can happen that script will throw you exception. Every time you create new service which you want to use in DI, dont forget to add it in ServiceContainer as Singleton,Transient or Scoped service. All your NuGet packages should be same version ( List of dependencies is below ). Needed Dependencies for DI Microsoft Extensions Configuration Json (3.1.32) Microsoft Extensions Dependency Injection (3.1.32) Microsoft Extensions Dependency Injection Abstractions (3.1.32)
  5. CREATING SERVER SIDE SCRIPT USING ENTITY FRAMEWORK CORE AND POSTGRESQL - Intro After little bit of researching, and learning a bit more about EF core, I made a decision to create tutorial how to implement it in RAGE-MP script with PostgreSQL. First of all... This tutorial may not be perfect, but all members can write ideas and different approaches. If we all find it better, I will modify this tutorial. Also, this tutorial is not made for complete new guys in programming and scripting in RAGE-MP. Not because I think someone cant do it, but this is a bit complex and may not be perfect for new guys... After all, all are welcome to try and I will try to give the answer on any question you submit. - Entity Framework Core Intro I will try to simplife this story behind Entity Framework Core. For much more details you can Google it and find it on Microsoft official page. Micosoft Entity Framework In my words: Entity Framework Core is data access technology which help us by-pass writing queries to database and make our project cleaner. EF Core is using model type approache where we write our models in the shape of c# classes. In this way EF Core will generate all necessary queries to create new table in context of our model written in c# with neccessery primary key and foreign keys to our database. What is primary and foreign keys ??. This may look to complicated and stupid, and it would be if you are creating simple small scripts in RAGE-MP. Maybe there is no need for this, but I think there is a lot of developers who wants to create some roleplay script which is becoming over complicated in short amount of time. One more thing that is really important before using EF Core. That is LINQ ( Language-Integrated Query ) library. I will not get into it, because its contain a lot of functions and this is not point of this tutorial. Check LINQ here ! - PostgreSQL Database Intro I am not expert in databases and cant tell you which one is better and faster or which one should you use for your project. I prefer PostgreSQL because its FREE and simple to use. Dont care about speed and technical specification. Syntax is similar to SQL (not the same) and most important like I said its free. If you prefer more SQL, MySQL or SQLite you can use it also with EF Core just need to download correct NuGet for your database. In this tutorial I will move fast through this section and show you only how to download PostgreSQL, create instance of your server and couple of simple steps how to update or add new row in your table. So lets start with database first ... - Downloading and installing PostgreSQL - 1. Lets visit PostgreSQL and download installation setup. PostgreSQL Download LINK. Download the installation file and run it. - 2. After download, open it and move through installation setup. Choose your components to be installed. You dont need stack builder so you can uncheck that if you want. - 3. Select your directory for database, press NEXT and then insert your password for super user account. Dont forget that password. You will use it for connecting to database server. - 4. Insert port on which database will run. Default port is 5432, if you want to run it on another port, be sure that its not use by some program. - 5. After all necessary inputs, just press next next next until its finish installation. You will need to restart your PC and its done. - 6. Lets open up pgAdmin that we have installed with postgreSQL. Navigate to installed folder of postgreSQL or write in window search bar "pgAdmin". - 7. You should have one server group called "Servers". Double click on it and pgAdmin will ask you for password. Remember password you wrote in installation setup? Enter that password. - 8. If you typed in correct password you will enter in that server group and find one server instance called "PostgreSQL 14". If you dont have it, you can create your own instance of server. - 9. That should be all from postgreSQL. Images are copied from tutorial "How to Downolad and Install PostgreSQL on Windows" written by Aleksandar Kovačevič. You can also check tutorial on This link to see more information about postgreSQL. - Installing NuGet packages and connecting to postgreSQL. In this tutorial I am using Visual Studio IDE with targeted framework 3.1... I first started with 2.0 because GTANetwork.API, then figured out that I need to make reference to Bootstrap.dll ... Never mind, you will see that I used EF core compatible with netcore 2.0 or greater. Stick with that! Also make sure that every NuGet package for EF Core is the same version! If its not you will have problems at migrations and updating data base. Follow the tutorial... I will make more notes about that through steps. - 1. Open your script in visual studio, In Solution Explorer press right mouse button > Go to "Manage NuGet packages" > Install next packages. - I highlighted versions on right side. You can see that they all have same version. When you open installation window, press dropdown menu and select that version "2.1.0" or if you are using greater netcore like 3.1 you need to check which version of following packages support your targeted framework. On next image I highlighted Dependencies. You see how 2.1.0 is using Version 2.0. This is because my Targeted framework is 2.0. To see your targeted framework press right mouse button in Solution Explorer > Properties > In section "Application/Taget framework" you can see your framework and change it if you want. - 2. Okey, now when we installed everything we need, lets create some code. We will start by creating new class called postgreSQL.cs in constructor we will create try catch block where we will try to connect to our postgreSQL. If we successfully connect to database we will print version of postgreSQL. If not we will print Exception. public string connectionString = "Host=localhost;Username=postgres;Password=mypassword;Database=postgres"; public postgreSQL() { NAPI.Util.ConsoleOutput("Trying to start postgreSQL script ..."); try { var connection = new NpgsqlConnection(connectionString); connection.Open(); var sql = "SELECT version()"; var cmd = new NpgsqlCommand(sql, connection); var version = cmd.ExecuteScalar().ToString(); NAPI.Util.ConsoleOutput($"Succesfully connected to PostgreSQL Version: {version}"); } catch (Exception ex) { NAPI.Util.ConsoleOutput($"Error: Can't connect to the database."); NAPI.Util.ConsoleOutput($"Exception: {ex.Message.ToString()}"); } finally { } } Check variable "connectionString". Its our connection string for postgreSQL. Host is your localhost or "127.0.0.1". Username you can find in pgAdmin clicking right mouse button on server "PostgreSQL 14" and going to Connection section of window. There you can find everything expect password. Password you need to input is password from postgreSQL installation for super user. Be sure to write everything right in connection string. Database we are using is postgres, also default made by postgreSQL. If you want you can create your new database called "Server" or something like that. Be sure that match with connection string database parameter. Also be sure to create instance of this object and call it in OnResourceStart or put it in contructor of starting class... public postgreSQL sqlConnection; public mainScript() { sqlConnection = new postgreSQL(); } WARNING: If you dont want to be asked for password from localhost you can change postgreSQL settings "pg_hba.conf" and below METHOD set everything as "trust". "pg_hba.conf" is in postgreSQL installation folder. In my case: C:\Program Files\PostgreSQL\14\data for more information about postgresql access visit THIS link. - Lets try to connect. If console will print PostgreSQL then we connected to our database. If will print exception. - As you can see I connected successfully to database and it printed installed verison. - 3. Now lets create new folder in our project. Right click on solution explorer > Add > Add new folder. Call it "DataContext". In DataContext folder create "DataContext.cs" class. Paste next code in that class. internal class DataContext : DbContext { public string connectionString = "Host=127.0.0.1;Database=server;Username=postgres;Password=mypassword"; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql(connectionString); } As you can see we have class DataContext that inherit DbContext, again connection string, and override function called "OnConfiguration". For now we dont need to sniff other possibilities... This is all we need for now. We will come back later when we create some models. So lets go... - 5. Create new folder in our project. Right mouse button on Solution Explorer > Add >New Folder. Lets call it "Models". In Models folder lets create classes, Right mouse button on folder "Models" > Add > Class... Lets call it "playerModel.cs", also create one more class and call it "weaponModel.cs". Okey we have some basic models. Copy this code and put inside playerModel and weaponModel. internal class playerModel { [Key] public Guid Id { get; set; } public string socialClubName { get; set; } public string rageName { get; set; } public string characterName { get; set; } public int healthBar { get; set; } public List<weaponModel> playerWeapons; } This is our playerModel properties. We have primary key Id. This is important. Lets say I didnt add Id property... Entity framework would give me a error, because this model doesnt have "Primary key". Also before Id property I added "Key" Decorator. Guid type object is not required. You can use also number. Pay attention to playerWeapons. Its a list that contain weaponModel. So player can have multiple weapons as we already know... Now lets put next code inside your "weaponModel.cs" class. internal class weaponModel { public Guid Id { get; set; } public string weaponName { get; set; } public int weaponAmmo { get; set; } public playerModel playerModel { get; set; } } This is our weaponModel properties. As you can see there is not much inside just few parameters. property playerModel is actually interesting. Why? Because EF Core will automatically create Foreign key that will refer to playerModel Id. This is called 1:n relationships where player can have MANY weapon models, but one weapon model can be owned just by one player! For more you visit This link. - 4. Lets go back to our "DataContext.cs" class. And add this models inside our context. internal class DataContext : DbContext { public DbSet<playerModel> playerModel { get; set; } public DbSet<weaponModel> weaponModel { get; set; } public string connectionString = "Host=127.0.0.1;Database=postgres;Username=postgres;Password=mypassword"; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql(connectionString); } You can see that we added 2 new properties inside over DataContext. Entity Framework will generate all code for us with this models. Its important to add it in DataContext. Not to much to say... If you are interested in what this actually do, google it. Lets move to another part. - 5. Lets create our first migrations. First lets create folder "Migrations" In our project. Right mouse button in Solution explorer > Add > Folder. Lets switch to Package Manager Console. You can open it in next steps... Tools > NuGet Package Manager >Package Manager Console. Should be opened in bottom of your Visual Studio IDE. Okey now lets make some migrations. In your Package Manager Console write next command. "firstMigration" is just a name of this migration. You can call it whatever you want. Add-Migration firstMigration If everything was without error you should see next text. You can also undo this snapshot with "Remove-Migration" if you missed something. Okey now lets update database. - 6. In the Package Manager Console input next command: "update-database". As you can see I had some problems with authentication. If you have similar problem refer to this text I wrote: After I change everything to trust, Console said "Applying migration '200220828182213_firstMigraton' > 'Done.' And now we know everything was done successfully... Lets check our database now. Open pgAdmin, connect to your server using your password. Navigate to database you are using. Go to Schemas > public >Tables. You should see 3 tables. We see _EFMigrationsHistory where all migrations will be stored and also our playerModel and weaponModel table. Lets check that also. Right mouse button on playerModel > View/Edit Data > All rows. We can see all properties we set in our playerModel class here in database... Expect playerWeapons List... Lets open weaponModel table in database... Here we can see playerModelId. So when player save some weapon it will be saved in weaponModel table, but it will refer on that player with foreign key. - 7. Okey now we done with everything... But how can we fetch data from database and store it on server. For purpose of this tutorial I made some class to fetch data from database and save data. Create new class with right mouse button in Solution Explorer > Add >Class.. Lets call it "OnPlayerLogin.cs" Put next code inside it... internal class OnPlayerLogin : Script { public DataContext dataContext; public OnPlayerLogin() { dataContext = new DataContext(); } [ServerEvent(Event.ResourceStart)] public void ResourceStart() { NAPI.Util.ConsoleOutput("OnPlayerLogin started"); } [ServerEvent(Event.PlayerSpawn)] public async void OnPlayerSpawn(Player player) { NAPI.Chat.SendChatMessageToPlayer(player, $"Hello {player.SocialClubName}"); await GetAllDataFromDatabaseAsync(player); var allProperty = typeof(playerModel).GetProperties(); foreach (PropertyInfo property in allProperty) { string EntityDataName = property.Name.ToString(); var result = NAPI.Data.GetEntityData(player, EntityDataName).ToString(); NAPI.Chat.SendChatMessageToPlayer(player, "propertyName ", EntityDataName); NAPI.Chat.SendChatMessageToPlayer(player, "value: ", result); } player.Health = NAPI.Data.GetEntityData(player, nameof(playerModel.healthBar)); } /// <summary> /// Async function that pull all data from database and store it with SetEntityData method. /// Data is stored in patern of given player model context. /// </summary> /// <param name="player"></param> /// <returns>System.Threading.Tasks.Task</returns> public async Task GetAllDataFromDatabaseAsync(Player player) { await Task.Run(() => { // Dont use social club name. Use Social club ID. var result = dataContext.playerModel.Where(x => x.socialClubName == player.SocialClubName).First(); var allProperty = typeof(playerModel).GetProperties(); foreach (PropertyInfo property in allProperty) { string EntityDataName = property.Name.ToString(); dynamic value = property.GetValue(result); NAPI.Data.SetEntityData(player, EntityDataName, value); NAPI.Util.ConsoleOutput($"{EntityDataName}: {property.GetValue(result)}"); } }); } /// <summary> /// Async function that save all data from GetEntityData method to Database. /// Data is saved in patern of given player model context. /// </summary> /// <param name="player"></param> /// <returns>System.Threading.Tasks.Task</returns> public async Task SaveAllDataToDatabaseAsync(Player player) { await Task.Run(() => { var result = dataContext.playerModel.Where(x => x.socialClubName == player.SocialClubName).First(); var allProperty = typeof(playerModel).GetProperties(); foreach (PropertyInfo property in allProperty) { string EntityDataName = property.Name.ToString(); property.SetValue(result, NAPI.Data.GetEntityData(player, EntityDataName)); } dataContext.SaveChanges(); }); } [Command("savedata", "Use /savedata", GreedyArg = true)] public void CMD_SavePosition(Player player) { NAPI.Chat.SendChatMessageToPlayer(player, "Started saving all your data. Please wait ..."); SaveAllDataToDatabaseAsync(player).ContinueWith(task => NAPI.Chat.SendChatMessageToPlayer(player, "Finished all saving ...")); } [Command("hp", "Use /hp", GreedyArg = true)] public void SetLowHP(Player player) { NAPI.Data.SetEntityData(player, nameof(playerModel.healthBar), 10); player.Health = 10; } } In code above 90% is just dump code for testing. Only 2 functions are important. Lets check them. /// <summary> /// Async function that pull all data from database and store it with SetEntityData method. /// Data is stored in patern of given player model context. /// </summary> /// <param name="player"></param> /// <returns>System.Threading.Tasks.Task</returns> public async Task GetAllDataFromDatabaseAsync(Player player) { await Task.Run(() => { // Dont use social club name. Use Social club ID. var result = dataContext.playerModel.Where(x => x.socialClubName == player.SocialClubName).First(); var allProperty = typeof(playerModel).GetProperties(); foreach (PropertyInfo property in allProperty) { string EntityDataName = property.Name.ToString(); dynamic value = property.GetValue(result); NAPI.Data.SetEntityData(player, EntityDataName, value); NAPI.Util.ConsoleOutput($"{EntityDataName}: {property.GetValue(result)}"); } }); } /// <summary> /// Async function that save all data from GetEntityData method to Database. /// Data is saved in patern of given player model context. /// </summary> /// <param name="player"></param> /// <returns>System.Threading.Tasks.Task</returns> public async Task SaveAllDataToDatabaseAsync(Player player) { await Task.Run(() => { var result = dataContext.playerModel.Where(x => x.socialClubName == player.SocialClubName).First(); var allProperty = typeof(playerModel).GetProperties(); foreach (PropertyInfo property in allProperty) { string EntityDataName = property.Name.ToString(); property.SetValue(result, NAPI.Data.GetEntityData(player, EntityDataName)); } dataContext.SaveChanges(); }); } This 2 functions are refering to our playerModel class, check for all properties inside and loop through it so we can pull it from database and store in SetEntityData function OR to Save it from GetEntityData to database. The magic behind this is after adding new properties to playerModel class, we need to create new migration with "Add-Migration" command, and "Update-Database", after that we are able to use our new properties and access it with very easy. Example is "/hp" command. Check next code. [Command("hp", "Use /hp", GreedyArg = true)] public void SetLowHP(Player player) { // nameof(playerModel.healthBar return "healthBar" as a string NAPI.Data.SetEntityData(player, nameof(playerModel.healthBar), 10); player.Health = 10; } - 8. Now lets test it. I will manualy add to my database my social club name and other parameters, lets check if its getting loaded inside game. Go to pgAdmin > playerModel table > View/Edit Data > All rows. Yellow button is for adding new row. I used online Guid generator from HERE. After adding data dont forget to press F6 to update playerModel table. Watch out! Dont press enter to add new line to columns case it will add "\n" sign for new line. Just check you dont have new lines in text editor inside pgAdmin when adding new text in some columns. We can see how game pulled from database. Lets check one more time code and for the end make conclusion on this tutorial. /// <summary> /// Async function that pull all data from database and store it with SetEntityData method. /// Data is stored in patern of given player model context. /// </summary> /// <param name="player"></param> /// <returns>System.Threading.Tasks.Task</returns> public async Task GetAllDataFromDatabaseAsync(Player player) { await Task.Run(() => { // Dont use social club name. Use Social club ID. var result = dataContext.playerModel.Where(x => x.socialClubName == player.SocialClubName).First(); var allProperty = typeof(playerModel).GetProperties(); foreach (PropertyInfo property in allProperty) { string EntityDataName = property.Name.ToString(); dynamic value = property.GetValue(result); NAPI.Data.SetEntityData(player, EntityDataName, value); NAPI.Util.ConsoleOutput($"{EntityDataName}: {property.GetValue(result)}"); } }); } - Tutorial Conclusion. This code is definitely not code you would use in your script. There is no any error handling or better management. That was not even the point of this tutorial. My point was to introduce you to EF Core and how you can use it in RAGE MP. We can see there is a little bit more work and preparation for script. But once you create everything right, every other step will be easier, also your code will be much cleaner. Unlucky for you didn't cover much more functions with LINQ. How to chain functions, get all weapon models where foreign key is connected with my account ... Also I didn't even used "using" keyword to dispose instance after program leaves that block where I call dataContext, which is not great. But like I said, main goal was not to create perfect script. If you guys find some problems in this tutorial, write it and I will try to fix it.
  6. Hello. I've been meddling around with the RageMP API and I've learned most of it myself with the help of the discord members. Shoutout to Xabi, Sake and everyone else for helping me out with this language. Anywho I've come to realise that when I had started out there was nothing that would guide me through the process of making a server or creating the script for that matter. So here I bring you a YouTube playlist of the RageMP C# language tutorial. It is still under progress but I keep uploading new tutorials daily. And I mostly describe most of the elements so the videos might seem longer than usual tutorials. But I'd suggest to not skip anything and go over everything that I have to offer thoroughly. And if you do like my tutorials then do subscribe and like it too! And happy coding!
  7. Hi , in this video I am going to show a simple way how to make a marker on your new server. I will assume that you followed all the steps on how to get your server to work and that you installed Node.js and so on. This is not the best way of doing this but I find it the most simple way. I am also a beginner and I would love to help myself and others who are trying to build their own and unique servers. If you need any other help, please leave a comment. Hope you enjoyed. { To all experts out there, I am sorry, I am just trying to help out the community. }
  8. Hi everyone! 🖐️ Today I was a reading the "Getting started running a server" guide when I thought about putting the stuff in Docker, to be minimal as possible. Then, I came here to show you how to do it. You will need to create a folder with the name of your project, and inside it, we'll put only three files. You need to have Docker Desktop installed already. Step 1 - Dockerfile Create a file with the name Dockerfile, and without an extension. Inside it, paste the code below: FROM ubuntu:latest WORKDIR /opt/app COPY ./app /opt/app RUN chmod +x ragemp-server CMD ["./ragemp-server"] This will be our base system, based on Ubuntu 20.04 LTS (Linux dist). We are going to create an app folder inside opt (default by the system) and give permission to a file that we are going to add later. At the end, the Dockerfile starts the server with the command provided in the CMD directive. Step 2 - docker-compose.yml Create a file with the name docker-compose.yml, this will be our orchestrator: the file that manage all the services that the server needs in order to run properly. Paste the code below: version: "3.9" services: ragemp_server: build: . hostname: "ragemp_server" container_name: "ragemp_server" ports: - "22005:22005/udp" - "22006:22006" tty: true networks: default: external: name: ragemp_network This will add only one service called ragemp_server, and it'll contain the server files. The file will map the ports between the container and your PC. You will need to create the network with the following command: docker network create ragemp_network Step 3 - app folder Finally, you need to download the linux server files and extract them into the app folder. Once you got the files inside the app folder (you need to have the bin and dotnet folders, and the ragemp-server executable) you can run the following command in the root of the project: docker-compose up. This will create the container and run the server. Then, you can go to RageMP > Direct Connect > 127.0.0.1 : 22005 In my case, I'm running the server on a Macbook Pro and testing it on a Windows machine, so in that case you will need to run the ifconfig or ipconfig command to know your IP address, and then connect to it (i.e: 192.168.0.102:22005). Your machines need to be in the same network. Step 4 - (Optional) Get into the container If you need to get into the Ubuntu machine to run some commands, you can do it with the following cmd: docker exec -it container_name bash Replace container_name by the name of your container. Once inside, you can run whatever you want because you'll be the root user. If you have questions, please leave a comment and I'll be answering ASAP. I'm new at RageMP so I don't have a great knowledge about it, but I'm a programmer anyway 🤷‍♂️ Goodbye! 🖐️
  9. Hello, I would like to show you how to properly install the RageMP server on the Centos 7 linux distribution. Table of Contents: System update Package installation Building GCC 7.3.0 Adding a user Server installation Starting the server Informations: Yum - Package manager in the RHel system Update - Argument to yum Install - Argument to yum -y - skipping accepting installation Screen - Allows you to run processes in the background Warning! Change USERNAME to your username! 1. System update yum update -y; 2. Package installation yum install epel-release -y; yum install nano zip unzip libunwind libunwind-devel libicu libicu-devel nodejs npm screen psmisc curl wget gmp-devel mpfr-devel libmpc-devel; yum groupinstall 'Development Tools'; 3. Building GCC (7.3.0) - The process takes about 1H or 2H depends on what server you have. cd /root; wget https://ftp.gnu.org/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz; tar -xf gcc-7.3.0.tar.gz; mkdir gcc-build; cd gcc-build; ../gcc-7.3.0/configure --enable-languages=c,c++ --disable-multilib --prefix=/usr/ ; make -j$(nproc); make install; 4. Adding a user adduser USERNAME Setting the password passwd USERNAME 5. Server installation su - USERNAME wget https://cdn.rage.mp/lin/ragemp-srv.tar.gz; tar -xf ragemp-srv.tar.gz; cd ragemp-srv; mv * ../; cd ../; rm -rf ragemp-srv; wget https://cdn.gtanet.work/bridge-package-linux.tar.gz; tar -xf bridge-package-linux.tar.gz; rm -rf *.tar.gz 6. Starting the server screen -dmS serwer ./server Going to the console screen -r serwer Original Polish Tutorial: 2018 © Matix8981 All rights reserved
  10. Hey ich wollte mal fragen ob mir hier jemand c# scripten beibringen kann. Bin ein kompletter Anfänger und hatte noch nie was mit diesem Thema zutun wäre also nett wenn man mir das scripten beibringen würde z.B. wie man ein Handy scriptet mit jeder Funktion Sms, Telefonieren usw.
  11. plz puch it in german scripting base i can not start a topic on the channel Ich habe ein server genau nach der anleitung von Flashrex aufgesetzt und eingestellt weil ich scripten lernen wollte. Aber wenn ich alles genau wie im video mache was ein wenig dürftig erklärt und in meinen augen einfach nur durch gerusht ist um ja die 15mins einzuhalten fehlen einfach die infos wenn fehler auf treten wie mann sie fixt oder wie mann an den error rann kommt weil eine console die nur System.InvalidOperationException: There is an error in XML document (8, 2). ---> System.Xml.XmlException: There are multiple root elements. Line 8, position 2. at void System.Xml.XmlTextReaderImpl.Throw(Exception e) at void System.Xml.XmlTextReaderImpl.Throw(string res, string arg) at bool System.Xml.XmlTextReaderImpl.ParseDocumentContent() at bool System.Xml.XmlTextReaderImpl.Read() at bool System.Xml.XmlTextReader.Read() at void System.Xml.XmlReader.ReadEndElement() at void System.Xml.Serialization.XmlSerializationReader.ReadEndElement() at ResourceInfo Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderResourceInfo.Read14_ResourceInfo(bool isNullable, bool checkType) at object Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderResourceInfo.Read15_meta() --- End of inner exception stack trace --- at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events) at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream) at GTANetworkInternals.GameServer.StartResource(String resourceName, String parent) ausgiebt und nicht mal genau angiet welche datei es ist bringt einenem nichts wenn mann den fehler fixen will. ich hoffe das einer helfen kann um das problem zu lösen und vllt Flashrex seine video nochmal überarbeitet oder auch die kommentare darunter mal bantwotet. MFG TheMock
  12. Ich habe gesehen, dass es bisher nur wenige deutsche Tutorials zu RageMP und vor allem zur Beta gibt und dachte ich mach mal eine Reihe für die Community. In der Reihe werden wir C# Serverseitig und Js Clientseitig verwenden. Die Reihe richtet sich an Leute die bereits programmieren können und zumindest die Grundlagen einer objektorientierten Sprache kennen. Ich hoffe ich kann mit den Videos einigen helfen. Fragen, Wünsche für zukünftige Videos & Kritik ist natürlich gerne gesehen. Geplant ist bisher: (nicht unbedingt in der Reihenfolge) - einfache Befehle - GetData/SetData - Arbeiten mit .json-Dateien - Einfache Datenbank (Mysql) - Login-System (Arbeiten mit CEF) - Erklärung von Clientside/Serverside Beta installieren, Server-Files einrichten, Projekt aufsetzen: Arbeiten mit Server Events:
  13. Kleines Videoprojekt wo ich euch mithilfe von Javascript/Visual Studio Code ein paar Basics der Scriptens beibringen/zeigen möchte. Finde aktuell im deutschsprachigen Raum kaum/keine Tutorials. Ich hoffe die Videos gefallen euch und helfen euch weiter. Vielleicht animiere ich den ein oder anderen ein Projekt zu starten Abonnieren, Liken & Kommentieren !!!Bei Fragen in die Kommentare oder checkt unseren Discord aus!!! Discord: Nia#6075 Link zum Video:
  14. Create file 'commandline.js' to dir 'packages/keker' with the following code: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function ParseCmd(s){ var args = s.split(" "); var cmd = args[0].toLowerCase(); var res = ''; switch(cmd){ case "ban": mp.players.forEach(player => { if(player.name.toLowerCase() == args[1].toLowerCase()){ player.ban("Console"); res = " Player "+player.name+" was banned!!!"; } }); break; case "kick": mp.players.forEach(player => { if(player.name.toLowerCase() == args[1].toLowerCase()){ player.kick("Console"); res = " Player "+player.name+" was kicked!!!"; } }); break; case "tppos": if(args.length>4){ mp.players.forEach(player => { if(player.name.toLowerCase() == args[1].toLowerCase()){ player.position = new mp.Vector3(parseFloat(args[2]), parseFloat(args[3]), parseFloat(args[4])); res = " Player "+player.name+" was teleported to X:"+parseFloat(args[2])+" Y:"+parseFloat(args[3])+" Z:"+parseFloat(args[4])+"!!!"; } }); } else { res = " Invalid arguments!!!" } break; case "give.weapons": if(args.length>3){ mp.players.forEach(player => { if(player.name.toLowerCase() == args[1].toLowerCase()){ player.giveWeapon(mp.joaat(args[2]), parseInt(args[3])); res = " Player "+player.name+" received weapons!!!"; } }); } else { res = " Invalid arguments!!!" } break; case "status": res = "\n Players: "+mp.players.length+"/"+mp.players.size+"\n Vehicles: "+mp.vehicles.length+"\n Objects: "+mp.objects.length+"\n Wheather: "+mp.environment.weather+"\n Game Time: "+mp.environment.time.hour+"h\n Uptime: "+process.uptime()+"\n"; break; case "online": res = "\n Online: "+mp.players.length+"/"+mp.players.size+"\n "; mp.players.forEach(player => { res += player.name+" | "+player.ip+" | "+player.ping+"\n "; }); break; default: res = " Unknown command!!!"; break; } return res; } rl.on('line', (s) => { var res = ParseCmd(s); console.log(res); }); After that, append to file 'packages/keker/index.js' the following line: require("./commandline"); Then you can execute commands on the server console. The list of available commands as seen from the code: ban <PlayerName> -> Kiked player kick <PlayerName> -> Baned player tppos <PlayerName> <X> <Y> <Z> -> Teleport player to coordinates give.weapons <PlayerName> <WeaponName> <Amount> -> Give weapon to player status -> Show server info online -> Show players list with info(Name,IP,Ping)
  15. This tutorial will only work if you already have your MySQL + RAGE project set up. Step 1 Right-click on your project and select 'Manage NuGet Packages...'. Browse for the following packages and make sure you install the same version for all! (this example uses version 2.2.0) Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Tools Pomelo.EntityFrameworkCore.MySql Step 2 Create a Player.cs class with the following code: Step 3 Create a new class called '<myProject>Context.cs', in this example we will use TutorialContext.cs Paste the following code: Step 4 To make things easier for future classes, we will make an interface called IRepository.cs. This is not part of EF Core but it's a nice programming pattern to use with it. Copy-paste the code below into your interface: Step 5 Create a class called PlayerRepository.cs Now we will implement the interface we just created in our PlayerRepository.cs Step 6 Create a class called Main.cs so we can test our code on ResourceStart event. Paste the following code Step 7 Build and run your server You may get an error like: This means that in your RAGE runtime folder (D:\RAGEMP\server-files\bridge\runtime) you are missing the necessary dlls. Head over to (for example) A:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.entityframeworkcore\2.2.0\lib\netstandard2.0 and copy the needed .dll to the runtime folder of RAGE. You might have to do this for a couple of dlls. Just go back to the NuGetFallbackFolder and find the right one. If you fixed these errors, this should be the result: Step 8 (Extra) If you're adding more and more classes and you want to add changes to your database, use the following method: Create your new class (House.cs for example) and go back to your TutorialContext.cs and add public DbSet<House> Houses { get; set; } under Players (which we did in this tutorial). On the top left of your Visual Studio you will see a tab called 'View'. Click on it, go to 'Other Windows' and select 'Package Manager Console'. In the Package Manager Console, type: Add-Migration addedHouse Wait for the console to finish and type: Update-Database Your house class has now been added to the database. Enjoy.
  16. Hallo allerseits! Ich selber habe lange damit zugebracht zu schauen wie ich EntityFrameworkCore möglichst so nutzen kann wie EF6 (EntityFramework 6). Nach einer langen Zeit auf Google habe ich es mittlerweile auf eine recht einfache Art hinbekommen, die so jeder übernehmen kann. Ich spare mir die meisten Erklärungen, ich zeige die Schritte die ihr anwenden müsst. Inkompatibilität wenn schon andere MySQL Packages installiert sind, kann durchaus vorkommen, bitte vorher löschen. Erster Schritt Ladet folgende NuGet Packages herunter Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Tools Pomelo.EntityFrameworkCore.MySQL Pomelo.EntityFrameworkCore.MySQL.Designer Der zweite Schritt Jetzt müsst ihr eurer Projekt entladen, und dann die CSProj Datei bearbeiten. Dort fügt ihr einfach folgende zwei Informationen ein: GenerateRuntimeConfigrationFiles ist ein Workaround was den Fehler behebt wenn er beim Datenbank-Model erzeugen den Net.Core nicht finden kann. Tools.DotNet... benötigen wir damit wir (dotnet ef...) nutzen können. <PropertyGroup> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> </PropertyGroup> <ItemGroup> <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" /> </ItemGroup> Und jetzt der dritte Schritt Jetzt compilieren wir einmal das komplette Projekt (dafür das entladene Projekt wieder laden und dann neu erstellen). Wenn das erfolgreich war, können wir zum nächsten Schritt springen. Falls nicht, alle bisherigen MySQL Funktionen ausklammern, damit wir gleich das Model generieren können, müssen wir einmal compiliert haben. Jetzt der vierte Schritt, zusammgengefasst Wir öffnen jetzt Powershell oder CMD (am besten als Administrator). Jetzt navigieren wir zu unseren Projektfiles (wo die .csproj Datei liegt). Beispiel: "cd C:\Users\Administrator\ragemp_project\proj" Dort führen wir schnell noch einen kleinen Befehl aus - "dotnet restore" Um jetzt die Modelle zu generieren, müssen wir uns einen kleinen Befehl zusammenschreiben. dotnet ef dbcontext scaffold "Host=localhost;Port=3306;Database=vita;Username=root;Password=xxx" Pomelo.EntityFrameworkCore.MySql -o Model -f Hier die richtigen MySQL Daten hinterlegen. Wenn wir das jetzt ausführen, und wir keine Fehler erhalten, müssten im Projekt jetzt die Modelle liegen unter dem Ordner "Model". Wenn ihr Änderungen an der Datenbank durchführt, dann müsst ihr das nochmal ausführen, am besten schreibt ihr dafür eine .bat Datei! Der fünfte Schritt, ein Beispielcode Jetzt haben wir EntityFrameworkCore funktionsfähig in das Projekt integriert. Wir können jetzt auf die Datenbank zugreifen, siehe Beispiel! using System.Linq; using(var db = new Model.databasenameContext()) { var accounts = db.Accounts.FirstOrDefault(x => x.SocialClub == player.SocialClub); // Accounts = Model if(accounts == null) return; // Account wurde nicht gefunden accounts.Online = 1; db.SaveChanges(); } Bei Fragen einfach melden, oder falls ich etwas nicht richtig geschrieben habe einfach bescheid geben! Viel Spaß damit. Mit freundlichen Grüßen, Max Jackson
  17. Hello Someone asks me, how to create a car at right side next to player. So i just wrote this little tutorial about. I hope you enjoy this little thing, which was did in two hours, and explained with a horrible english ;D Spend time: 2 hours testing the spawn of vehicles and coding + doc 3 hours making this tutorial with translation 0.5 hours thinking about, why i am doing this ... (i didn't found an answer -.-) First we have to know some things: How is the World working How is the Position working How is the Rotation working How can i spawn a car (Code snippet) How is the World working? => It is a north axis oriented map. If you open the full map ingame, top is north, bottom is south. It is every time a constant and will not change How is the Position working? => It is a Vector based information. It has three types. X => left - | + right Y => top - | + bottom Z => down - | + up The "+" and "-" are the operators here in our coordination system, which we have to use later. How is the Rotation working? => It is a Vector based information. Same here we have three types, but the number is always positive. So we can just use the Z variable. X => back | front (Not tested) Y => left | right (Not tested) Z => ground Then we will get four options: N => 0° E => 270° S => 180° W => 90° We have to use the radius to know how the player is rotated away from north. Just think about your shool days. back then you had geometry and raius was a topic of it. Ok, we got our information. Let us code that stuff Small version Doc version
  18. Requirements Rage MP server files NodeJS VS Code (or preferred IDE/text editor) Basic typescript knowledge typescript in 5 minutes typescript overview Basic js/nodeJs knowledge Rage:MP TypeScript type definition for Server-side (credit: CocaColaBear) Introduction We are going to setup a simple rage mp server using typescript Getting Started Install typescript globally > npm install -g typescript Verify that you installed typescript correctly > tsc -v //version 2.9.2 (or whatever version you installed) Download Rage MP Typescript type files from: https://github.com/CocaColaBear/types-ragemp-s Place the the following files inside server-files folder index.d.ts vehicle_hashes.d.ts ped_hashes.d.ts weapon_hashes.d.ts enums.d.ts Setting Up Environment Go inside server-files and initiate a new npm project > npm init keep pressing enter until it asks "is this ok" and type yes or press enter. Now you should have a package.json in your server-files folder. Next install typescript dev dependencies > npm install --save-dev typescript After the install is complete, open your package.json and you should see typescript under devDependencies Next create a tsconfig.json file by running the following command > tsc --init You should now have a tsconfig.json file in your server-files directory. Open tsconfig.json and replace with: { "compileOnSave": true, "compilerOptions": { /* Basic Options */ "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "resolveJsonModule": true, /* needed to read json*/ "esModuleInterop": true, /* needed to read json*/ "outDir": "./packages/mygamemode", /* Redirect output structure to the directory. */ "strict": true /* Enable all strict type-checking options. */ }, "files": [ "index.d.ts", "vehicle_hashes.d.ts", "weapon_hashes.d.ts", "ped_hashes.d.ts", "enums.d.ts" ], "include": [ "src/**/*" ], "exclude": [ "node_modules", "**/*.spec.ts" ] } Next create a new folder called "src" inside server-files Inside of src folder create another folder called "mygamemode" or whatever your gamemode will be. Note*: make sure your "outDir": "./packages/[GAMEMODENAMEHERE]" matches your gamemode folder name in tsconfig.json Within the mygamemode create a typescript file called index.ts(this will be your initial index.js file) mygamemode/index.ts import './commands'; Next create a folder within mygamemode called commands and inside this new commands folder create a new typescript file called index.ts mygamemode/commands/index.ts function setArmour(player: PlayerMp) { player.armour = 100; } mp.events.addCommand('armour', setArmour); Compiling Now we will compile the typescript files to output to packages/mygamemode open command and type > tsc -w what this command does is it compiles your whole project first and then watches for all .ts file changes and compiles/outputs them to packages/mygamemode which is specified in the tsconfig.json. Note*: Whenever you edit a .ts file, the typescript watch (tsc -w) will automatically compile the files to packages/mygamemode. Finally run your server.exe and enjoy coding in typescript! GitHub link: https://github.com/tameemi/ragemp-typescript
  19. Getting Started with Development 🛠 🔰 The easiest way is with no doubt to download the boilerplate / example project from GitHub.You can look at the example package that is included in there to figure out how everything works. Once you've ran the Package option in IntelliJ within the boilerplate, copy the contents of the client_packages folder that should now have appeared in the project folder to the server's client_packages folder. It's that simple? Is there some kind of catch? 🤔 Nope! There is no catch. All you need to get started is an IDE that supports Kotlin. I recommend JetBrain's IntelliJ IDEA due to its performance, flexibility and customization options. I'm super excited for what the simplicity of Kotlin will bring to the RageMP community and all of your creations that have been made just a tiny bit easier 😉 (PS If you click on the header picture, it'll take you straight to the GitHub page for the library with more examples)
  20. Witajcie, Chciał bym wam zaprezentować jak zainstalować poprawnie serwer RageMP na dystrybucji linux'a Centos 7. Spis treści: Aktualizacja systemu Instalacja pakietów Budowanie GCC 7.3.0 Dodawanie użytkownika Instalacja serwera Uruchamianie serwera Informacje: Yum - Menadzer pakietów w systemie RHel'owskich Update - Argument do yum Install - Argument do yum -y - skip'owanie akceptacji Screen - Umożliwia uruchamiać procesy w tle 1. Aktualizacja Systemu yum update -y; 2. Instalacja pakietów yum install epel-release -y; yum install nano zip unzip libunwind libunwind-devel libicu libicu-devel nodejs npm screen psmisc curl wget gmp-devel mpfr-devel libmpc-devel; yum groupinstall 'Development Tools'; 3. Budowanie GCC (7.3.0) - Proces trwa około 1H lub 2H zależy jaki posiadasz serwer. cd /root; wget https://ftp.gnu.org/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz; tar -xf gcc-7.3.0.tar.gz; mkdir gcc-build; cd gcc-build; ../gcc-7.3.0/configure --enable-languages=c,c++ --disable-multilib --prefix=/usr/ ; make -j$(nproc); make install; 4. Dodawanie użytkownika adduser nazwaużytkownika Ustawianie hasła passwd nazwaużytkownika 5. Instalacja serwera su - nazwaużytkownika wget https://cdn.rage.mp/lin/ragemp-srv.tar.gz; tar -xf ragemp-srv.tar.gz; cd ragemp-srv; mv * ../; cd ../; rm -rf ragemp-srv; wget https://cdn.gtanet.work/bridge-package-linux.tar.gz; tar -xf bridge-package-linux.tar.gz; rm -rf *.tar.gz 6. Uruchomienie serwera screen -dmS serwer ./server Przechodzenie do konsoli screen -r serwer 2018 © Matix8981 Wszelkie prawa zastrzeżone 2018 © Matix8981 All rights reserved
  21. Hello. For the lazy and I do not know, give a little tutorial how to use id PS This tutorial is desirable for a pure server. So, let's begin!) To get started in the "events" create a file "skin.js" Then we declare a global variable global.ped = { }; Then take out the list of our skins, I took only the animals global.ped = { skin: mp.joaat(["A_C_Boar", "A_C_Chickenhawk", "A_C_Chimp", "A_C_Chop", "A_C_Cormorant", "A_C_Cow", "A_C_Coyote", "A_C_Crow", "A_C_Deer", "A_C_Fish", "A_C_Hen", "A_C_Husky", "A_C_MtLion", "A_C_ig", "A_C_igeon", "A_C_Rat", "A_C_Retriever", "A_C_Rhesus", "A_C_Rottweiler", "A_C_Seagull", "A_C_SharkTiger", "A_C_shepherd")] }; I apologize for this ugly code)) in the description I'll leave the file with a complete list of skins)) Then go to the folder "commands" in "basiccommands.js" file We are looking for the string "model": (player, args) => and replace command "model": (player, args) => { if (args[1] >= 723) { player.outputChatBox("Use /model 0-722"); } else if (args[1] >= 0 || args[1] <= 722) { player.model = ped.skin[args[1]]; } else if (typeof args[1] === 'string') { player.outputChatBox("Use /model 0-722"); } }, 1. We checked for correct input id skin 2. If you enter /model 0 the output functions player.model = ped.skin [args [1]]; 3. If you enter /model A_C_Boar the output error player.outputChatBox("Use /model 0-722"); It was decided to withdraw a mistake because can ruin, using say /model infernus And so, what we have: when you type the command "/model 0" we will give the skin a boar If you somehow liked the tutorial support a good comment Sorry for my English, an interpreter)) skin.js - https://yadi.sk/d/rNFgkcpm36n3dV Help in correcting code CocaColaBear
×
×
  • Create New...