### Run Development Server (dotnet CLI) Source: https://aventussharp.com/getting_started/installation Starts the .NET development server from the project directory. This command compiles and runs the application, making it accessible via a local URL. ```bash dotnet run ``` -------------------------------- ### Install AventusSharp Package (dotnet CLI) Source: https://aventussharp.com/getting_started/installation Installs the AventusSharp NuGet package using the .NET command-line interface. This is the recommended method for adding the library to your project. ```bash dotnet add package AventusSharp ``` -------------------------------- ### Install AventusSharp Package (csproj) Source: https://aventussharp.com/getting_started/installation Adds the AventusSharp package reference directly to your project's .csproj file. This is an alternative to using the dotnet CLI. ```xml ``` -------------------------------- ### Integrate Aventus Initialization in Program.cs Source: https://aventussharp.com/getting_started/installation Updates the Program.cs file to initialize and use the AventusSharp library. It builds the WebApplication, calls the Aventus initialization method, and starts the application if initialization is successful. ```csharp using AventusSharp.Tools; using Demo; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); if (app != null) { // Initialize Aventus VoidWithError initResult = Aventus.Init(app); if (initResult.Success) { // Start the app if initialization succeeds app.Run(); } else { // Print any errors to the console initResult.Print(); } } ``` -------------------------------- ### Create New Web Project (dotnet CLI) Source: https://aventussharp.com/getting_started/installation Creates a new ASP.NET Core web project named 'Demo' using the .NET CLI. This command initializes a basic web application structure. ```bash dotnet new web --name Demo ``` -------------------------------- ### Create 'Hello World' Route in C# Source: https://aventussharp.com/getting_started/installation Defines a simple 'Hello World' route using AventusSharp. This class extends 'Router' and provides an 'Index' method that returns the string 'Hello World'. ```csharp using AventusSharp.Routes.Response; using AventusSharp.Routes; namespace Demo { // Extends Router => this allows Aventus RouterMiddleware to use it public class HelloWorld : Router { public string Index() { return "Hello World"; } } } ``` -------------------------------- ### Initialize AventusSharp in C# Source: https://aventussharp.com/getting_started/installation Initializes the AventusSharp library within a .NET WebApplication. It enables Aventus routing and registers all Aventus routes from the project. This code should be placed in a dedicated initialization file. ```csharp using AventusSharp.Tools; using RouterMiddleware = AventusSharp.Routes.RouterMiddleware; namespace Demo { public static class Aventus { public static VoidWithError Init(WebApplication app) { // This object handles errors without throwing exceptions VoidWithError initResult = new(); // Enable Aventus routing in the app app.Use(RouterMiddleware.OnRequest); // Register all Aventus routes from the current project initResult.Run(RouterMiddleware.Register); return initResult; } } } ``` -------------------------------- ### Add Newtonsoft.Json Package (dotnet CLI) Source: https://aventussharp.com/getting_started/installation Installs the Newtonsoft.Json NuGet package using the .NET command-line interface. This package is often used for JSON serialization and deserialization in .NET projects. ```bash dotnet add package Newtonsoft.Json ``` -------------------------------- ### Install HttpMultipartParser NuGet Package Source: https://aventussharp.com/route_http/route_management This command installs the necessary NuGet package to enable request body parsing for route methods. Ensure you have the .NET CLI installed. ```bash dotnet add package HttpMultipartParser ``` -------------------------------- ### Basic LINQ Query on User in AventusSharp Source: https://aventussharp.com/model/linq Demonstrates a basic LINQ query to filter users by name using AventusSharp. This is a fundamental example of how to apply filtering criteria to a collection of user objects. ```csharp var users = User.Where(u => u.Name == "John"); ``` -------------------------------- ### Create WebSocket Endpoint (C#) Source: https://aventussharp.com/route_ws/endpoint Example of creating a custom WebSocket endpoint by extending the `WsEndPoint` class in C#. It demonstrates how to define the connection path for the endpoint. ```csharp using AventusSharp.WebSocket; namespace Demo.Websocket { public class MainEndPoint : WsEndPoint { public override string DefinePath() { // Entry path => ws://localhost:5268/my_websocket return "/my_socket"; } } } ``` -------------------------------- ### Custom AventusSharp Router Configuration Example Source: https://aventussharp.com/route_http/configuration Provides an example of a custom router configuration in AventusSharp. This snippet shows how to set a custom view directory and enable route logging by modifying PrintRoute and PrintTrigger. ```csharp RouterMiddleware.Configure((config) => { config.ViewDir = (context, router) => { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CustomViews"); }; config.PrintRoute = true; config.PrintTrigger = true; }); ``` -------------------------------- ### Request Body Handling Source: https://aventussharp.com/route_http/route_management Demonstrates how to handle request bodies in route methods by installing the HttpMultipartParser NuGet package and defining routes with parameters that will be populated from the request body. ```APIDOC ## Handling Request Bodies Any additional parameters in a route method signature will be treated as part of the request body. To enable this functionality, install the `HttpMultipartParser` NuGet package: ``` dotnet add package HttpMultipartParser ``` Then you can create a route with a body: ```csharp using AventusSharp.Routes; using AventusSharp.Routes.Attributes; namespace Demo.Routes { public class MainRouter : Router { [Post] public string Hello(string name) { return "Hello " + name; } } } ``` Now, you can send a request with a JSON or form body containing a `name` field, and it will be automatically injected into the `Hello` method. ``` -------------------------------- ### Prepare Update Query with Parameters Source: https://aventussharp.com/model/crud The Prepare method allows for pre-execution setup of a query, such as adding parameters or additional objects. It's typically called on a query instance obtained via the New method, ensuring all necessary components are ready before the update is executed. ```csharp int userId = 1; var updateQuery = User.StartUpdate().Field(u => u.Username).WhereWithParameters(u => u.Id == userId).New(); updateQuery.Prepare(userId); List? updatedUsers = updateQuery.Run(new User { Id = userId, Username = "newUsername" }); ``` -------------------------------- ### Define Routes with Function Calls in C# Source: https://aventussharp.com/route_ws/routes Demonstrates how to define routes in C# using the AventusSharp framework. It shows how to create a router class that inherits from 'Router' and defines methods that act as routes. The example includes a base route '/' and a parameterized route '/mainrouter/{id}'. ```csharp using AventusSharp.Routes; using Path = AventusSharp.Routes.Attributes.Path; namespace Demo.Data.Routes { public class MainRouter : Router { // / public string Index() { return "It's working"; } // /mainrouter/{id}, where router name is generated by GetRouterName() [Path("/[GetRouterName]/{id}")] public string Test(int id) { return "It's a test for " + id; } protected string GetRouterName() { return GetType().Name; } } } ``` -------------------------------- ### Configure MySQL Database Connection in AventusSharp Source: https://aventussharp.com/model/configuration Initializes a MySQL database connection using provided credentials and configures the default data manager for persistence. Ensure the host, database, username, and password are correct for your MySQL setup. This sets up the storage and data manager for MySQL persistence. ```csharp MySQLStorage storage = new(new StorageCredentials( host: "localhost", database: "demo", username: "root", password: "" )); DataMainManager.Configure((config) => { config.defaultDM = typeof(SimpleDatabaseDM<>); config.defaultStorage = storage; }); ``` -------------------------------- ### User Creation with GUID Generation - C# Source: https://aventussharp.com/data_manager/internal_logique Demonstrates overriding `CanCreate` and `BeforeCreate` methods in a `UserDM` class to enforce username validation and generate a unique GUID for each new user during the creation process. It utilizes AventusSharp's data management framework. ```csharp using AventusSharp.Data.Manager.DB; using AventusSharp.Tools; using Demo.Data; namespace Demo.Logic.DM { public class UserDM : DatabaseDM { protected override List CanCreate(List values) { List errors = new List(); foreach (X item in values) { if (string.IsNullOrEmpty(item.Username)) { // In real code, use a custom error instead of GenericError errors.Add(new GenericError(500, "The username must be provided")); } } return errors; } protected override void BeforeCreate(List values) { foreach (X item in values) { item.Guid = Guid.NewGuid().ToString(); } } } } ``` -------------------------------- ### Create UserRouter with StorableWsRouter Source: https://aventussharp.com/route_ws/routes Example demonstrating how to create a custom WebSocket router for the 'User' storable object by inheriting from StorableWsRouter. It shows how to provide a Data Manager instance and optionally disable default routes using the [NoRoute] attribute. ```csharp using AventusSharp.Data.Manager; using AventusSharp.WebSocket; using AventusSharp.Tools.Attributes; using Demo.Data; using Demo.Logic.DM; namespace Demo.Websocket.Routes { public class UserRouter : StorableWsRouter { protected override IGenericDM? GetDM() { return UserDM.GetInstance(); } // You can disable on specific route if you need [NoRoute] public override ResultWithError Create(User item) { throw new NotImplementedException(); } } } ``` -------------------------------- ### Define Basic Routes with Default GET Method in AventusSharp Source: https://aventussharp.com/route_http/route_management This C# code snippet demonstrates how to define basic routes in AventusSharp. Public methods in a Router class automatically become routes, defaulting to the GET HTTP method. The route URL typically matches the method name, with '/' for the Index method. AventusSharp converts final URLs to lowercase. ```csharp using AventusSharp.Routes; namespace Demo.Routes { public class MainRouter : Router { // Route: url / (GET) public string Index() { return "It's working"; } // Route: url /test (GET) public string Test() { return "It's a test"; } } } ``` -------------------------------- ### Custom WebSocket Response Logic in C# Source: https://aventussharp.com/route_ws/routes Shows how to implement custom response logic for WebSocket messages by creating an attribute that inherits from Custom. The UserBroadcast example demonstrates sending messages only to connections belonging to a specific user. ```csharp using AventusSharp.WebSocket; using AventusSharp.WebSocket.Attributes; public class UserBroadcast : Custom { public override List GetConnections(WsEndPoint endPoint, WebSocketConnection? connection) { int userId = connection?.GetContext().GetUserId() ?? 0; if (endPoint is MainEndPoint mainEndPoint && userId != 0) { return mainEndPoint.GetConnectionsByUser(userId); } return new List(); } } ``` -------------------------------- ### Configure WebSocket Sessions and Middleware Source: https://aventussharp.com/route_ws/configuration Enables distributed memory cache and session services, then configures the application to use sessions and WebSockets with specified options. This setup is crucial for managing WebSocket connections. ```csharp builder.Services .AddDistributedMemoryCache() .AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); // Set session timeout here options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); var app = builder.Build(); app .UseSession() .UseWebSockets(new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), }); ``` -------------------------------- ### Configure AventusSharp Export Settings Source: https://aventussharp.com/export/introduction This JSON configuration file defines the essential settings for exporting AventusSharp C# code. It requires specifying the path to the C# project file (.csproj) and the output directory for the generated AventusJs files. This setup ensures consistency between frontend and backend development. ```json { "csProj": "./Demo.csproj", "outputPath": "./Front/src/generated" } ``` -------------------------------- ### Initialize AventusSharp Components in C# Source: https://aventussharp.com/getting_started/configuration This C# code snippet demonstrates the structure of the Aventus.cs file, which is used to configure and initialize AventusSharp. It includes methods for initializing data management, HTTP routing, and WebSocket handling. The Init method orchestrates these initializations and returns a VoidWithError to indicate success or failure. ```csharp using AventusSharp.Data; using AventusSharp.Tools; using AventusSharp.WebSocket; using RouterMiddleware = AventusSharp.Routes.RouterMiddleware; namespace Demo { public static class Aventus { public static VoidWithError Init(WebApplication app) { // This object handles errors without throwing exceptions VoidWithError initResult = new(); // Initialize each component InitData(initResult); InitHttp(initResult, app); InitWs(initResult, app); return initResult; } private static void InitData(VoidWithError initResult) { // Configure DataMainManager here DataMainManager.Configure((config) => { // Add your data configuration settings here }); // Initialize the data manager asynchronously initResult.RunAsync(DataMainManager.Init); } private static void InitHttp(VoidWithError initResult, WebApplication app) { // Configure RouterMiddleware here RouterMiddleware.Configure((config) => { // Add your HTTP routing settings here }); // Register routes and enable HTTP request handling initResult.Run(RouterMiddleware.Register); app.Use(RouterMiddleware.OnRequest); } private static void InitWs(VoidWithError initResult, WebApplication app) { // Configure WebSocketMiddleware here WebSocketMiddleware.Configure((config) => { // Add your WebSocket configuration here }); // Register WebSocket routes and enable WebSocket request handling initResult.Run(WebSocketMiddleware.Register); app.Use(WebSocketMiddleware.OnRequest); } } } ``` -------------------------------- ### Implement and Inject a DateTime Service in C# Source: https://aventussharp.com/route_ws/routes Shows how to create a simple service interface 'IDateTime' and its implementation 'SystemDateTime' for providing the current date and time. It also demonstrates how to register this service for dependency injection using 'WebSocketMiddleware.Inject'. ```csharp public interface IDateTime { DateTime Now { get; } } public class SystemDateTime : IDateTime { public DateTime Now => DateTime.Now; } ``` ```csharp private static void InitWs(VoidWithError initResult, WebApplication app) { WebSocketMiddleware.Configure((config) => {}); initResult.Run(WebSocketMiddleware.Register); app.Use(WebSocketMiddleware.OnRequest); // Inject IDateTime service implementation WebSocketMiddleware.Inject(); } ``` ```csharp using AventusSharp.WebSocket; using Demo.Logic; namespace Demo.Websocket.Routes { public class MainRouter : WsRouter { public string Time(IDateTime dateTime) { return "It's " + dateTime.Now; } } } ``` -------------------------------- ### Specify HTTP Methods for Routes in AventusSharp Source: https://aventussharp.com/route_http/route_management This C# code shows how to explicitly define HTTP methods for AventusSharp routes using attributes like `[Get]` and `[Post]`. This overrides the default GET method behavior and allows for more specific route handling based on the HTTP request method. ```csharp using AventusSharp.Routes; using AventusSharp.Routes.Attributes; namespace Demo.Routes { public class MainRouter : Router { [Get] public string Index() { return "It's working"; } // Route: url /test (POST) [Post] public string Test() { return "It's a test"; } } } ``` -------------------------------- ### Create Startup Error in AventusSharp (C#) Source: https://aventussharp.com/getting_started/error_handling Demonstrates two methods for creating a startup error using AventusSharp's error handling mechanisms. The first method directly uses VoidWithError, while the second utilizes the custom VoidWithDemoError and converts it to a generic VoidWithError. ```csharp using AventusSharp.Tools; namespace Demo { public static class Aventus { public static VoidWithError Init(WebApplication app) { VoidWithError initResult = new(); initResult.Errors.Add(new DemoError(DemoErrorCode.ManualFailed, "The program won't start")); return initResult; } public static VoidWithError Init2(WebApplication app) { VoidWithDemoError initResult = new(); initResult.Errors.Add(new DemoError(DemoErrorCode.ManualFailed, "The program won't start")); return initResult.ToGeneric(); } } } ``` -------------------------------- ### Prepare Query with Parameters Before Execution (C#) Source: https://aventussharp.com/model/crud The `Prepare` method allows for the pre-configuration of a query with its parameters. This is useful when you want to define all parameters upfront before executing the query, ensuring all necessary data is ready. ```csharp var userQuery = User.StartQuery().WhereWithParameters(u => u.Username == username); List users = userQuery.New().Prepare("John").Run(); ``` -------------------------------- ### Define Demo Error Enum (C#) Source: https://aventussharp.com/getting_started/error_handling Initializes a C# enum named 'DemoErrorCode' within the 'Demo' namespace. This enum is used to define specific error codes for the application, starting with 'ManualFailed'. ```csharp using System.Runtime.CompilerServices; using AventusSharp.Tools; namespace Demo { public enum DemoErrorCode { ManualFailed } } ``` -------------------------------- ### Initialize and Configure WebSocket Middleware Source: https://aventussharp.com/route_ws/configuration Configures the WebSocket middleware, registers WebSocket routes, and integrates WebSocket handling into the application's request pipeline. This method sets up the core WebSocket functionality. ```csharp private static void InitWs(VoidWithError initResult, WebApplication app) { WebSocketMiddleware.Configure((config) => { // Set configuration properties here // Example: // config.PrintRoute = true; }); // Register WebSocket routes initResult.Run(WebSocketMiddleware.Register); // Configure the app to use WebSocket handling app.Use(WebSocketMiddleware.OnRequest); } ``` -------------------------------- ### Basic WebSocket Router Source: https://aventussharp.com/route_ws/routes Demonstrates how to create a basic WebSocket router by inheriting from WsRouter and defining public methods as event handlers. ```APIDOC ## POST / ### Description Handles a WebSocket message sent to the root path and returns a simple string response. ### Method POST ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ``` (No request body for this example) ``` ### Response #### Success Response (200) - **string** - A confirmation message. #### Response Example ```json { "example": "It's working" } ``` ``` -------------------------------- ### Exclude Method from Routing with [NoRoute] Attribute (C#) Source: https://aventussharp.com/route_http/route_management This C# example shows how to prevent a public method from being exposed as an HTTP route using the [NoRoute] attribute. This is useful for internal methods that should not be accessible via HTTP requests. ```csharp using AventusSharp.Routes; using AventusSharp.Tools.Attributes; namespace Demo.Routes { public class MainRouter : WsRouter { public string Index() { return "It's working"; } // The route /test won't exist [NoRoute] public string Test() { return "It's a test"; } } } ``` -------------------------------- ### Prevent Exporting Elements with NoExport Attribute (C#) Source: https://aventussharp.com/export/introduction The `[NoExport]` attribute in C# prevents classes, interfaces, enums, or properties from being exported to AventusJs. This is useful for explicitly excluding specific elements. It can be applied to enums and properties as shown in the examples. ```csharp using AventusSharp.Tools.Attributes; namespace Demo.Routes { [NoExport] public enum InternalEnum { Value1 } } ``` ```csharp using AventusSharp.Tools.Attributes; namespace Demo.Routes { public class User { public int UserId { get; set; } [NoExport] public string InternalNotes { get; set; } = ""; } } ``` -------------------------------- ### Extend AventusFile for Custom File Type Validation Source: https://aventussharp.com/model/properties Illustrates extending the AventusFile class to implement custom file handling logic, such as validating file types before upload. This example restricts uploads to image files using a hypothetical FileTypeValidator. ```csharp public class ImageFile : AventusFile { public override ResultWithError SaveToFolderOnUpload(string filePath) { if (Upload == null) { return new ResultWithError(); } // Use File.TypeChecker or similar library to verify file type bool isValidImg = false; FileStream fileStream = File.OpenRead(Upload.FilePath); if (FileTypeValidator.IsTypeRecognizable(fileStream)) { isValidImg = fileStream.IsImage(); } if (!isValidImg) { ResultWithError result = new ResultWithError(); result.Errors.Add(new GenericError(405, "Not allowed")); return result; } // Proceed with the upload if file type is valid return base.SaveToFolderOnUpload(filePath); } } ``` -------------------------------- ### Define Basic WebSocket Route in C# Source: https://aventussharp.com/route_ws/introduction This C# code defines a basic WebSocket route using AventusSharp's WsRouter. It demonstrates how to create a router class that listens for messages on a specific path and returns a string response. This is useful for setting up simple real-time communication endpoints. ```csharp using AventusSharp.WebSocket; namespace Demo.Websocket.Routes { public class MainRouter : WsRouter { public string Index() { return "It's working"; } } } ``` -------------------------------- ### Dynamic Route Naming using Function Calls in C# Source: https://aventussharp.com/route_http/route_management Demonstrates how to use function calls within route paths, specifically for dynamic route naming, using the `[Path("/[GetRouterName]/{id}")]` syntax in C#. Function calls in routes are executed at initialization. This requires the AventusSharp.Routes namespace. ```csharp using AventusSharp.Routes; using Path = AventusSharp.Routes.Attributes.Path; namespace Demo.Routes { public class MainRouter : Router { // Route: url => / (GET) public string Index() { return "It's working"; } // Route: url => /mainrouter/{id} (GET), where router name is generated by GetRouterName() [Path("/[GetRouterName]/{id}")] public string Test(int id) { return "It's a test for " + id; } protected string GetRouterName() { return GetType().Name; } } } ``` -------------------------------- ### Get User with Error Handling in C# Source: https://aventussharp.com/data_manager/external_logique Retrieves a user by username 'John' using ResultWithError for robust error management. This pattern ensures consistent error handling for external calls, returning either the User object or an error. ```csharp using AventusSharp.Data.Manager.DB; using AventusSharp.Tools; using Demo.Data; namespace Demo.Logic.DM { public class UserDM : DatabaseDM { public ResultWithError GetJohn() { ResultWithError response = new ResultWithError(); // Execute actions response.Run(() => SingleWithError(p => p.Username == "John")); // Return the response return response; } } } ``` -------------------------------- ### Create One-to-Many Link Between Models in C# Source: https://aventussharp.com/model/properties Establishes a one-to-many relationship between User and Role models by including the related model as a property. Both models must inherit from Storable. The example shows a User having a single Role, which translates to a foreign key in the user table. ```csharp using AventusSharp.Data; namespace Demo.Data { public class Role : Storable { public string Name { get; set; } } } using AventusSharp.Data; namespace Demo.Data { public class User : Storable { // ... other properties public Role Role { get; set; } } } ``` -------------------------------- ### Prefixing WebSocket Routes in C# Source: https://aventussharp.com/route_ws/routes Illustrates how to apply a common prefix to all routes within a WebSocket router using the [Prefix] attribute. This helps in organizing related routes under a specific path, such as '/Main'. ```csharp using AventusSharp.WebSocket; using AventusSharp.WebSocket.Attributes; namespace Demo.Websocket.Routes { [Prefix("Main")] public class MainRouter : WsRouter { // /main/ public string Index() { return "It's working"; } } } ``` -------------------------------- ### LINQ String Function: StartsWith in AventusSharp Source: https://aventussharp.com/model/linq Shows how to use the `StartsWith` string function within a LINQ query in AventusSharp. This allows filtering based on the beginning of a string property. ```csharp var result = User.Where(u => u.Name.StartsWith("John")); ``` -------------------------------- ### Create Records - Static-Based (C#) Source: https://aventussharp.com/model/crud Illustrates creating multiple records using static methods. 'User.Create' returns a list of successfully created users, while 'User.CreateWithError' returns a ResultWithError object containing both created users and any errors. ```csharp var users = new List { new User { Username = "alice" }, new User { Username = "bob" } }; List createdUsers = User.Create(users); ``` ```csharp var users = new List { new User { Username = "alice" }, new User { Username = "bob" } }; ResultWithError> result = User.CreateWithError(users); ``` -------------------------------- ### Rename Router Methods with FctName Attribute (C#) Source: https://aventussharp.com/export/introduction The `[FctName(string name)]` attribute allows renaming of methods within router classes (e.g., HTTP or WebSocket routers) for cleaner programmatic access. This example shows renaming the `Test` method to `myFunc` for frontend use. ```csharp using AventusSharp.Routes; using AventusSharp.Tools.Attributes; using Demo.Data; namespace Demo.Routes { public class UserRouter : StorableRouter { // This method will be accessible as `new UserRouter().myFunc()` instead of `new UserRouter().Test()` [FctName("myFunc")] public void Test() { } } } ``` -------------------------------- ### Prefixing Routes with [Prefix] Attribute in C# Source: https://aventussharp.com/route_http/route_management Demonstrates how to apply a common prefix to all routes within a router using the `[Prefix(string)]` attribute in C#. This helps in organizing related routes under a single base path. It requires the AventusSharp.Routes and AventusSharp.Routes.Attributes namespaces. ```csharp using AventusSharp.Routes; using AventusSharp.Routes.Attributes; namespace Demo.Routes { [Prefix("Main")] public class MainRouter : Router { // Route: url => /main/ (GET) public string Index() { return "It's working"; } // Route: url => /main/test (GET) public string Test() { return "It's a test"; } } } ``` -------------------------------- ### Execute Query and Get Single Result with Error Handling (C#) Source: https://aventussharp.com/model/crud The `SingleWithError` method executes a query and returns a single result. If an error occurs during execution, the error details are encapsulated within the `ResultWithError` object, preventing application crashes and providing specific error information. ```csharp var userQuery = User.StartQuery().Where(u => u.Username == "john"); ResultWithError result = userQuery.SingleWithError(); ``` -------------------------------- ### Initialize and Manage Jobs with AventusSharp Scheduler Source: https://aventussharp.com/scheduler/introduction This C# code demonstrates how to initialize the JobManager and add a recurring job named 'ping'. The job is scheduled to run every 5 seconds and is automatically removed after it executes 5 times. It utilizes the AventusSharp scheduler, a fork of FluentScheduler. ```csharp namespace Demo { public static class Aventus { public static VoidWithError Init(WebApplication app) { VoidWithError initResult = new(); // Initialize various parts of the application InitData(initResult); InitHttp(initResult, app); InitWs(initResult, app); // Initialize the JobManager JobManager.Initialize(); int i = 0; // Add a recurring job named "ping" that runs every 5 seconds JobManager.AddJob( job: () => { Console.WriteLine("5sec ping"); i++; // Remove the job after it has run 5 times if (i == 5) { JobManager.RemoveJob("ping"); } }, schedule: s => s.ToRunEvery(5).Seconds(), name: "ping" ); return initResult; } } } ``` -------------------------------- ### Generate Frontend Objects with CreateObject Attribute (C#) Source: https://aventussharp.com/export/introduction The `[CreateObject]` attribute, when used with `[ForeignKey]`, generates a fully constructed object in frontend code. If no parameter is provided, the property name is derived by removing 'Id' or 'Key' from the original property name. This example demonstrates its use with a `RoleId` property. ```csharp using AventusSharp.Data; using AventusSharp.Data.Attributes; namespace Demo.Data { public class User : Storable { public string Username { get; set; } = ""; [ForeignKey, CreateObject] public int RoleId { get; set; } // The `Role` property will be created automatically when exported // public Role Role { get; set; } } } ``` -------------------------------- ### Prepare Delete Query with Prepare (C#) Source: https://aventussharp.com/model/crud The Prepare method allows preparing a query by adding additional objects or parameters before execution. This is often used in conjunction with New() and WhereWithParameters to set up the final query state before running. ```csharp int userId = 1; var deleteQuery = User.StartDelete().WhereWithParameters(u => u.Id == userId).New(); deleteQuery.Prepare(userId); List? deletedUsers = deleteQuery.Run(); ``` -------------------------------- ### Prepare Existence Check with Parameters - C# Source: https://aventussharp.com/model/crud The Prepare method allows setting parameters for an existence check query before execution. It's used in conjunction with WhereWithParameters and New to configure and run the query. ```csharp int userId = 1; var existQuery = User.StartExist().WhereWithParameters(u => u.Id == userId).New(); existQuery.Prepare(userId); bool exists = existQuery.Run(); ``` -------------------------------- ### Calling Functions in Routes Source: https://aventussharp.com/route_http/route_management Illustrates how to call functions within routes, useful for dynamic route naming or initialization logic. ```APIDOC ## Calling Functions in Routes ### Description Call functions within routes. These functions are executed at route initialization, allowing for dynamic route naming or setup. ### Method N/A (Attribute) ### Endpoint N/A (Attribute) ### Parameters #### Path Parameters - **id** (int) - Required - The ID to be used in the route. ### Request Example N/A ### Response N/A ### Code Example ```csharp using AventusSharp.Routes; using Path = AventusSharp.Routes.Attributes.Path; namespace Demo.Routes { public class MainRouter : Router { // Route: url => / (GET) public string Index() { return "It's working"; } // Route: url => /mainrouter/{id} (GET), where router name is generated by GetRouterName() [Path("/[GetRouterName]/{id}")] public string Test(int id) { return "It's a test for " + id; } protected string GetRouterName() { return GetType().Name; } } } ``` ``` -------------------------------- ### Prefixing Routes Source: https://aventussharp.com/route_http/route_management Demonstrates how to apply a common prefix to all routes within a router using the `[Prefix]` attribute for better organization. ```APIDOC ## Prefixing Routes ### Description Apply a common prefix to all routes within a router using the `[Prefix(string)]` attribute. ### Method N/A (Attribute) ### Endpoint N/A (Attribute) ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```csharp using AventusSharp.Routes; using AventusSharp.Routes.Attributes; namespace Demo.Routes { [Prefix("Main")] public class MainRouter : Router { // Route: url => /main/ (GET) public string Index() { return "It's working"; } // Route: url => /main/test (GET) public string Test() { return "It's a test"; } } } ``` ``` -------------------------------- ### Service Injection Source: https://aventussharp.com/route_http/route_management Explains how to register and inject services into routes for dependency injection. ```APIDOC ## Service Injection ### Description Supports injecting services into routes. Register services using `RouterMiddleware.Inject` and use them by including them as method parameters. ### Method N/A (Attribute/Configuration) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example (Interface and Implementation) ```csharp public interface IDateTime { DateTime Now { get; } } public class SystemDateTime : IDateTime { public DateTime Now => DateTime.Now; } ``` ### Code Example (Registration) ```csharp private static void InitHttp(VoidWithError initResult, WebApplication app) { RouterMiddleware.Configure((config) => {}); initResult.Run(RouterMiddleware.Register); app.Use(RouterMiddleware.OnRequest); // Inject IDateTime service implementation RouterMiddleware.Inject(); } ``` ### Code Example (Usage in Route) ```csharp using AventusSharp.Routes; using Demo.Logic; using Path = AventusSharp.Routes.Attributes.Path; namespace Demo.Routes { public class MainRouter : Router { public string Time(IDateTime dateTime) { return "It's " + dateTime.Now; } } } ``` ``` -------------------------------- ### Registering Services for Injection in AventusSharp C# Source: https://aventussharp.com/route_http/route_management Illustrates how to register a service implementation for dependency injection using `RouterMiddleware.Inject()` during application initialization in C#. This makes the service available to be injected into routes. It requires the AventusSharp.Routes namespace. ```csharp private static void InitHttp(VoidWithError initResult, WebApplication app) { RouterMiddleware.Configure((config) => {}); initResult.Run(RouterMiddleware.Register); app.Use(RouterMiddleware.OnRequest); // Inject IDateTime service implementation RouterMiddleware.Inject(); } ``` -------------------------------- ### Defining and Implementing a Service Interface in C# Source: https://aventussharp.com/route_http/route_management Shows the definition of a simple service interface `IDateTime` and its implementation `SystemDateTime` in C#. This pattern is used for dependency injection within AventusSharp routes. It uses the standard .NET `DateTime` class. ```csharp public interface IDateTime { DateTime Now { get; } } public class SystemDateTime : IDateTime { public DateTime Now => DateTime.Now; } ``` -------------------------------- ### Create a New User Record in AventusSharp Source: https://aventussharp.com/model/introduction This C# code snippet shows how to create a new instance of a 'User' model and add it to storage using the Create() method in AventusSharp. It assumes the User model has already been defined. ```csharp User u = new User(); u.Create(); ``` -------------------------------- ### Injecting Services into Routes in C# Source: https://aventussharp.com/route_http/route_management Demonstrates how to inject a registered service (e.g., `IDateTime`) into a route handler by including it as a function parameter in C#. AventusSharp automatically resolves and provides the service instance. This requires the AventusSharp.Routes namespace. ```csharp using AventusSharp.Routes; using Demo.Logic; using Path = AventusSharp.Routes.Attributes.Path; namespace Demo.Routes { public class MainRouter : Router { public string Time(IDateTime dateTime) { return "It's " + dateTime.Now; } } } ``` -------------------------------- ### URL Parameters in Routes Source: https://aventussharp.com/route_ws/routes Illustrates how to define URL parameters within route paths (e.g., `{id}`) and have them automatically mapped to function arguments. ```APIDOC ## POST /main/demo/{id} ### Description Handles a WebSocket message sent to `/main/demo/{id}`, where `{id}` is a URL parameter automatically mapped to the `id` integer argument. ### Method POST ### Endpoint /main/demo/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The identifier for the route. #### Query Parameters None #### Request Body None ### Request Example ``` (No request body for this example) ``` ### Response #### Success Response (200) - **string** - A confirmation message including the provided ID. #### Response Example ```json { "example": "It's a test for 123" } ``` ``` -------------------------------- ### Query Builder - Run Method Source: https://aventussharp.com/model/crud Executes a query built using the query builder and returns the results directly as a list of objects. ```csharp var usersQuery = User.StartQuery().Where(u => u.IsActive); List activeUsers = usersQuery.Run(); ``` -------------------------------- ### Enable SQL Query Debugging in AventusSharp Source: https://aventussharp.com/model/linq Shows how to enable SQL query logging for `MySQLStorage` in AventusSharp by setting the `Debug` boolean to `true`. This is crucial for troubleshooting and understanding the SQL queries generated by LINQ operations. ```csharp // storage is MySQLStorage Aventus.storage.Debug = true; ``` -------------------------------- ### URL Parameters Source: https://aventussharp.com/route_http/route_management Details how to define URL parameters within route paths and map them to method arguments. ```APIDOC ## URL Parameters ### Description Add parameters to routes by enclosing them in `{}` within the path. Parameters are defined as function arguments and their types are automatically inferred. ### Method N/A (Attribute) ### Endpoint N/A (Attribute) ### Parameters #### Path Parameters - **id** (int) - Required - The ID to be used in the route. ### Request Example N/A ### Response N/A ### Code Example ```csharp using AventusSharp.Routes; using AventusSharp.Routes.Attributes; using Path = AventusSharp.Routes.Attributes.Path; namespace Demo.Routes { [Prefix("Main")] public class MainRouter : Router { // Route: url => /main/ (GET) public string Index() { return "It's working"; } // Route: url => /main/demo/{id} (GET), where {id} is inferred as an integer [Path("/Demo/{id}")] public string Test(int id) { return "It's a test for " + id; } } } ``` ``` -------------------------------- ### Configure DataManager with Lambda - C# Source: https://aventussharp.com/model/configuration This snippet shows how to configure the DataManager using a lambda function. The `Configure` method accepts a `DataManagerConfig` object, allowing you to set various properties for data management, such as default storage or logging. ```csharp DataMainManager.Configure((config) => { // Set configuration properties here // Example: // config.defaultStorage = myStorage; }); ``` -------------------------------- ### Create Record - Instance-Based (C#) Source: https://aventussharp.com/model/crud Demonstrates creating a single record using an instance of a model. The standard 'Create' method returns a boolean indicating success, while 'CreateWithError' returns a list of GenericError objects for detailed error handling. ```csharp var user = new User { Username = "john" }; bool success = user.Create(); // Returns true if creation succeeds. ``` ```csharp var user = new User { Username = "john" }; List errors = user.CreateWithError(); ``` -------------------------------- ### Create StorableRouter for Specific Object Type (C#) Source: https://aventussharp.com/route_http/route_management This C# code illustrates how to use the generic StorableRouter to automatically generate standard CRUD HTTP routes for a specific storable object type. Replace 'User' with your actual object type. ```csharp using AventusSharp.Routes; using Demo.Data; namespace Demo.Routes { public class UserRouter : StorableRouter { } } ```