} // func GetClientRelationFromServerRelation /// <summary></summary> /// <param name="xTable"></param> public void WriteSchema(XElement xTable) { var clientDataType = Meta.GetProperty <string>("clientDataType", null); var xColumn = new XElement("column", new XAttribute("name", Name), new XAttribute("dataType", clientDataType ?? LuaType.GetType(DataType).AliasOrFullName) ); if (IsPrimaryKey) { xColumn.Add(new XAttribute("isPrimary", IsPrimaryKey)); } if (IsIdentity) { xColumn.Add(new XAttribute("isIdentity", IsIdentity)); } if (IsRelationColumn) { xColumn.Add(new XAttribute("parentRelationName", parentRelationName)); xColumn.Add(new XAttribute("parentRelationType", GetClientRelationFromServerRelation(parentType))); xColumn.Add(new XAttribute("parentTable", ParentColumn.Table.Name)); xColumn.Add(new XAttribute("parentColumn", ParentColumn.Name)); } xTable.Add(xColumn); // meta data PpsDataSetServerDefinition.WriteSchemaMetaInfo(xColumn, metaInfo); } // proc WriteSchema
} // func InvokeExpression private static Expression InvokeMemberExpression(Scope scope, Token tStart, Expression instance, string sMember, InvokeResult result, ArgumentsList arguments) { if (LuaEmit.IsDynamicType(instance.Type)) { return(EnsureInvokeResult(scope, tStart, DynamicExpression.Dynamic(scope.Runtime.GetInvokeMemberBinder(sMember, arguments.CallInfo), typeof(object), new Expression[] { ConvertExpression(scope.Runtime, tStart, instance, typeof(object)) }.Concat( from c in arguments.Expressions select Lua.EnsureType(c, typeof(object)) ).ToArray() ), result, instance, sMember )); } else { // look up the method MethodInfo method = LuaEmit.FindMethod( LuaType.GetType(instance.Type).GetInstanceMethods(sMember, false), arguments.CallInfo, arguments.Expressions, getExpressionTypeFunction, true); if (method != null) { return(EnsureInvokeResult(scope, tStart, SafeExpression(() => InvokeMemberExpressionBind(method, scope.Runtime, instance, arguments), tStart), result, instance, sMember)); } else { return(InvokeMemberExpressionDynamic(scope, tStart, instance, sMember, result, arguments)); } } } // func InvokeMemberExpression
} // proc WriteAttributeString /// <summary>Convert the xml node to an property dictionary.</summary> /// <param name="attributes"></param> /// <param name="wellKnownProperties"></param> /// <returns></returns> public static IPropertyReadOnlyDictionary ToPropertyDictionary(this IEnumerable <XElement> attributes, params KeyValuePair <string, Type>[] wellKnownProperties) { var props = new PropertyDictionary(); foreach (var x in attributes) { var propertyName = x.GetAttribute <string>("name", null); if (String.IsNullOrEmpty(propertyName)) { throw new ArgumentException("@name is missing."); } Type dataType; var wellKnownPropertyIndex = Array.FindIndex(wellKnownProperties, c => String.Compare(c.Key, propertyName, StringComparison.OrdinalIgnoreCase) == 0); if (wellKnownPropertyIndex == -1) { dataType = LuaType.GetType(x.GetAttribute("dataType", "string")); } else { dataType = wellKnownProperties[wellKnownPropertyIndex].Value; } props.SetProperty(propertyName, dataType, x.Value); } return(props); } // func IPropertyReadOnlyDictionary
} // proc Execute private XElement CreateException(XElement x, Exception e) { var aggE = e as AggregateException; if (aggE != null) { var enumerator = aggE.InnerExceptions.GetEnumerator(); if (enumerator.MoveNext()) { CreateException(x, enumerator.Current); while (enumerator.MoveNext()) { x.Add(CreateException(new XElement("innerException"), enumerator.Current)); } } else { x.Add(new XAttribute("message", e.Message)); } } else { x.Add(new XAttribute("message", e.Message)); x.Add(new XAttribute("type", LuaType.GetType(e.GetType()).AliasOrFullName)); var data = LuaExceptionData.GetData(e); x.Add(new XElement("stackTrace", data == null ? e.StackTrace : data.StackTrace)); if (e.InnerException != null) { x.Add(CreateException(new XElement("innerException"), e.InnerException)); } } return(x); } // proc CreateException
} // proc FreeAndNil #endregion #region -- ChangeType ------------------------------------------------------------- /// <summary>Konvertiert den Datentyp zum gewünschten Ziel-Datentyp.</summary> /// <param name="value"></param> /// <param name="typeTo"></param> /// <returns></returns> /// <remarks>Es wird der Lua Converter verwendet, da er Schnittstelle, Operatoren und allgemeine Regeln beherrscht ohne auf das TypeDescriptor-Framework zu verweisen.</remarks> public static object ChangeType(object value, Type typeTo) { if (typeTo == typeof(bool) && value is string) { var t = (string)value; return(t == "1" || String.Compare(t, Boolean.TrueString, StringComparison.OrdinalIgnoreCase) == 0); } else if (typeTo == typeof(DateTimeOffset) && (value == null || value is string)) { return(value == null ? DateTimeOffset.MinValue : DateTimeOffset.Parse((string)value, CultureInfo.InvariantCulture)); } else if (typeTo == typeof(XDocument) && (value == null || value is string)) { return(value == null ? null : XDocument.Parse((string)value)); } else if (typeTo == typeof(string) && (value == null || value is XDocument)) { return(value == null ? null : value.ToString()); } else if (typeTo == typeof(Type) && (value == null || value is string)) { return(value == null ? null : LuaType.GetType((string)value, lateAllowed: false).Type); } else if (typeTo == typeof(string) && value is Type) { return(LuaType.GetType((Type)value).AliasOrFullName); } else { return(Lua.RtConvertValue(value, typeTo)); } } // func ChangeType
} // proc UpdateData private bool TryParseColumn(XElement cur, out SimpleDataColumn col) { var name = cur.GetAttribute("name", null); if (String.IsNullOrEmpty(name)) { goto Error; } var type = LuaType.GetType(cur.GetAttribute("type", null), lateAllowed: false); var attributes = new PropertyDictionary(); foreach (var xAttr in cur.Elements("attribute")) { if (TryParseAttribute(xAttr, out var attr)) { attributes.SetProperty(attr); } } col = new SimpleDataColumn(name, type, attributes); return(true); Error: col = null; return(false); } // func TryParseColumn
} // proc WriteType public void WriteItem(DEListItemWriter xml, object item) { var caItem = (KeyValuePair <string, DEConfigAction>)item; var ca = caItem.Value; xml.WriteStartProperty("action"); xml.WriteAttributeProperty("id", caItem.Key); xml.WriteAttributeProperty("description", ca.Description); xml.WriteAttributeProperty("safecall", ca.IsSafeCall.ToString()); xml.WriteAttributeProperty("security", ca.SecurityToken); xml.WriteAttributeProperty("return", ca.MethodDescription.ReturnType.ToString()); xml.WriteStartProperty("arguments"); foreach (var p in ca.MethodDescription.GetParameters()) { xml.WriteStartProperty("argument"); xml.WriteAttributeProperty("name", p.Name); xml.WriteAttributeProperty("type", LuaType.GetType(p.ParameterType).AliasOrFullName); if (p.DefaultValue != null) { xml.WriteValue(p.DefaultValue); } xml.WriteEndProperty(); } xml.WriteEndProperty(); xml.WriteEndProperty(); } // proc WriteItem
} // func GetLogPropertyInfo public static async Task GetLogPropertiesAsync(DEHttpClient http, string path, Action <string, LogProperty> process = null) { var xProperties = await http.GetXmlAsync(Program.MakeUri(path, new PropertyValue("action", "listget"), new PropertyValue("id", "tw_properties") ), rootName : "list"); var properties = xProperties.Element("items")?.Elements("property"); if (properties != null) { foreach (var x in properties) { var name = x.GetAttribute("name", null); if (name == null) { continue; } // parse info var propertyInfo = new LogPropertyInfo(name, x.GetAttribute("displayname", name), LuaType.GetType(x.GetAttribute("type", "string"), lateAllowed: true).Type, x.GetAttribute("description", name), x.GetAttribute("format", null) ); UpdatePropertyInfo(propertyInfo); // process value process?.Invoke(path, new LogProperty(propertyInfo, x.Value)); } } } // func GetLogProperties
public void TypeTest04() { dynamic t = LuaType.GetType(typeof(int)); Type t1 = t; Type t2 = (Type)t; Assert.IsTrue(t1 == typeof(int)); Assert.IsTrue(t2 == typeof(int)); }
public void TypeTest01() { var t = LuaType.GetType(typeof(Stream)); Assert.IsTrue(t.Type != null); t = LuaType.GetType("System.Test.Test", false, true); Assert.IsTrue(t.Type == null); var t1 = LuaType.GetType("LuaDLR.Test.LuaTypeTests.SubClass", false, true); Assert.AreEqual(typeof(SubClass), t1.Type); var t2 = LuaType.GetType("LuaDLR.Test.LuaTypeTests+SubClass", false, true); Assert.AreEqual(t1, t2); t = LuaType.GetType("System.String[,,]"); Assert.AreEqual(typeof(string[, , ]), t.Type); t = LuaType.GetType("System.String[][][]"); Assert.AreEqual(typeof(string[][][]), t.Type); t = LuaType.GetType(typeof(Tuple)); Assert.IsTrue(t.Type != null); t1 = LuaType.GetType("System.Tuple[System.String][,,]"); Assert.AreEqual(typeof(Tuple <String> [, , ]), t1.Type); t2 = LuaType.GetType("System.Tuple`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]][,,]"); Assert.AreEqual(t1, t2); t1 = LuaType.GetType("System.Collections.Generic.List[System.Collections.Generic.List[System.Tuple[System.String]]]"); Assert.AreEqual(typeof(List <List <Tuple <String> > >), t1.Type); t2 = LuaType.GetType(Lines("System.Collections.Generic.List`1[", "[System.Collections.Generic.List`1[", "[System.Tuple`1[", "[System.String, mscorlib, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089]", "], mscorlib, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089]", "], mscorlib, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089]]" )); Assert.AreEqual(t1, t2); t = LuaType.GetType(typeof(List <string>)); Assert.IsTrue(t.Type != null); t = LuaType.GetType(typeof(string[])); Assert.IsTrue(t.Type != null); t = LuaType.GetType("System.StringF[]"); Assert.IsNull(t.Type); t = LuaType.GetType("System.Tuple[System.AAA]"); Assert.IsNull(t.Type); t = LuaType.GetType(typeof(TestRek)); Assert.AreEqual(typeof(TestRek), t.Type); }
private static LuaTable GetColumnData(IDataColumn c, LuaTable t) { t["Name"] = c.Name; t["Type"] = LuaType.GetType(c.DataType).AliasOrFullName; foreach (var a in c.Attributes) { t[a.Name] = a.Value; } return(t); } // func GetColumnData
internal static void AddMetaGroup(XElement xMetaGroup, Action <string, Func <Type>, object> add) { if (xMetaGroup == null) { return; } foreach (XElement c in xMetaGroup.Elements()) { add(c.Name.LocalName, () => LuaType.GetType(c.GetAttribute("dataType", "object"), lateAllowed: false), c.Value); } } // proc AddMetaGroup
} // ctor #endregion #region -- void RegisterPackage --------------------------------------------------- /// <summary>Registers a type as an library.</summary> /// <param name="sName"></param> /// <param name="type"></param> public void RegisterPackage(string sName, Type type) { if (String.IsNullOrEmpty(sName)) { throw new ArgumentNullException("name"); } if (type == null) { throw new ArgumentNullException("type"); } this[sName] = LuaType.GetType(type); } // func RegisterPackage
} // func ToXml private static object GetValue(XElement x) { var type = LuaType.GetType(x.Attribute("t")?.Value ?? "string", lateAllowed: false).Type; if (type == typeof(LuaTable)) { return(CreateLuaTable(x)); } else { return(Procs.ChangeType(x.Value, type)); } } // func GetValue
public void MethodTest03() { using (Lua l = new Lua()) { l.PrintExpressionTree = Console.Out; dynamic g = l.CreateEnvironment(); g.console = LuaType.GetType(typeof(Console)); g.dochunk("console.WriteLine('Hallo!');", "test"); g.dochunk("c = console.WriteLine[clr.System.String];"); //g.c = g.console.WriteLine[typeof(string)]; g.c("Hallo"); g.dochunk("c('Hallo!')"); } }
public void TypeTest01() { LuaType t = LuaType.GetType(typeof(Stream)); Assert.IsTrue(t.Type != null); t = LuaType.GetType("System.Test.Test", false, true); Assert.IsTrue(t.Type == null); t = LuaType.GetType("LuaDLR.Test.LuaTypeTests.SubClass", false, true); Assert.IsTrue(t.Type != null); t = LuaType.GetType(typeof(List <string>)); Assert.IsTrue(t.Type != null); t = LuaType.GetType(typeof(string[])); Assert.IsTrue(t.Type != null); }
} // proc CreateException private XElement CreateMember(object member, object value, Type type = null) { var x = new XElement("v", member is int?new XAttribute("i", member) : new XAttribute("n", member.ToString()), new XAttribute("t", LuaType.GetType(type ?? (value != null ? value.GetType() : typeof(object))).AliasOrFullName) ); if (value != null) { x.Add(new XText(Procs.ChangeType <string>(value))); } return(x); } // func CreateMember
/// <summary></summary> /// <param name="dataType"></param> /// <returns></returns> public virtual Type GetColumnType(string dataType) { if (String.Compare(dataType, "formular", StringComparison.OrdinalIgnoreCase) == 0) { return(typeof(PpsStaticCalculated)); } else if (String.Compare(dataType, "formatted", StringComparison.OrdinalIgnoreCase) == 0) { return(typeof(PpsFormattedStringValue)); } else { return(LuaType.GetType(dataType, lateAllowed: false).Type); } } // func GetColumnType
public void MethodTest02() { using (Lua l = new Lua()) { dynamic g = l.CreateEnvironment(); g.console = LuaType.GetType(typeof(Console)); g.dochunk("console.WriteLine('Hallo!');", "test"); dynamic wl = g.console.WriteLine; Delegate dlg1 = wl[LuaType.GetType(typeof(string))]; Delegate dlg2 = g.dochunk("return console.WriteLine[clr.System.String]"); Delegate dlg3 = g.dochunk("return console.WriteLine[]"); Assert.IsTrue(dlg1 == dlg2); Assert.IsTrue(dlg3 != null); } }
} // func InvokeExpression private static Expression InvokeMemberExpression(Scope scope, Token tStart, Expression instance, string memberName, InvokeResult result, ArgumentsList arguments) { if (LuaEmit.IsDynamicType(instance.Type) || arguments.Expressions.Any(c => LuaEmit.IsDynamicType(c.Type))) { var dynamicArguments = new Expression[arguments.Count + 1]; // first argument is the instance dynamicArguments[0] = ConvertObjectExpression(scope.Runtime, tStart, instance, false); if (arguments.Count > 0) { // single object for (var i = 0; i < arguments.Count - 1; i++) { dynamicArguments[i + 1] = ConvertObjectExpression(scope.Runtime, tStart, arguments.Expressions[i], false); } // last argument is different if (arguments.CallInfo.ArgumentNames.Count > 0) { dynamicArguments[dynamicArguments.Length - 1] = ConvertObjectExpression(scope.Runtime, tStart, arguments.Expressions[arguments.Count - 1], false); } else { dynamicArguments[dynamicArguments.Length - 1] = Lua.EnsureType(arguments.Expressions[arguments.Count - 1], typeof(object)); } } return(EnsureInvokeResult(scope, tStart, DynamicExpression.Dynamic(scope.Runtime.GetInvokeMemberBinder(memberName, arguments.CallInfo), typeof(object), dynamicArguments), result, instance, memberName )); } else { return(EnsureInvokeResult(scope, tStart, SafeExpression(() => { Expression expr; if (!LuaEmit.TryInvokeMember <Expression>(scope.Runtime, LuaType.GetType(instance.Type), instance, arguments.CallInfo, arguments.Expressions, memberName, false, e => e, e => e.Type, true, out expr)) { throw new LuaEmitException(LuaEmitException.MemberNotFound, instance.Type, memberName); } return expr; }, tStart), result, instance, memberName )); } } // func InvokeMemberExpression
private static void AddValue(object value, XElement c) { var t = value as LuaTable; if (t != null) { c.Add(new XAttribute("t", "table")); ToXml(t, c); } else if (value != null) { var type = value.GetType(); c.Add(new XAttribute("t", LuaType.GetType(type).AliasOrFullName)); c.Add(new XText(value.ChangeType <string>())); } } // proc AddValue
} // func TryParseColumn private bool TryParseAttribute(XElement xAttr, out PropertyValue attr) { var name = xAttr.GetAttribute("name", null); if (String.IsNullOrEmpty(name)) { goto Error; } var type = LuaType.GetType(xAttr.GetAttribute("dataType", null), lateAllowed: false); attr = new PropertyValue(name, type, xAttr.Value); return(true); Error: attr = null; return(false); } // func TryParseAttribute
} // func FallbackInvoke public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { // defer target and all arguments if (!target.HasValue || args.Any(c => !c.HasValue)) { return(Defer(target, args)); } if (target.Value == null) { return(errorSuggestion ?? new DynamicMetaObject( ThrowExpression(Resources.rsNilNotCallable, ReturnType), target.Restrictions.Merge(BindingRestrictions.GetInstanceRestriction(target.Expression, null)) )); } else { try { var luaType = LuaType.GetType(target.LimitType); Expression expr; if (LuaEmit.TryInvokeMember <DynamicMetaObject>(lua, luaType, target, CallInfo, args, Name, IgnoreCase, mo => mo.Expression, mo => mo.LimitType, false, out expr)) { return(new DynamicMetaObject(Lua.EnsureType(expr, ReturnType), GetMethodSignatureRestriction(target, args))); } else { return(errorSuggestion ?? new DynamicMetaObject (ThrowExpression(String.Format(Resources.rsMemberNotResolved, luaType.FullName, Name), ReturnType), GetMethodSignatureRestriction(target, args) )); } } catch (LuaEmitException e) { return(errorSuggestion ?? new DynamicMetaObject(ThrowExpression(e.Message, ReturnType), GetMethodSignatureRestriction(target, args))); } } } // func FallbackInvokeMember
} // proc AddMetaFromElement /// <summary></summary> /// <param name="xParent"></param> /// <param name="metaInfo"></param> public static void WriteSchemaMetaInfo(XElement xParent, PpsMetaCollection metaInfo) { if (metaInfo.Count > 0) { var xMeta = new XElement("meta"); xParent.Add(xMeta); foreach (var m in metaInfo) { if (m.Name == "dataType" || m.Value == null) { continue; } xMeta.Add(new XElement(m.Name, new XAttribute("dataType", LuaType.GetType(m.Value.GetType()).AliasOrFullName), m.Value.ChangeType <string>() )); } } } // proc WriteSchemaMetaInfo
} // ctor /// <summary></summary> /// <param name="serviceProvider"></param> /// <returns></returns> public override object ProvideValue(IServiceProvider serviceProvider) { var type = Type; if (type == null) { if (TypeName == null) { var target = serviceProvider.GetService <IProvideValueTarget>(true); if (target.TargetProperty is PropertyInfo pi) { type = pi.PropertyType; } } else { type = LuaType.GetType(TypeName); } } return(type == null ? Value : StuffUI.ChangeTypeWithConverter(Value, type)); } // func ProvideValue
} // func WriteProperty /// <summary>Beschreibt eine Eigenschaft.</summary> /// <param name="propertyName">Wird ein @ vor die Eigenschaft gesetzt, so wird das Element als Property angelegt.</param> /// <param name="type"></param> public void WriteProperty(string propertyName, Type type) { if (String.IsNullOrEmpty(propertyName)) { throw new ArgumentNullException(); } string sTypeName = LuaType.GetType(type).AliasOrFullName; if (propertyName == ".") { WriteProperty(PropertyType.Value, String.Empty, sTypeName); } else if (propertyName.StartsWith("@")) { WriteProperty(PropertyType.Attribute, propertyName.Substring(1), sTypeName); } else { WriteProperty(PropertyType.Element, propertyName, sTypeName); } } // proc WriteProperty
public void TypeTest02() { using (Lua l = new Lua()) { dynamic g = l.CreateEnvironment(); Type t = typeof(SubClass); LuaType tl = LuaType.GetType(t); TestResult(g.dochunk("return clr.LuaDLR.Test.LuaTypeTests.SubClass"), tl); TestResult(g.dochunk("return clr.LuaDLR.Test.LuaTypeTests.SubClass:GetType()"), t); TestResult(g.dochunk("return clr.System.IO.Stream"), LuaType.GetType(typeof(Stream))); LuaType tNull = g.dochunk("return clr.System.Test.Test"); Assert.IsTrue(tNull.Type == null); tl = g.dochunk("return clr.System.Collections.Generic.List[clr.System.String]", "test"); TestResult(new LuaResult(tl.Type), typeof(List <string>)); tl = g.dochunk("return clr.System.String[]", "test"); TestResult(new LuaResult(tl.Type), typeof(string[])); } }
// -- Static ---------------------------------------------------------- /// <summary></summary> /// <param name="xMeta"></param> /// <param name="wellknownTypes"></param> /// <param name="add"></param> public static void AddMetaFromElement(XElement xMeta, IReadOnlyDictionary <string, Type> wellknownTypes, Action <string, Func <Type>, object> add) { if (xMeta == null) { return; } var name = xMeta.GetAttribute("name", String.Empty); if (String.IsNullOrEmpty(name)) { throw new DEConfigurationException(xMeta, "@name is empty."); } try { add(name, () => LuaType.GetType(xMeta.GetAttribute("dataType", "object")), xMeta.Value); } catch (ArgumentNullException e) { throw new DEConfigurationException(xMeta, $"Datatype '{xMeta.GetAttribute("dataType", "object")}' unknown.", e); } } // proc AddMetaFromElement
} // prop IsConnected #endregion #region -- GetMemberValue, ParseReturn -------------------------------------------- private Type GetType(string typeString) { if (typeString.IndexOf(",") == -1) { return(LuaType.GetType(typeString)); } else { return(Type.GetType(typeString, name => { // do not load new assemblies var asm = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(c => c.FullName == name.FullName); if (asm == null) { throw new TypeLoadException("Assembly is not loaded."); } return asm; }, (asm, name, ignorecase) => LuaType.GetType(typeString).Type, false )); } } // func GetType
public void MethodTest01() { using (Lua l = new Lua()) { dynamic g = l.CreateEnvironment(); g.console = LuaType.GetType(typeof(Console)); g.dochunk("console.WriteLine('Hallo!');", "test"); dynamic wl = g.console.WriteLine; Assert.IsTrue(wl.GetType() == typeof(LuaOverloadedMethod)); int iCount = wl.Count; Assert.IsTrue(iCount == 19); for (int i = 0; i < wl.Count; i++) { if (i == 17) { Console.WriteLine("VarArgs NotImplemented."); } else { Console.WriteLine("{0}: {1}", i, wl[i].GetType().Name); } } } }