Moonglade

Modern Markdown blogging with AI-powered localization and search.

All Posts


Thoroughly understand what ASCII, Unicode, UTF-8, and UTF-32 are, as well as their differences and relationships

This article provides an in-depth analysis of the core logic and distinctions among encoding systems such as ASCII, Unicode, and UTF-8. ASCII addresses the digital storage of English through a mapping of 128 characters, while Unicode introduces the concepts of graphemes and code points to support global languages, achieving unified identification for over 100,000 characters. In terms of encoding strategies, UTF-32 facilitates indexing but suffers from significant space waste, whereas UTF-8 balances compatibility and efficiency through variable-length encoding of 1 to 4 bytes, making it the mainstream choice. The article emphasizes that within the Unicode system, a grapheme is not equivalent to a code point, nor is it equivalent to a byte. This complexity results in different programming languages defining string length differently; for instance, Python, C#, and Go yield different results when handling multi-byte characters such as Emojis. Developers need to distinguish between functions for imperceptible Unicode, perceptible Unicode, and perceptible graphemes to avoid garbled text and logical errors. Understanding the difference between character codes and character encodings, and mastering the underlying encoding rules of each language, is a critical foundation for handling multilingual text and ensuring accurate data storage and parsing.

Views 131
ASCII Character Encoding Go Programming Language UTF 8 Unicode dotnet

Simplifying DDD Value Object Comparison with EF Core Dynamic Expression Trees

This article explores technical solutions for implementing semantic equality queries with value objects in EF Core. It first points out that traditional field-by-field query code is verbose and lacks semantic clarity, while directly comparing value objects for equality results in a compilation exception. To address this, the article proposes and implements a generic `ValueObjectEqualHelper` static class, whose core is the `CheckEqual` method. This method dynamically builds expression trees, iterates through the value object's properties, automatically skips null values to avoid generating redundant `IS NULL` conditions, and correctly constructs binary expression trees for equality comparisons based on property types (primitive or reference types), finally connecting all conditions with `AndAlso` logic. This approach preserves the intuitive semantics of `p => p.Address == new Address(...)` while being correctly translated into SQL by EF Core, solving the pain point of being unable to directly compare value objects for equality in database queries and providing a generic and elegant implementation path.

Views 168
.NET C# Dynamic Condition Generation EF Core Entity Framework Core expression trees

Dynamically Building Expression Trees in EF Core to Set Soft Delete Query Filters for All Entities

This article introduces two QueryFilter configuration approaches for implementing soft delete in Entity Framework Core. First, it demonstrates the conventional method of manually adding `builder.HasQueryFilter(x => !x.SoftDelete)` in each entity configuration class. While simple and direct, this approach incurs high maintenance costs when dealing with a large number of entities. Subsequently, it proposes a superior dynamic expression tree construction scheme. By iterating through all entity types in the model, this approach automatically detects the presence of a `bool` type `SoftDelete` property and uses the `Expression` class to dynamically generate the `x => !x.SoftDelete` Lambda expression to uniformly set the query filter. This method eliminates code duplication and achieves global automation of soft delete filtering. The article also demonstrates how to use the `IgnoreQueryFilters()` method to ignore the filter when necessary to query deleted data, and provides various code implementations ranging from detailed construction to simplified syntax. Finally, it emphasizes the flexibility and vitality of C# syntax in constructing expression trees.

Views 136
.NET Dynamic Expression Trees EF Core Entity Framework Core Soft Delete lambda expressions

Building C# Expression Trees Step by Step

This article uses the construction of the common Lambda expression `p => p.Age > 18` as an example to demonstrate in detail the entire process of manually building an expression tree in C#. The article first analyzes the correspondence between the elements of the expression and the tree nodes, then step-by-step shows how to sequentially create parameter expressions, member expressions, constant expressions, and binary operator expressions. Finally, it uses `Expression.Lambda` to combine these nodes into a complete Lambda expression. The text also includes actual code for compiling the expression and using it for list filtering. Addressing the question of why manual compilation might seem redundant, the article points out that its core value lies in its use with `IQueryable` and EF Core, enabling dynamic queries without the need for manual compilation. This technique can be used to simplify dynamic comparison of value objects in DDD, or to set global filters for entity properties (such as soft delete), thereby enhancing code flexibility and maintainability.

Views 121
.NET C# Dynamic Expression EF Core Linq Expressions expression trees

How to use C# expression trees?

Expression trees are a technique that uses tree-based data structures to represent the logic of code operations. In .NET, they correspond to the `Expression<TDelegate>` type. They allow code to be manipulated as data, and can be compiled into executable delegate objects via the `Compile` method. This article demonstrates, through a hands-on example of manually constructing an expression tree, how to replace hardcoded property name validation logic. The specific steps include: first, creating a `ParameterExpression` as the parameter node; next, using `Expression.PropertyOrField` or `MakeMemberAccess` to build member access nodes; and finally, assembling a complete Lambda expression via `Expression.Lambda` and invoking it using `DynamicInvoke`. This approach effectively resolves maintenance challenges caused by property name changes, enhancing code flexibility and maintainability. Although dynamically constructing expression trees involves relatively complex and less intuitive code, its advantages are significant in scenarios requiring the avoidance of hardcoding and the implementation of runtime dynamic logic. It serves as an effective means of simplifying complex query operations, such as comparing value objects.

Views 106
C# Dynamic Code Generation Functional Programming Property Access expression trees lambda expressions

[Translated] How Data Is Stored in SQL Databases

