### CoreBasicItem Configuration Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Example JSON configuration for the CoreBasicItem, controlling core proxy engine behavior like logging and multiplexing. ```json { "CoreBasicItem": { "LogEnabled": true, "Loglevel": "info", "MuxEnabled": true, "DefAllowInsecure": false, "DefFingerprint": "chrome", "DefUserAgent": "Mozilla/5.0...", "EnableFragment": false } } ``` -------------------------------- ### DNS over QUIC (DoQ) Protocol Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Demonstrates setting up a DNS over QUIC (DoQ) server using the 'quic://' prefix in NormalDNS. ```csharp var dnsItem = new DNSItem { NormalDNS = "quic://1.1.1.1" }; ``` -------------------------------- ### DownloadFileAsync Usage Example with Event Subscription Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DownloadService.md Example demonstrating how to use DownloadFileAsync, including subscribing to UpdateCompleted and Error events for progress and error handling. It specifies a URL, save path, proxy usage, and timeout. ```csharp var service = new DownloadService(); // Subscribe to events service.UpdateCompleted += (sender, result) => { if (result.Success) { Console.WriteLine($"Downloaded: {result.Msg}"); } else { Console.WriteLine($"Progress: {result.Msg}"); } }; service.Error += (sender, args) => { Console.WriteLine($"Error: {args.GetException().Message}"); }; // Start download await service.DownloadFileAsync( "https://example.com/large-file.zip", "/path/to/save/file.zip", useProxy: true, downloadTimeout: 60000); ``` -------------------------------- ### Sing-box DNS Configuration Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Sets up a DNSItem for the sing-box core, defining both normal and TUN mode DNS servers. ```csharp var dnsItem = new DNSItem { Id = Guid.NewGuid().ToString(), Remarks = "Sing-box DNS", Enabled = true, CoreType = ECoreType.sing_box, UseSystemHosts = false, NormalDNS = "1.1.1.1", TunDNS = "8.8.8.8" }; ``` -------------------------------- ### TUN Mode Configuration Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Example JSON for configuring TUN mode, controlling features like auto-routing, strict routing, and MTU. ```json { "TunModeItem": { "EnableTun": false, "AutoRoute": true, "StrictRoute": true, "Stack": "system", "Mtu": 9000, "EnableIPv6Address": false, "IcmpRouting": "auto", "EnableLegacyProtect": false } } ``` -------------------------------- ### HTTP Inbound Configuration Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Example JSON for configuring an HTTP inbound listener, specifying port and disabling UDP support. ```json { "LocalPort": 8080, "Protocol": "http", "UdpEnabled": false, "SniffingEnabled": true, "AllowLANConn": false } ``` -------------------------------- ### Simple DNS Configuration Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Creates a basic DNSItem configuration for Xray core, specifying normal DNS servers and a domain strategy. ```csharp var dnsItem = new DNSItem { Id = Guid.NewGuid().ToString(), Remarks = "Basic DNS", Enabled = true, CoreType = ECoreType.Xray, UseSystemHosts = false, NormalDNS = "8.8.8.8,1.1.1.1", DomainStrategy4Freedom = "AsIs" }; ``` -------------------------------- ### Example Global Hotkey Configuration Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Shows an example of defining a global hotkey using KeyEventItem. This snippet configures a hotkey action with specific modifier keys (Alt, Control, Shift) and a virtual key code. ```json { "GlobalHotkeys": [ { "EGlobalHotkey": 0, "Alt": true, "Control": false, "Shift": false, "KeyCode": 83 } ] } ``` -------------------------------- ### SOCKS Inbound Configuration Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Example JSON for configuring a SOCKS inbound listener, specifying port, protocol, and UDP support. ```json { "LocalPort": 10808, "Protocol": "socks", "UdpEnabled": true, "SniffingEnabled": true, "DestOverride": ["http", "tls"], "RouteOnly": false, "AllowLANConn": false, "User": "", "Pass": "" } ``` -------------------------------- ### Example UI Configuration Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Customize the V2RayN user interface, such as column widths, panel heights, language, font, and behavior settings. ```json { "UiItem": { "EnableAutoAdjustMainLvColWidth": true, "MainGirdHeight1": 400, "MainGirdHeight2": 200, "MainGirdOrientation": 0, "CurrentLanguage": "en", "CurrentFontFamily": "Segoe UI", "CurrentFontSize": 12, "EnableDragDropSort": true, "DoubleClick2Activate": true, "AutoHideStartup": false, "Hide2TrayWhenClose": true } } ``` -------------------------------- ### C# Example: Setting Up with Custom Sing-box Ruleset Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/RoutingItem.md Shows how to create a RoutingItem specifically for Sing-box, setting the DomainStrategy4Singbox and providing a path to a custom ruleset file. ```csharp var routing = new RoutingItem { Id = Guid.NewGuid().ToString(), Remarks = "Sing-box Rules", Enabled = true, DomainStrategy4Singbox = "prefer_ipv4", CustomRulesetPath4Singbox = "/home/user/.config/v2rayN/rulesets/custom.srs", Sort = 1 }; ``` -------------------------------- ### Standard DNS Protocol Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Demonstrates setting a standard DNS server with a specific port using the NormalDNS property. ```csharp var dnsItem = new DNSItem { NormalDNS = "8.8.8.8:53" // Standard DNS }; ``` -------------------------------- ### C# Example: Creating a Basic Routing Rule Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/RoutingItem.md Demonstrates how to instantiate a RoutingItem with essential properties like Id, Remarks, Url, Enabled, Sort, and DomainStrategy for V2Ray. ```csharp var routing = new RoutingItem { Id = Guid.NewGuid().ToString(), Remarks = "China Routes Direct", Url = "https://example.com/geosite-cn.json", Enabled = true, Sort = 1, DomainStrategy = "IPIfNonMatch", IsActive = false }; ``` -------------------------------- ### Example System Proxy Configuration Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Configure system-wide proxy settings, including proxy mode, exceptions, and local address handling. ```json { "SystemProxyItem": { "SysProxyType": 1, "SystemProxyExceptions": "localhost;127.*;10.*;172.16.*;192.168.*", "NotProxyLocalAddress": true } } ``` -------------------------------- ### C# Example: Loading Routing Rules from URL Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/RoutingItem.md Illustrates downloading a routing ruleset from a URL, saving it locally, and then parsing its content to populate the RuleSet and RuleNum properties of a RoutingItem. ```csharp var routing = new RoutingItem { Id = Guid.NewGuid().ToString(), Remarks = "Remote Routing", Url = "https://raw.githubusercontent.com/2dust/sing-box-rules/rule-set-gfw/gfw.srs", Enabled = true, RuleNum = 0 // Will be updated after download }; // Download and parse the ruleset var downloader = new DownloadService(); string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"routing_{routing.Id}.json"); await downloader.DownloadFileAsync(routing.Url, filePath, useProxy: true, downloadTimeout: 30000); // Read and populate ruleset routing.RuleSet = File.ReadAllText(filePath); routing.RuleNum = CountRulesInRuleSet(routing.RuleSet); ``` -------------------------------- ### GetSummary() Method Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ProfileItem.md Generates a human-readable summary of the profile. Use this to display a concise representation of the profile's connection details. ```csharp var profile = new ProfileItem { ConfigType = EConfigType.VLESS, Remarks = "MyServer", Address = "192.168.1.1", Port = 443 }; string summary = profile.GetSummary(); // "[VLESS] MyServer(***1)" ``` -------------------------------- ### DownloadDataAsync Usage Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DownloadService.md Example of using DownloadDataAsync to fetch data from a URL with a console progress callback. Uses null for no proxy and specifies a timeout. ```csharp var service = new DownloadService(); await service.DownloadDataAsync( "https://example.com/data.json", null, // No proxy 30000, // 30 second timeout async (isComplete, message) => { Console.WriteLine($"[{(isComplete ? "DONE" : "...")}] {message}"); }); ``` -------------------------------- ### DNS Configuration with Fallback Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Creates a DNSItem using a DoH server for normal resolution and a fallback IP address for domain-specific lookups. ```csharp var dnsItem = new DNSItem { Id = Guid.NewGuid().ToString(), Remarks = "DNS with Fallback", Enabled = true, CoreType = ECoreType.Xray, NormalDNS = "https://1.1.1.1/dns-query", // DoH DomainDNSAddress = "8.8.8.8", // Fallback DomainStrategy4Freedom = "IPOnDemand" }; ``` -------------------------------- ### Handle Core Process Startup Failures in C# Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/errors.md This code attempts to start the V2Ray core process and handles specific exceptions like FileNotFoundException if the executable is missing or IOException if a port is already in use. ```csharp try { var process = await ProcessService.StartCoreAsync(coreType, configPath); } catch (FileNotFoundException) { Console.WriteLine($"Core executable not found: {coreType}"); Console.WriteLine("Download and install core from releases"); } catch (IOException ex) when (ex.Message.Contains("port")) { Console.WriteLine("Port already in use - check inbound configuration"); } ``` -------------------------------- ### DNS over HTTPS (DoH) Protocol Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Shows how to configure a DNS over HTTPS (DoH) server using the NormalDNS property. ```csharp var dnsItem = new DNSItem { NormalDNS = "https://cloudflare-dns.com/dns-query" }; ``` -------------------------------- ### Check if Core Type is Installed Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/types.md Extension method to verify if a core type is currently installed. ```csharp // Check if core type is installed bool isInstalled = coreType.IsInstalled(); ``` -------------------------------- ### Example Simple DNS Configuration Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Demonstrates how to configure simple DNS settings using SimpleDNSItem. This includes options for using system hosts, adding common hosts, FakeIP mode, and specifying direct and remote DNS servers. ```json { "SimpleDNSItem": { "UseSystemHosts": false, "AddCommonHosts": true, "FakeIP": false, "BlockBindingQuery": false, "DirectDNS": "8.8.8.8", "RemoteDNS": "1.1.1.1", "BootstrapDNS": "8.8.4.4", "ServeStale": false, "ParallelQuery": false } } ``` -------------------------------- ### DNS over TLS (DoT) Protocol Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Illustrates configuring a DNS over TLS (DoT) server by specifying the 'tls://' prefix in NormalDNS. ```csharp var dnsItem = new DNSItem { NormalDNS = "tls://1.1.1.1" }; ``` -------------------------------- ### V2Ray DNS with System Hosts Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Configures a DNSItem for the v2fly core, enabling the use of the system's hosts file for resolution. ```csharp var dnsItem = new DNSItem { Id = Guid.NewGuid().ToString(), Remarks = "V2Ray with System Hosts", Enabled = true, CoreType = ECoreType.v2fly, UseSystemHosts = true, NormalDNS = "8.8.8.8", DomainStrategy4Freedom = "IPIfNonMatch" }; ``` -------------------------------- ### Filter Pattern Examples Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SubItem.md Illustrates various filter patterns that can be used to exclude specific proxies from a subscription. Examples include excluding expired proxies, specific regions, and proxies with certain markers. ```regex # Exclude expired proxies expire ``` ```regex # Exclude specific regions HK|TW|JP ``` ```regex # Exclude low-quality markers expire|trial|test|ban ``` ```regex # Complex pattern ^(test|trial|free|expired) ``` ```regex # Case-insensitive matching (?i)china|taiwan|restricted ``` -------------------------------- ### TUN Mode DNS Configuration Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Configures DNSItem for TUN mode, setting specific DNS servers for TUN traffic and normal traffic, conditional on TUN mode being enabled. ```csharp var config = ConfigHandler.LoadConfig(); if (config.TunModeItem.EnableTun) { var dnsItem = new DNSItem { TunDNS = "1.1.1.1", // DNS for TUN traffic NormalDNS = "8.8.8.8" // DNS for normal traffic }; } ``` -------------------------------- ### Error Handling Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/README.md Demonstrates a robust try-catch block for handling potential exceptions during configuration loading, profile retrieval, and general operations. It includes specific catches for argument and IO exceptions, along with a general catch-all. ```csharp try { var config = ConfigHandler.LoadConfig(); if (config == null) throw new InvalidOperationException("Config load failed"); var profile = await GetProfileAsync(profileId); if (!profile.IsValid()) throw new ArgumentException("Invalid profile"); // Do work } catch (ArgumentException ex) { Logging.SaveLog("TaskName", ex); // Handle validation errors } catch (IOException ex) { Logging.SaveLog("TaskName", ex); // Handle file I/O errors } catch (Exception ex) { Logging.SaveLog("TaskName", ex); // Handle unexpected errors throw; } ``` -------------------------------- ### Save V2RayN Configuration Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Saves the current V2RayN configuration after making modifications. This example demonstrates modifying a setting (AutoRun) and then saving the configuration, checking the result. ```csharp var config = ConfigHandler.LoadConfig(); config.GuiItem.AutoRun = true; int result = ConfigHandler.SaveConfig(config); if (result == 0) { Console.WriteLine("Configuration saved successfully"); } ``` -------------------------------- ### C# Example: Custom Icons for Routing Rules Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/RoutingItem.md Demonstrates how to assign a custom icon to a RoutingItem by converting an image file (icon.png) into a Base64 encoded string and assigning it to the CustomIcon property. ```csharp var routing = new RoutingItem { Id = Guid.NewGuid().ToString(), Remarks = "Custom Routed", Enabled = true, CustomIcon = Convert.ToBase64String(File.ReadAllBytes("icon.png")) }; ``` -------------------------------- ### GetAlpn() Method Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ProfileItem.md Parses a comma-separated ALPN string into a list of protocol names. Useful for understanding the supported application-layer protocols for TLS connections. ```csharp profile.Alpn = "h2,http/1.1"; var alpnList = profile.GetAlpn(); // ["h2", "http/1.1"] ``` -------------------------------- ### V2Ray JSON Rule Format Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/RoutingItem.md Illustrates the structure of routing rules in V2Ray's JSON format, specifying conditions like domain or IP and the corresponding outbound tag. ```json { "rules": [ { "type": "field", "domain": ["geosite:cn"], "outboundTag": "direct" }, { "type": "field", "ip": ["geoip:cn"], "outboundTag": "direct" }, { "type": "field", "domain": ["geosite:geolocation-!cn"], "outboundTag": "proxy" } ] } ``` -------------------------------- ### Create a DNS Rule for Google Domains Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/RulesItem.md This snippet shows how to configure a RulesItem to use a remote DNS resolver for specific domains, using Google domains as an example. ```csharp var dnsRule = new RulesItem { Type = "field", Domain = new List { "geosite:google" }, OutboundTag = "remote-dns", // Use remote DNS RuleType = ERuleType.DNS, Remarks = "Resolve Google via remote DNS" }; ``` -------------------------------- ### Good vs. Bad Remarks Conventions Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/RulesItem.md Illustrates best practices for writing clear and descriptive remarks for routing rules, contrasting effective examples with unhelpful ones. ```text Good: "Route Google APIs through proxy" Bad: "rule1" Good: "Direct access to corporate network" Bad: "local" Good: "Block BitTorrent traffic" Bad: "block p2p" ``` -------------------------------- ### Download Data with Custom Progress Callback Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DownloadService.md Downloads data from a specified URL and provides a custom callback function to report progress. The callback can be used to display progress percentages, download speeds, or other relevant information. This example demonstrates downloading JSON data. ```csharp var service = new DownloadService(); // Define custom update handler async Task OnProgress(bool isComplete, string message) { Console.WriteLine($"{(isComplete ? "[COMPLETE]" : "[PROGRESS]")} {message}"); // Could parse message to extract progress percentage, speed, etc. if (message.Contains("%")) { if (int.TryParse(message.Split('%')[0], out int progress)) { Console.WriteLine($" Progress bar: [{new string('=', progress / 5)}{new string('-', 20 - progress / 5)}] {progress}%"); } } } await service.DownloadDataAsync( "https://example.com/data.json", webProxy: null, // No proxy downloadTimeout: 60000, updateFunc: OnProgress); ``` -------------------------------- ### Start Speed Test Loop Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SpeedtestService.md Initiates an asynchronous speed test loop for a list of selected profiles. The test type determines the method of measurement (TCPing, Realping, UdpTest, Speedtest, Mixedtest). Results are reported via the provided callback and automatically saved. ```csharp public void RunLoop(ESpeedActionType actionType, List selecteds) ``` ```csharp var config = ConfigHandler.LoadConfig(); var profiles = await AppManager.Instance.GetProfileItems(); async Task OnSpeedTestUpdate(SpeedTestResult result) { Console.WriteLine($ ``` -------------------------------- ### Error Handling for ResolveConfig Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/FmtHandler.md Illustrates how to check the error message returned by FmtHandler.ResolveConfig when parsing fails. Provides examples for specific error conditions like empty input, unknown protocols, and general parsing exceptions. ```csharp var profile = FmtHandler.ResolveConfig(configString, out string msg); if (profile == null) { // Check which error occurred if (msg == ResUI.FailedReadConfiguration) { // Empty or whitespace-only input } else if (msg == ResUI.NonvmessOrssProtocol) { // Unknown protocol scheme } else if (msg == ResUI.Incorrectconfiguration) { // Exception during parsing } else { // Generic format error } // Log or display error Console.WriteLine($"Configuration parsing failed: {msg}"); } ``` -------------------------------- ### UrlRedirectAsync Usage Example Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DownloadService.md Example of using UrlRedirectAsync to get a redirect URL. It checks a subscription URL with proxy enabled and logs the redirect target if found. ```csharp var service = new DownloadService(); string? redirectUrl = await service.UrlRedirectAsync( "https://example.com/subscribe?token=xyz", useProxy: true); if (redirectUrl != null) { Console.WriteLine($"Redirects to: {redirectUrl}"); // Use the final URL for download } ``` -------------------------------- ### Get Core Executable Name Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/types.md Extension method to obtain the executable name for a given core type. ```csharp // Get core executable name string exeName = coreType.GetCoreExeName(); ``` -------------------------------- ### Get Protocol Name Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/types.md Extension method to retrieve the specific protocol name associated with a configuration type. ```csharp // Get protocol-specific information string protocolName = configType.GetProtocolName(); ``` -------------------------------- ### Create Basic VLESS Profile Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ProfileItem.md Demonstrates creating a VLESS profile with essential settings including address, port, password, network, stream security, and transport extras. Includes validation and logging. ```csharp var profile = new ProfileItem { IndexId = Guid.NewGuid().ToString(), ConfigType = EConfigType.VLESS, CoreType = ECoreType.Xray, Remarks = "Production Server", Address = "vless.example.com", Port = 443, Password = "00000000-0000-0000-0000-000000000000", Network = "tcp", StreamSecurity = "tls", Sni = "example.com", DisplayLog = true, ConfigVersion = 4 }; // Set transport settings var transportExtra = new TransportExtraItem { RawHeaderType = "http" }; profile.SetTransportExtra(transportExtra); // Validate if (profile.IsValid()) { Console.WriteLine($"Profile: {profile.GetSummary()}"); } ``` -------------------------------- ### Set Up SOCKS and HTTP Inbounds Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ConfigHandler.md Loads configuration, checks for an existing SOCKS inbound, and adds a new HTTP inbound on a different port. ```csharp var config = ConfigHandler.LoadConfig(); var socksInbound = ConfigHandler.GetInbound(config, 0); if (socksInbound?.Protocol != "socks") { Console.WriteLine("Warning: First inbound should be SOCKS"); } var httpInbound = new InItem { Protocol = "http", LocalPort = 8080, UdpEnabled = false }; ConfigHandler.AddInbound(config, httpInbound); ConfigHandler.SaveConfig(config); ``` -------------------------------- ### Load, Modify, and Save Configuration Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ConfigHandler.md Demonstrates how to load the current configuration, modify core settings and add a new HTTP inbound, and then save the changes. ```csharp var config = ConfigHandler.LoadConfig(); if (config == null) { Console.WriteLine("Failed to load configuration"); return; } config.CoreBasicItem.Loglevel = "debug"; config.CoreBasicItem.MuxEnabled = true; var httpInbound = new InItem { Protocol = "http", LocalPort = 8080, UdpEnabled = false, SniffingEnabled = true, RouteOnly = false }; ConfigHandler.AddInbound(config, httpInbound); ConfigHandler.SaveConfig(config); ``` -------------------------------- ### Initialize and Save Logs with NLog Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/errors.md Sets up NLog for structured error logging and demonstrates saving simple messages or exceptions with details. ```csharp // Initialize logging Logging.Setup(); // Save simple log message Logging.SaveLog("Configuration loaded successfully"); // Save exception with details try { // operation } catch (Exception ex) { Logging.SaveLog("OperationName", ex); } ``` -------------------------------- ### Initiating Speed Test Service Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/types.md Demonstrates how to initialize and run the SpeedTestService with a specific action type (e.g., Tcping) and a list of selected profiles. Requires a configuration object and an update callback. ```csharp SpeedTestService service = new(config, updateCallback); service.RunLoop(ESpeedActionType.Tcping, selectedProfiles); ``` -------------------------------- ### GetNetwork() - Get Transport Network Protocol Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ProfileItem.md Retrieves the transport network protocol of the profile. Returns a default value if the configured network is invalid. ```csharp public string GetNetwork() { // ... implementation details ... return Network ?? "raw"; // Example default } ``` ```csharp profile.Network = "ws"; string net = profile.GetNetwork(); // "ws" profile.Network = "invalid"; string net = profile.GetNetwork(); // "raw" (default) ``` -------------------------------- ### Build a Proxy Importer Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/FmtHandler.md Demonstrates how to create a reusable ProxyImporter class that attempts to resolve, validate, and save a profile from a given configuration string. Returns true on success, false on failure. ```csharp public class ProxyImporter { public bool TryImport(string configString) { var profile = FmtHandler.ResolveConfig(configString, out string msg); if (profile == null) { Console.WriteLine($"Import failed: {msg}"); return false; } if (!profile.IsValid()) { Console.WriteLine("Profile validation failed"); return false; } // Save the profile SaveProfile(profile); return true; } private void SaveProfile(ProfileItem profile) { // Implementation } } ``` -------------------------------- ### Check if Config Type is Complex Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/types.md Extension method to determine if a configuration type represents a complex setup like a policy group or proxy chain. ```csharp // Check if config type is a complex type (policy group or proxy chain) bool isComplex = configType.IsComplexType(); ``` -------------------------------- ### Testing Multiple Profiles with Different Methods Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SpeedtestService.md Demonstrates how to initialize and run the SpeedtestService for TCP ping tests on a list of profiles. Includes a callback for handling test results. ```csharp public class ProxyTester { private readonly Config _config; private List _results = new(); public ProxyTester(Config config) { _config = config; } public async Task TestProxiesAsync(List profiles) { async Task HandleSpeedTestUpdate(SpeedTestResult result) { _results.Add(result); Console.WriteLine($"✓ {result.Remarks}: {result.TotalTime}ms"); } // Test 1: Quick latency check Console.WriteLine("=== TCP Ping Test ==="); var tcpService = new SpeedtestService(_config, HandleSpeedTestUpdate); tcpService.RunLoop(ESpeedActionType.Tcping, profiles); await Task.Delay(TimeSpan.FromSeconds(10)); // Wait for results } } ``` -------------------------------- ### Initialize CoreBasicItem Configuration Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Initializes the CoreBasicItem section of the configuration if it is missing. This ensures default values for logging and multiplexing are set. ```csharp config.CoreBasicItem ??= new() { LogEnabled = false, Loglevel = "warning", MuxEnabled = false }; ``` -------------------------------- ### Unix Milliseconds Timestamp Conversion Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SubItem.md Shows how to get the current Unix timestamp in milliseconds and convert it back to a DateTime object for display. This is useful for handling the `UpdateTime` property. ```csharp // Get current timestamp long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // Convert to DateTime var updateDate = DateTimeOffset.FromUnixTimeMilliseconds(sub.UpdateTime).DateTime; Console.WriteLine($"Last updated: {updateDate:yyyy-MM-dd HH:mm:ss}"); ``` -------------------------------- ### Create a Basic Subscription Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SubItem.md Instantiates a SubItem with essential properties like ID, remarks, URL, and enabled status. Sets an auto-update interval and the last update time. ```csharp var subscription = new SubItem { Id = Guid.NewGuid().ToString(), Remarks = "Public Free Proxies", Url = "https://example.com/subscribe?token=xyz", Enabled = true, Sort = 1, AutoUpdateInterval = 24, // Update every 24 hours UpdateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }; ``` -------------------------------- ### Import Proxy from Clipboard Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/FmtHandler.md Resolves a proxy configuration string obtained from the clipboard into a ProfileItem. Handles successful imports by adding the profile and displays errors if resolution fails. ```csharp string clipboardContent = Clipboard.GetText(); // e.g., "vless://uuid@..." var profile = FmtHandler.ResolveConfig(clipboardContent, out string msg); if (profile != null) { // Profile successfully imported await AppManager.Instance.AddProfileItem(profile); Console.WriteLine("Proxy imported successfully"); } else { // Show error message to user MessageBox.Show($"Failed to import proxy: {msg}", "Error"); } ``` -------------------------------- ### SubItem with Memo and Notes Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SubItem.md Example of creating a SubItem with a detailed memo, which can include multi-line notes for user reference. The Memo field is useful for storing additional information about the subscription. ```csharp var subscription = new SubItem { Id = Guid.NewGuid().ToString(), Remarks = "Work VPN", Url = "https://corporate.example.com/vpn/subscribe", Memo = "Company-provided VPN\nExpires on 2025-12-31\nContact IT if issues", Enabled = true }; // Notes can be displayed in UI for user reference ``` -------------------------------- ### ProfileItem() - Constructor Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ProfileItem.md Initializes a new ProfileItem instance with default values for all properties. String properties are empty, numeric to 0, and booleans to false. ```csharp public ProfileItem() { // Default initializations for properties } ``` -------------------------------- ### Implement Speed Test Timeout Handling Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/errors.md Aborts a speed test if it exceeds a configured timeout (60 seconds in this example) and logs the timeout event. Requires CancellationTokenSource for managing the delay. ```csharp var service = new SpeedtestService(config, updateCallback); service.RunLoop(ESpeedActionType.Speedtest, profiles); // Implement timeout var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60)); try { await Task.Delay(TimeSpan.FromSeconds(60), cts.Token); } catch (OperationCanceledException) { service.ExitLoop(); Console.WriteLine("Speed test timed out"); } ``` -------------------------------- ### Handle Empty Configuration String Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/errors.md Attempts to resolve configuration from an empty string and captures the resulting error message. ```csharp string config = ""; var profile = FmtHandler.ResolveConfig(config, out string msg); // msg = "Failed to read configuration" ``` -------------------------------- ### Handle Speedtest Errors Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SpeedtestService.md This example shows how to implement error handling for speed tests by checking the TotalTime property of SpeedTestResult. It separates successful results from failed tests and reports the counts. ```csharp var config = ConfigHandler.LoadConfig(); var results = new List(); var errors = new List(); async Task OnSpeedTestUpdate(SpeedTestResult result) { // Check for test failures if (result.TotalTime <= 0) { errors.Add($"Test failed for {result.Remarks}"); } else { results.Add(result); } } var service = new SpeedtestService(config, OnSpeedTestUpdate); service.RunLoop(ESpeedActionType.Tcping, profiles); await Task.Delay(TimeSpan.FromSeconds(30)); Console.WriteLine($"Successful: {results.Count}"); Console.WriteLine($"Failed: {errors.Count}"); ``` -------------------------------- ### Handle Errors During Configuration Parsing Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/FmtHandler.md When ResolveConfig fails to parse a configuration string, it returns null and provides an error message. This example demonstrates how to check for parsing failures and display the error. ```csharp string invalidUri = "invalid://data"; var profile = FmtHandler.ResolveConfig(invalidUri, out string msg); if (profile == null) { // msg will be one of: // - "Configuration format is incorrect" // - "Not vmess or ss protocol" Console.WriteLine($"Failed to parse: {msg}"); } ``` -------------------------------- ### Download Subscription Update Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DownloadService.md Initiates a download for a subscription file. It sets up event handlers for completion and errors, and specifies download parameters like proxy usage and timeout. Use this for single file downloads. ```csharp var service = new DownloadService(); var config = ConfigHandler.LoadConfig(); service.UpdateCompleted += (sender, result) => { if (result.Success) { Console.WriteLine("Subscription updated successfully"); } else { Console.WriteLine($"Progress: {result.Msg}"); } }; service.Error += (sender, args) => { Console.WriteLine($"Download failed: {args.GetException().Message}"); }; await service.DownloadFileAsync( "https://sub.example.com/api/subscribe?token=abc123", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sub.txt"), useProxy: config.SystemProxyItem.Enabled, downloadTimeout: config.GuiItem.DownloadTimeout ?? 30000); ``` -------------------------------- ### Bandwidth Test with Cancellation and Timeout Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SpeedtestService.md Illustrates how to perform a bandwidth test using the SpeedtestService and handle potential timeouts using a CancellationTokenSource. Includes logic to exit the test loop upon cancellation. ```csharp public class BandwidthTester { public async Task> TestBandwidthAsync( List profiles, TimeSpan timeout) { var results = new List(); var cts = new CancellationTokenSource(timeout); async Task OnSpeedTestUpdate(SpeedTestResult result) { results.Add(result); Console.WriteLine($"Speed: {result.Remarks} - {result.TotalTime}ms"); } var config = ConfigHandler.LoadConfig(); var service = new SpeedtestService(config, OnSpeedTestUpdate); try { // Start bandwidth test with multiple concurrent connections service.RunLoop(ESpeedActionType.Mixedtest, profiles); // Wait for completion or timeout await Task.Delay(timeout, cts.Token); } catch (OperationCanceledException) { // Timeout reached, stop testing service.ExitLoop(); } return results; } } ``` -------------------------------- ### Configuring Load Balancing Strategy Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/types.md Illustrates how to configure load balancing for policy groups, specifically using the 'LeastPing' strategy. This is used when a policy group needs to distribute traffic across multiple proxies based on latency. ```csharp var group = new PolicyGroup { MultipleLoad = EMultipleLoad.LeastPing, // Configuration for least-ping load balancing }; ``` -------------------------------- ### Load Application Configuration Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ConfigHandler.md Loads the application configuration from disk. If the configuration file does not exist, it initializes a new Config object with default values for various settings. ```csharp public static Config? LoadConfig() ``` ```csharp var config = ConfigHandler.LoadConfig(); if (config == null) { Console.WriteLine("Failed to load configuration"); return; } Console.WriteLine($"Inbound count: {config.Inbound.Count}"); foreach (var inbound in config.Inbound) { Console.WriteLine($" - {inbound.Protocol} on port {inbound.LocalPort}"); } ``` -------------------------------- ### China Split DNS Configuration Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Configures a split DNS setup for China, routing Chinese domains to a local DNS server and foreign domains through a proxy. Uses the Xray core. ```csharp var dnsItem = new DNSItem { Remarks = "China Split DNS", Enabled = true, CoreType = ECoreType.Xray, NormalDNS = "119.29.29.29", // Tencent DNS (China) DomainDNSAddress = "8.8.8.8", // Google DNS (proxy) DomainStrategy4Freedom = "IPIfNonMatch" }; ``` -------------------------------- ### Set Up Proxy Chaining Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SubItem.md Configures a SubItem to route its proxies through other existing profiles in a chain. This allows for complex routing scenarios by linking multiple proxy configurations. ```csharp // Get existing profiles var profile1 = await AppManager.Instance.GetProfileItem("profile-id-1"); var profile2 = await AppManager.Instance.GetProfileItem("profile-id-2"); var subscription = new SubItem { Id = Guid.NewGuid().ToString(), Remarks = "Chained Subscription", Url = "https://example.com/subscribe", PrevProfile = profile1?.IndexId, // Route through profile1 first NextProfile = profile2?.IndexId, // Then through profile2 Enabled = true }; // Proxies from this subscription will be chained with specified profiles ``` -------------------------------- ### Verify PAC Server Accessibility in C# Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/errors.md This snippet checks if the PAC server is running and accessible by making an HTTP GET request. If the server is unresponsive or inaccessible, it suggests a fallback proxy type. ```csharp if (config.SystemProxyItem.SysProxyType == ESysProxyType.Pac) { var pacUrl = "http://127.0.0.1:16823/pac/"; // Verify PAC server is running using (var client = new HttpClient()) { try { var response = await client.GetAsync(pacUrl); if (!response.IsSuccessStatusCode) { Console.WriteLine("PAC server not responding"); config.SystemProxyItem.SysProxyType = ESysProxyType.ForcedChange; } } catch { Console.WriteLine("Cannot access PAC server"); } } } ``` -------------------------------- ### RunLoop Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SpeedtestService.md Starts an asynchronous speed test loop for a list of selected profiles based on the specified action type. The tests run in a background thread and results are automatically saved upon completion. ```APIDOC ## RunLoop(ESpeedActionType actionType, List selecteds) ### Description Starts asynchronous speed test loop based on the specified action type. Runs in background thread and automatically saves results when complete. ### Parameters #### Path Parameters - **actionType** (ESpeedActionType) - Required - Type of speed test to perform - **selecteds** (List) - Required - List of profiles to test ### Test Types: | Action Type | Description | Use Case | |------------|-------------|----------| | ESpeedActionType.Tcping | TCP connection ping test | Quick latency check | | ESpeedActionType.Realping | Real ICMP ping test (requires network access) | Accurate latency measurement | | ESpeedActionType.UdpTest | UDP connectivity test | Check UDP protocol support | | ESpeedActionType.Speedtest | Single-threaded bandwidth test | Accurate speed measurement | | ESpeedActionType.Mixedtest | Multi-threaded bandwidth test | Fast concurrent speed measurement | ### Request Example ```csharp var config = ConfigHandler.LoadConfig(); var profiles = await AppManager.Instance.GetProfileItems(); async Task OnSpeedTestUpdate(SpeedTestResult result) { Console.WriteLine($"Speed test result: {result.Remarks} - {result.TotalTime}ms"); } var speedTestService = new SpeedtestService(config, OnSpeedTestUpdate); // Start TCP ping test var selectedProfiles = profiles.Take(5).ToList(); speedTestService.RunLoop(ESpeedActionType.Tcping, selectedProfiles); // Results will be reported via callback and saved automatically ``` ``` -------------------------------- ### Create Shadowsocks Profile Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ProfileItem.md Instantiates a ProfileItem for a Shadowsocks configuration. Use this to set basic connection details and protocol-specific options like encryption method. ```csharp var profile = new ProfileItem { IndexId = Guid.NewGuid().ToString(), ConfigType = EConfigType.Shadowsocks, Remarks = "SS Server", Address = "ss.example.com", Port = 8388, Password = "mystrongpassword", Network = "tcp" }; // Set protocol-specific method var protoExtra = new ProtocolExtraItem { SsMethod = "aes-128-gcm" }; profile.SetProtocolExtra(protoExtra); ``` -------------------------------- ### Handle ArgumentException for Invalid Arguments in C# Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/errors.md This is a general example of how to catch ArgumentException, which can occur due to invalid enum values, configuration parameters, or out-of-range values. It logs the parameter name and the reason for the exception. ```csharp try { // Configuration operation } catch (ArgumentException ex) { Console.WriteLine($"Invalid argument: {ex.ParamName}"); Console.WriteLine($"Reason: {ex.Message}"); } ``` -------------------------------- ### GUI Application Configuration Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/configuration.md Configure GUI application settings such as auto-run, statistics, and UI preferences. ```json { "GuiItem": { "AutoRun": false, "EnableStatistics": true, "DisplayRealTimeSpeed": true, "KeepOlderDedupl": false, "AutoUpdateInterval": 24, "TrayMenuServersLimit": 20, "EnableHWA": false, "EnableLog": true } } ``` -------------------------------- ### Download Multiple Files with Progress Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DownloadService.md Manages the download of multiple subscription files sequentially. It uses a DownloadService instance and configures event handlers for download completion and errors. Includes a small delay between downloads to avoid overwhelming the server. ```csharp public class SubscriptionUpdater { private readonly DownloadService _downloadService = new(); private readonly Config _config; public SubscriptionUpdater(Config config) { _config = config; _downloadService.UpdateCompleted += OnDownloadCompleted; _downloadService.Error += OnDownloadError; } public async Task UpdateSubscriptionsAsync(List subscriptions) { foreach (var sub in subscriptions.Where(s => s.Enabled)) { Console.WriteLine($"Downloading: {sub.Remarks}"); string filePath = Path.Combine( _config.AppDataPath, $"sub_{sub.Id}.txt"); await _downloadService.DownloadFileAsync( sub.Url, filePath, _config.SystemProxyItem.Enabled, 30000); // Small delay between downloads await Task.Delay(500); } } private void OnDownloadCompleted(object? sender, UpdateResult result) { if (result.Success) { Console.WriteLine($"✓ {result.Msg}"); } } private void OnDownloadError(object? sender, ErrorEventArgs args) { Console.WriteLine($"✗ Download error: {args.GetException().Message}"); } } ``` -------------------------------- ### Configure Speed Test Settings Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ConfigHandler.md Loads configuration and adjusts parameters for speed test functionality, including page size, delay, concurrency, and timeout. ```csharp var config = ConfigHandler.LoadConfig(); config.SpeedTestItem.SpeedTestPageSize = 500; config.SpeedTestItem.SpeedTestDelayInterval = 2; config.SpeedTestItem.MixedConcurrencyCount = 4; config.SpeedTestItem.TimeOut = 30; ConfigHandler.SaveConfig(config); ``` -------------------------------- ### Handle Missing Default Configuration Resources Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/errors.md Verifies if the default configuration template can be loaded from embedded resources. If the result is empty, it indicates that the template is missing and suggests reinstalling the application. ```csharp var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient); if (result.IsNullOrEmpty()) { Console.WriteLine("Sample configuration template is missing"); Console.WriteLine("Reinstall v2rayN application"); } ``` -------------------------------- ### SubItem with Pre-SOCKS Port Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/SubItem.md Demonstrates creating a SubItem and specifying a PreSocksPort. This allows proxies from this subscription to use a dedicated SOCKS port when selected. ```csharp var subscription = new SubItem { Id = Guid.NewGuid().ToString(), Remarks = "Dedicated Port Sub", Url = "https://example.com/subscribe", PreSocksPort = 10809, // Use different SOCKS port for this subscription Enabled = true }; // When proxies from this subscription are selected, // they will use the specified SOCKS port ``` -------------------------------- ### Get Routing Display Information Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/RoutingItem.md Formats routing item details into a displayable string, including remarks, rule count, locked status, active status, and enabled status. Useful for UI elements displaying routing configurations. ```csharp public string GetRoutingDisplayInfo(RoutingItem routing) { var info = $"[{routing.Remarks}]"; if (routing.RuleNum > 0) { info += $" {routing.RuleNum} rules"; } if (routing.Locked) { info += " [Locked]"; } if (routing.IsActive) { info += " [Active]"; } if (!routing.Enabled) { info += " [Disabled]"; } return info; } ``` -------------------------------- ### LoadConfig Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/ConfigHandler.md Loads the application configuration from disk or returns a new Config with default settings. It handles initializing default values for various configuration sections if they are missing. ```APIDOC ## LoadConfig() ### Description Loads the application configuration from disk or returns a new Config with default settings. It handles initializing default values for various configuration sections if they are missing. ### Method GET ### Endpoint /config/load ### Returns `Config?` - Application configuration object, or null if a critical error occurs ### Example ```csharp var config = ConfigHandler.LoadConfig(); if (config == null) { Console.WriteLine("Failed to load configuration"); return; } Console.WriteLine($"Inbound count: {config.Inbound.Count}"); foreach (var inbound in config.Inbound) { Console.WriteLine($" - {inbound.Protocol} on port {inbound.LocalPort}"); } ``` ``` -------------------------------- ### C# Class for Managing Routing Rules Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/RoutingItem.md Provides utility methods for managing a list of RoutingItem objects, including filtering active routings, getting the selected routing, selecting a specific routing by ID, and counting total enabled rules. ```csharp public class RoutingManager { public List GetActiveRoutings(List routings) { return routings .Where(r => r.Enabled) .OrderBy(r => r.Sort) .ToList(); } public RoutingItem? GetSelectedRouting(List routings) { return routings.FirstOrDefault(r => r.IsActive); } public void SelectRouting(List routings, string routingId) { foreach (var routing in routings) { routing.IsActive = (routing.Id == routingId); } } public int CountTotalRules(List routings) { return routings .Where(r => r.Enabled) .Sum(r => r.RuleNum); } } ``` -------------------------------- ### Round-Trip Conversion of Profile Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/FmtHandler.md Demonstrates converting a ProfileItem object to a shareable URI using GetShareUri and then parsing that URI back into a ProfileItem using ResolveConfig. Verifies that key properties match after the round trip. ```csharp // Original profile var original = new ProfileItem { ConfigType = EConfigType.VLESS, Remarks = "Test Server", Address = "example.com", Port = 443, Password = "00000000-0000-0000-0000-000000000000", Network = "tcp", StreamSecurity = "tls" }; // Convert to URI string uri = FmtHandler.GetShareUri(original); Console.WriteLine($"URI: {uri}"); // Parse back from URI var parsed = FmtHandler.ResolveConfig(uri, out string msg); if (parsed != null) { Console.WriteLine($"Successfully round-tripped: {parsed.Remarks}"); Console.WriteLine($"Address match: {original.Address == parsed.Address}"); Console.WriteLine($"Port match: {original.Port == parsed.Port}"); } ``` -------------------------------- ### Standard DNS Server Formats Source: https://github.com/2dust/v2rayn/blob/master/_autodocs/api-reference/DNSItem.md Illustrates different ways to specify DNS servers, including single, multiple, port-specific, DoH, DoT, and DoQ formats. ```text Single server: 1.1.1.1 Multiple servers: 1.1.1.1,8.8.8.8 With port: 1.1.1.1:53 HTTPS DNS (DoH): https://1.1.1.1/dns-query TLS DNS (DoT): tls://1.1.1.1 QUIC DNS (DoQ): quic://1.1.1.1 ```