Search the Community

Showing results for tags 'csharp'.



More search options

  • 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


About Me


Facebook


Youtube


Skype


Web


VK

Found 37 results

  1. This occurs due to player stamina hitting zero, resulting in hp being lost. Below is the workaround for this in both C# and JavaScript. C# //Subscribe the Tick event Events.Tick += Tick; public void Tick(List<Events.TickNametagData> nametags) { RAGE.Game.Player.RestorePlayerStamina(1.0F); } JavaScript mp.events.add('render', () => { mp.game.player.restoreStamina(100); });
  2. 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 - Latest RageMP and C# Bridge files - 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 Microsoft.EntityFrameworkCore.Tools Pomelo.EntityFrameworkCore.MySql Pomelo.EntityFrameworkCore.MySql.Design Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.Json Pomelo.EntityFrameworkCore.MySql is a MySQL provider. There are many more providers, but Pomelo's is just fine. Microsoft.Extensions.Configuration.Json is used for appsettings.json. How it looks when everything's added: 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 { // Base constructor public DefaultDbContext(DbContextOptions options) : base(options) { } // Account model class created somewhere else public DbSet<Account> Accounts { get; set; } } public class ContextFactory : IDesignTimeDbContextFactory<DefaultDbContext> { private static DefaultDbContext _instance; private static string _connectionString; public DefaultDbContext CreateDbContext(string[] args) { var builder = new DbContextOptionsBuilder<DefaultDbContext>(); // Load the connection string for the first time if (string.IsNullOrEmpty(_connectionString)) { LoadConnectionString(); } // Use it to init the connection builder.UseMySql(_connectionString, optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(DefaultDbContext).GetTypeInfo().Assembly.GetName().Name)); return new DefaultDbContext(builder.Options); } public static DefaultDbContext Instance { get { if (_instance != null) return _instance; return _instance = new ContextFactory().CreateDbContext(new string[] { }); } private set { } } private static void LoadConnectionString() { var builder = new ConfigurationBuilder(); builder.AddJsonFile("appsettings.json", optional: false); var configuration = builder.Build(); // Get the connection string located inside the appsettings.json file under the name "DefaultConnection" _connectionString = configuration.GetConnectionString("DefaultConnection"); } } } 2a. And now the appsettings.json file which is used for the connection string. You actually don't have to do it this way, but it's considered better practice and it will help you in the long run. You can place the file everywhere you want. For the simplicity I created it inside the project root. Write this short code inside: { "ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=efcoretutorial;Uid=root;Pwd=" } } 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 Important! When you have created the file, right click on it and select properties. Change "Copy To Output Directory" to "Copy always". 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 }; // Add this account data to the current context ContextFactory.Instance.Accounts.Add(account); // And finally insert the data into the database ContextFactory.Instance.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() { var playerCount = ContextFactory.Instance.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 This was my first tutorial/guide. Leave feedback and opinions. Thank you for reading! xForcer
  3. Привет!!! Продолжаем. Рассмотрим настройку среды разработки для клиентской части. Сразу извините за звук, поехали: Строка настройки событий после сборки: del "E:\RageMP\client_packages\cs_packages\*.*" /Q for /R %CD% %%i in (*.cs) do ( xcopy %%i "E:\RageMP\client_packages\cs_packages\" /Q /Y /EXCLUDE:exclude.txt ) Пока!!!
  4. Good evening, I have a big problem with the two methods mentioned above in the title, I try to get the clothes that my player wears on him, the problem is that every time the method GetClothesDrawable returns to me the value 0, no matter which slot I give it to you, do you have any idea how I can do to get the hold that my player wears? Thank you in advance for your answer.
  5. Xabi

    WiredPlayers-RP

    Version 1.1.0

    4009 downloads

    Hello everybody. Some weeks ago i made a post on this forum's spanish section releasing my old gamemode, which I have been porting to RAGE:MP right after the bridge was released for the first time. In the beginning it was only in spanish, so I didn't thought it was a good idea to release to the whole community, as not so many people here speak spanish (I guess) but, after seeing that more people than I had expected downloaded it and also taking the suggestion George made me, I decided to start translating it and also, allowing to be multilanguage in a future. That above is the main reason I'm writing this post, I want to release here my gamemode (even if the link is already in this forum) so all the people using this excelent mod can just start their development with a base gamemode, instead of making it from the scratch. I have to say that it's not 100% ported and translated but I will be working on it in my spare time, meaning this won't be an abandoned project, it will have continuous support and development. Any suggestion for the gamemode, any question or any issue, you can contact me on the forum, sending a PM or posting here. One last thing I have to point out is that I know the gamemode is not documented but please, understand that I can't explain how all the systems inside work, as it's quite big. Anyway in a near future I will be adding some wiki or documentacion explaining briefly its contents and a guide to know the structure maybe.
  6. Hi guys! Please tell me how to know. Can I start server-side development in C#? And in parallel to develop the client-side in JavaScript language? I want to use 2 languages simultaneously for development. Each side has its own. How can I implement this?
  7. Всем привет! Пожалуйста, подскажите кто знает. Могу ли я начать разработку на стороне сервера на языке C#? И параллельно разрабатывать клиент на языке JavaScript? Я хочу использовать одновременно 2 языка для разработки. На каждой стороне свой. Как я могу это реализовать?
  8. Hello. Does anyone know why my client scripts will not be executed? I created the "enable-clientside-cs.txt" in the RAGEMP root folder. My Script in "client_packages/cs_packages/Main/Main.cs": using RAGE; namespace UFFRClientScripts { public class Main : Events.Script { public Main() { Chat.Output ("Loaded Client Scripts!"); } } }
  9. I want to do a job with the Trashmaster and i need the rear position of the car. There should be a marker and u have to throw trash in the vehicle there. I cant find a function that i could use for that. I thought about getting the vehicle rotation and then calculate the position (where the trash should be thrown in). Maybe you guys could help me here with the calculation for that or smth like that. Thank you.
  10. adri1

    SAMP Dialogs

    Version 1.0.0

    164 downloads

    SA-MP Dialogs for RAGE MP (C# clientside). This is my first resource so may contains bugs... You must enable C# clientside! Usage is simple: examples in Test.cs Dialog(string dialog_name, string dialog_caption, string dialog_info, string[] dialog_buttons, string[] dialog_list_items = null, string dialog_input = null, string dialog_password_input = null)
  11. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Data.Common, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Не удается найти указанный файл. at new ServerSide.mysqli(string host, string user, string password, string db) at new ServerSide.Manager() in D:\rumod\ragemp\server-files\ragemp_csharp_scripts\ragemp_uncomiled_scripts_csharp\ServerSide\Manager.cs:line 9 --- End of inner exception stack trace --- at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at GTANetworkInternals.GameServer.<InstantiateScripts>d__61.MoveNext() at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext() at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable) at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) at GTANetworkInternals.GameServer.StartResource(String resourceName, String parent) Я подключил модуль MySql, написал реализации класса, но появляются такие ошибки. Сразу скажу, что он не может найти библиотеку я понимаю, дело в том, что она присутствует. I connected the MySql module, wrote class implementations, but such errors appear. I must say right away that he cannot find the library, I understand, the fact is that it is present.
  12. I'm thinking which language should I use to make a server. Which is more supported for RageMP? Which would u recommend to start and why? I have learned both so the knowledge wouldn't be a problem.
  13. Hi guys! Can I use Graphics.DrawSprite() method and how? The wiki has a JS language description only. I want to make a C# program, and I need this function.
  14. Hey, just started with RageMP scripting and wonder if its possible to let the Game load the compiled Assemblys instead of the raw .cs files for C# client-side scripts. If its not possible, are there any plans to support this in future releases? Thanks in advance and thanks for RageMP - comparing to some other MP mods the development feels way more "natural"!
  15. 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
  16. Hey, I'm trying to play around a bit with the C# development of RageMP to get to know it, however I got stuck in something I think it's either me doing something wrong, or possibly bug. I suppose the first, as no one else seems to cover this problem I've. I've this very simple script so far, running on NetCore 2.0, RageMP at latest stable version, but yet my server crash each time I leave a vehicle, even though I don't have any events hooked into that. However what I found very peculiar is that if I remove/comment out the OnPlayerEnterVehicle function, the crashes are gone! I've tried to debug this in VS2017 but it says this runtime error comes from external source, so it can't point at anything specific in my script. Any suggestions of what this could be? Suggestions on how to debug it further is also appreciated The runtime error The project using System; using GTANetworkAPI; namespace MyCustomResource { public class Main : Script { [ServerEvent(Event.ResourceStart)] //This type of event is mainly used for handling stuff after this resource has been initiated. public void ResourceStart() { Console.WriteLine("\n--------------------------------------"); Console.WriteLine("Blank Script by your name here v2"); Console.WriteLine("--------------------------------------\n"); } [Command("hi", Alias = "hello, hey, howdy")] public void SayHi(Client player) { NAPI.Chat.SendChatMessageToPlayer(player, "Hello!"); } [Command("car")] public void CmdCreateCar(Client client) { NAPI.Vehicle.CreateVehicle(VehicleHash.Adder, client.Position.Around(5), 0f, 0, 0, "Test"); //Spawned vehicle is visible in all Dimensions } [ServerEvent(Event.PlayerEnterVehicle)] public void OnPlayerEnterVehicle(Client player, Vehicle vehicle, sbyte seatID) { Console.WriteLine("TEst"); } } }
  17. Hey, ich bin ziemlich neu im C# Programmieren, belege derzeitig noch einen Video Kurs auf udemy.com und programmiere nebenbei kleinweise eine RP Resource. Ich stehe nun kurz davor das ganze mit einer Datenbank zu verbinden. Nun wollte ich fragen, ob es egal ist das ganze einfach nur via Mysql mit der Datenbank zu verbinden oder gibt es noch bessere Wege. Nebenbei wollte ich fragen, ob eine Verbindung mit der Datenbank alleine via C# möglich wäre und ob's empfehlenswert ist. Liebe Grüße, Jeff
  18. Guten tag I was going to build a server but soon learned it was not going to be quick. Kind of gone off the idea now, but I have still been enjoying messing around. I've made a repo in the case I do go completely go off the idea which should help the next person with a bit more to look at. Read the inital readme to update the submodules before building. If you want built resources I can provide. https://github.com/horseyhorsey/RageMpResources Credit to anyone that helped in discord, xabi (atms) (project to look through), Guad, george, extra thank to rootcause because providing great snippets & data and Sake4Mod
  19. Version 1.0.0

    351 downloads

    This function helps you to add keys binding if you use C # client side ... Example of use : Tick Event KeyManager.KeyBind(0xA2, () => { Chat.Output("Key Bind Work"); }); KeyManager.KeyBind(KeyManager.KeyMouse, () => { Cursor.Visible = !Cursor.Visible; });
  20. Hi guys! It's me again. We have our server setup on Ubuntu 16.04 64bit. Actually almost everything works perfect. Except "NAPI.Vehicle.CreateVehicle()". After using this line our server crashes just with info: Aborted (core dumped). Do you have any ideas why? What could we do? Thanks for your help
  21. Hi guys, after some hours of programming, I've got an error. This is my exception-log: ==================[28.12.2018 04:10:52]================== System.NullReferenceException: Object reference not set to an instance of an object. at void GTV.Systems.Cargo.Core.AttachCargosToLoadings() in C:\Users\Kacper\Documents\GT-V\GTV\GTV\Systems\Cargo\core.cs:line 118 ========================================================= ==================[28.12.2018 04:10:52]================== System.Reflection.TargetParameterCountException: Parameter count mismatch. at object[] System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) ========================================================= Here's my console: Step 1 Step 2 Step 3 Step 4, r: 1, c: 0, llc: 3 Step 5 [Cargo] Cargo destination has been set to 3 Step 6, 0 GTV.Systems.Cargo.Cargo And here are the functions doing this staff: ... public void AttachCargosToLoadings() { try { if (cargos_list.Count <= 0) throw new Exception("Brak towarów"); if (loadings_list.Count <= 1) throw new Exception("Brak załadunków"); int currentLoadingID = 0; NAPI.Util.ConsoleOutput("Step 1"); foreach (Loading load in loadings_list) { NAPI.Util.ConsoleOutput("Step 2"); for (var i=0;i<5;i++) { NAPI.Util.ConsoleOutput("Step 3"); int randomIndex = random.Next(cargos_list.Count - 1); AttachDestinationToCargo(cargos_list[randomIndex],currentLoadingID); NAPI.Util.ConsoleOutput("Step 6, "+randomIndex); NAPI.Util.ConsoleOutput(cargos_list[randomIndex].ToString()); NAPI.Util.ConsoleOutput(cargos_list[randomIndex].GetType().ToString()); load.cargos.Add(cargos_list[randomIndex]); NAPI.Util.ConsoleOutput("Step 7"); NAPI.Util.ConsoleOutput("[Cargo] Inserted Cargo ("+cargos_list[randomIndex].name+") to Loading ("+load.id+")", ConsoleColor.DarkGreen); NAPI.Util.ConsoleOutput("Step 8"); } currentLoadingID++; } } catch (Exception e) { NAPI.Util.ConsoleOutput("[Cargo] " + e.Message + " (Init Attach)", ConsoleColor.Red); } } public void AttachDestinationToCargo(Cargo cargo, int currentLoadingID) { int randomIndex = random.Next(loadings_list.Count - 1); while(randomIndex==currentLoadingID) { randomIndex = random.Next(loadings_list.Count - 1); } NAPI.Util.ConsoleOutput("Step 4, r: "+randomIndex+", c: "+currentLoadingID+", llc: "+loadings_list.Count); cargo.destination = loadings_list[randomIndex]; NAPI.Util.ConsoleOutput("Step 5"); NAPI.Util.ConsoleOutput("[Cargo] Cargo destination has been set to "+loadings_list[randomIndex].id, ConsoleColor.DarkCyan); } ... Cargo class: public int id { get; set; } public string name { get; set; } public bool legal { get; set; } public string color = "#ffffff"; public double money_multipler { get; set; } public double exp_multipler { get; set; } public int event_id = 0; public int courses = 0; public Loading destination { get; set; } Loading class: public int id { get; set; } public Vector3 pos { get; set; } // Init cargos public List<Cargo> cargos { get; set; } //After InGame Create public Marker marker { get; set; } public ColShape colshape { get; set; } public Blip blip { get; set; } public TextLabel text { get; set; } bool error = false; What Am I doing wrong? I really appreciate your help
  22. DjEnzo

    How to use MySQL

    Hi guys! Am about to start programming my new server, but I cannot use MySQL. I started with this tutorial -> https://rage.mp/forums/topic/1807-c-getting-started-debugging/ This is how my code looks like: using System; using System.Data; using GTANetworkAPI; using MySql.Data.MySqlClient; namespace GTV { class MySQL { private string connectionString = "SERVER=localhost;" + "DATABASE=gtv;" + "UID=root;" + "PASSWORD=;" + "SslMode=none"; public bool FirstConnect() { MySqlConnection db = new MySqlConnection(connectionString); db.Open(); string state = db.State.ToString(); NAPI.Util.ConsoleOutput(state); if (db.State == ConnectionState.Open) return true; else return false; } } } And here my pretty long exception: What did I do wrong? Thank you for your help.
  23. Version 1.0.0

    67 downloads

    Send mails from the server simple and easy. Ex: To work, you need to enable IMAP Access *This code was only tested on the GMAIL service
  24. using System; using GTANetworkAPI; namespace roleplay { public class Main : Script { public Main() { } [ServerEvent(Event.PlayerSpawn)] public void OnPlayerConnected(Client player) { NAPI.Util.ConsoleOutput("Roleplay wurde sasd!"); } [ServerEvent(Event.ResourceStart)] public void OnResourceStart() { NAPI.Util.ConsoleOutput("Roleplay wurde gestartet!"); } } } This is my code and the onPlayerConnected Event make nothing. I don't know why. I hope you can help me! Thank you.
  25. Djoe_

    RAGEMP Merger

    Version 1.0.0

    6 downloads

    What is it? This tool allows you to gather your files in your solution in one file ".cs" while keeping the necessary assembly, namespace, class ... Usage: Just drag your solution on the program or launch from a cmd console "RAGEMP_Merger.exe YourSolutionPath NameFile.cs".