XAML – DECODE https://decode.red/blog data decode, decoder or decoded ... design of code Mon, 15 Dec 2025 06:15:00 +0000 ja hourly 1 https://wordpress.org/?v=4.7.29 C# JSON / macOS ../../../202505101906/ Sat, 10 May 2025 01:16:01 +0000 ../../../?p=1906 C#でJSONを変換するプログラムを実装しようと思ったところ、最近はほとんどmacOSを使って開発をしていたため、macで試してみました。
macOSでC#の開発というと、まず違和感を感じますが、MAUIというマルチプラットホームのライブラリが出たり、VisualStudio for Macがサポートされないことになったり、環境に変化があるため、ちょっとやっておこうと思いました。(まずはコンソールアプリの動作確認。その後MAUI)

UnityはC#
https://decode.red/net/archives/844

かなり前にWindows以外でC#を試したときは、下記のようにmonoを使いました。
http://crossframe.iiv.jp/?s=mono

VS Code / macOS を使ったC#の開発は初めてでしたので、いろいろメモすることも目的です。

インストールファイル
dotnet-sdk-8.0.408-osx-arm64.pkg (205,144,863 バイト)

VS Codeや、Xcodeはすでに入っているものとします。(要マイクロソフトまたはGithubアカウント)

VS Code機能拡張

コマンドから新規プロジェクトを作成できます。(コンソールプロジェクト)

Program.cs

class Program
{
    static void Main()
    {
        // JSON → CSV
        JsonToCsvConverter.Convert("input.json", "output.csv");

        // CSV → JSON
        CsvToJsonConverter.Convert("input.csv", "output.json");
    }
}

input.json

[
  { "Name": "Alice", "Age": "30", "City": "Tokyo" },
  { "Name": "Bob", "Age": "25", "City": "Osaka" },
  { "Name": "Charlie", "Age": "35", "City": "Kyoto" }
]

input.csv

Name,Age,City
Alice,30,Tokyo
Bob,25,Osaka
Charlie,35,Kyoto

JsonToCsv.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

class JsonToCsvConverter
{
    public static void Convert(string jsonFilePath, string csvFilePath)
    {
        var json = File.ReadAllText(jsonFilePath);
        var array = JArray.Parse(json);

        var sb = new StringBuilder();

        // ヘッダー
        var headers = ((JObject)array[0]).Properties();
        sb.AppendLine(string.Join(",", headers.Select(h => h.Name)));

        // データ
        foreach (var obj in array)
        {
            var values = ((JObject)obj).Properties().Select(p => p.Value.ToString());
            sb.AppendLine(string.Join(",", values));
        }

        File.WriteAllText(csvFilePath, sb.ToString());
    }
}

CsvToJson.cs

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

class CsvToJsonConverter
{
    public static void Convert(string csvFilePath, string jsonFilePath)
    {
        var lines = File.ReadAllLines(csvFilePath);
        var headers = lines[0].Split(',');

        var jsonList = new List<Dictionary<string, string>>();

        for (int i = 1; i < lines.Length; i++)
        {
            var values = lines[i].Split(',');
            var dict = new Dictionary<string, string>();

            for (int j = 0; j < headers.Length; j++)
            {
                dict[headers[j]] = values[j];
            }

            jsonList.Add(dict);
        }

        var json = JsonConvert.SerializeObject(jsonList, Formatting.Indented);
        File.WriteAllText(jsonFilePath, json);
    }
}

ファイル構成

パッケージインストールと実行

dotnet add package Newtonsoft.Json
dotnet run

ビルドはVSCodeの三角ボタンから(やり方はいろいろあり)

JSONは今後 System.Text.Jsonを使うことになりそうです。

https://learn.microsoft.com/ja-jp/dotnet/standard/serialization/system-text-json/migrate-from-newtonsoft?pivots=dotnet-9-0

次にMAUIも試してみました。(サンプルプログラムのビルドと実行)

workloadのインストール

sudo dotnet workload install maui
dotnet workload list

実行

dotnet run

参考)https://qiita.com/aqua_ix/items/ba9533d60633abe4c850

]]>
Loose XAML ../../../202505041897/ Sun, 04 May 2025 02:46:56 +0000 ../../../?p=1897 Windows Presentation Foundation (WPF) のマークアップ言語XAMLをアプリケーションの外部ファイルとして編集するテストをしてみました。
アプリケーションをリビルドすることなく、またコードを変更することなく、レイアウト、文字列などを変更することが目的です。
アプリケーションの信頼性が下がるので、推奨されるやり方ではないようですが、できるということは利用価値があります。

using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

using System.Windows.Markup;

namespace WpfApp4
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            LoadLooseXaml("Views/HelloView.xaml");
        }

        private void LoadLooseXaml(string path)
        {
            if (!File.Exists(path))
            {
                MessageBox.Show($"XAMLファイルが見つかりません: {path}");
                return;
            }

            using var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
            var content = (UIElement)XamlReader.Load(stream);
            MainGrid.Children.Clear();
            MainGrid.Children.Add(content);
        }
    }
}

HelloView.xaml

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
        <TextBlock Text="Hello from Loose XAML!" FontSize="24" HorizontalAlignment="Center"/>
        <Button Content="Click me" Width="100" Margin="10"/>
    </StackPanel>
</Grid>

上記をテキストエディタで編集するだけで表示が変更されました。

昔のMacOSは、リソースエディタというものが標準で備わっており、アプリケーションの文字列などのリソースを改変することが簡単にできました。ローカリゼーションにはうってつけですね。
アプリの改変が今の時代、セキュリティリスクになることを考えると当たり前ですが、そんないい時代があったものだと、(みんないい人だったね)懐かしい気持ちになります。

]]>