lintx 3 months ago
commit
efa20f8f15
5 changed files with 346 additions and 0 deletions
  1. 22 0
      data/json/test.json
  2. 13 0
      data/json/test01.json
  3. 148 0
      note/hello-polyglot.dib
  4. 154 0
      note/json-converter.dib
  5. 9 0
      utils/EnumHelper.cs

+ 22 - 0
data/json/test.json

@@ -0,0 +1,22 @@
+[
+    {
+        "id": 1,
+        "name": "video game"
+    },
+    {
+        "id": 2,
+        "name": "book"
+    },
+    {
+        "id": 3,
+        "name": "movie"
+    },
+    {
+        "id": 4,
+        "name": "music"
+    },
+    {
+        "id": 5,
+        "name": "food"
+    }
+]

+ 13 - 0
data/json/test01.json

@@ -0,0 +1,13 @@
+{
+    "enable": false,
+    "rule": {
+        "S88F88": {
+            "action": "ignore",
+            "message": null
+        },
+        "S99F99": {
+            "action": "reply",
+            "message": "<A \"Hello World\">"
+        }
+    }
+}

+ 148 - 0
note/hello-polyglot.dib

@@ -0,0 +1,148 @@
+#!meta
+
+{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"}]}}
+
+#!markdown
+
+# Polyglot Notebook
+
+#!csharp
+
+Console.WriteLine("Hello World")
+
+#!csharp
+
+#r "nuget: System.Net.Http, 4.3.4"
+using System.Net.Http;
+
+var httpClient = new HttpClient();
+var response = await httpClient.GetAsync("https://httpbin.org/get");
+var content = await response.Content.ReadAsStringAsync();
+Console.WriteLine(content);
+
+#!csharp
+
+public class Person {
+    public string FirstName { get; set; }
+    public string LastName { get; set; }
+    public int Age { get; set; }
+
+    override public string ToString() {
+        return $"{FirstName} {LastName} is {Age} years old.";
+    }
+}
+
+var person = new Person {
+    FirstName = "john",
+    LastName = "Doe",
+    Age = 25
+};
+
+Console.WriteLine(person);
+person.Display();
+
+#!csharp
+
+#!import ../utils/EnumHelper.cs
+
+enum DayOfWeek {
+    [Description("星期一")]
+    Monday = 1,
+    [Description("星期二")]
+    Tuesday = 2,
+    [Description("星期三")]
+    Wednesday = 3,
+    [Description("星期四")]
+    Thursday = 4,
+    [Description("星期五")]
+    Friday = 5,
+    [Description("星期六")]
+    Saturday = 6,
+    [Description("星期日")]
+    Sunday = 7
+}
+
+var desc = EnumHelper.GetDescription(DayOfWeek.Monday);
+desc.Display();
+
+#!csharp
+
+var msg = "Hello Ployglot Notebook!";
+
+#!csharp
+
+#!set --name message --value @csharp:msg
+message.Display();
+
+#!csharp
+
+#!share --from csharp message --as newMessage
+newMessage.Display();
+
+#!csharp
+
+#!set --name url --value @input:"Please enter a URL"
+url.Display();
+
+#!csharp
+
+#!set --name age --value 19
+age.Display();
+
+#!csharp
+
+#!value --name products --mime-type application/json
+[
+    {"id": 1, "name": "video game"},
+    {"id": 2, "name": "book"}
+]
+
+#!csharp
+
+#!share products --from value --as productsJson
+using System.Text.Json;
+
+class Product {
+    public int Id { get; set; }
+    public string Name { get; set; }
+}
+
+var jsonSerializerOptions = new JsonSerializerOptions {
+    PropertyNameCaseInsensitive = true
+};
+var products = JsonSerializer.Deserialize<Product[]>(productsJson, jsonSerializerOptions);
+products.Display();
+
+#!csharp
+
+#!value --from-file ../data/json/test.json --name TestJsonData
+
+#!csharp
+
+#!share TestJsonData --from value --as jsonData
+using System.Text.Json;
+
+jsonData.Display();
+
+var jsonDoc = JsonDocument.Parse(jsonData);
+jsonDoc.Display();
+
+var jsonSerializerOptions = new JsonSerializerOptions {
+    PropertyNameCaseInsensitive = true
+};
+var products = JsonSerializer.Deserialize<Product[]>(jsonDoc, jsonSerializerOptions);
+products.Display();
+
+#!csharp
+
+#!time
+var msg = "Hello Ployglot Notbool!";
+Console.Write(msg);
+
+#!http
+
+GET https://httpbin.org/get
+
+#!http
+
+POST https://httpbin.org/post

+ 154 - 0
note/json-converter.dib

@@ -0,0 +1,154 @@
+#!meta
+
+{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"}]}}
+
+#!csharp
+
+#!value --from-file ../data/json/test01.json --name JsonData
+
+#!csharp
+
+class ADT {
+    public string Value { get; set; }
+    public string Action { get; set; }
+}
+
+#!csharp
+
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+class ADTJsonConverter : JsonConverter<ADT> {
+    public override ADT Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) {
+        if (reader.TokenType != JsonTokenType.StartObject) {
+            throw new JsonException();
+        }
+
+        ADT result = new ADT();
+
+        while (reader.Read()) {
+            if (reader.TokenType == JsonTokenType.EndObject) {
+                return result;
+            }
+
+            if (reader.TokenType != JsonTokenType.PropertyName) {
+                throw new JsonException();
+            }
+
+            string PropertyName = reader.GetString();
+
+            switch (PropertyName) {
+                case "action":
+                    if (reader.Read()) {
+                        result.Action = reader.GetString();
+                    }
+                break;
+                case "message":
+                    if (reader.Read()) {
+                        result.Value = reader.GetString();
+                    }
+                break;
+            }
+        }
+
+        return null;
+    }
+
+    public override void Write(Utf8JsonWriter writer, ADT value, JsonSerializerOptions options) {
+        writer.WriteStartObject();
+    
+        writer.WritePropertyName("action");
+        writer.WriteStringValue(value.Action);
+
+        writer.WritePropertyName("message");
+        writer.WriteStringValue(value.Value);
+
+        writer.WriteEndObject();
+    }
+}
+
+#!csharp
+
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Text.RegularExpressions;
+
+class RuleJsonConverter : JsonConverter<Dictionary<int, ADT>> {
+    public override Dictionary<int, ADT> Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) {
+        if (reader.TokenType != JsonTokenType.StartObject) {
+            throw new JsonException();
+        }
+
+        var converter = (JsonConverter<ADT>)options.GetConverter(typeof(ADT));
+        Dictionary<int, ADT> dictionary = new Dictionary<int, ADT>();
+        Regex regex = new Regex(@"S(?<stream>\d{1,3})F(?<function>\d{1,3})");
+        while (reader.Read()) {
+            if (reader.TokenType == JsonTokenType.EndObject) {
+                return dictionary;
+            }
+
+            if (reader.TokenType != JsonTokenType.PropertyName) {
+                throw new JsonException();
+            }
+
+            string PropertyName = reader.GetString();
+            Match match = regex.Match(PropertyName);
+            int stream = int.Parse(match.Groups["stream"].ToString());
+            int function = int.Parse(match.Groups["function"].ToString());
+            if (0 > stream || stream > 256 || 0 > function || function > 256) {
+                throw new JsonException();
+            }
+			int key = (stream << 8) | (function);
+            
+			if (reader.Read()) {
+				ADT value = converter.Read(ref reader, typeof(ADT), options);
+				if (dictionary.TryAdd(key, value) == false) {
+					dictionary[key] = value;
+				}
+			}
+        }
+
+        return null;
+    }
+
+    public override void Write(Utf8JsonWriter writer, Dictionary<int, ADT> dictionary, JsonSerializerOptions options) {
+        writer.WriteStartObject();
+        
+        var converter = (JsonConverter<ADT>)options.GetConverter(typeof(ADT));
+        foreach ((int key, ADT value) in dictionary)
+        {
+            string propertyName = $"S{(key >> 8) & 0xff}F{key & 0xff}";
+            writer.WritePropertyName(propertyName);
+            converter.Write(writer, value, options);
+        }
+
+        writer.WriteEndObject();
+    }
+}
+
+#!csharp
+
+#!share JsonData --from value --as jsonData
+using System.Text.Json;
+using System.Text.Json.Nodes;
+
+var jsonSerializeOptions = new JsonSerializerOptions
+{
+    WriteIndented = true,
+    Converters =
+    {
+        new RuleJsonConverter(),
+        new ADTJsonConverter(),
+    }
+};
+
+var nodes = JsonNode.Parse(jsonData);
+
+var enableNode = nodes["enable"];
+var ruleNode = nodes["rule"];
+
+bool enableValue = enableNode.GetValue<bool>();
+Dictionary<int, ADT> ruleValue = JsonSerializer.Deserialize<Dictionary<int, ADT>>(ruleNode.ToJsonString(), jsonSerializeOptions);
+
+enableValue.Display();
+ruleValue.Display();

+ 9 - 0
utils/EnumHelper.cs

@@ -0,0 +1,9 @@
+using System.ComponentModel;
+
+public class EnumHelper {
+    public static string GetDescription(Enum value) {
+        var field = value.GetType().GetField(value.ToString());
+        var attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
+        return attributes.Length > 0 ? attributes[0].Description : value.ToString();
+    }
+}