This article provides an in-depth analysis of the physical data storage mechanisms in SQL Server. It highlights that while data logically exists in rows and columns, it is physically stored using 8KB data pages as the basic unit. When a table has a primary key, SQL Server creates a clustered index by default, ensuring that data is physically ordered by the primary key. This storage structure takes the form of a B-tree (also known as the clustered index structure), composed of root nodes, intermediate levels, and leaf nodes. The leaf nodes directly store the actual data rows, whereas the root nodes and intermediate levels contain index rows that include key values and pointers to lower-level nodes. Through this hierarchical pointer structure, the database engine can efficiently locate and retrieve data. Understanding this underlying structure is crucial for developers, particularly when performing SQL Server performance tuning, troubleshooting, and optimizing slow queries. Mastering the operational principles of data pages, B-trees, and index rows forms the foundation for enhancing database performance.

Views 132
B Tree Clustered Index DB Data Page Data Storage Root Node

[Translation] How SQL Indexes Work

This article provides an in-depth analysis of how indexes work in SQL Server, with a particular focus on distinguishing between clustered and non-clustered indexes. First, the article explains that clustered indexes are based on a B-tree structure, where data is physically sorted and stored by primary key. By traversing pointers from the root node through intermediate levels to the leaf nodes, the system can quickly locate data, enabling efficient index seeks (Seek) that retrieve results by reading only a minimal number of rows. Next, it contrasts this with a full table scan (Scan) performed in the absence of an index, noting that such scans must traverse millions of data rows, resulting in poor performance. Subsequently, the article introduces the structure of non-clustered indexes, which store only key values and row locators pointing to the clustered index. When querying non-indexed columns, SQL Server first uses the non-clustered index to quickly find the corresponding clustered key, then leverages the clustered index to retrieve the complete data row. This process involves an index seek, a key lookup, and a nested loop join. The article illustrates these mechanisms using execution plans, demonstrating how indexes significantly enhance query efficiency by reducing I/O reads. This helps developers understand the underlying logic of index-accelerated queries and their central role in database optimization.

Views 174
Clustered Index DB Database Index Execution Plan Non Clustered Index Query Optimization

How to Use UTC Time in C# and EF Core

This article delves into the handling of UTC time in C# and its integration with EF Core. It begins by analyzing the `Kind` property of `DateTime`, noting that EF Core defaults to reading times from the database with a `Kind` of `Unspecified`. To address this, a `ValueConverter` is used to uniformly correct properties ending with "Utc" to the `Utc` type. The article then discusses three approaches for converting UTC time to local time: using the `NotMapped` attribute, manual mapping, or an automatic mapping library, weighing the trade-offs between entity purity and development efficiency. The author ultimately chose to use the Mapster library, configuring `TypeAdapterConfig` to automatically invoke the `ToLocalTime` method when mapping to DTOs, thereby achieving a convenient conversion from UTC to local time. This solution maintains the simplicity of Entity classes while ensuring the accuracy of time displayed on the front end, resolving time logic errors that occur during cross-timezone deployments and providing practical code practice references for handling time display in global applications.

Views 171
.NET C# EF Core mapster time zones utc time

Unlocking the Dark Side of AI: Talking to Unconstrained AI Models

Unlocking the Dark Side of AI: Talking to Unconstrained AI Models

This article explains how to deploy the uncensored Vicuna 13B model locally to address the issue of ChatGPT being unable to answer sensitive topics due to safety restrictions. The article first highlights Vicuna's characteristics, including that it is fine-tuned based on LLaMA and offers high conversational quality. It then provides a detailed guide on running the quantized model using llama.cpp on a resource-constrained ultrabook. The author compares the impact of different quantization precisions (such as q4 and q5) on speed and accuracy, and provides specific command-line parameter configurations, including settings for temperature, context length, and interaction mode. By testing the case of "How to destroy a small country's economy," the article demonstrates the model's generation capabilities after content restrictions have been removed. Finally, from the perspectives of the importance of open source, data privacy and security, and avoiding technological monopoly, the article elaborates on the necessity and advantages of using local open-source LLMs as an alternative to closed-source commercial services, emphasizing the individual's right to explore unrestricted knowledge.

Views 1,075
AI AI Deployment Closed source Models Data Security Open Source LLM Technical Fairness

How to Implement an AI Virtual Town? My Discussion with NewBing and GPT-4

This article introduces a complete technical solution for building an AI-driven RPG game based on LangChain, the Phaser game engine, and the FAISS vector database. The core architecture consists of four key components: the Environment component defines environmental elements such as beds and bookshelves along with their functionalities; the Decision component leverages the GPT-4 language model, combining NPCs' initial personas and memory variables to generate autonomous decisions through vector retrieval; the Interaction component handles the interaction logic between NPCs and the environment, as well as among NPCs themselves; and the Application component is responsible for displaying game states and model outputs. The implementation steps cover initializing the Phaser scene and FAISS index, creating an NPC class with vectorization capabilities, integrating a large language model interface to drive the decision system, and developing a distance-triggered interaction mechanism. Through modular design, this solution enables multiple NPCs with independent memories and personalities to develop and interact freely in a virtual world, thereby simulating a small-scale social ecosystem composed of AI agents. The article provides detailed guidance from basic framework setup to specific code implementation, emphasizing the importance of decomposing game logic into independent modules. It aims to provide developers with a reusable starting point to help them build intelligent role-playing games with high autonomy and interactivity.

Views 681
AI Environment Interaction FAISS NPC Logic Phaser.js RPG Game