Utilities
Utility functions for unit conversion work flows and helper functions.
using Autodesk.DesignScript.Runtime;
using Autodesk.ForgeUnits;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace DynamoUnits
{
public static class Utilities
{
private static UnitsEngine unitsEngine;
private static List<string> candidateDirectories;
[SupressImportIntoVM]
public static string SchemaDirectory { get; set; }
internal static UnitsEngine ForgeUnitsEngine {
get {
if (unitsEngine == null) {
string str = string.Join(", ", candidateDirectories);
throw new Exception("There was an issue loading Unit Schemas. Attempted paths: " + str);
}
return unitsEngine;
}
}
private static string BundledSchemaDirectory {
get {
string location = Assembly.GetExecutingAssembly().Location;
return Path.Combine(Path.GetDirectoryName(location), "unit");
}
}
static Utilities()
{
candidateDirectories = new List<string>();
SchemaDirectory = string.Empty;
Initialize();
}
internal static void Initialize()
{
candidateDirectories.Clear();
string location = Assembly.GetExecutingAssembly().Location;
Configuration configuration = ConfigurationManager.OpenExeConfiguration(location);
string text = configuration.AppSettings.Settings["schemaPath"]?.Value;
if (!string.IsNullOrEmpty(text) && Directory.Exists(text))
candidateDirectories.Add(text);
AddAscSchemaPaths(candidateDirectories);
candidateDirectories.Add(BundledSchemaDirectory);
using (List<string>.Enumerator enumerator = candidateDirectories.GetEnumerator()) {
while (enumerator.MoveNext()) {
string schemaDirectory = SchemaDirectory = enumerator.Current;
unitsEngine = TryLoadSchemaFromDirectory(schemaDirectory);
if (unitsEngine != null)
break;
}
}
}
internal static void SetTestEngine(string testSchemaDir)
{
unitsEngine = TryLoadSchemaFromDirectory(testSchemaDir);
}
public static double ConvertByUnits(double value, Unit fromUnit, Unit toUnit)
{
return ForgeUnitsEngine.convert(value, fromUnit.TypeId, toUnit.TypeId);
}
[IsVisibleInDynamoLibrary(false)]
public static double ConvertByUnitIds(double value, string fromUnit, string toUnit)
{
return ForgeUnitsEngine.convert(value, fromUnit, toUnit);
}
public static double ParseExpressionByUnit(Unit targetUnit, string expression)
{
return ForgeUnitsEngine.parse(targetUnit.TypeId, expression);
}
[IsVisibleInDynamoLibrary(false)]
public static double ParseExpressionByUnitId(string targetUnit, string expression)
{
return ForgeUnitsEngine.parse(targetUnit, expression);
}
public static double ParseExpression(string expression)
{
return ForgeUnitsEngine.parseUnitless(expression);
}
[IsVisibleInDynamoLibrary(false)]
public static IEnumerable<Quantity> GetAllQuantities()
{
return CovertForgeQuantityDictionaryToCollection(ForgeUnitsEngine.getAllQuantities());
}
[IsVisibleInDynamoLibrary(false)]
public static IEnumerable<Unit> GetAllUnits()
{
return ConvertForgeUnitDictionaryToCollection(ForgeUnitsEngine.getAllUnits());
}
[IsVisibleInDynamoLibrary(false)]
public static IEnumerable<Symbol> GetAllSymbols()
{
return ConvertForgeSymbolDictionaryToCollection(ForgeUnitsEngine.getAllSymbols());
}
internal static IEnumerable<Quantity> CovertForgeQuantityDictionaryToCollection(Dictionary<string, Quantity> forgeDictionary)
{
List<Quantity> list = new List<Quantity>();
Dictionary<string, Version> allRegisteredQuantityVersions = GetAllRegisteredQuantityVersions(forgeDictionary);
foreach (KeyValuePair<string, Version> item in allRegisteredQuantityVersions) {
string key = item.Key + "-" + item.Value.ToString();
if (forgeDictionary.TryGetValue(key, out Quantity value))
list.Add(new Quantity(value));
}
return list;
}
internal static IEnumerable<Symbol> ConvertForgeSymbolDictionaryToCollection(Dictionary<string, Symbol> forgeDictionary)
{
List<Symbol> list = new List<Symbol>();
Dictionary<string, Version> allLastestRegisteredSymbolVersions = GetAllLastestRegisteredSymbolVersions(forgeDictionary);
foreach (KeyValuePair<string, Version> item in allLastestRegisteredSymbolVersions) {
string key = item.Key + "-" + item.Value.ToString();
if (forgeDictionary.TryGetValue(key, out Symbol value))
list.Add(new Symbol(value));
}
return list;
}
internal static IEnumerable<Unit> ConvertForgeUnitDictionaryToCollection(Dictionary<string, Unit> forgeDictionary)
{
List<Unit> list = new List<Unit>();
Dictionary<string, Version> allLatestRegisteredUnitVersions = GetAllLatestRegisteredUnitVersions(forgeDictionary);
foreach (KeyValuePair<string, Version> item in allLatestRegisteredUnitVersions) {
string key = item.Key + "-" + item.Value.ToString();
if (forgeDictionary.TryGetValue(key, out Unit value))
list.Add(new Unit(value));
}
return list;
}
internal static Dictionary<string, Version> GetAllRegisteredQuantityVersions()
{
return GetAllRegisteredQuantityVersions(ForgeUnitsEngine.getAllQuantities());
}
internal static Dictionary<string, Version> GetAllRegisteredQuantityVersions(Dictionary<string, Quantity> forgeDictionary)
{
Dictionary<string, Version> dictionary = new Dictionary<string, Version>();
foreach (string key in forgeDictionary.Keys) {
if (TryParseTypeId(key, out string typeName, out Version version) && (!dictionary.TryGetValue(typeName, out Version value) || value.CompareTo(version) < 0))
dictionary[typeName] = version;
}
return dictionary;
}
internal static Dictionary<string, Version> GetAllLastestRegisteredSymbolVersions()
{
return GetAllLastestRegisteredSymbolVersions(ForgeUnitsEngine.getAllSymbols());
}
internal static Dictionary<string, Version> GetAllLastestRegisteredSymbolVersions(Dictionary<string, Symbol> forgeDictionary)
{
Dictionary<string, Version> dictionary = new Dictionary<string, Version>();
foreach (string key in forgeDictionary.Keys) {
if (TryParseTypeId(key, out string typeName, out Version version) && (!dictionary.TryGetValue(typeName, out Version value) || value.CompareTo(version) < 0))
dictionary[typeName] = version;
}
return dictionary;
}
internal static Dictionary<string, Version> GetAllLatestRegisteredUnitVersions()
{
return GetAllLatestRegisteredUnitVersions(ForgeUnitsEngine.getAllUnits());
}
internal static Dictionary<string, Version> GetAllLatestRegisteredUnitVersions(Dictionary<string, Unit> forgeDictionary)
{
Dictionary<string, Version> dictionary = new Dictionary<string, Version>();
foreach (string key in forgeDictionary.Keys) {
if (TryParseTypeId(key, out string typeName, out Version version) && (!dictionary.TryGetValue(typeName, out Version value) || value.CompareTo(version) < 0))
dictionary[typeName] = version;
}
return dictionary;
}
internal static bool TryParseTypeId(string typeId, out string typeName, out Version version)
{
string[] array = typeId.Split('-', StringSplitOptions.None);
if (array.Length == 2 && Version.TryParse(array[1], out Version result)) {
typeName = array[0];
version = result;
return true;
}
typeName = "";
version = null;
return false;
}
private static void AddAscSchemaPaths(List<string> candidateDirectories)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.get_Windows()))
try {
Assembly assembly = Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "DynamoInstallDetective.dll"));
Type type = assembly.GetType("DynamoInstallDetective.AscSdkWrapper");
if (!(type == (Type)null)) {
string[] array = (string[])type.GetMethod("GetMajorVersions", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, null);
if (array != null) {
Type nestedType = type.GetNestedType("ASC_STATUS");
object obj = Enum.Parse(nestedType, "SUCCESS");
string[] array2 = array;
foreach (string text in array2) {
object obj2 = Activator.CreateInstance(type, text);
MethodInfo method = type.GetMethod("GetInstalledPath");
object[] array3 = new object[1] {
string.Empty
};
object obj3 = method?.Invoke(obj2, array3);
if (obj3 != null && obj3.Equals(obj)) {
string path = (string)array3[0];
string item = Path.Combine(path, "coreschemas", "unit");
candidateDirectories.Add(item);
}
}
}
}
} catch {
}
}
private static UnitsEngine TryLoadSchemaFromDirectory(string schemaDirectory)
{
try {
if (!IsValidSchemaDirectory(schemaDirectory))
return null;
UnitsEngine val = new UnitsEngine();
SchemaUtility.addDefinitionsFromFolder(schemaDirectory, val);
val.resolveSchemas();
return val;
} catch {
return null;
}
}
private static bool IsValidSchemaDirectory(string schemaDirectory)
{
if (string.IsNullOrEmpty(schemaDirectory) || !Directory.Exists(schemaDirectory))
return false;
string[] array = new string[4] {
"dimension",
"quantity",
"symbol",
"unit"
};
string[] array2 = array;
foreach (string path in array2) {
string text = Path.Combine(schemaDirectory, path);
if (!Directory.Exists(text))
return false;
}
return true;
}
}
}