# 使用 CSX 脚本进行快速 C# 测试

需要测试 C # 代码的片段而不旋转一个完整的工程吗 ? C # 脚本文件 (C)`.csx`让您像脚本语言一样写和运行 C# 代码 。 `Program.cs`, 没有 `.csproj`没有构建步骤 - 只写和运行。 适合测试 API 、 验证逻辑或原型, 然后再承诺全面实施 。

因为我要推出完整的SemantiC搜索功能 我想分享我如何使用 `.csx` 用于此工程和其他工程中临时测试的文件 。

<datetime class="hidden">2025-11-26T20:00</datetime>

<!--category-- C#, Testing, Scripting, dotnet-script -->
[TOC]

## CSX vs.NET 10 基于文件的应用程序

在潜入之前,让我们先对房间里的大象说一下: .NET 10 现在有本地的“基于文件的应用程序”让你运行 `.cs` 直接与 `dotnet run app.cs`与 CSX 相比如何?

### NET 10 基于文件的应用程序( 现在可用 !)

使用.NET 10, 您可以直接运行单页 C # :

```bash
# .NET 10 - available now!
dotnet run app.cs
```

**特点:**

- SDK 原生自 SDK - 不需要额外工具
- 熟悉使用 `.cs` 扩展扩展
- 通过 NuGet 引用 `#:package` 指令指令
- 从第一天起提供全部调试器支持
- 与经常项目相同的汇编器

```csharp
// app.cs - .NET 10 style
#:package Newtonsoft.Json@13.0.3

using Newtonsoft.Json;

var obj = new { Name = "Test", Value = 42 };
Console.WriteLine(JsonConvert.SerializeObject(obj));
```

### CSX 脚本( 现在可播放)

CSX通过 `dotnet-script` 自2017年以来,

```bash
# Available today
dotnet script app.csx
```

**特点:**

- 与.NET6、7、8、9、10一起工作
- 富丰富的生态系统和工具
- 互动勘探的REPL模式
- 证明和试战

```csharp
// app.csx - CSX style
#r "nuget: Newtonsoft.Json, 13.0.3"

using Newtonsoft.Json;

var obj = new { Name = "Test", Value = 42 };
Console.WriteLine(JsonConvert.SerializeObject(obj));
```

### 你该用哪个?

功能  CSX (dotnet- statim)  .NET 10 文件 Apps
|---------|---------------------|-------------------|
| **可用程度** * NET 6+ * . NET 10 *
| **安装安装** | `dotnet tool install -g dotnet-script` 建在SDK里
| **文件扩展扩展名** | `.csx` | `.cs` |
| **NuGet 语法** | `#r "nuget: Pkg, Ver"` | `#:package Pkg@Ver` |
| **REPL 模式** 是的 还没有
| **IDE 支持 IDE 支持** 好(VS代码,骑手) 改善
| **除调调** *是的 * *是的(母语) *是的* *是的(母语) *

**我的建议:**

- **先尝试.NET 10 文件应用程序** - 本地支持意味着减少间接费的工具
- **返回到 CSX** 如果您需要 REPL 模式或使用旧的.NET 版本
- 这些概念几乎完全相同 -- -- 两个概念之间很容易进行知识转让

本篇文章的其余部分涵盖CSX, 其功能仍然很好, 并具有某些特性(如REPL), 即.NET 10 文件应用程序尚未具备。

## 什么是CSX? (CSX: CSX: CSX: CSX: CSX: CSX: CSX: CSX: CSX: CSX: CSX:什么是CSX: CSX: CSX: CSX: CSX: CSX: CSX: CSX: CSX: CSX是什么CSX: CSX: CSX: CSX: CSX: CSX: CSX: CSX: CSX: CSX:

