public NfTypeName(string name) { if (string.IsNullOrWhiteSpace(name)) { return; } _ctorString = name; var parseItem = TypeNameParseTree.ParseIl(name); if (parseItem == null) { return; } _className = NfReflect.GetTypeNameWithoutNamespace(parseItem.FullName); _namespace = NfReflect.GetNamespaceWithoutTypeName(parseItem.FullName); _publicKeyToken = parseItem.PublicKeyTokenValue; if (!string.IsNullOrWhiteSpace(parseItem.AssemblyFullName)) { _asmName = new AssemblyName(parseItem.AssemblyFullName); } if (parseItem.GenericItems == null || !parseItem.GenericItems.Any()) { return; } foreach (var gi in parseItem.GenericItems) { _genericArgs.Add(new NfTypeName(gi)); } }
/// <summary> /// Returns string specific to graph-viz (ver. 2.38+) /// see [http://www.graphviz.org/] /// </summary> /// <returns></returns> public static string ToGraphVizString(this CgMember cgMem) { var graphViz = new StringBuilder(); graphViz.Append("<tr><td align=\"left\">"); graphViz.Append(cgMem.Name); graphViz.Append(" "); var typeColor = Etc.ValueTypesList.Contains(NfReflect.GetLastTypeNameFromArrayAndGeneric(cgMem.TypeName.Trim(), "<")) ? "blue" : "grey"; if (cgMem.HasGetter || cgMem.HasSetter) { graphViz.Append("("); graphViz.Append(string.Join(", ", cgMem.Args.Select(x => x.ToGraphVizString()))); graphViz.Append(")"); } graphViz.Append(": <font color=\""); graphViz.Append(typeColor); graphViz.Append("\">"); graphViz.Append(NfReflect.GetLastTypeNameFromArrayAndGeneric(cgMem.TypeName, "<")); if (cgMem.IsEnumerableType) { graphViz.Append("[*]"); } graphViz.Append("</font></td></tr>"); return(graphViz.ToString()); }
/// <summary> /// Returns a node definition with just the type name's header. /// This is specific to graph-viz (ver. 2.38+) /// </summary> /// <param name="typeFullName"></param> /// <param name="enumValues">Optional values to be listed as line items with no type specifiers nor .gv port ids.</param> /// <returns></returns> public static string EmptyGraphVizClassNode(string typeFullName, string[] enumValues) { var className = NfReflect.GetTypeNameWithoutNamespace(typeFullName); var ns = NfReflect.GetNamespaceWithoutTypeName(typeFullName); var fullName = string.Format("{0}{1}", string.IsNullOrWhiteSpace(ns) ? string.Empty : ns + ".", className); var graphViz = new StringBuilder(); graphViz.Append(NfString.SafeDotNetIdentifier(fullName)); graphViz.AppendLine(" [shape=Mrecord, label=<<table bgcolor=\"white\" border=\"0\" >"); graphViz.AppendLine("<th>"); graphViz.AppendLine("<td bgcolor=\"grey\" align=\"center\">"); graphViz.Append("<font color=\"white\">"); graphViz.AppendFormat("{0} :: {1}", className, string.IsNullOrWhiteSpace(ns) ? "global" : ns); graphViz.AppendLine("</font></td></th>"); if (enumValues != null && enumValues.Length > 0) { foreach (var enumVal in enumValues) { graphViz.Append("<tr><td><font color=\"blue\">"); graphViz.Append(enumVal); graphViz.AppendLine("</font></td></tr>"); } } else { graphViz.AppendLine("<tr><td></td></tr>"); graphViz.AppendLine("<tr><td></td></tr>"); } graphViz.AppendLine("</table>> ];"); return(graphViz.ToString()); }
/// <summary> /// Returns edge definitions specific to graph-viz (ver. 2.38+) /// see [http://www.graphviz.org/] /// </summary> /// <returns></returns> public static string ToGraphVizEdge(this CgType cgType) { var graphViz = new StringBuilder(); var myName = NfString.SafeDotNetIdentifier(cgType.FullName); var edges = new List <string>(); foreach ( var property in cgType.Properties.Where( x => !Etc.ValueTypesList.Contains(NfReflect.GetLastTypeNameFromArrayAndGeneric(x.TypeName, "<"))) ) { var toName = NfString.SafeDotNetIdentifier(NfReflect.GetLastTypeNameFromArrayAndGeneric(property.TypeName, "<")); var edg = new StringBuilder(); edg.AppendFormat("{0} -> {1}", myName, toName); edg.Append(property.IsEnumerableType ? " [arrowhead=odiamond]" : " [arrowhead=vee]"); edg.Append(";"); if (!edges.Contains(edg.ToString())) { edges.Add(edg.ToString()); } } foreach (var edge in edges) { graphViz.AppendLine(edge); } return(graphViz.ToString()); }
public void TestGetTypeNameFromArrayAndGeneric() { var testResult = NfReflect.GetLastTypeNameFromArrayAndGeneric("int[]"); Assert.AreEqual("int", testResult); testResult = NfReflect.GetLastTypeNameFromArrayAndGeneric("System.Collections.Generic.List`1[System.String]"); Assert.AreEqual("System.String", testResult); testResult = NfReflect.GetLastTypeNameFromArrayAndGeneric("System.Tuple`2[System.Int32,System.String]"); Assert.AreEqual("System.Int32", testResult); testResult = NfReflect.GetLastTypeNameFromArrayAndGeneric("System.Tuple`2[System.Collections.Generic.List`1[SomeNamespace.AType],System.String]"); Assert.AreEqual("SomeNamespace.AType", testResult); //test C# style testResult = NfReflect.GetLastTypeNameFromArrayAndGeneric( "System.Collections.Generic.List<System.String>", "<"); Assert.AreEqual("System.String", testResult); testResult = NfReflect.GetLastTypeNameFromArrayAndGeneric("System.Tuple<System.Int32, System.String>", "<"); Assert.AreEqual("System.Int32", testResult); testResult = NfReflect.GetLastTypeNameFromArrayAndGeneric("System.Tuple<System.Collections.Generic.List<SomeNamespace.AType>,System.String>", "<"); Assert.AreEqual("SomeNamespace.AType", testResult); var testResults = NfReflect.GetTypeNamesFromGeneric( "System.Tuple`3[System.Collections.Generic.List`1[System.String], System.String, System.Tuple`2[System.Int32, System.String]]"); Console.WriteLine(string.Join(" | ", testResults)); }
public void TestIsClrMethodForProperty() { var testInput = "get_MyProperty"; string testOutput; var testResult = NfReflect.IsClrMethodForProperty(testInput, out testOutput); Assert.IsTrue(testResult); Assert.AreEqual("MyProperty", testOutput); testInput = "set_MyProperty"; testResult = NfReflect.IsClrMethodForProperty(testInput, out testOutput); Assert.IsTrue(testResult); Assert.AreEqual("MyProperty", testOutput); testInput = "add_MyProperty"; testResult = NfReflect.IsClrMethodForProperty(testInput, out testOutput); Assert.IsTrue(testResult); Assert.AreEqual("MyProperty", testOutput); testInput = "remove_MyProperty"; testResult = NfReflect.IsClrMethodForProperty(testInput, out testOutput); Assert.IsTrue(testResult); Assert.AreEqual("MyProperty", testOutput); testInput = "GetMyValues"; testResult = NfReflect.IsClrMethodForProperty(testInput, out testOutput); Assert.IsFalse(testResult); Assert.IsNull(testOutput); }
/// <summary> /// Returns the field's names of the <see cref="enumTypeName"/> /// being that such an enum was encountered while reflecting the type. /// </summary> /// <param name="enumTypeName"></param> /// <returns></returns> public string[] EnumsValues(string enumTypeName) { if (string.IsNullOrWhiteSpace(enumTypeName)) { return(null); } var vals = EnumValueDictionary.ContainsKey(enumTypeName) ? EnumValueDictionary[enumTypeName] : null; if (vals != null) { return(vals); } var clearName = NfReflect.GetLastTypeNameFromArrayAndGeneric(enumTypeName); vals = EnumValueDictionary.ContainsKey(clearName) ? EnumValueDictionary[clearName] : null; if (vals != null) { return(vals); } //try one last time for cs style generics clearName = NfReflect.GetLastTypeNameFromArrayAndGeneric(enumTypeName, "<"); vals = EnumValueDictionary.ContainsKey(clearName) ? EnumValueDictionary[clearName] : null; return(vals); }
public FlattenedItem(Type flType) { FlType = flType; IsEnumerable = NfReflect.IsEnumerableReturnType(flType); TypeFullName = NfReflect.GetLastTypeNameFromArrayAndGeneric(flType); MetadataToken = flType?.MetadataToken ?? 0; }
public HbmCommand(string typeFullName, string idTypeFullName) { TypeFullName = typeFullName; IdTypeFullName = idTypeFullName; OuputNamespace = NfReflect.GetTypeNameWithoutNamespace(TypeFullName); IdTypeTest = Gen.Settings.LangStyle.GenUseIsNotDefaultValueTest(IdTypeFullName, "DataId"); ClassName = NfReflect.GetTypeNameWithoutNamespace(TypeFullName); }
public void TestGetPropertyValuetype() { var testContext = new Address(); var testInput = testContext.GetType().GetProperty("Id"); var testResult = NfReflect.GetPropertyValueType(testInput); Assert.IsNotNull(testResult); Assert.AreEqual("System.Int32", testResult.FullName); Console.WriteLine(testResult.FullName); }
/// <summary> /// Gets the <see cref="PropertyInfo"/> as a code gen member (<see cref="CgMember"/>) /// </summary> /// <param name="pi"></param> /// <param name="valueTypeOnly"></param> /// <param name="enumValueDictionary"></param> /// <returns></returns> public static CgMember GetAsCgMember(PropertyInfo pi, bool valueTypeOnly, Dictionary <string, string[]> enumValueDictionary) { if (pi == null) { return(null); } var piType = pi.NfPropertyType(); if (valueTypeOnly && piType.NfBaseType() != null && piType.NfBaseType().Name != VALUE_TYPE) { return(null); } var cgMem = new CgMember { TypeName = Settings.LangStyle.TransformClrTypeSyntax(piType), IsEnumerableType = NfReflect.IsEnumerableReturnType(piType), Name = pi.Name, MetadataToken = pi.MetadataToken }; if (pi.CanRead) { cgMem.HasGetter = true; if (pi.NfGetGetMethod() != null) { cgMem.IsStatic = pi.NfGetGetMethod().IsStatic; } } if (pi.CanWrite) { cgMem.HasSetter = true; if (pi.NfGetSetMethod() != null) { cgMem.IsStatic = pi.NfGetSetMethod().IsStatic; } } string[] enumVals; if (NfReflect.IsEnumType(piType, out enumVals) && enumValueDictionary != null) { cgMem.IsEnum = true; var clearName = NfReflect.GetLastTypeNameFromArrayAndGeneric(cgMem.TypeName, "<"); if (!enumValueDictionary.ContainsKey(clearName)) { enumValueDictionary.Add(clearName, enumVals); } } return(cgMem); }
public bool TryFindLastLineInClass(string typename, string[] srcFileLines, out int lastLine) { lastLine = int.MaxValue; if (srcFileLines == null) { return(false); } var srcFile = srcFileLines.ToArray(); if (String.IsNullOrWhiteSpace(typename)) { return(false); } if (srcFile.Length <= 0) { return(false); } lastLine = srcFile.Length; //these preserve all lines srcFile = RemoveLineComments(srcFile, LINE_COMMENT_CHAR_SEQ); srcFile = RemoveBlockComments(srcFile); var joinedContent = string.Join("\n", srcFile); var myXDocFrame = new XDocFrame(C_OPEN_CURLY, C_CLOSE_CURLY); var mytokens = myXDocFrame.FindEnclosingTokens(joinedContent); if (mytokens == null || mytokens.Count < 1) { return(false); } var targetToken = NfReflect.GetTypeNameWithoutNamespace(typename) == typename ? mytokens[0] : mytokens[1]; var joinedContentAsChars = joinedContent.ToCharArray(); //need to count the number of newlines from the bottom up to token's end for (var i = joinedContent.Length - 1; i >= targetToken.End; i--) { if (joinedContentAsChars[i] != '\n') { continue; } lastLine -= 1; } //add one more if (lastLine < srcFile.Length) { lastLine -= 1; } return(lastLine < srcFile.Length); }
public override void WriteOutputToDisk(byte[] bytes, string fileName = null, string fileExt = ".json") { if (string.IsNullOrWhiteSpace(_reassignAssemblySubjectName)) { base.WriteOutputToDisk(bytes, fileName, fileExt); return; } var isFullAssemblyName = NfReflect.IsAssemblyFullName(_reassignAssemblySubjectName); var isFullPath = Path.IsPathRooted(_reassignAssemblySubjectName); var isFileName = _reassignAssemblySubjectName.EndsWith(".dll") || _reassignAssemblySubjectName.EndsWith(".exe"); if (isFullAssemblyName) { var assemblyName = new System.Reflection.AssemblyName(_reassignAssemblySubjectName); _reassignAssemblySubjectName = assemblyName.Name; } if (isFullPath) { var dirName = Path.GetDirectoryName(_reassignAssemblySubjectName); if (!string.IsNullOrWhiteSpace(dirName)) { _reassignAssemblySubjectName = _reassignAssemblySubjectName.Replace(dirName, ""); } } if (isFileName) { var flname = Path.GetFileNameWithoutExtension(_reassignAssemblySubjectName); if (!string.IsNullOrWhiteSpace(flname)) { _reassignAssemblySubjectName = flname; } } var tn = fileName ?? GetType().Name; tn = NfPath.SafeFilename(tn); var dir = MyProgram == null ? NfSettings.AppData : MyProgram.LogDirectory; var rootAsmName = NfPath.SafeDirectoryName(_reassignAssemblySubjectName); dir = Path.Combine(dir, rootAsmName); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllBytes(Path.Combine(dir, tn + fileExt), bytes); }
public static string HbmFileNameFromAsmQualTypeName(string asmFullName, bool prependDir = false) { if (string.IsNullOrWhiteSpace(asmFullName) || !NfReflect.IsFullAssemblyQualTypeName(asmFullName)) { return(HbmFileName(asmFullName)); } var nfName = new NfTypeName(asmFullName); var tbl = nfName.Namespace.Replace($"{nfName.AssemblySimpleName}.", string.Empty) + "." + nfName.ClassName; var flNm = HbmFileName(tbl); return(prependDir ? Path.Combine(Settings.HbmDirectory, flNm) : flNm); }
/// <summary> /// Attempts to assign all the property's values on <see cref="fromObj"/> to /// some property on <see cref="toObj"/> based on the closest matching name. /// </summary> /// <param name="fromObj"></param> /// <param name="toObj"></param> /// <returns>1.0 when it was a perfect match</returns> /// <remarks> /// Use the <see cref="GetAssignPropertiesData"/> to see what it ended up choosing. /// </remarks> public static double TryAssignProperties(object fromObj, object toObj) { if (fromObj == null || toObj == null) { return(0); } var rScores = new List <Tuple <int, int> >(); var prevActions = new Dictionary <string, int>(); try { //remove any previous records. assignPiLog.Clear(); //only fromObj's value-type props rScores.AddRange(TryAssignValueTypeProperties(fromObj, toObj, prevActions)); //only fromObj's ref-type props foreach (var fromPi in fromObj.GetType().GetProperties(DefaultFlags)) { if (fromPi == null || !fromPi.CanRead) { continue; } if (NfReflect.IsValueTypeProperty(fromPi, true)) { continue; } var fromPv = fromPi.GetValue(fromObj); if (fromPv == null && TryGetInstanceOfPiType(fromPi, out fromPv)) { fromPi.SetValue(fromObj, fromPv); } rScores.AddRange(TryAssignValueTypeProperties(fromPv, toObj, prevActions, fromPi.Name)); } } catch (Exception ex) { assignPiLog.Add(new[] { ERROR_PREFIX, ex.Message, ex.StackTrace }); return(0); } var num = rScores.Select(x => (double)x.Item2).Sum(); var den = rScores.Select(x => (double)x.Item1).Sum(); var ratio = den == 0.0D ? 0.0D : num / den; return(1D - ratio); }
public void TestGetTypeNameWithoutNamespace() { var testResult = NfReflect.GetTypeNameWithoutNamespace("NoFuture.Asm.Fii.MyType"); Console.WriteLine(testResult); Assert.AreEqual("MyType", testResult); testResult = NfReflect.GetTypeNameWithoutNamespace("My_SillyName_NoNamespace_Pos_Class"); Console.WriteLine(testResult); Assert.AreEqual("My_SillyName_NoNamespace_Pos_Class", testResult); testResult = NfReflect.GetNamespaceWithoutTypeName( "Wanker.DCF.UI.Controller.Operator.OperatorUIController::set_OperatorContacts(Wanker.DCF.DTO.WankerContact)"); }
public bool TryFindFirstLineInClass(string typename, string[] srcFileLines, out int firstLine) { firstLine = 1; if (srcFileLines == null) { return(false); } var srcFile = srcFileLines.ToArray(); if (String.IsNullOrWhiteSpace(typename)) { return(false); } if (srcFile.Length <= 0) { return(false); } //these preserve all lines srcFile = RemoveLineComments(srcFile, LINE_COMMENT_CHAR_SEQ); srcFile = RemoveBlockComments(srcFile); var joinedContent = String.Join("\n", srcFile); var myXDocFrame = new XDocFrame(C_OPEN_CURLY, C_CLOSE_CURLY); var mytokens = myXDocFrame.FindEnclosingTokens(joinedContent); if (mytokens == null || mytokens.Count < 1) { return(false); } var targetToken = NfReflect.GetTypeNameWithoutNamespace(typename) == typename ? mytokens[0] : mytokens[1]; var joinedContentAsChars = joinedContent.ToCharArray(); //need to count the number of newlines up to the token's start for (var i = 0; i <= targetToken.Start; i++) { if (joinedContentAsChars[i] != '\n') { continue; } firstLine += 1; } return(firstLine > 1); }
public SqlDbType GetSqlDataType() { if (IsUserDefinedType && NfReflect.IsAssemblyFullName(DataType)) { return(SqlDbType.Udt); } if (NfReflect.IsAssemblyFullName(DataType)) { return(SqlDbType.NVarChar); } SqlDbType dbTypeOut; Enum.TryParse(dataType, true, out dbTypeOut); return(dbTypeOut); }
protected internal void GetIdName() { _idName = _idNode.Attributes[HbmXmlNames.NAME].Value; var idTypeAttr = _idNode.Attributes[HbmXmlNames.TYPE] ?? _idNode.Attributes[HbmXmlNames.CLASS]; if (idTypeAttr == null) { throw new ItsDeadJim( string.Format( "Found the ID node but did not find either the attribute 'type' nor 'class' in hbm.xml file at '{0}'", _fileNamePath)); } _idType = idTypeAttr.Value; if (string.IsNullOrWhiteSpace(IdType)) { throw new ItsDeadJim( string.Format( "Found the ID and an attribute (either 'type' or 'class') but its value is empty in hbm.xml file at '{0}'", _fileNamePath)); } if (IsCompositeKey) { _idType = NfReflect.IsFullAssemblyQualTypeName(IdType) ? (new NfTypeName(IdType)).FullName : IdType; } else { if (_idNode.HasChildNodes && _idNode.FirstChild.HasChildNodes) { var columnNode = _idNode.FirstChild; var columnJson = columnNode.FirstChild.InnerText; ColumnMetadata dataOut; if (ColumnMetadata.TryParseJson(columnJson, out dataOut)) { AddToKeyColumns(IdName, dataOut); } } _idType = Lexicon.Hbm2NetTypes[IdType]; } }
public string ToDecl(CgMember cgMem, bool includesAccessModifier = false) { if (cgMem == null) { return(string.Empty); } var cgArgs = cgMem.Args.Select(cgArg => $"{cgArg.ArgType} {cgArg.ArgName}").ToList(); var accessMod = includesAccessModifier ? TransposeCgAccessModToString(cgMem.AccessModifier) + " " : string.Empty; var args = string.Join(", ", cgArgs); if (cgMem.IsCtor) { var ctorName = NfReflect.GetTypeNameWithoutNamespace(cgMem.TypeName); return($"{accessMod}{ctorName}({args})"); } if (cgArgs.Any() || cgMem.IsMethod) { //TODO - this is only going to work for when there is only one generic arg return(cgMem.IsGeneric && !cgMem.IsCtor ? $"{accessMod}{cgMem.TypeName} {cgMem.Name}<{cgMem.TypeName}>({args})" : $"{accessMod}{cgMem.TypeName} {cgMem.Name}({args})"); } var propSyntax = ""; if (cgMem.HasSetter || cgMem.HasGetter) { propSyntax += " { "; if (cgMem.HasGetter) { propSyntax += "get; "; } if (cgMem.HasSetter) { propSyntax += "set; "; } propSyntax += "}"; } return($"{accessMod}{cgMem.TypeName} {cgMem.Name}{propSyntax}"); }
public void TestGetNamespaceWithoutTypeName() { var testResult = NfReflect.GetNamespaceWithoutTypeName("NoFuture.Asm.Fii.MyType"); Console.WriteLine(testResult); Assert.AreEqual("NoFuture.Asm.Fii", testResult); var testResult2 = NfReflect.GetNamespaceWithoutTypeName("My_SillyName_NoNamespace_Pos_Class"); Assert.IsNull(testResult2); testResult = NfReflect.GetNamespaceWithoutTypeName( "global::Wanker.DCF.UI.Controller.Operator.OperatorUIController::set_OperatorContacts(Wanker.DCF.DTO.WankerContact)"); Console.WriteLine(testResult); Assert.AreEqual("Wanker.DCF.UI.Controller.Operator", testResult); testResult = NfReflect.GetNamespaceWithoutTypeName("NeedItInIl.DomainAdapterBase`2[[AThirdDll.Whatever, AThirdDll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]," + "[System.Tuple`3[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Collections.Generic.IEnumerable`1[[MoreBinaries.DomainObject+MyInnerType, MoreBinaries, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]," + " mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], " + "NeedItInIl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); Console.WriteLine(testResult); Assert.AreEqual("NeedItInIl", testResult); testResult = NfReflect.GetNamespaceWithoutTypeName( "Wanker.DCF.UI.Controller.Operator.OperatorUIController::set_OperatorContacts(Wanker.DCF.DTO.WankerContact)"); Console.WriteLine(testResult); Assert.AreEqual(testResult, "Wanker.DCF.UI.Controller.Operator"); testResult = NfReflect.GetNamespaceWithoutTypeName( ".Controller.Operator.OperatorUIController::set_OperatorContacts(Wanker.DCF.DTO.WankerContact)"); Console.WriteLine(testResult); Assert.AreEqual(testResult, "Controller.Operator"); }
public string ToSignatureRegex(CgMember cgMem) { var regexPattern = new StringBuilder(); regexPattern.Append(@"(\b" + TransposeCgAccessModToString(cgMem.AccessModifier) + @"\b)"); if (cgMem.AccessModifier == CgAccessModifier.Assembly) { regexPattern.Append("?"); } regexPattern.Append(@"([^\x2c\x3b\x7d\x7b]+?)"); regexPattern.AppendFormat(@"\b{0}\b", cgMem.Name); if (cgMem.IsGeneric) { //needs to handle crazy shit like 'global::System.Tuple<int, Func<Mynamespace.MyType, global::System.Int64>>' regexPattern.Append(@"\x3c.*?\x3e"); } if (!cgMem.IsMethod) { return(regexPattern.ToString()); } if (cgMem.Args.Count <= 0) { regexPattern.Append(@"\(\s*?\)"); return(regexPattern.ToString()); } var simpleArgTypes = cgMem.Args.Select( x => @"\s*\b" + NfReflect.GetTypeNameWithoutNamespace(x.ArgType).EscapeString() + @"\b\s*([^\,]+?)").ToList(); regexPattern.AppendFormat(@"\s*\({0}\)", string.Join(@"\,", simpleArgTypes)); return(regexPattern.ToString()); }
/// <summary> /// Gets the <see cref="FieldInfo"/> as a code gen member (<see cref="CgMember"/>) /// </summary> /// <param name="fi"></param> /// <param name="valueTypeOnly"></param> /// <param name="enumValueDictionary"></param> /// <returns></returns> public static CgMember GetAsCgMember(FieldInfo fi, bool valueTypeOnly, Dictionary <string, string[]> enumValueDictionary) { if (fi == null) { return(null); } if (NfReflect.IsClrGeneratedType(fi.Name)) { return(null); } var fiType = fi.NfFieldType(); if (valueTypeOnly && fiType.NfBaseType() != null && fiType.NfBaseType().Name != VALUE_TYPE) { return(null); } var cgMem = new CgMember { TypeName = Settings.LangStyle.TransformClrTypeSyntax(fiType), IsEnumerableType = NfReflect.IsEnumerableReturnType(fiType), Name = fi.Name, IsStatic = fi.IsStatic, MetadataToken = fi.MetadataToken }; string[] enumVals; if (NfReflect.IsEnumType(fiType, out enumVals) && enumValueDictionary != null) { cgMem.IsEnum = true; var clearName = NfReflect.GetLastTypeNameFromArrayAndGeneric(cgMem.TypeName, "<"); if (!enumValueDictionary.ContainsKey(clearName)) { enumValueDictionary.Add(clearName, enumVals); } } return(cgMem); }
public static string ClassName(string name, string outputNamespace) { var asmQualifiedName = new StringBuilder(); if (name.Split(Shared.Core.NfSettings.DefaultTypeSeparator).Length > 1) { var nameParts = name.Split(Shared.Core.NfSettings.DefaultTypeSeparator); var actualClassName = nameParts[(nameParts.Length - 1)].Replace(" ", Globals.REPLACE_SPACE_WITH_SEQUENCE); nameParts[(nameParts.Length - 1)] = NfString.SafeDotNetTypeName(actualClassName); name = string.Join(Shared.Core.NfSettings.DefaultTypeSeparator.ToString(CultureInfo.InvariantCulture), nameParts); } //remove any chars not allowed in C# ids name = NfString.SafeDotNetTypeName(name); //capitalize first letter of whole word to avoid conflict with C# reserved words name = NfString.CapWords(name, Shared.Core.NfSettings.DefaultTypeSeparator); if (!String.IsNullOrWhiteSpace(outputNamespace)) { outputNamespace = NfString.CapWords(outputNamespace, Shared.Core.NfSettings.DefaultTypeSeparator); asmQualifiedName.AppendFormat("{0}{1}", outputNamespace, Shared.Core.NfSettings.DefaultTypeSeparator); } asmQualifiedName.Append(name); if (!String.IsNullOrWhiteSpace(outputNamespace)) { asmQualifiedName.AppendFormat(", {0}", NfReflect.DraftCscExeAsmName(outputNamespace)); } var typeName = new NfTypeName(asmQualifiedName.ToString()); if (!String.IsNullOrWhiteSpace(outputNamespace)) { return(typeName.AssemblyQualifiedName); } return(typeName.FullName); }
public void CopyFrom(System.Data.DataColumn col) { if (!string.IsNullOrWhiteSpace(col.ColumnName)) { column_name = col.ColumnName; } if (col.Ordinal > 0) { column_ordinal = col.Ordinal; } if (col.DataType != null && !string.IsNullOrWhiteSpace(col.DataType.FullName)) { data_type = NfReflect.GetLastTypeNameFromArrayAndGeneric(col.DataType.FullName); if (data_type == "System.String") { string_length = Globals.MSSQL_MAX_VARCHAR; } } is_auto_increment = col.AutoIncrement; is_nullable = col.AllowDBNull; }
/// <summary> /// Assigns property values on the <see cref="rtInstance"/> from /// the x-ref data source. /// </summary> /// <param name="elem"></param> /// <param name="rtInstance"></param> public static void SetTypeXrefValue(XmlElement elem, object rtInstance) { var nameAttr = elem.Attributes[NAME]; if (string.IsNullOrWhiteSpace(nameAttr?.Value)) { return; } if (rtInstance == null) { return; } var propertyName = nameAttr.Value; var pi = rtInstance.GetType().GetProperty(propertyName); if (pi == null || !pi.CanWrite) { return; } var valueAttr = elem.Attributes[VALUE]; if (!string.IsNullOrWhiteSpace(valueAttr?.Value)) { pi.SetValue(rtInstance, valueAttr.Value, null); return; } if (!elem.HasChildNodes || pi == null) { return; } var piType = pi.PropertyType; var propertyInstance = Activator.CreateInstance(piType); //expecting the type to have a getter and setter of generic List<T> if (NfReflect.IsEnumerableReturnType(piType)) { var addMi = piType.GetMethod("Add"); if (addMi == null) { return; } var enumerableTypeName = NfReflect.GetLastTypeNameFromArrayAndGeneric(piType); if (string.IsNullOrWhiteSpace(enumerableTypeName)) { return; } var asm = AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(a => a.GetType(enumerableTypeName) != null); if (asm == null) { return; } var enumerableType = asm.GetType(enumerableTypeName); if (enumerableType == null) { return; } var enumerableInstance = Activator.CreateInstance(enumerableType); foreach (var cNode in elem.ChildNodes) { var cElem = cNode as XmlElement; if (cElem == null) { continue; } SetTypeXrefValue(cElem, enumerableInstance); } addMi.Invoke(propertyInstance, new[] { enumerableInstance }); } else//no generic type { foreach (var cNode in elem.ChildNodes) { var cElem = cNode as XmlElement; if (cElem == null) { continue; } SetTypeXrefValue(cElem, propertyInstance); } } pi.SetValue(rtInstance, propertyInstance, null); }
public static string ToGraphVizString(this CgArg cgArg) { return(NfReflect.GetTypeNameWithoutNamespace(cgArg.ArgType)); }
internal static Action GetSimpleAssignment(PropertyInfo toPi, object toObj, PropertyInfo fromPi, object fromObj, out string logInfo) { Action noop = () => { }; logInfo = null; if (toPi == null || toObj == null || fromPi == null || fromObj == null) { return(noop); } //only deal in value types to value types if (!NfReflect.IsValueTypeProperty(toPi, true) || !NfReflect.IsValueTypeProperty(fromPi, true)) { return(noop); } //enums require alot of special handling especially when wrapped in Nullable`1[ var cpiIsEnum = NfReflect.IsPropertyEnum(toPi); var fromPiIsEnum = NfReflect.IsPropertyEnum(fromPi); //get each pi's type var cpiType = cpiIsEnum ? NfReflect.GetEnumType(toPi) : NfReflect.GetPropertyValueType(toPi); var fromPiType = fromPiIsEnum ? NfReflect.GetEnumType(fromPi) : NfReflect.GetPropertyValueType(fromPi); //get each pi's type's full name var cpiTypeFullname = cpiType.FullName; var fromPiTypeFullname = fromPiType.FullName; logInfo = String.Join("->", fromPiTypeFullname, cpiTypeFullname); //easy assignment for same types if (cpiTypeFullname == fromPiTypeFullname) { return(() => toPi.SetValue(toObj, fromPi.GetValue(fromObj))); } //going from Enum to a string if (fromPiIsEnum && cpiTypeFullname == STR_FN) { //take enum value and get its name return(() => { var enumName = Enum.GetName(fromPiType, fromPi.GetValue(fromObj)); if (enumName != null) { toPi.SetValue(toObj, enumName); } }); } //going from a string to an enum if (cpiIsEnum && fromPiTypeFullname == STR_FN) { return(() => { var val = fromPi.GetValue(fromObj); if (val != null && !String.IsNullOrWhiteSpace(val.ToString()) && Enum.GetNames(cpiType) .Any(x => String.Equals(x, val.ToString(), StringComparison.OrdinalIgnoreCase))) { var enumVal = Enum.Parse(cpiType, val.ToString(), true); toPi.SetValue(toObj, enumVal); } }); } //going from enum to enum if (fromPiIsEnum && cpiIsEnum) { //will this require any cast? return(() => { toPi.SetValue(toObj, fromPi.GetValue(fromObj)); }); } //going from some value-type to a string if (cpiTypeFullname == STR_FN) { return(() => toPi.SetValue(toObj, fromPi.GetValue(fromObj).ToString())); } //going from something to value-type switch (cpiTypeFullname) { case "System.Byte": return(() => { byte bout; var bpiv = fromPi.GetValue(fromObj); var byteString = bpiv == null ? "0" : bpiv.ToString(); if (Byte.TryParse(byteString, out bout)) { toPi.SetValue(toObj, bout); } }); case "System.Int16": return(() => { short vout; var piv = fromPi.GetValue(fromObj); var vStr = piv == null ? "0" : piv.ToString(); if (Int16.TryParse(vStr, out vout)) { toPi.SetValue(toObj, vout); } }); case "System.Int32": return(() => { int vout; var piv = fromPi.GetValue(fromObj); var vStr = piv == null ? "0" : piv.ToString(); if (Int32.TryParse(vStr, out vout)) { toPi.SetValue(toObj, vout); } }); case "System.DateTime": return(() => { DateTime vout; var piv = fromPi.GetValue(fromObj); var vStr = piv == null ? "0" : piv.ToString(); if (DateTime.TryParse(vStr, out vout)) { toPi.SetValue(toObj, vout); } }); case "System.Decimal": return(() => { decimal vout; var piv = fromPi.GetValue(fromObj); var vStr = piv == null ? "0" : piv.ToString(); if (Decimal.TryParse(vStr, out vout)) { toPi.SetValue(toObj, vout); } }); case "System.Single": return(() => { float vout; var piv = fromPi.GetValue(fromObj); var vStr = piv == null ? "0" : piv.ToString(); if (Single.TryParse(vStr, out vout)) { toPi.SetValue(toObj, vout); } }); case "System.Double": return(() => { double vout; var piv = fromPi.GetValue(fromObj); var vStr = piv == null ? "0" : piv.ToString(); if (Double.TryParse(vStr, out vout)) { toPi.SetValue(toObj, vout); } }); } //default out to no operation return(noop); }
internal static List <Tuple <int, int> > TryAssignValueTypeProperties(object fromObj, object toObj, Dictionary <string, int> prevActions, string contextName = null) { var df = new List <Tuple <int, int> > { new Tuple <int, int>(Int32.MaxValue, 0) }; if (fromObj == null || toObj == null) { return(df); } var rScores = new List <Tuple <int, int> >(); try { var fromObjTypeName = fromObj.GetType().FullName; var fromObjPropertyNames = fromObj.GetType().GetProperties(DefaultFlags).Select(p => p.Name).ToArray(); //if still nothing found - just leave if (!fromObjPropertyNames.Any()) { return(df); } var toPis = toObj.GetType().GetProperties(DefaultFlags); prevActions = prevActions ?? new Dictionary <string, int>(); foreach (var pn in fromObjPropertyNames) { var fromPi = fromObj.GetType().GetProperty(pn); if (fromPi == null || !fromPi.CanRead || !NfReflect.IsValueTypeProperty(fromPi, true)) { continue; } //this will get us those closest on name only var closestMatches = GetClosestMatch(fromPi, fromObj, toPis, toObj); if (closestMatches == null || !Enumerable.Any <Tuple <Action, int, string, string> >(closestMatches)) { continue; } //have to decide how to break a tie if (closestMatches.Count > 1) { closestMatches = Enumerable.Where <Tuple <Action, int, string, string> >(closestMatches, x => x.Item3.Contains(pn)).ToList(); } foreach (var cm in closestMatches) { //its possiable that two different pi names are both attempting to write to the exact same target pi in toObj if (prevActions.ContainsKey(cm.Item3) && cm.Item2 >= prevActions[cm.Item3]) { //we only want the one with the shortest distance continue; } //exec the assignment on the target cm.Item1(); //get this distance as a ratio to the possible max distance rScores.Add(new Tuple <int, int>(cm.Item2, pn.Length)); //add this to the log var logPn = !String.IsNullOrWhiteSpace(contextName) ? String.Join(".", contextName, pn) : pn; var logPath = !String.IsNullOrWhiteSpace(contextName) ? String.Join("`", fromObjTypeName, cm.Item4) : cm.Item4; assignPiLog.Add(new[] { logPn, cm.Item3, logPath, cm.Item2.ToString() }); prevActions.Add(cm.Item3, cm.Item2); } } } catch (Exception ex) { assignPiLog.Add(new[] { ERROR_PREFIX, ex.Message, ex.StackTrace }); return(df); } //return average return(rScores); }
internal static List <Tuple <Action, int, string, string> > GetClosestMatch(PropertyInfo fromPi, object fromObj, PropertyInfo[] toPis, object toObj, string namePrefix = null, int minLen = 2) { if (fromPi == null || toPis == null || !toPis.Any()) { return(new List <Tuple <Action, int, string, string> >()); } //we want to map a whole assignment expression to a distance on name var ops2Score = new List <Tuple <Action, int, string, string> >(); Func <PropertyInfo, string, bool, string> getMeasureableName = (gmnPi, prefix, inReverse) => { if (gmnPi.Name.Length <= minLen) { return(inReverse ? String.Join("", gmnPi.Name, prefix) : String.Join("", prefix, gmnPi.Name)); } return(gmnPi.Name); }; foreach (var toPi in toPis) { if (NfReflect.IsValueTypeProperty(toPi, true)) { string toFromTns; Action simpleAssignment = GetSimpleAssignment(toPi, toObj, fromPi, fromObj, out toFromTns); if (String.IsNullOrWhiteSpace(namePrefix)) { //for simple value types -to- value types where dest has a very short name namePrefix = toObj.GetType().Name; } var fromPiName = getMeasureableName(fromPi, namePrefix, false); var cpiName = getMeasureableName(toPi, namePrefix, false); var fromPiReverseName = getMeasureableName(fromPi, namePrefix, true); var cpiReverseName = getMeasureableName(toPi, namePrefix, true); var score = (int)NfString.LevenshteinDistance(fromPiName, cpiName); //with short property names, prehaps a better score is when prefix is a suffix instead if (fromPiName != fromPiReverseName || cpiName != cpiReverseName) { var revScore = (int)NfString.LevenshteinDistance(fromPiReverseName, cpiReverseName); if (revScore < score) { score = revScore; } } ops2Score.Add(new Tuple <Action, int, string, string>(simpleAssignment, score, toPi.Name, toFromTns)); } else { var toInnerPi = toPi.PropertyType.GetProperties(DefaultFlags); if (!toInnerPi.Any()) { continue; } var toInnerObj = toPi.GetValue(toObj) ?? Activator.CreateInstance(toPi.PropertyType); var innerMeasurements = GetClosestMatch(fromPi, fromObj, toInnerPi, toInnerObj, toPi.Name, minLen); if (!innerMeasurements.Any()) { continue; } //these will by def, be the shortest distance foreach (var innerM in innerMeasurements) { //we will chain-link these actions Action complexAction = () => { innerM.Item1(); if (toPi.GetValue(toObj) == null) { toPi.SetValue(toObj, toInnerObj); } }; var actionId = String.Join(".", toPi.Name, innerM.Item3); ops2Score.Add(new Tuple <Action, int, string, string>(complexAction, innerM.Item2, actionId, String.Join("`", toPi.PropertyType.FullName, innerM.Item4))); } } } var totalMin = ops2Score.Min(x => x.Item2); var closest = ops2Score.Where(x => x.Item2 == totalMin).ToList(); return(closest); }