🌐 English | 简体中文
XFEExtension is a C# DLL library designed to optimize common statements in C# code and provide more concise access patterns, rapid server/client setup, a free ChatGPT API interface, a free communication server, an XFE downloader, new formats, and more.
The XFEExtension library is suitable for a wide variety of C# projects, especially when improving code readability is a priority. It includes extension methods for many common operations, making code writing more efficient and straightforward. Here are some examples of what XFEExtension can do:
-
Simplify code access: XFEExtension provides cleaner syntax, making access operations in your code clearer and more readable.
-
Optimize performance: With XFEExtension you can perform various performance-optimization operations to improve application efficiency.
-
Accelerate development: By reducing boilerplate code, XFEExtension speeds up project development while improving code maintainability.
XFEJson.Parse does not parse the complete document when the root node is created. A container is scanned only when it is queried, and unvisited descendants are not materialized or decoded.
using XFEExtension.NetCore.XFETransform.Json;
using XFEExtension.NetCore.StringExtension.Json;
XFEJsonNode json = """
{
"status": 200,
"data": {
"items": [
{ "id": 1, "text": "first", "unused": { "large": true } },
{ "id": 2, "text": "second" }
]
}
}
""";
var status = json["status"]?.GetInt32();
var secondId = (json > "data" > "items" > 1 > "id")?.GetInt64();
var projections = json["data"]!["items"]!.ProjectArray("id", "text");Missing properties and out-of-range array indexes return null. Read scalar values with typed APIs such as GetString, GetInt32, GetDouble, and GetBoolean.
var model = XFEJson.Deserialize<MyModel>(jsonText);
var jsonText = XFEJson.Serialize(model, new XFEJsonOptions
{
PropertyNamingPolicy = XFEJsonPropertyNamingPolicy.CamelCase,
WriteIndented = true
});
// Extension forms are also available: model.ToJson(), jsonText.FromJson<MyModel>()Lazy navigation guarantees only that visited fragments are valid. Call XFEJson.Validate(jsonText) or XFEJson.TryValidate(jsonText, out var error) when the whole input must be checked first. The old QueryableJsonNode and package:* APIs remain available in 5.x but are obsolete.
var lANDeviceDetector = new LANDeviceDetector();
lANDeviceDetector.DeviceFind += (sender) =>
{
Console.WriteLine($"IP: {sender.IPAddress}\tDevice name: {sender.DeviceName}");
};
await lANDeviceDetector.StartDetecting();var lANDeviceDetector = new LANDeviceDetector("100.73.121.*"); // scans 100.73.121.1 – 100.73.121.255
lANDeviceDetector.DeviceFind += (sender) =>
{
Console.WriteLine($"IP: {sender.IPAddress}\tDevice name: {sender.DeviceName}");
};
await lANDeviceDetector.StartDetecting();var lANDeviceDetector = new LANDeviceDetector("100.73.121.*", 2000); // sets timeout to 2000 ms
lANDeviceDetector.DeviceFind += (sender) =>
{
Console.WriteLine($"IP: {sender.IPAddress}\tDevice name: {sender.DeviceName}");
};
await lANDeviceDetector.StartDetecting();var testClass = new TestClass("Test Name", "Test Description", 15); // the object you want to analyze
testClass.X(); // prints all information about the object to the consolevar testClass = new TestClass("Test Name", "Test Description", 15); // the object you want to analyze
testClass.XL(); // writes all information about the object to the debug trace output// Ask GPT and receive a reply
var result = await XFEChatGPT.SendAndGetGPTResponse("Hello");
Console.WriteLine(result);// Use XFEChatGPT for interactive GPT conversations
XFEChatGPT xFEChatGPT = new XFEChatGPT("You are an AI assistant", true);
// Subscribe to events
xFEChatGPT.XFEChatGPTMessageReceived += (sender, e) =>
{
switch (e.GenerateState)
{
case GenerateState.Start:
Console.Write("[Generation started] ChatGPT:");
break;
case GenerateState.Continue:
Console.Write(e.Message);
break;
case GenerateState.End:
Console.WriteLine("[Generation complete]");
break;
case GenerateState.Error:
Console.WriteLine($"[Error] {e.Message}");
break;
default:
break;
}
};
// Read the user's question
var askContent = Console.ReadLine();
// Send with a random message ID
xFEChatGPT.SendGPTMessage(Guid.NewGuid().ToString(), askContent);// Create a MemorableXFEChatGPT object with conversation memory
MemorableXFEChatGPT memorableXFEChatGPT = new MemorableXFEChatGPT();
// Create a new dialog and set the system message
memorableXFEChatGPT.CreateDialog("dialog-id", "You are an AI assistant developed by XFEstudio", true, true);
// Subscribe to the message-received event
memorableXFEChatGPT.XFEChatGPTMessageReceived += (sender, e) =>
{
switch (e.GenerateState)
{
case GenerateState.Start:
Console.Write("[Generation started] ChatGPT:");
break;
case GenerateState.Continue:
Console.Write(e.Message);
break;
case GenerateState.End:
Console.WriteLine("[Generation complete]");
break;
case GenerateState.Error:
Console.WriteLine($"[Error] {e.Message}");
break;
default:
break;
}
};
// Read the user's question
var askContent = Console.ReadLine();
// Send using the dialog ID created above, a random message ID, and the question
memorableXFEChatGPT.AskChatGPT("dialog-id", Guid.NewGuid().ToString(), askContent);// Simplify file read/write operations with XFEExtension
"Hello World!".WriteIn("test.txt");
string txt = "test.txt".ReadOut();// Encrypt and decrypt text using XFEExtension
string text = "This is text that will be encrypted";
$"Plain text: {text}".CW();
string password = "my-secret-key";
string encrypt = text.XEAEncrypt(password); // encrypt
Console.WriteLine("Encrypted: " + encrypt);
Console.WriteLine("Decrypted: " + encrypt.XEADecrypt(password)); // decrypt// Simplify attribute reading with XFEExtension
string str = testObject.GetAttribute<string>();Starting with XFEExtension.NetCore 5.0, the testing framework is provided by the
XFEExtension.NetCore.XUnit 4.0 package. The base extension package no longer
defines XFECode, CTest, MTest, or SMTest.
Use [Test], [TestCase], [Benchmark], and Assert from the dedicated package.
public class CustomServer
{
CyberCommServer CyberCommServer { get; } = new("http://127.0.0.1:19019/");
public async Task StartServer()
{
CyberCommServer.ServerStarted += CyberCommServer_ServerStarted;
CyberCommServer.ConnectionClosed += CyberCommServer_ConnectionClosed;
CyberCommServer.ClientConnected += CyberCommServer_ClientConnected;
CyberCommServer.MessageReceived += CyberCommServer_MessageReceived;
await CyberCommServer.StartCyberCommServer();
}
private void CyberCommServer_MessageReceived(object? sender, CyberCommServerEventArgs e)
{
e.ReplyMessage("Server received your message");
Console.WriteLine($"Message from client [{e.IPAddress}]: {e.TextMessage}"); // plain-text example
}
private void CyberCommServer_ClientConnected(object? sender, CyberCommServerEventArgs e)
{
Console.WriteLine($"New client connected: {e.IPAddress}");
}
private void CyberCommServer_ConnectionClosed(object? sender, CyberCommServerEventArgs e)
{
Console.WriteLine($"Client [{e.IPAddress}] disconnected");
}
private void CyberCommServer_ServerStarted(object? sender, EventArgs e)
{
Console.WriteLine("Server started");
}
}public class CustomClient
{
CyberCommClient CyberCommClient { get; } = new("http://127.0.0.1:19019/");
public async Task StartClient()
{
CyberCommClient.Connected += CyberCommClient_Connected;
CyberCommClient.ConnectionClosed += CyberCommClient_ConnectionClosed;
CyberCommClient.MessageReceived += CyberCommClient_MessageReceived;
await CyberCommClient.StartCyberCommClient();
}
private void CyberCommClient_MessageReceived(object? sender, CyberCommClientEventArgs e)
{
Console.WriteLine($"Message received: {e.TextMessage}"); // receive plain-text message
// reply here if needed:
// e.ReplyMessage();
}
private void CyberCommClient_ConnectionClosed(object? sender, EventArgs e)
{
Console.WriteLine("Disconnected from server");
}
private void CyberCommClient_Connected(object? sender, EventArgs e)
{
Console.WriteLine("Connected to server");
CyberCommClient.SendTextMessage("This is a test message"); // plain-text example
}
}XCCNetWork xCCNetWork = new(); // create XCC network base
var group = xCCNetWork.CreateGroup("Test Group", "Member Name"); // create a group, provide group name and member name
#region Subscribe to events
xCCNetWork.Connected += (sender, e) =>
{
Console.WriteLine($"Group: {e.Group.GroupId}\tConnected");
group.SendTextMessage("Test message");
};
xCCNetWork.ConnectionClosed += (sender, e) =>
{
Console.WriteLine($"Group: {e.Group.GroupId}\tDisconnected");
};
xCCNetWork.TextMessageReceived += (sender, e) =>
{
Console.WriteLine($"Group: {e.Group.GroupId}\tText message received: {e.TextMessage}");
};
#endregion
await group.StartXCC(); // start the group's network communicationXFEDownloader xFEDownloader = new()
{
DownloadUrl = "https://www.nuget.org/api/v2/package/XFEExtension.NetCore/4.1.0",
SavePath = "XFEExtension.NetCore.nupkg",
FileSegmentCount = 9 // use 9 threads to accelerate the download (recommended: no more than 15)
};
xFEDownloader.BufferDownloaded += (sender, e) =>
{
Console.WriteLine($"Progress: {e.DownloadedBufferSize.FileSize()}/{e.TotalBufferSize?.FileSize()}");
};
await xFEDownloader.Download();