CSX (C# Script) 文件是 C# 代码文件, 无需编译为工程即可直接执行。 把它当作“ Python- style” C# - 您写入代码, 您运行它, 您看到结果 。

```csharp
// hello.csx
Console.WriteLine("Hello from C# Script!");
```

运行它:

```bash
dotnet script hello.csx
```

就是这样,不 `Main()` 方法、 无命名空间、 不需要类包装 。

## 正在安装 dotnet 标记

运行 CSX 文件最常用的方法就是通过 [dotnet 脚本](https://github.com/dotnet-script/dotnet-script):

```bash
dotnet tool install -g dotnet-script
```

校验安装 :

```bash
dotnet script --version
```

## CSX 适合测试周期的地方

在潜入“如何”之前,让我们来理解一下“何时” CSX脚本在测试金字塔中占据了一个独特的位置:

```
                    ┌─────────────────┐
                    │   E2E Tests     │  ← Full system, slow, expensive
                    │   (Playwright)  │
                   ─┼─────────────────┼─
                   │ Integration Tests │  ← Multiple components, database
                   │    (xUnit + DB)   │
                  ─┼───────────────────┼─
                 │   CSX Scripts        │  ← Quick validation, exploration
                 │   (Ad-hoc testing)   │     ★ YOU ARE HERE ★
                ─┼─────────────────────┼─
               │      Unit Tests         │  ← Single class, mocked deps
               │   (xUnit, NUnit, etc)   │
              ─┴─────────────────────────┴─
```

### CSX 脚本作为“ Miini 集成测试” 。

CSX脚本不能取代正式测试 **补充**将之视为:

- **执行前激增** - 核实API工作后再围绕它建立服务
- **调试辅助工具** - 孤立和复制问题,不重建你的整个应用程序
- **探索试验** - 了解图书馆在写作单位测试前的行为
- **烟烟测试** - 对实际服务(数据库、API、排队)进行快速精神检查

### 发展工作流量

CSX如何融入典型特征发展周期:

```
1. EXPLORE (CSX Script)
   └─→ "Does this API even work? What's the response format?"
   └─→ Write a quick script to call the API and see the output

2. PROTOTYPE (CSX Script)
   └─→ "How should I structure this service?"
   └─→ Test different approaches without project scaffolding

3. IMPLEMENT (Production Code)
   └─→ Build the actual service with proper error handling, DI, etc.
   └─→ You already know the API works from step 1!

4. TEST (xUnit/NUnit)
   └─→ Write formal unit tests with mocks
   └─→ Write integration tests against test database

5. DEBUG (CSX Script)
   └─→ Production issue? Write a script to reproduce it
   └─→ Faster than adding logging, rebuilding, deploying
```

### 实实在在的例子:建立瓜米米融合

当我为这个博客建立Ummi分析集成时, 我的工作流程是:

1. **CSX: 测试原API** - 认证有效吗?
2. **CSX: 测试时间戳转换** - 在写任何生产代码之前在这里发现了一个窃听器!
3. **实施: 构建 UmamiClient** - 充满信心 因为我已经验证了API
4. **x单位:写单位测试** - Mock HttpClient, 测试序列化逻辑
5. **CSX:调试生产问题** 将问题孤立的脚本

CSX脚本没有取代我的单位测试 **阻止我写那些没用的代码** 助我,助我, **更快调试问题** 当它们发生的时候。

## 为什么使用 CSX 测试?

### 1. 零仪式

检验API呼叫的传统方法:

1. 创建新控制台工程
2. 添加 NuGet 软件包
3. 写写 `Program.cs`
4. 构建构建
5. 运行运行中
6. 完成后删除项目

CSX 方法 :

1. 写入脚本
2. 运行脚本

### 2. 内内内内内纳Get 引用

需要一个包吗? 在您的脚本中直接引用它 :

```csharp
#r "nuget: Newtonsoft.Json, 13.0.3"
#r "nuget: RestSharp, 110.2.0"

using Newtonsoft.Json;
using RestSharp;

var client = new RestClient("https://api.github.com");
var request = new RestRequest("users/scottgal", Method.Get);
request.AddHeader("User-Agent", "CSX-Test");

var response = await client.ExecuteAsync(request);
Console.WriteLine(JsonConvert.SerializeObject(
    JsonConvert.DeserializeObject(response.Content),
    Formatting.Indented));
```

首运行的下载软件包。 随后运行使用缓存 。

### 3. 参考参考本地最低生活水平

测试您自己的图书馆吗? 直接引用 :

```csharp
#r "bin/Debug/net9.0/MyLibrary.dll"

using MyLibrary;

var result = MyClass.DoSomething();
Console.WriteLine(result);
```

### 4. 其他参考脚本

将复杂脚本拆分为可重复使用的部件 :

```csharp
#load "helpers.csx"
#load "config.csx"

// Use functions/classes from loaded scripts
var config = LoadConfig();
var result = ProcessData(config);
```

## 此工程的真实实例

这些并不是精心设计的例子--它们其实是我用来调试和测试这个博客的代码库的脚本。每个脚本都解决了我在发展过程中遇到的一个真正的问题。

### API 测试时戳

**问题:** 我的 Umami 分析集成正在返回空数据。 在调试数小时后,我怀疑时间戳转换是错误的 — Umami API 期待 Unix 时间戳在毫秒内, 但我不确定我的.NET 代码是否生成了正确的格式 。

**为什么是CSX?** 我本可以在生产代码中添加伐木,重建、部署和检查日志。 或者我可以在30秒内写一个快速的脚本来验证我的假设。

```csharp
#!/usr/bin/env dotnet-script

// This script helped debug an issue where the Umami API was returning empty data.
// The API expects Unix timestamps in milliseconds, and I suspected my conversion was wrong.

// Start with known values we can verify
var now = DateTime.UtcNow;
var yesterday = now.AddHours(-24);

// The "O" format specifier gives us ISO 8601 format - precise and unambiguous
// Example output: "2025-11-24T10:30:45.1234567Z"
Console.WriteLine($"Now: {now:O}");
Console.WriteLine($"Yesterday: {yesterday:O}");

// The Umami API expects Unix timestamps in MILLISECONDS (not seconds!)
// DateTimeOffset is the safest way to convert - it handles time zones correctly.
// Always use ToUniversalTime() first to ensure we're working with UTC.
var nowOffset = new DateTimeOffset(now.ToUniversalTime());
var yesterdayOffset = new DateTimeOffset(yesterday.ToUniversalTime());

// ToUnixTimeMilliseconds() returns milliseconds since 1970-01-01 00:00:00 UTC
var nowMs = nowOffset.ToUnixTimeMilliseconds();
var yesterdayMs = yesterdayOffset.ToUnixTimeMilliseconds();

Console.WriteLine($"\nNow in milliseconds: {nowMs}");
Console.WriteLine($"Yesterday in milliseconds: {yesterdayMs}");

// IMPORTANT: Verify the conversion is reversible!
// This catches off-by-one errors and timezone issues
var nowConverted = DateTimeOffset.FromUnixTimeMilliseconds(nowMs);
var yesterdayConverted = DateTimeOffset.FromUnixTimeMilliseconds(yesterdayMs);

Console.WriteLine($"\nConverted back (should match above):");
Console.WriteLine($"Now: {nowConverted:O}");
Console.WriteLine($"Yesterday: {yesterdayConverted:O}");

// THE ACTUAL BUG: I found this timestamp in my application logs
// Let's see what date it actually represents...
var suspiciousTimestamp = 1763440087664L;
var suspiciousDate = DateTimeOffset.FromUnixTimeMilliseconds(suspiciousTimestamp);
Console.WriteLine($"\nSuspicious timestamp {suspiciousTimestamp} = {suspiciousDate:O}");

// Output showed this timestamp was in the year 2025... but it should have been in 2024!
// Tracing back, I found I was using DateTime.Now instead of DateTime.UtcNow,
// causing the local timezone offset to be applied incorrectly.
```

**成果:** 此脚本证明了时间戳是未来一年。 我追踪到错误到使用 `DateTime.Now` 代替 `DateTime.UtcNow` 固定在5分钟内,而不是可能5小时调试。

### 测试查询字符串生成

**问题:** 我需要核实ASP.NET的 `QueryHelpers` 类以 Umami API 期望的准确格式生成查询字符串。 它是否具有 URL- encode 特殊字符? 参数的顺序是什么 ?

**为什么是CSX?** 阅读文档是一回事, 但看到实际输出会告诉你代码将产生什么。

```csharp
#!/usr/bin/env dotnet-script

// Pull in ASP.NET's WebUtilities package - this is the same package
// that ASP.NET Core uses internally for query string manipulation
#r "nuget: Microsoft.AspNetCore.WebUtilities, 9.0.0"

using Microsoft.AspNetCore.WebUtilities;

// These are the exact parameters I need to send to the Umami metrics API
// Using a Dictionary makes it easy to see all parameters at once
var queryParams = new Dictionary<string, string>
{
    {"startAt", "1730000000000"},   // Unix timestamp in milliseconds
    {"endAt", "1730086400000"},     // 24 hours later
    {"type", "url"},                // Type of metric to fetch
    {"unit", "day"},                // Aggregation unit
    {"limit", "500"}                // Maximum results to return
};

// QueryHelpers.AddQueryString builds a properly formatted query string
// First parameter: base URL (empty string = just the query string portion)
// Second parameter: dictionary of key-value pairs
var queryString = QueryHelpers.AddQueryString(string.Empty, queryParams);

Console.WriteLine($"Generated query string:");
Console.WriteLine(queryString);
// Output: ?startAt=1730000000000&endAt=1730086400000&type=url&unit=day&limit=500

// Now let's verify we can parse it back - this catches encoding issues
// that might not be obvious in the generated string
Console.WriteLine($"\nParsed back (verifying round-trip):");
var parsed = QueryHelpers.ParseQuery(queryString);
foreach (var kvp in parsed)
{
    // Note: parsed values are StringValues, not string
    // StringValues can hold multiple values for the same key (e.g., ?tag=a&tag=b)
    Console.WriteLine($"  {kvp.Key} = {kvp.Value}");
}

// What I learned: QueryHelpers properly handles URL encoding for special characters
// This became important when I later added search terms with spaces and unicode
```

### 测试原始 HTTP API 呼叫

**问题:** 在建立有依赖性注射、错误处理、重试逻辑和单位测试的完整服务级之前,我想核实API实际上有效,并理解其反应格式。

**为什么是CSX?** 写50行探索代码比建立合适的服务基础设施要快。如果API不像我预期的那样工作,我浪费了5分钟而不是5小时。

```csharp
#!/usr/bin/env dotnet-script

// System.Net.Http.Json provides extension methods like PostAsJsonAsync and GetFromJsonAsync
// This is the same package ASP.NET Core uses internally
#r "nuget: System.Net.Http.Json, 9.0.0"

using System.Net.Http.Json;
using System.Text.Json;

// Configuration - in a real app these would come from appsettings.json
var websiteId = "32c2aa31-b1ac-44c0-b8f3-ff1f50403bee";
var umamiPath = "https://umami.mostlylucid.net";
var username = "admin";

// SECURITY: Never hardcode passwords! Use environment variables instead.
// Set before running: $env:UMAMI_PASSWORD = "your-password" (PowerShell)
//               or:   export UMAMI_PASSWORD="your-password" (bash)
var password = Environment.GetEnvironmentVariable("UMAMI_PASSWORD") ?? "";

if (string.IsNullOrEmpty(password))
{
    // Provide helpful instructions when the password is missing
    Console.WriteLine("ERROR: Set UMAMI_PASSWORD environment variable");
    Console.WriteLine("  PowerShell: $env:UMAMI_PASSWORD = 'your-password'");
    Console.WriteLine("  Bash:       export UMAMI_PASSWORD='your-password'");
    return;  // In CSX, 'return' at top level exits the script
}

// Create a single HttpClient instance - never create multiple instances in a loop!
// BaseAddress means all subsequent requests can use relative URLs
var httpClient = new HttpClient { BaseAddress = new Uri(umamiPath) };

// === STEP 1: Authenticate ===
// PostAsJsonAsync automatically serializes our anonymous object to JSON
// and sets the Content-Type header to application/json
Console.WriteLine("Step 1: Logging in...");
var loginPayload = new { username, password };
var loginResponse = await httpClient.PostAsJsonAsync("/api/auth/login", loginPayload);

// Always check for errors before trying to read the response body
if (!loginResponse.IsSuccessStatusCode)
{
    Console.WriteLine($"Login failed: {loginResponse.StatusCode}");
    var error = await loginResponse.Content.ReadAsStringAsync();
    Console.WriteLine($"Error body: {error}");
    return;
}

Console.WriteLine("Login successful!");

// === STEP 2: Extract JWT Token ===
// Use JsonDocument for one-off JSON parsing without creating dedicated DTOs
// This is perfect for exploratory testing when we don't know the exact schema
var loginContent = await loginResponse.Content.ReadAsStringAsync();
var loginJson = JsonDocument.Parse(loginContent);
var token = loginJson.RootElement.GetProperty("token").GetString();

// Add the JWT token to all future requests via the Authorization header
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

// === STEP 3: Build the API Request ===
// Always use UTC for API calls to avoid timezone confusion
var now = DateTime.UtcNow;
var yesterday = now.AddHours(-24);
var nowMs = ((DateTimeOffset)now).ToUnixTimeMilliseconds();
var yesterdayMs = ((DateTimeOffset)yesterday).ToUnixTimeMilliseconds();

var testUrl = $"/api/websites/{websiteId}/metrics?startAt={yesterdayMs}&endAt={nowMs}&type=url&unit=day&limit=10";

Console.WriteLine($"\nStep 2: Testing metrics endpoint...");
Console.WriteLine($"URL: {testUrl}");

// === STEP 4: Make the Request ===
var response = await httpClient.GetAsync(testUrl);
Console.WriteLine($"Status: {response.StatusCode}");

// Pretty-print the JSON response so we can understand the structure
var responseBody = await response.Content.ReadAsStringAsync();
try
{
    var formatted = JsonSerializer.Serialize(
        JsonSerializer.Deserialize<JsonElement>(responseBody),
        new JsonSerializerOptions { WriteIndented = true });
    Console.WriteLine($"Response:\n{formatted}");
}
catch
{
    // If it's not valid JSON, just print raw
    Console.WriteLine($"Response (raw):\n{responseBody}");
}

// What I learned from this script:
// 1. The API returns an array of objects with 'x' (url) and 'y' (count) properties
// 2. Empty results return [] not null
// 3. The JWT token expires after 24 hours
```

### 使用依赖性注射测试

**问题:** 我出版了一个NuGet软件包(Umami.Net), 并想用消费者使用该软件来测试,

**为什么是CSX?** 创建测试控制台工程, 添加我的 NuGet 参考文件, 写入所有 DI 锅炉板 - 15 + 分钟的仪式。 使用 CSX, 我可以在两分钟内验证消费者经验 。

```csharp
#!/usr/bin/env dotnet-script

// Reference my published NuGet package - this tests the ACTUAL PUBLISHED VERSION,
// not my local source code. This is crucial for verifying releases work correctly!
#r "nuget: Umami.Net, 0.1.0"

// Standard Microsoft DI packages - the same ones ASP.NET Core uses
#r "nuget: Microsoft.Extensions.DependencyInjection, 9.0.0"
#r "nuget: Microsoft.Extensions.Logging.Console, 9.0.0"

using Umami.Net;
using Umami.Net.UmamiData;
using Umami.Net.UmamiData.Models.RequestObjects;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

// Configuration
var websiteId = "32c2aa31-b1ac-44c0-b8f3-ff1f50403bee";
var umamiPath = "https://umami.mostlylucid.net";
var password = Environment.GetEnvironmentVariable("UMAMI_PASSWORD") ?? "";

if (string.IsNullOrEmpty(password))
{
    Console.WriteLine("ERROR: Set UMAMI_PASSWORD environment variable");
    return;
}

// === BUILD THE DI CONTAINER ===
// This mimics exactly what happens in a real ASP.NET Core app's Program.cs

var services = new ServiceCollection();

// Add logging so we can see what the library is doing internally
// Debug level will show HTTP requests, retries, token refreshes, etc.
services.AddLogging(builder =>
{
    builder.AddConsole();
    builder.SetMinimumLevel(LogLevel.Debug);  // Show everything
});

// This is my library's extension method - this is the public API that users call
// I want to verify this works correctly without any hidden dependencies
services.AddUmamiData(umamiPath, websiteId);

// Build the container and resolve our service
var serviceProvider = services.BuildServiceProvider();
var umamiDataService = serviceProvider.GetRequiredService<UmamiDataService>();

Console.WriteLine("=== Testing Umami.Net Package via DI ===\n");

// === TEST THE LOGIN FLOW ===
Console.WriteLine("Testing login...");
var loginSuccess = await umamiDataService.LoginAsync("admin", password);
if (!loginSuccess)
{
    Console.WriteLine("ERROR: Login failed - check credentials");
    return;
}
Console.WriteLine("Login successful!\n");

// === TEST THE METRICS API ===
Console.WriteLine("Testing metrics API...");
var metricsResult = await umamiDataService.GetMetrics(new MetricsRequest
{
    StartAtDate = DateTime.UtcNow.AddHours(-24),
    EndAtDate = DateTime.UtcNow,
    Type = MetricType.url,   // Get URL metrics (most visited pages)
    Unit = Unit.day,
    Limit = 10
});

// Display results
Console.WriteLine($"API returned status: {metricsResult?.Status}");
if (metricsResult?.Data?.Length > 0)
{
    Console.WriteLine($"\nTop {Math.Min(5, metricsResult.Data.Length)} URLs in the last 24 hours:");
    foreach (var metric in metricsResult.Data.Take(5))
    {
        // metric.x = the URL path, metric.y = the view count
        Console.WriteLine($"  {metric.y,5} views - {metric.x}");
    }
}
else
{
    Console.WriteLine("No data returned - check date range or website ID");
}

// What I verified with this script:
// 1. The NuGet package installs correctly
// 2. The DI registration extension method works
// 3. The service can be resolved from the container
// 4. Login and API calls work as expected
```

### 测试 Qdrant 矢量数据库

**问题:** 我正在整合一个 Qdrant 矢量数据库, 用于语义搜索 。 在写入制作服务之前, 我需要了解 GRPC 客户端是如何工作的, API 长什么样, 并验证我的本地 Qdrant 实例运行正确 。

**为什么是CSX?** 对许多开发者来说,矢量数据库是新的领域。 CSX让我进行交互式实验,尝试不同的操作,在对一个建筑作出承诺之前看到直接的结果。

```csharp
#!/usr/bin/env dotnet-script

// Qdrant.Client is the official .NET client for the Qdrant vector database
#r "nuget: Qdrant.Client, 1.12.0"

using Qdrant.Client;
using Qdrant.Client.Grpc;

// === CRITICAL: Windows gRPC HTTP/2 Fix ===
// By default, .NET on Windows doesn't allow unencrypted HTTP/2 connections (used by gRPC)
// Without this line, you'll get cryptic "Protocol error" exceptions
// This must be called BEFORE creating the QdrantClient!
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

// Connect to Qdrant running locally
// Note: Port 6334 is gRPC (faster), port 6333 is REST API
// The .NET client uses gRPC for better performance
var client = new QdrantClient("localhost", 6334);

Console.WriteLine("=== Qdrant Vector Database Testing ===\n");

// === STEP 1: List Existing Collections ===
// A "collection" in Qdrant is like a table - it holds vectors with the same dimensionality
Console.WriteLine("Step 1: Checking existing collections...");
var collections = await client.ListCollectionsAsync();

if (!collections.Any())
{
    Console.WriteLine("No collections found. This is a fresh Qdrant instance.\n");
}
else
{
    foreach (var collection in collections)
    {
        var info = await client.GetCollectionInfoAsync(collection);
        Console.WriteLine($"  Collection: {collection}");
        Console.WriteLine($"    Points (vectors): {info.PointsCount}");
        Console.WriteLine($"    Status: {info.Status}");
    }
    Console.WriteLine();
}

// === STEP 2: Create a Test Collection ===
// Vector databases store "points" - each point has a vector and optional metadata (payload)
var testCollection = "csx_demo";

Console.WriteLine($"Step 2: Creating test collection '{testCollection}'...");
try
{
    await client.CreateCollectionAsync(
        collectionName: testCollection,
        vectorsConfig: new VectorParams
        {
            // Vector size MUST match your embedding model!
            // all-MiniLM-L6-v2 produces 384-dimensional vectors
            // text-embedding-ada-002 produces 1536-dimensional vectors
            Size = 384,

            // Cosine similarity is standard for text embeddings
            // Alternatives: Distance.Dot (dot product), Distance.Euclid (euclidean)
            Distance = Distance.Cosine
        });
    Console.WriteLine("Collection created successfully!\n");
}
catch (Exception ex) when (ex.Message.Contains("already exists"))
{
    Console.WriteLine("Collection already exists, continuing...\n");
}

// === STEP 3: Insert Test Data ===
// In production, vectors come from an embedding model (BERT, OpenAI, etc.)
// For testing, we'll use random vectors
Console.WriteLine("Step 3: Inserting test point...");

var testVector = Enumerable.Range(0, 384)
    .Select(_ => (float)Random.Shared.NextDouble())
    .ToArray();

// Payload = metadata attached to the vector
// This is what you filter on and return in search results
var payload = new Dictionary<string, Value>
{
    ["title"] = "Understanding Vector Databases",
    ["slug"] = "understanding-vector-databases",
    ["language"] = "en",
    ["created"] = DateTime.UtcNow.ToString("O")
};

await client.UpsertAsync(
    collectionName: testCollection,
    points: new[]
    {
        new PointStruct
        {
            Id = Guid.NewGuid(),  // Unique identifier for this point
            Vectors = testVector,
            Payload = { payload }
        }
    });
Console.WriteLine("Point inserted!\n");

// === STEP 4: Search for Similar Vectors ===
// In production, you'd embed a search query and find similar documents
Console.WriteLine("Step 4: Searching for similar vectors...");

var searchVector = Enumerable.Range(0, 384)
    .Select(_ => (float)Random.Shared.NextDouble())
    .ToArray();

var results = await client.SearchAsync(
    collectionName: testCollection,
    vector: searchVector,
    limit: 5,
    scoreThreshold: 0.0f  // Return all results (random vectors won't have high similarity)
);

Console.WriteLine($"Found {results.Count} results:");
foreach (var result in results)
{
    // Score: 0 to 1 for cosine similarity (higher = more similar)
    Console.WriteLine($"  Score: {result.Score:F4}");
    Console.WriteLine($"    Title: {result.Payload["title"].StringValue}");
    Console.WriteLine($"    Slug: {result.Payload["slug"].StringValue}");
}

// === STEP 5: Clean Up ===
Console.WriteLine($"\nStep 5: Deleting test collection...");
await client.DeleteCollectionAsync(testCollection);
Console.WriteLine("Done! Test collection cleaned up.");

// What I learned from this script:
// 1. The gRPC client is fast but needs the HTTP/2 switch on Windows
// 2. Collection creation requires specifying vector dimensions upfront
// 3. Payloads can be arbitrary key-value pairs
// 4. Search returns results sorted by similarity score
```

## 更实用实例

### 测试 HTTP 端点

```csharp
#r "nuget: System.Net.Http.Json, 9.0.0"

using System.Net.Http.Json;

var http = new HttpClient();
http.DefaultRequestHeaders.Add("User-Agent", "CSX-Test");

// Test a GET endpoint
var response = await http.GetFromJsonAsync<JsonElement>(
    "https://api.github.com/repos/dotnet/runtime");

Console.WriteLine($"Stars: {response.GetProperty("stargazers_count")}");
Console.WriteLine($"Forks: {response.GetProperty("forks_count")}");
```

### 测试 JSON 序列化

```csharp
#r "nuget: System.Text.Json, 8.0.0"

using System.Text.Json;
using System.Text.Json.Serialization;

public record Person(
    string Name,
    int Age,
    [property: JsonPropertyName("email_address")] string Email);

var person = new Person("Scott", 50, "scott@example.com");

var options = new JsonSerializerOptions
{
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

var json = JsonSerializer.Serialize(person, options);
Console.WriteLine(json);

// Deserialize back
var parsed = JsonSerializer.Deserialize<Person>(json, options);
Console.WriteLine($"Parsed: {parsed}");
```

### 测试数据库查询

```csharp
#r "nuget: Npgsql, 8.0.0"
#r "nuget: Dapper, 2.1.24"

using Npgsql;
using Dapper;

var connectionString = "Host=localhost;Database=test;Username=postgres;Password=secret";

await using var conn = new NpgsqlConnection(connectionString);

// Quick query test
var results = await conn.QueryAsync<dynamic>(
    "SELECT * FROM users WHERE created_at > @date",
    new { date = DateTime.UtcNow.AddDays(-7) });

foreach (var row in results)
{
    Console.WriteLine($"{row.id}: {row.name}");
}
```

### 测试 Regex 模式

```csharp
using System.Text.RegularExpressions;

var patterns = new[]
{
    @"^\d{4}-\d{2}-\d{2}$",           // Date
    @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", // Email
    @"^https?://[\w\-]+(\.[\w\-]+)+", // URL
};

var testCases = new[]
{
    "2025-11-24",
    "test@example.com",
    "https://mostlylucid.net",
    "not-a-date",
    "invalid-email",
};

foreach (var test in testCases)
{
    Console.WriteLine($"\n{test}:");
    foreach (var pattern in patterns)
    {
        var match = Regex.IsMatch(test, pattern);
        if (match) Console.WriteLine($"  ✓ Matches: {pattern}");
    }
}
```

### LINQ 测试查询

```csharp
var data = new[]
{
    new { Name = "Alice", Age = 30, Department = "Engineering" },
    new { Name = "Bob", Age = 25, Department = "Marketing" },
    new { Name = "Charlie", Age = 35, Department = "Engineering" },
    new { Name = "Diana", Age = 28, Department = "Engineering" },
};

// Test complex LINQ query
var result = data
    .Where(x => x.Department == "Engineering")
    .GroupBy(x => x.Age >= 30)
    .Select(g => new
    {
        Senior = g.Key,
        Count = g.Count(),
        Names = string.Join(", ", g.Select(x => x.Name))
    });

foreach (var group in result)
{
    Console.WriteLine($"Senior: {group.Senior}, Count: {group.Count}, Names: {group.Names}");
}
```

### 测试 Qdrant 矢量搜索

```csharp
#r "nuget: Qdrant.Client, 1.12.0"

using Qdrant.Client;
using Qdrant.Client.Grpc;

var client = new QdrantClient("localhost", 6334);

// Test collection exists
var collections = await client.ListCollectionsAsync();
Console.WriteLine("Collections:");
foreach (var collection in collections)
{
    Console.WriteLine($"  - {collection}");
}

// Test a search (assuming you have embeddings)
var testVector = Enumerable.Range(0, 384).Select(_ => (float)Random.Shared.NextDouble()).ToArray();

try
{
    var results = await client.SearchAsync(
        collectionName: "blog_posts",
        vector: testVector,
        limit: 5);

    foreach (var result in results)
    {
        Console.WriteLine($"Score: {result.Score}, Id: {result.Id}");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Search failed: {ex.Message}");
}
```

## IDE 支持 IDE 支持

### 视觉工作室代码

安装 [C# 德夫吉](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) 扩展名。您可获得 :

- 语法突出语法
- Intelli 感知
- 通过代码Lens 运行/调试

创建创建 `.vscode/launch.json`:

```json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Run CSX",
            "type": "coreclr",
            "request": "launch",
            "program": "dotnet",
            "args": ["script", "${file}"],
            "cwd": "${workspaceFolder}"
        }
    ]
}
```

### 喷气冲压骑士

Rider 拥有 CSX 支持的嵌入 CSX 支持。 任何单击右键 `.csx` 并选择“运行”文件。

## 提示和诡计

### 使用 Shebang 游戏

在 Linux/ Mac 上添加一个 shebang , 使脚本可以直接执行 :

```csharp
#!/usr/bin/env dotnet-script

Console.WriteLine("Runs directly with ./script.csx");
```

### 默认参数

通过全球访问访问命令线参数 `Args` 变量 :

```csharp
// run: dotnet script test.csx -- arg1 arg2 "arg with spaces"
Console.WriteLine($"Arguments: {Args.Count}");
foreach (var (arg, index) in Args.Select((a, i) => (a, i)))
{
    Console.WriteLine($"  [{index}]: {arg}");
}

// Common pattern: use args with defaults
var environment = Args.ElementAtOrDefault(0) ?? "development";
var verbose = Args.Contains("--verbose");

Console.WriteLine($"Environment: {environment}, Verbose: {verbose}");
```

### 秘密的环境变量

永不硬代码机密 - 使用环境变量 :

```csharp
var apiKey = Environment.GetEnvironmentVariable("API_KEY");
var dbPassword = Environment.GetEnvironmentVariable("DB_PASSWORD");

if (string.IsNullOrEmpty(apiKey))
{
    Console.Error.WriteLine("ERROR: API_KEY not set");
    Console.Error.WriteLine("Run: $env:API_KEY='your-key' (PowerShell)");
    Console.Error.WriteLine(" or: export API_KEY='your-key' (bash)");
    Environment.Exit(1);
}

// Safely log partial key for debugging
Console.WriteLine($"Using API key: {apiKey[..4]}...{apiKey[^4..]}");
```

### 交互式模式 (REPL)

启动互动的探索会话 :

```bash
dotnet script
```

你得到一个C#REPL:

```
> var x = 42;
> x * 2
84
> #r "nuget: Newtonsoft.Json, 13.0.3"
> using Newtonsoft.Json;
> JsonConvert.SerializeObject(new { foo = "bar" })
"{"foo":"bar"}"
```

### 除调调

用 VS 代码调试, 添加一个断点, 用 F5 运行, 或者 :

```bash
dotnet script test.csx --debug
```

### 使用快速 DTO 记录

不需要类文件 - 定义内嵌 :

```csharp
// Records are perfect for CSX - single line definitions
public record Person(string Name, int Age, string Email);
public record ApiResponse<T>(bool Success, T? Data, string? Error);
public record SearchResult(string Title, string Slug, float Score);

var person = new Person("Scott", 50, "scott@example.com");
var response = new ApiResponse<Person>(true, person, null);
```

### 美美打印, 与集成化

```csharp
#r "nuget: Dumpify, 0.6.5"

using Dumpify;

var data = new
{
    Name = "Test",
    Items = new[] { 1, 2, 3 },
    Nested = new { Foo = "bar" }
};

data.Dump();  // Pretty console output with colors
```

## 共同问题和难题

### 问题 : “ 找不到 NuGet 软件包”

首运行慢 - 软件包在背景中下载 :

```csharp
#r "nuget: SomePackage, 1.0.0"  // First run: downloads
                                  // Second run: uses cache
```

**修整**:等待第一次运行完成,或预下載:

```bash
dotnet script init  # Creates omnisharp.json
dotnet script       # Downloads packages in REPL
```

### 问题: 找不到“ 类型或命名空间 ”

软件包版本可能错误或不兼容 :

```csharp
// Bad - version doesn't have the type you need
#r "nuget: Microsoft.Extensions.Http, 6.0.0"

// Good - use matching version for your .NET SDK
#r "nuget: Microsoft.Extensions.Http, 9.0.0"
```

### 问题: 在 Windows 上的 GRPC

Qdrant 和其他 GRPC 服务因 HTTP/2 错误失败 :

```csharp
// Add this BEFORE creating gRPC clients
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

var client = new QdrantClient("localhost", 6334);  // Now works
```

### 问题: HttpClient Socket 解析

不要在循环中创建多个 HttpClient 实例 :

```csharp
// Bad - creates socket exhaustion
foreach (var url in urls)
{
    using var client = new HttpClient();  // DON'T do this
    await client.GetAsync(url);
}

// Good - reuse HttpClient
using var client = new HttpClient();
foreach (var url in urls)
{
    await client.GetAsync(url);
}
```

### 议题: 顶层同步

顶级助产器刚刚在 CSX 工作,

```csharp
// This works - no async Main needed
var response = await httpClient.GetAsync("https://example.com");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
```

### 问题: 组装负载冲突

当查找有依赖性的本地 DLL 时:

```csharp
// Order matters - load dependencies first
#r "Mostlylucid.Shared/bin/Debug/net9.0/Mostlylucid.Shared.dll"
#r "Mostlylucid.Services/bin/Debug/net9.0/Mostlylucid.Services.dll"

// Or use NuGet for dependencies, local for your code
#r "nuget: Microsoft.Extensions.Logging, 9.0.0"
#r "MyLibrary/bin/Debug/net9.0/MyLibrary.dll"
```

### 议题: 编辑后不会运行脚本

IntelliSensense 缓存可能会变老 :

```bash
# Clear the cache
rm -rf ~/.dotnet-script/          # Linux/Mac
rd /s /q %USERPROFILE%\.dotnet-script\  # Windows
```

### 问题:无法律约束力参考类型

CSX 使用不同的默认值 - 必要时明确启用 :

```csharp
#nullable enable

string? nullableString = null;  // OK
string nonNullable = null;      // Warning
```

## 何时使用 CSX vs 完整工程

**使用 CSX 时 :**

- 快速一次性测试
- APP 勘探
- 原型算法
- 在添加到工程前测试 NuGet 软件包
- 校验 Regex、 LINQ、 JSON 序列化
- 数据库查询测试
- 学习/学习/经验

**在下列情况下使用完整项目:**

- 复杂依赖的多个文件
- 单位测试(使用x单位/单位)
- 生产守则
- 团队协作
- CI/CD输油管

## 真实世界实例:测试我的博客API

以下是我用来测试最精密搜索端点的脚本:

```csharp
#r "nuget: System.Net.Http.Json, 8.0.0"

using System.Net.Http.Json;

var baseUrl = Args.Length > 0 ? Args[0] : "https://www.mostlylucid.net";
var searchTerm = Args.Length > 1 ? Args[1] : "docker";

var http = new HttpClient { BaseAddress = new Uri(baseUrl) };

Console.WriteLine($"Searching {baseUrl} for '{searchTerm}'...\n");

var results = await http.GetFromJsonAsync<JsonElement>(
    $"/api/search?term={Uri.EscapeDataString(searchTerm)}");

if (results.TryGetProperty("results", out var items))
{
    foreach (var item in items.EnumerateArray().Take(5))
    {
        var title = item.GetProperty("title").GetString();
        var slug = item.GetProperty("slug").GetString();
        Console.WriteLine($"- {title}");
        Console.WriteLine($"  /{slug}\n");
    }
}
```

运行它:

```bash
dotnet script search-test.csx -- https://localhost:5001 "entity framework"
```

## 摘要摘要摘要

CSX 脚本是 C# REPL 和一个完整的项目之间的完美中间地带。 它们的理想用途是:

- **速度速度**: 以秒数书写并运行
- **简单化**: 没有项目仪式
- **电力**由 NuGet 支持的全 C #
- **便捷性**:共享单个文件

下次你下次需要快速测试 C#,跳跳 `dotnet new console` 所达到的 `dotnet script` 取而代之。

**资源:**

- [GitHub 刻画](https://github.com/dotnet-script/dotnet-script)
- [C# 脚本文档](https://docs.microsoft.com/en-us/archive/msdn-magazine/2016/january/essential-net-csharp-scripting)