📄 LIBRARY_USAGE.md

ChatworkBulkSender ライブラリ使用方法

1. Microsoft.Extensions.DependencyInjection (v8.0.1)

概要

依存性注入(DI)コンテナを提供し、サービスの登録と解決を管理します。

使用方法

Program.cs での初期化

using Microsoft.Extensions.DependencyInjection;

static class Program
{
public static IServiceProvider ServiceProvider { get; private set; }

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

// DIコンテナの設定
var services = new ServiceCollection();
ConfigureServices(services);
ServiceProvider = services.BuildServiceProvider();

// メインフォームの起動
var mainForm = ServiceProvider.GetRequiredService<MainMenuForm>();
Application.Run(mainForm);
}

private static void ConfigureServices(IServiceCollection services)
{
// DAOの登録
services.AddScoped<BaseDao>();
services.AddScoped<ChatworkAccountDao>();
services.AddScoped<CustomerMasterDao>();
services.AddScoped<LabelDao>();
services.AddScoped<MessageTemplateDao>();
services.AddScoped<RecipientDao>();
services.AddScoped<RecipientGroupDao>();
services.AddScoped<SendHistoryDao>();
services.AddScoped<SendScheduleDao>();

// サービスの登録
services.AddScoped<ChatworkApiService>();
services.AddScoped<MessageSendService>();
services.AddScoped<ScheduleService>();
services.AddScoped<ValidationService>();

// フォームの登録
services.AddTransient<MainMenuForm>();
services.AddTransient<SettingsMenuForm>();
services.AddTransient<ChatworkMasterForm>();
// その他のフォームも同様に登録
}
}

フォーム内でのサービス利用

public partial class ChatworkMasterForm : Form
{
private readonly ChatworkAccountDao _accountDao;
private readonly ValidationService _validationService;

public ChatworkMasterForm(ChatworkAccountDao accountDao, ValidationService validationService)
{
InitializeComponent();
_accountDao = accountDao;
_validationService = validationService;
}

private void LoadData()
{
var accounts = _accountDao.GetAll();
// データの処理
}
}

2. System.Text.Json (v8.0.5)

概要

高性能なJSONシリアライザー。Newtonsoft.Jsonの代替として使用可能。

使用方法

ChatworkApiService での利用例

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

public class ChatworkApiService
{
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _jsonOptions;

public ChatworkApiService()
{
_httpClient = new HttpClient();
_jsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
}

public async Task<SendMessageResponse> SendMessageAsync(string roomId, string message, string apiToken)
{
var request = new HttpRequestMessage(HttpMethod.Post, $"https://api.chatwork.com/v2/rooms/{roomId}/messages");
request.Headers.Add("X-ChatWorkToken", apiToken);

var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("body", message)
});
request.Content = content;

var response = await _httpClient.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();

return JsonSerializer.Deserialize<SendMessageResponse>(json, _jsonOptions);
}
}

// レスポンスモデル
public class SendMessageResponse
{
[JsonPropertyName("message_id")]
public string MessageId { get; set; }
}

設定の保存/読み込み

public class SettingsService
{
private readonly string _settingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"ChatworkBulkSender",
"settings.json"
);

public void SaveSettings(AppSettings settings)
{
var options = new JsonSerializerOptions { WriteIndented = true };
var json = JsonSerializer.Serialize(settings, options);
File.WriteAllText(_settingsPath, json);
}

public AppSettings LoadSettings()
{
if (!File.Exists(_settingsPath))
return new AppSettings();

var json = File.ReadAllText(_settingsPath);
return JsonSerializer.Deserialize<AppSettings>(json);
}
}

3. System.Memory (v4.5.5) & System.Runtime.CompilerServices.Unsafe (v6.0.0)

概要

高性能なメモリ操作のための基盤ライブラリ。SpanやMemoryをサポート。

使用方法

大量データの効率的な処理

public class BulkDataProcessor
{
public void ProcessLargeFile(string filePath)
{
// ファイル全体をメモリに読み込む代わりに、Spanを使用
using var stream = File.OpenRead(filePath);
var buffer = new byte[4096];

while (stream.Read(buffer, 0, buffer.Length) > 0)
{
ProcessBuffer(buffer.AsSpan());
}
}

private void ProcessBuffer(Span<byte> buffer)
{
// 効率的なバッファ処理
}
}

4. Microsoft.Bcl.AsyncInterfaces (v8.0.0)

概要

IAsyncEnumerableなどの非同期インターフェースを提供。

使用方法

非同期データストリーミング

public class MessageStreamService
{
public async IAsyncEnumerable<MessageDto> GetMessagesAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var page = 1;
while (!cancellationToken.IsCancellationRequested)
{
var messages = await FetchMessagesPageAsync(page);
if (messages.Count == 0)
yield break;

foreach (var message in messages)
{
yield return message;
}

page++;
}
}

// 使用例
public async Task ProcessAllMessagesAsync()
{
await foreach (var message in GetMessagesAsync())
{
Console.WriteLine($"Processing message: {message.Id}");
// メッセージの処理
}
}
}

5. System.Threading.Tasks.Extensions (v4.5.4)

概要

ValueTaskなどの追加の非同期プログラミング機能を提供。

使用方法

ValueTaskを使用した効率的な非同期処理

public class CacheService
{
private readonly Dictionary<string, object> _cache = new();

public ValueTask<T> GetAsync<T>(string key)
{
if (_cache.TryGetValue(key, out var value))
{
// キャッシュヒット時は同期的に返す(効率的)
return new ValueTask<T>((T)value);
}

// キャッシュミス時は非同期でデータを取得
return new ValueTask<T>(LoadFromDatabaseAsync<T>(key));
}

private async Task<T> LoadFromDatabaseAsync<T>(string key)
{
// データベースからの読み込み処理
await Task.Delay(100); // 仮の処理
var value = default(T);
_cache[key] = value;
return value;
}
}

6. Newtonsoft.Json (v13.0.3)

概要

最も広く使われているJSONライブラリ。複雑なシナリオに対応。

使用方法

カスタムコンバーターの使用

public class DateTimeJSTConverter : JsonConverter<DateTime>
{
public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var value = reader.Value?.ToString();
if (DateTime.TryParse(value, out var date))
{
// JSTからUTCに変換
return date.AddHours(-9);
}
return DateTime.MinValue;
}

public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
{
// UTCからJSTに変換
var jstTime = value.AddHours(9);
writer.WriteValue(jstTime.ToString("yyyy-MM-dd HH:mm:ss"));
}
}

// 使用例
public class ChatworkMessage
{
[JsonConverter(typeof(DateTimeJSTConverter))]
public DateTime SendTime { get; set; }

public string Body { get; set; }
}

パッケージの復元

Visual Studioでプロジェクトを開いた際、NuGetパッケージは自動的に復元されます。 手動で復元する場合は以下のコマンドを使用:

# Package Manager Console
Update-Package -reinstall

# または .NET CLI
dotnet restore

注意事項

  1. System.Text.Json vs Newtonsoft.Json ○○ ○○
  2. プロジェクトでは両方を使い分けることが可能

  3. 非同期プログラミング

  4. UIスレッドをブロックしないよう、async/awaitを適切に使用
  5. ConfigureAwait(false)を使用してデッドロックを回避

  6. メモリ効率

  7. 大量データ処理時はSpanやMemoryの使用を検討
  8. IAsyncEnumerableでストリーミング処理を実装