Skip to content

Instantly share code, notes, and snippets.

@rido-min
Last active April 8, 2022 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rido-min/3364aa967ffc66ec503511bc6f01dcfd to your computer and use it in GitHub Desktop.
Save rido-min/3364aa967ffc66ec503511bc6f01dcfd to your computer and use it in GitHub Desktop.
DTDLParserExtensions.cs
namespace dtdl_dotnet
{
using Microsoft.Azure.DigitalTwins.Parser;
using Microsoft.Azure.DigitalTwins.Parser.Models;
public static class DtmiExtensions
{
public static string ToPath(this Dtmi dtmi) => $"{dtmi.ToString().ToLowerInvariant().Replace(":", "/").Replace(";", "-")}.json";
}
public static class ModelParserExtensions
{
public class InterfaceInfo
{
public IReadOnlyDictionary<Dtmi, DTEntityInfo> ObjectModel;
DTEntityInfo root;
public InterfaceInfo(IReadOnlyDictionary<Dtmi, DTEntityInfo> m)
{
ObjectModel = m;
root = m.Values.Where(v => v.EntityKind == DTEntityKind.Interface).First(e => e.ChildOf == null);
}
public string Id => root.Id.ToString();
public IEnumerable<DTTelemetryInfo> Telemetries =>
((DTInterfaceInfo)root).Contents
.Where(c => c.Value.EntityKind == DTEntityKind.Telemetry)
.Select(t => (DTTelemetryInfo)t.Value);
public IEnumerable<DTPropertyInfo> Properties =>
((DTInterfaceInfo)root).Contents
.Where(c => c.Value.EntityKind == DTEntityKind.Property)
.Select(p => (DTPropertyInfo)p.Value);
public IEnumerable<DTCommandInfo> Commands =>
((DTInterfaceInfo)root).Contents
.Where(c => c.Value.EntityKind == DTEntityKind.Command)
.Select(c => (DTCommandInfo)c.Value);
public IEnumerable<DTComponentInfo> Components =>
((DTInterfaceInfo)root).Contents
.Where(c => c.Value.EntityKind == DTEntityKind.Component)
.Select(c => (DTComponentInfo)c.Value);
public IEnumerable<DTRelationshipInfo> Relationships =>
((DTInterfaceInfo)root).Contents
.Where(c => c.Value.EntityKind == DTEntityKind.Relationship)
.Select(r => (DTRelationshipInfo)r.Value);
}
public static async Task<InterfaceInfo> ParseAsync(this ModelParser parser, string jsonContent)
=> new InterfaceInfo(await parser.ParseAsync(new string[] { jsonContent }));
}
}
@rido-min
Copy link
Author

Allows to iterate over parsed results as

using DTDL_scratch;
using Microsoft.Azure.DigitalTwins.Parser;

string ReadFile(string path) => File.ReadAllText(Path.Join(System.Reflection.Assembly.GetExecutingAssembly().Location + @"./../../../../", path));

var model = await new ModelParser().ParseAsync(ReadFile("dtmi/samples/aninterface-1.json"));

Console.WriteLine(model.Id);

foreach (var t in model.Telemetries)
{
    Console.WriteLine($" [T] {t.Name} {t.Schema.Id}");
}

foreach (var p in model.Properties)
{
    Console.WriteLine($" [P] {p.Name} {p.Schema.Id}");
}

foreach (var c in model.Commands)
{
    Console.WriteLine($" [C] {c.Name} {c.Request.Id} {c.Response.Id}");
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment