public IBindingType CreateBindingType(CodeTypeRef type) { var fullName = type.AsFullName; int lastPeriodIndex = fullName.LastIndexOf('.'); var name = lastPeriodIndex >= 0 ? fullName.Substring(lastPeriodIndex + 1) : fullName; return new BindingReflectionType(name, fullName); }
private TypescriptType TryResolveType(CodeTypeRef codeType) { if (codeType.TypeKind == vsCMTypeRef.vsCMTypeRefArray) { return new ArrayType() { ElementType = GetTypeScriptType(codeType.ElementType) }; } return GetTypeScriptType(codeType.AsFullName); }
public IBindingType CreateBindingType(CodeTypeRef type) { if (type == null) return null; var fullName = type.AsFullName; if (string.IsNullOrWhiteSpace(fullName) || fullName.Equals(typeof(void).FullName)) return null; int lastPeriodIndex = fullName.LastIndexOf('.'); var name = lastPeriodIndex >= 0 ? fullName.Substring(lastPeriodIndex + 1) : fullName; return new BindingType(name, fullName); }
public TypescriptType GetTypeScriptType(CodeTypeRef codeType) { switch (codeType.TypeKind) { case vsCMTypeRef.vsCMTypeRefChar: case vsCMTypeRef.vsCMTypeRefString: return new StringType(); case vsCMTypeRef.vsCMTypeRefBool: return new BoolType(); case vsCMTypeRef.vsCMTypeRefByte: case vsCMTypeRef.vsCMTypeRefDouble: case vsCMTypeRef.vsCMTypeRefInt: case vsCMTypeRef.vsCMTypeRefShort: case vsCMTypeRef.vsCMTypeRefFloat: case vsCMTypeRef.vsCMTypeRefLong: case vsCMTypeRef.vsCMTypeRefDecimal: return new NumberType(); default: return TryResolveType(codeType); } }
public TypescriptType GetTypeScriptType(CodeTypeRef codeType) { switch (codeType.TypeKind) { case vsCMTypeRef.vsCMTypeRefChar: case vsCMTypeRef.vsCMTypeRefString: return(new StringType()); case vsCMTypeRef.vsCMTypeRefBool: return(new BoolType()); case vsCMTypeRef.vsCMTypeRefByte: case vsCMTypeRef.vsCMTypeRefDouble: case vsCMTypeRef.vsCMTypeRefInt: case vsCMTypeRef.vsCMTypeRefShort: case vsCMTypeRef.vsCMTypeRefFloat: case vsCMTypeRef.vsCMTypeRefLong: case vsCMTypeRef.vsCMTypeRefDecimal: return(new NumberType()); default: return(TryResolveType(codeType)); } }
/// <summary> /// Determines whether the supplied CodeTypeRef represents the specified .NET type. /// If the CodeTypeRef represents a nullable type, we match the *underlying type* (e.g., /// from int? we match int). /// This requires that the CodeTypeRef be attached to a parent code element so we can detect /// what language it is written in; otherwise we'll throw an InvalidOperationException. /// </summary> public static bool UnderlyingTypeIs <T>(this CodeTypeRef codeTypeRef) { return(codeTypeRef.UnderlyingTypeIs(typeof(T))); }
public override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeProperty originalClassCodeProperty) { vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction; object functionType = null; functionKind = vsCMFunction.vsCMFunctionSub; functionType = vsCMTypeRef.vsCMTypeRefVoid; string nextAvailableName = originalClassCodeProperty.Name; if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass, nextAvailableName)) { nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject); } CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction( nextAvailableName, functionKind, functionType, -1, originalClassCodeProperty.Access, -1); unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1); try { unitTestCodeFunction.Comment = originalClassCodeProperty.Comment; unitTestCodeFunction.DocComment = originalClassCodeProperty.DocComment; } catch (Exception ex) { Logger.LogException(ex); //ignore } TextPoint bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint(); //Stop here if not read-write type property now... if (originalClassCodeProperty.Setter == null) { boydEditPoint = bodyStartingPoint.CreateEditPoint(); boydEditPoint.Insert(StringHelper.GetTabString() + "' Property is not read-write please add your own code here." + Environment.NewLine); return(unitTestCodeFunction); } string tvFunctionCallTemplate = string.Empty; // "iv{0}Type.{1} = default({2});"; tvFunctionCallTemplate = "iv{0}Type.{1} = New {2}()" + Environment.NewLine; string tvFunctionCall = tvFunctionCallTemplate; CodeTypeRef tvPropertyType = originalClassCodeProperty.Type; string tvPropertyTypeAsString = tvPropertyType.AsString; tvFunctionCall = string.Format(tvFunctionCall, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString); bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody); boydEditPoint = bodyStartingPoint.CreateEditPoint(); //FIX ME (tabing) boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine); //FIX ME (tabbing) string tvTempString = string.Empty; // "iv{0}Type.{1}, default({2})"; tvTempString = "iv{0}Type.{1}, New {2}()"; tvTempString = string.Format(tvTempString, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString); boydEditPoint.Insert(Environment.NewLine); boydEditPoint.Insert("\t\t\t'TODO: Update Assert to meet test needs" + Environment.NewLine); boydEditPoint.Insert("\t\t\t'Assert.AreEqual(" + tvTempString + ")" + Environment.NewLine); boydEditPoint.Insert("\t\t\t" + Environment.NewLine); boydEditPoint.Insert("\t\t\tThrow New Exception 'Not Implemented'" + Environment.NewLine); return(unitTestCodeFunction); }
private static string ExtractFirstGenericArgOfSpecificCollectionType(CodeTypeRef typeRef, string codeLanguageGuid, params Type[] candidateCollectionTypes) { if ((typeRef == null) || string.IsNullOrEmpty(typeRef.AsFullName)) return null; var codeDomProvider = string.Equals(codeLanguageGuid, VsConstants.VbCodeModelLanguageGuid, StringComparison.OrdinalIgnoreCase) ? (CodeDomProvider)new VBCodeProvider() : new CSharpCodeProvider(); foreach (var collectionType in candidateCollectionTypes) { var languageSpecificCollectionTypeName = codeDomProvider.GetTypeOutput(new CodeTypeReference(collectionType)); var regex = string.Format("^{0}$", languageSpecificCollectionTypeName.Replace(".", @"\.") .Replace(")", string.Empty) .Replace(">", string.Empty) .Replace("<", @"<([^>]+)>")) .Replace("(Of ", @"\(Of ([^\)]+)\)"); var match = Regex.Match(typeRef.AsFullName, regex); if (match.Success) return match.Groups[1].Captures[0].Value; } return null; }
private static bool IsBindableType(CodeTypeRef type) { return type.IsPrimitiveType() || _bindableNonPrimitiveTypes.Any(x => type.IsMatchForReflectionType(x)); }
/// <summary> /// Gets the full names of the types involved with the received type reference. /// </summary> /// <param name="typeRef">TypeRef from where to obtained the type full names involved with it.</param> /// <returns></returns> public static List<string> GetTypesFullNamesFromTypeRef(CodeTypeRef typeRef) { var result = new List<string>(); if (typeRef.TypeKind == vsCMTypeRef.vsCMTypeRefArray) { result.AddRange(VisualStudioHelper.GetTypesFullNamesFromTypeRef(typeRef.ElementType)); } else { result.AddRange(VisualStudioHelper.GetFullNamesFromFullName(typeRef.AsFullName)); } return result; }
protected string GetType(CodeTypeRef type, string path, StringBuilder sb, CodeProperty property) { var fullName = type.AsFullName; if (SimpleTypeMapping.ContainsKey(fullName)) { return(SimpleTypeMapping[fullName]); } if (fullName.Contains("[]")) { return($"Array<{GetType(type.ElementType, path, sb, null)}>"); } var generic = GenericReplace.Match(fullName); if (generic.Success) { if (ArrayGenericTypeMapping.ContainsKey(generic.Groups[1].Value)) { var element = FindCodeTypeByFullName(generic.Groups[2].Value); return(element != null ? $"Array<{GetType(ToCodeTypeRef(element), path, sb, null)}>" : string.Empty); } } if (property != null && fullName.Equals(ObjectTypeString, StringComparison.Ordinal) && property.Kind == vsCMElement.vsCMElementProperty) { var attributes = ((CodeProperty2)property).Attributes.Cast <CodeAttribute2>().ToArray(); foreach (var attribute in attributes) { if (!attribute.Name.Equals(DataEntityGeneratorAttributeName, StringComparison.Ordinal)) { continue; } var argument = attribute.Arguments.Cast <CodeAttributeArgument>().First(); var value = Regex.Replace(argument.Value, "^typeof.*\\((.*)\\)$", "$1"); var codeElements = property.ProjectItem.FileCodeModel.CodeElements.Cast <CodeElement>().ToArray(); var imports = GetTypeByKind(codeElements, vsCMElement.vsCMElementImportStmt).Cast <CodeImport>().Select(x => x.Namespace).ToList(); var namespaces = GetTypeByKind(codeElements, vsCMElement.vsCMElementNamespace).Cast <CodeNamespace>().Select(x => x.Name).ToArray(); if (namespaces.Any()) { imports.AddRange(namespaces); } foreach (var codeImport in imports) { var typeCode = FindCodeTypeByFullName($"{codeImport}.{value}"); if (typeCode == null) { continue; } DependencyCodeTypes[typeCode.FullName] = new EntityCodeType { Type = typeCode }; return("any"); } } } var childCodeType = FindCodeTypeByFullName(fullName); if (childCodeType != null) { DependencyCodeTypes[childCodeType.FullName] = new EntityCodeType { Type = childCodeType, IsNeedImport = true }; return(childCodeType.Name.ToCamelCase()); } return(string.Empty); }
private static bool IsPrimitive(CodeTypeRef codeTypeRef) { if (codeTypeRef.TypeKind != vsCMTypeRef.vsCMTypeRefOther && codeTypeRef.TypeKind != vsCMTypeRef.vsCMTypeRefCodeType) return true; if (codeTypeRef.AsString.EndsWith("DateTime", StringComparison.Ordinal)) return true; return false; }
private static IntellisenseType GetType(ProjectItem projectItem, DefinitionMapData definitionMapData, CodeClass rootElement, CodeTypeRef codeTypeRef, HashSet <string> traversedTypes, HashSet <string> references) { var isArray = codeTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefArray; var isCollection = codeTypeRef.AsString.StartsWith("System.Collections", StringComparison.Ordinal); var isNullable = codeTypeRef.AsFullName.StartsWith("System.Nullable", StringComparison.Ordinal); var isDictionary = false; var effectiveTypeRef = codeTypeRef; if (isArray && codeTypeRef.ElementType != null) { effectiveTypeRef = effectiveTypeRef.ElementType; } else if (isCollection || isNullable) { effectiveTypeRef = TryToGuessGenericArgument(rootElement, effectiveTypeRef); } if (isCollection) { isDictionary = codeTypeRef.AsString.StartsWith("System.Collections.Generic.Dictionary", StringComparison.Ordinal); } string typeName = effectiveTypeRef.AsFullName; try { var codeClass = effectiveTypeRef.CodeType as CodeClass2; var codeEnum = effectiveTypeRef.CodeType as CodeEnum; var isPrimitive = IsPrimitive(effectiveTypeRef); // Some definitions may be defined inside of another project if (Options.AssumeExternalType == false && (codeClass != null || codeEnum != null) && effectiveTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType && effectiveTypeRef.CodeType.InfoLocation == vsCMInfoLocation.vsCMInfoLocationExternal) { // Try retrieving the external codeclass by walking all references the current project has if (TryGetExternalType(projectItem, definitionMapData, codeClass != null ? codeClass.FullName : codeEnum.FullName, out CodeClass2 externalCodeClass, out CodeEnum externalCodeEnum)) { // If successful use the new type codeClass = externalCodeClass; codeEnum = externalCodeEnum; } } var result = new IntellisenseType { IsArray = !isDictionary && (isArray || isCollection), IsDictionary = isDictionary, IsOptional = isNullable, CodeName = effectiveTypeRef.AsString }; if (effectiveTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType && (effectiveTypeRef.CodeType.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject || (Options.AssumeExternalType == false && effectiveTypeRef.CodeType.InfoLocation == vsCMInfoLocation.vsCMInfoLocationExternal))) { try { result.ClientSideReferenceName = (codeClass != null && HasIntellisense(codeClass.ProjectItem, references) ? (GetNamespace(codeClass) + "." + Utility.CamelCaseClassName(GetClassName(codeClass))) : null) ?? (codeEnum != null && HasIntellisense(codeEnum.ProjectItem, references) ? (GetNamespace(codeEnum) + "." + Utility.CamelCaseClassName(codeEnum.Name)) : null); } catch (Exception) { } } else if (Options.AssumeExternalType && effectiveTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType && effectiveTypeRef.CodeType.InfoLocation == vsCMInfoLocation.vsCMInfoLocationExternal) { try { result.ClientSideReferenceName = (codeClass != null ? (GetNamespace(codeClass) + "." + Utility.CamelCaseClassName(GetClassName(codeClass))) : null) ?? (codeEnum != null ? (GetNamespace(codeEnum) + "." + Utility.CamelCaseClassName(codeEnum.Name)) : null); } catch (Exception) { } } else { result.ClientSideReferenceName = null; } if (!isPrimitive && codeClass != null && !traversedTypes.Contains(effectiveTypeRef.CodeType.FullName) && !isCollection) { traversedTypes.Add(effectiveTypeRef.CodeType.FullName); result.Shape = GetProperties(projectItem, definitionMapData, effectiveTypeRef.CodeType.Members, traversedTypes, references).ToList(); traversedTypes.Remove(effectiveTypeRef.CodeType.FullName); } return(result); } catch (InvalidCastException) { VSHelpers.WriteOnOutputWindow(string.Format("ERROR - Cannot find definition for {0}", typeName)); throw new ArgumentException(string.Format("Cannot find definition of {0}", typeName)); } }
protected CodeTypeRef ObjectToTypeRef(object type) { if (null == type) { throw new ArgumentNullException("type"); } CodeTypeRef ctr = type as CodeTypeRef; if (ctr != null) { return(ctr); } if (type is int) { type = (vsCMTypeRef)(int)type; } if (type is vsCMTypeRef) { vsCMTypeRef typeRef = (vsCMTypeRef)type; switch (typeRef) { case vsCMTypeRef.vsCMTypeRefVoid: return(GetSystemType("System.Void")); case vsCMTypeRef.vsCMTypeRefString: return(GetSystemType("System.String")); case vsCMTypeRef.vsCMTypeRefShort: return(GetSystemType("System.Int16")); case vsCMTypeRef.vsCMTypeRefObject: return(GetSystemType("System.Object")); case vsCMTypeRef.vsCMTypeRefLong: return(GetSystemType("System.Int64")); case vsCMTypeRef.vsCMTypeRefInt: return(GetSystemType("System.Int32")); case vsCMTypeRef.vsCMTypeRefFloat: return(GetSystemType("System.Single")); case vsCMTypeRef.vsCMTypeRefDouble: return(GetSystemType("System.Double")); case vsCMTypeRef.vsCMTypeRefDecimal: return(GetSystemType("System.Decimal")); case vsCMTypeRef.vsCMTypeRefCodeType: return(GetSystemType("System.Type")); case vsCMTypeRef.vsCMTypeRefChar: return(GetSystemType("System.Char")); case vsCMTypeRef.vsCMTypeRefByte: return(GetSystemType("System.Byte")); case vsCMTypeRef.vsCMTypeRefBool: return(GetSystemType("System.Boolean")); case vsCMTypeRef.vsCMTypeRefArray: return(GetSystemType("System.Array")); case vsCMTypeRef.vsCMTypeRefVariant: case vsCMTypeRef.vsCMTypeRefPointer: case vsCMTypeRef.vsCMTypeRefOther: throw new NotImplementedException(String.Format("Unknown system type: {0}", type)); } } string stringType = type as string; if (stringType != null) { return(new CodeDomCodeTypeRef(dte, stringType)); } throw new InvalidOperationException(String.Format("unknown type to get type from: {0} ({1})", type.GetType(), type)); }
public override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeFunction originalClassCodeFuntion) { vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction; object functionType = null; functionKind = vsCMFunction.vsCMFunctionSub; functionType = vsCMTypeRef.vsCMTypeRefVoid; string nextAvailableName = originalClassCodeFuntion.Name; if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass, nextAvailableName)) { nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject); } CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction( nextAvailableName, functionKind, functionType, -1, originalClassCodeFuntion.Access, -1); bool tvIsStatic = originalClassCodeFuntion.IsShared; //add the NUnit attribute to the function unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1); try { unitTestCodeFunction.Comment = originalClassCodeFuntion.Comment; unitTestCodeFunction.DocComment = originalClassCodeFuntion.DocComment; } catch (Exception ex) { //ignore, for some reason the doc throws in vb Logger.LogException(ex); } string tvFunctionCallTemplate = string.Empty; //"iv{0}Type.{1}("; string tvFunctionReturnTemplate = string.Empty; //"{0} iv{1}Return = "; tvFunctionCallTemplate = "iv{0}Type.{1}("; if (tvIsStatic) { tvFunctionCallTemplate = "{0}.{1}("; } tvFunctionReturnTemplate = "Dim iv{1}Return As {0} = "; string tvTempParameterList = string.Empty; string tvFunctionCall = tvFunctionCallTemplate; string tvFunctionReturn = tvFunctionReturnTemplate; if (!originalClassCodeFuntion.FunctionKind.ToString().Equals("vsCMFunctionConstructor")) { CodeElements tvParameters = originalClassCodeFuntion.Parameters; foreach (CodeElement tvCodeElement in tvParameters) { if (!tvFunctionCall.Equals(tvFunctionCallTemplate)) { tvFunctionCall += ", "; } CodeParameter2 tvCodeParameter = (CodeParameter2)tvCodeElement; string parameterName = tvCodeParameter.Name; CodeTypeRef tvParameterType = tvCodeParameter.Type; vsCMParameterKind tvParameterKind = tvCodeParameter.ParameterKind; string parameterTypeAsString = tvParameterType.AsString; tvTempParameterList += "Dim " + parameterName + " As " + parameterTypeAsString + " = New " + parameterTypeAsString + "()" + Environment.NewLine + StringHelper.GetTabString(); if (tvParameterKind == vsCMParameterKind.vsCMParameterKindRef) { tvFunctionCall += parameterName; } else if (tvParameterKind == vsCMParameterKind.vsCMParameterKindOut) { tvFunctionCall += parameterName; } else if (tvParameterKind == vsCMParameterKind.vsCMParameterKindIn) { tvFunctionCall += parameterName; } else { tvFunctionCall += parameterName; } } tvFunctionCall = string.Format(tvFunctionCall + ")" + Environment.NewLine, ((CodeClass)originalClassCodeFuntion.Parent).Name, originalClassCodeFuntion.Name); } if (originalClassCodeFuntion.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid) { tvFunctionReturn = string.Format(tvFunctionReturn, originalClassCodeFuntion.Type.AsString, originalClassCodeFuntion.Name); tvFunctionCall = tvFunctionReturn + tvFunctionCall; } TextPoint bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint(); if (!originalClassCodeFuntion.FunctionKind.ToString().Equals("vsCMFunctionConstructor")) { boydEditPoint.Insert("\t\t\t' TODO: Update variable/s' defaults to meet test needs" + Environment.NewLine); boydEditPoint.Insert(StringHelper.GetTabString() + tvTempParameterList + Environment.NewLine); boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine); } if (originalClassCodeFuntion.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid) { string stringHolder = "iv{0}Return"; stringHolder = string.Format(stringHolder, originalClassCodeFuntion.Name); //FIX ME (tabing) //boydEditPoint.Insert(string.Format("\t\t\tAssert.AreEqual({0}, default({1}));\r\n", stringHolder, originalClassCodeFuntion.Type.AsString)); } boydEditPoint.Insert(Environment.NewLine); boydEditPoint.Insert("\t\t\t'TODO: Update Assert to meet test needs" + Environment.NewLine); boydEditPoint.Insert("\t\t\t'Assert.AreEqual( , )" + Environment.NewLine); boydEditPoint.Insert("\t\t\t" + Environment.NewLine); boydEditPoint.Insert("\t\t\tThrow New Exception 'Not Implemented'" + Environment.NewLine); return(unitTestCodeFunction); }
/// <summary> /// /// </summary> private void Set(CodeTypeRef type) { this._list = new List<TypeInfo>(); this._rank = 0; this._attributes = null; this._classRef = null; this.IsVoid = false; this.IsEnumerable = false; this.IsClass = false; this.MethodInfolst = null; this.EventInfolst = null; this.PropertyInfolst = null; this.type = type; switch (type.TypeKind) { case vsCMTypeRef.vsCMTypeRefArray: case vsCMTypeRef.vsCMTypeRefCodeType: case vsCMTypeRef.vsCMTypeRefBool: case vsCMTypeRef.vsCMTypeRefByte: case vsCMTypeRef.vsCMTypeRefDecimal: case vsCMTypeRef.vsCMTypeRefDouble: case vsCMTypeRef.vsCMTypeRefFloat: case vsCMTypeRef.vsCMTypeRefInt: case vsCMTypeRef.vsCMTypeRefLong: case vsCMTypeRef.vsCMTypeRefShort: case vsCMTypeRef.vsCMTypeRefVariant: case vsCMTypeRef.vsCMTypeRefChar: case vsCMTypeRef.vsCMTypeRefString: Name = type.AsString; break; case vsCMTypeRef.vsCMTypeRefVoid: Name = "void"; break; case vsCMTypeRef.vsCMTypeRefOther: case vsCMTypeRef.vsCMTypeRefPointer: case vsCMTypeRef.vsCMTypeRefObject: Name = type.AsFullName; break; } this.KindType = type.TypeKind.ToString().Substring(11); if (!(this.IsVoid = (type.TypeKind == vsCMTypeRef.vsCMTypeRefVoid))) { this.IsClass = (type.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType) || type.TypeKind == vsCMTypeRef.vsCMTypeRefString; if (!this.IsClass && type.TypeKind == vsCMTypeRef.vsCMTypeRefArray) this.IsClass = (type.Rank > 0 && type.ElementType.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType); else if (!this.IsClass && type.TypeKind != vsCMTypeRef.vsCMTypeRefOther) this.IsEnumerable = type.CodeType.get_IsDerivedFrom(typeof(System.Collections.IEnumerable).FullName); if (type.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType) if (type.CodeType.InfoLocation != vsCMInfoLocation.vsCMInfoLocationExternal) this.project = this.type.CodeType.ProjectItem.ContainingProject; } int i = 0; Parse(Name, this, ref i); DispatchType(); OnCreated(); /* vsCMTypeRefOther, vsCMTypeRefCodeType, vsCMTypeRefArray, vsCMTypeRefVoid, vsCMTypeRefPointer, vsCMTypeRefString, vsCMTypeRefObject, vsCMTypeRefByte, vsCMTypeRefChar, vsCMTypeRefShort, vsCMTypeRefInt, vsCMTypeRefLong, vsCMTypeRefFloat, vsCMTypeRefDouble, vsCMTypeRefDecimal, vsCMTypeRefBool, vsCMTypeRefVariant */ }
/// <summary> /// /// </summary> public TypeInfo(CodeTypeRef type) { Set(type); }
/// <summary> /// Creates the specified type. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static TypeInfo Create(CodeTypeRef type) { TypeInfo t = ObjectFactory.Instance.CreateType(type); return t; }
private static IntellisenseType GetType(CodeClass rootElement, CodeTypeRef codeTypeRef, HashSet<string> traversedTypes, HashSet<string> references) { var isArray = codeTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefArray; var isCollection = codeTypeRef.AsString.StartsWith("System.Collections", StringComparison.Ordinal); var effectiveTypeRef = codeTypeRef; if (isArray && codeTypeRef.ElementType != null) effectiveTypeRef = effectiveTypeRef.ElementType; else if (isCollection) effectiveTypeRef = TryToGuessGenericArgument(rootElement, effectiveTypeRef); var codeClass = effectiveTypeRef.CodeType as CodeClass2; var codeEnum = effectiveTypeRef.CodeType as CodeEnum; var isPrimitive = IsPrimitive(effectiveTypeRef); var result = new IntellisenseType { IsArray = isArray || isCollection, CodeName = effectiveTypeRef.AsString, ClientSideReferenceName = effectiveTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType && effectiveTypeRef.CodeType.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject ? (codeClass != null && HasIntellisense(codeClass.ProjectItem, Ext.TypeScript, references) ? (GetNamespace(codeClass) + "." + codeClass.Name) : null) ?? (codeEnum != null && HasIntellisense(codeEnum.ProjectItem, Ext.TypeScript, references) ? (GetNamespace(codeEnum) + "." + codeEnum.Name) : null) : null }; if (!isPrimitive && codeClass != null && !traversedTypes.Contains(effectiveTypeRef.CodeType.FullName) && !isCollection) { traversedTypes.Add(effectiveTypeRef.CodeType.FullName); result.Shape = GetProperties(effectiveTypeRef.CodeType.Members, traversedTypes, references).ToList(); traversedTypes.Remove(effectiveTypeRef.CodeType.FullName); } return result; }
/// <summary> /// /// </summary> public virtual TypeInfo CreateType(CodeTypeRef type) { return new TypeInfo(type); }
/// <summary> /// Invokes proper processing assigned to current action. /// </summary> public void Execute(object sender, EventArgs e) { CodeEditPoint point = parent.CurrentEditPoint; CodeTypeRef type = null; IList <string> names = null; if (point != null) { // check if there is variable defined: CodeVariable var = point.GetCurrentCodeElement <CodeVariable>(vsCMElement.vsCMElementVariable); type = (var != null ? var.Type : null); // or maybe clicked on parameter: if (type == null) { CodeParameter param = point.GetCurrentCodeElement <CodeParameter>(vsCMElement.vsCMElementParameter); type = (param != null ? param.Type : null); } } // extract enum values: if (type != null && type.CodeType as CodeEnum != null) { names = new List <string>(); foreach (CodeElement f in type.CodeType.Members) { names.Add(f.Name); } } if (type == null) { CodeElement elem = point.GetCurrentCodeElement <CodeElement>(vsCMElement.vsCMElementFunctionInvokeStmt); if (elem != null) { names = new List <string>(); names.Add(elem.Name); } } if (type == null && names == null) { string identifier = point.CodeExtractor.CurrentIdentifier; System.Windows.Forms.MessageBox.Show(identifier); CodeType t = point.CodeExtractor.GetTypeInfo(identifier); names = new List <string>(); if (point.CodeExtractor.Namespaces != null) { foreach (string n in point.CodeExtractor.Namespaces) { names.Add(n); } } names.Add("-----------"); names.Add(identifier); if (t != null) { foreach (CodeElement f in t.Members) { names.Add(f.Name); } } //CodeFunction elem = point.GetCurrentCodeElement<CodeFunction>(vsCMElement.vsCMElementFunction); //if (elem != null) //{ // EditPoint body = elem.StartPoint.CreateEditPoint(); // string content = body.GetText(elem.EndPoint); // names = new List<string>(); // names.Add(content); // string[] xNames = new string[] { "System.GCCollectionMode", "GCCollectionMode", point.Selection.Text}; // foreach (string n in xNames) // { // CodeType t = point.GetTypeInfo(n); // names.Add("-----------"); // names.Add(n); // if (t != null) // foreach (CodeElement f in t.Members) // names.Add(f.Name); // } //} } // and populate them into dialog if (names != null) { if (dlgExpand == null) { dlgExpand = new ExpandEnumForm(); } dlgExpand.SetUI(names); dlgExpand.ShowDialog(); } }
/// <summary> /// Get the short type name (no namespace) for CodeRef (might have arrays) /// </summary> /// <param name="codeTypeRef">CodeTypeRef the short type name of which we want</param> /// <returns>The name (including nesting classes if nested) but without namespace</returns> public static string GetNamespaceOf(CodeTypeRef codeTypeRef) { CodeTypeRef inner = codeTypeRef; while (inner.TypeKind == vsCMTypeRef.vsCMTypeRefArray) inner = inner.ElementType; if (inner.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType) return inner.CodeType.Namespace.FullName; else return string.Empty; }
private static string getArray(CodeTypeRef type) { try { return type.CodeType.FullName; } catch { return type.AsString; } }
/// <summary> /// Get the short type name (no namespace) for CodeRef (might have arrays) /// </summary> /// <param name="codeTypeRef">CodeTypeRef the short type name of which we want</param> /// <returns>The name (including nesting classes if nested) but without namespace</returns> public static string GetShortTypeName(CodeTypeRef codeTypeRef) { string suffix = string.Empty; CodeTypeRef inner = codeTypeRef; while (inner.TypeKind == vsCMTypeRef.vsCMTypeRefArray) { suffix = "[" + new string(',', inner.Rank - 1) + "]" + suffix; inner = inner.ElementType; } if (inner.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType) return GetShortTypeName(inner.CodeType) + suffix; else return inner.AsFullName + suffix; }
static string GetTypeName(CodeTypeRef type) { var name = ""; try { var elm = type.CodeType; if (elm != null) { var chain = GetChain (elm); name = GetChainName (chain.TakeWhile (x => x.Kind == vsCMElement.vsCMElementNamespace || x.IsType)); } else { name = type.AsFullName; } } catch (Exception) { } if (string.IsNullOrEmpty (name)) { name = type.AsString; } return name; }
protected void DoPrepareClassFiledSelectorData(string childForeignKeyPrefix, string childForeignKeyName, ObservableCollection <PropertySelectorViewModel> fkpp, CodeElement currentCodeElement, List <SolutionCodeElement> primKeyProps, int currentNestedLevel) { currentNestedLevel++; if (this.MaxNestedLevel < currentNestedLevel) { return; } if (fkpp == null) { return; } if (fkpp.Count > 0) { return; } if (currentCodeElement.Kind != vsCMElement.vsCMElementClass) { return; } CodeClass currentCodeClass = currentCodeElement as CodeClass; if (primKeyProps == null) { primKeyProps = GetPrimaryKeyProperties(currentCodeClass); } if (primKeyProps.Count < 1) { // throw an exception here return; } IList <CodeProperty> navigationProps = new List <CodeProperty>(); IList <String> fkeys = new List <String>(); int columnOrder = 0; foreach (CodeElement ce in currentCodeClass.Members) { fkeys.Clear(); bool isNotMapped = false; //bool keyAttrib = false; bool hasForeignAttrib = false; string foreignKeyName = ""; bool inversePropertyAttribute = false; bool requiredAttribute = false; // bool columnAttribute = false; int columnAttributeOrder = -1; String typeName = ""; bool typeIsNullable = false; if (ce.Kind != vsCMElement.vsCMElementProperty) { continue; } CodeProperty cp = ce as CodeProperty; if (cp.Access != vsCMAccess.vsCMAccessPublic) { continue; } if (cp.Type == null) { continue; } if (cp.Type.CodeType == null) { continue; } foreach (CodeElement cea in cp.Attributes) { CodeAttribute ca = cea as CodeAttribute; if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute")) { isNotMapped = true; } //if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.KeyAttribute")) //{ // keyAttrib = true; //} if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.Schema.ForeignKeyAttribute")) { hasForeignAttrib = true; foreach (CodeElement chld in ca.Children) { if (chld is CodeAttributeArgument) { foreignKeyName = (chld as CodeAttributeArgument).Value; } foreignKeyName = foreignKeyName.Replace("\"", ""); if (!string.IsNullOrEmpty(foreignKeyName)) { if (!fkeys.Contains(foreignKeyName)) { fkeys.Add(foreignKeyName); } } } } if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.Schema.InversePropertyAttribute")) { inversePropertyAttribute = true; } if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.RequiredAttribute")) { requiredAttribute = true; } if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.Schema.ColumnAttribute")) { // columnAttribute = true; foreach (CodeElement chld in ca.Children) { if ("Order".Equals(chld.Name, System.StringComparison.OrdinalIgnoreCase)) { if (chld is CodeAttributeArgument) { int val; if (int.TryParse((chld as CodeAttributeArgument).Value, out val)) { columnAttributeOrder = val; } } } } } } if (inversePropertyAttribute || isNotMapped) { continue; } CodeTypeRef ctf = cp.Type; // if CodeTypeRef.TypeKind = vsCMTypeRef.vsCMTypeRefArray the 'CodeTypeRef.ElementType' holds the type of the array Item // but in our case we will ignory Arrays if (ctf.TypeKind == vsCMTypeRef.vsCMTypeRefArray) { continue; } if (ctf.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType) { // this is ForeignKey-navigation property so it must be saved for a while if (cp.Type.CodeType.Kind == vsCMElement.vsCMElementClass) { navigationProps.Add(cp); continue; } // ICollection<T> property: this is InverseProperty(...) so it must be ignored if (cp.Type.CodeType.Kind == vsCMElement.vsCMElementInterface) { string fl = cp.Type.CodeType.FullName; if (fl != null) { fl = ""; } continue; } if (!ctf.AsFullName.StartsWith("System.Nullable")) { continue; } typeName = ctf.AsFullName.Replace("System.Nullable", "").Replace("<", "").Replace(">", "").Trim(); typeIsNullable = true; } else { typeName = ctf.AsFullName; } if (columnAttributeOrder < 0) { columnAttributeOrder = columnOrder; } ClassFiledSelectorViewModel aProperty = new ClassFiledSelectorViewModel() { OriginalPropertyName = cp.Name, ViewModelFieldName = childForeignKeyPrefix + childForeignKeyName + cp.Name, JsonPropertyFieldName = childForeignKeyPrefix + childForeignKeyName + cp.Name, FieldOrder = columnAttributeOrder, IsForeignKeyField = hasForeignAttrib, ForeignKeyName = childForeignKeyName, ForeignKeyAlias = childForeignKeyName, ChildForeignKeyPrefix = childForeignKeyPrefix, TypeFullName = ctf.AsFullName, UnderlyingTypeName = typeName, TypeIsNullable = typeIsNullable, UpdateDependent = true, UpdateNested = true, PocoName = currentCodeClass.Name, PocoFullName = currentCodeClass.FullName, HasRequiredAttribute = requiredAttribute }; if (hasForeignAttrib) { foreach (string fk in fkeys) { if (aProperty.ForeigKeyParentProperties == null) { aProperty.ForeigKeyParentProperties = new ObservableCollection <PropertySelectorViewModel>(); } PropertySelectorViewModel fko = new PropertySelectorViewModel() { ForeignKeyName = fk, ChildForeignKeyPrefix = childForeignKeyPrefix + childForeignKeyName, ForeignKeyAlias = fk, UpdateDependent = true, UpdateNested = true, }; aProperty.ForeigKeyParentProperties.Add(fko); } } fkpp.Add(aProperty); columnOrder++; } foreach (SolutionCodeElement cp in primKeyProps) { string propNmae = cp.CodeElementName; foreach (ClassFiledSelectorViewModel itm in fkpp) { if (propNmae.Equals(itm.OriginalPropertyName, StringComparison.OrdinalIgnoreCase)) { itm.IsKeyField = true; break; } } } foreach (CodeProperty cp in navigationProps) { DefineForeignKeyNodes(childForeignKeyPrefix, childForeignKeyName, cp, fkpp, currentCodeClass.Name, currentNestedLevel); } OnPropertyChanged("ForeigKeyParentProperties"); }
private StaticTypeWrapper MakeType(CodeTypeRef typeHandle) { int kind = (int)typeHandle.TypeKind; switch (kind) { case (int)vsCMTypeRef.vsCMTypeRefOther: throw new NotSupportedException("Other"); case (int)vsCMTypeRef.vsCMTypeRefCodeType: return(MakeDeclaredType(typeHandle.CodeType)); case (int)vsCMTypeRef.vsCMTypeRefArray: return(MakeType(typeHandle.ElementType).MakeArrayType(typeHandle.Rank)); case (int)vsCMTypeRef.vsCMTypeRefPointer: return(MakeType(typeHandle.ElementType).MakePointerType()); case (int)vsCMTypeRef2.vsCMTypeRefReference: return(MakeType(typeHandle.ElementType).MakeByRefType()); case (int)vsCMTypeRef2.vsCMTypeRefMCBoxedReference: throw new NotSupportedException("Boxed Reference"); case (int)vsCMTypeRef.vsCMTypeRefVoid: return(WrapNativeType(typeof(void))); case (int)vsCMTypeRef.vsCMTypeRefString: return(WrapNativeType(typeof(String))); case (int)vsCMTypeRef.vsCMTypeRefObject: return(WrapNativeType(typeof(Object))); case (int)vsCMTypeRef.vsCMTypeRefByte: return(WrapNativeType(typeof(Byte))); case (int)vsCMTypeRef2.vsCMTypeRefSByte: return(WrapNativeType(typeof(SByte))); case (int)vsCMTypeRef.vsCMTypeRefChar: return(WrapNativeType(typeof(Char))); case (int)vsCMTypeRef2.vsCMTypeRefUnsignedChar: throw new NotSupportedException("Unsigned Char"); case (int)vsCMTypeRef.vsCMTypeRefShort: return(WrapNativeType(typeof(Int16))); case (int)vsCMTypeRef2.vsCMTypeRefUnsignedShort: return(WrapNativeType(typeof(UInt16))); case (int)vsCMTypeRef.vsCMTypeRefInt: return(WrapNativeType(typeof(Int32))); case (int)vsCMTypeRef2.vsCMTypeRefUnsignedInt: return(WrapNativeType(typeof(UInt32))); case (int)vsCMTypeRef.vsCMTypeRefLong: return(WrapNativeType(typeof(Int64))); case (int)vsCMTypeRef2.vsCMTypeRefUnsignedLong: return(WrapNativeType(typeof(UInt64))); case (int)vsCMTypeRef.vsCMTypeRefFloat: return(WrapNativeType(typeof(Single))); case (int)vsCMTypeRef.vsCMTypeRefDouble: return(WrapNativeType(typeof(Double))); case (int)vsCMTypeRef.vsCMTypeRefDecimal: return(WrapNativeType(typeof(Decimal))); case (int)vsCMTypeRef.vsCMTypeRefBool: return(WrapNativeType(typeof(Boolean))); case (int)vsCMTypeRef.vsCMTypeRefVariant: throw new NotSupportedException("Variant"); default: throw new NotSupportedException("Kind: " + kind); } }
/// <summary> /// GetPrimaryKeyProperties returns the list of properties which are used as a Primary Key /// SolutionCodeElement.CodeElementRef holds CodeElement object that can be typecasted to CodeProperty /// </summary> /// <remarks> /// the following rules are applied: /// if KeyAttribute is found then "Id"-property and "ClassName"+"Id"-property will be ignoried /// if KeyAttribute is not found but there is "Id"-property then "ClassName"+"Id"-property will be ignoried /// if there is no KeyAttribute, "Id"-property and "ClassName"+"Id"-property then List<SolutionCodeElement> will be returned with Count==0 /// </remarks> protected List <SolutionCodeElement> GetPrimaryKeyProperties(CodeClass cc) { List <SolutionCodeElement> result = new List <SolutionCodeElement>(); int currOrder = -1; foreach (CodeElement ce in cc.Members) { currOrder++; if (ce.Kind != vsCMElement.vsCMElementProperty) { continue; } CodeProperty cp = ce as CodeProperty; if (cp.Access != vsCMAccess.vsCMAccessPublic) { continue; } if (cp.Type == null) { continue; } if (cp.Type.CodeType == null) { continue; } bool isNotMapped = false; foreach (CodeElement cea in cp.Attributes) { CodeAttribute ca = cea as CodeAttribute; if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute")) { isNotMapped = true; break; } } if (isNotMapped) { continue; } CodeTypeRef ctf = cp.Type; if (ctf.TypeKind == vsCMTypeRef.vsCMTypeRefArray) { continue; } if (ctf.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType) { continue; } foreach (CodeElement cea in cp.Attributes) { CodeAttribute ca = cea as CodeAttribute; if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.KeyAttribute")) { SolutionCodeElement sce = new SolutionCodeElement() { Order = currOrder, CodeElementName = ce.Name, CodeElementFullName = ce.FullName, CodeElementRef = ce }; result.Add(sce); break; } } } if (result.Count > 0) { return(result); } foreach (CodeElement ce in cc.Members) { if (ce.Kind != vsCMElement.vsCMElementProperty) { continue; } CodeProperty cp = ce as CodeProperty; if (cp.Access != vsCMAccess.vsCMAccessPublic) { continue; } if (cp.Type == null) { continue; } if (cp.Type.CodeType == null) { continue; } CodeTypeRef ctf = cp.Type; if (ctf.TypeKind == vsCMTypeRef.vsCMTypeRefArray) { continue; } if (ctf.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType) { continue; } if ("Id".Equals(cp.Name, StringComparison.OrdinalIgnoreCase)) { SolutionCodeElement sce = new SolutionCodeElement() { Order = currOrder, CodeElementName = ce.Name, CodeElementFullName = ce.FullName, CodeElementRef = ce }; result.Add(sce); return(result); } } if (result.Count > 0) { return(result); } string[] names = cc.FullName.Split(new char[] { '.' }); string typeName = names[names.Length - 1]; string propName = typeName + "Id"; foreach (CodeElement ce in cc.Members) { if (ce.Kind != vsCMElement.vsCMElementProperty) { continue; } CodeProperty cp = ce as CodeProperty; if (cp.Access != vsCMAccess.vsCMAccessPublic) { continue; } if (cp.Type == null) { continue; } if (cp.Type.CodeType == null) { continue; } CodeTypeRef ctf = cp.Type; if (ctf.TypeKind == vsCMTypeRef.vsCMTypeRefArray) { continue; } if (ctf.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType) { continue; } if (propName.Equals(cp.Name, StringComparison.OrdinalIgnoreCase)) { SolutionCodeElement sce = new SolutionCodeElement() { Order = currOrder, CodeElementName = ce.Name, CodeElementFullName = ce.FullName, CodeElementRef = ce }; result.Add(sce); return(result); } } return(result); }
private static IntellisenseType GetType(CodeClass rootElement, CodeTypeRef codeTypeRef, HashSet <string> traversedTypes, HashSet <string> references) { var isArray = codeTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefArray; var isCollection = codeTypeRef.AsString.StartsWith("System.Collections", StringComparison.Ordinal); var isDictionary = false; var effectiveTypeRef = codeTypeRef; if (isArray && codeTypeRef.ElementType != null) { effectiveTypeRef = effectiveTypeRef.ElementType; } else if (isCollection) { effectiveTypeRef = TryToGuessGenericArgument(rootElement, effectiveTypeRef); } if (isCollection) { isDictionary = codeTypeRef.AsString.StartsWith("System.Collections.Generic.Dictionary", StringComparison.Ordinal); } string typeName = effectiveTypeRef.AsFullName; try { var codeClass = effectiveTypeRef.CodeType as CodeClass2; var codeEnum = effectiveTypeRef.CodeType as CodeEnum; var isPrimitive = IsPrimitive(effectiveTypeRef); var result = new IntellisenseType { IsArray = !isDictionary && (isArray || isCollection), IsDictionary = isDictionary, CodeName = effectiveTypeRef.AsString }; if (effectiveTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType && effectiveTypeRef.CodeType.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject) { if (codeClass != null && HasIntellisense(codeClass.ProjectItem, references)) { string ns = GetNamespace(codeClass); if (!string.IsNullOrEmpty(ns)) { ns += "."; } result.ClientSideReferenceName = ns + Utility.CamelCaseClassName(GetClassName(codeClass)); } else if (codeEnum != null && HasIntellisense(codeEnum.ProjectItem, references)) { string ns = GetNamespace(codeEnum); if (!string.IsNullOrEmpty(ns)) { ns += "."; } result.ClientSideReferenceName = ns + Utility.CamelCaseClassName(codeEnum.Name); } } if (!isPrimitive && codeClass != null && !traversedTypes.Contains(effectiveTypeRef.CodeType.FullName) && !isCollection) { traversedTypes.Add(effectiveTypeRef.CodeType.FullName); result.Shape = GetProperties(effectiveTypeRef.CodeType.Members, traversedTypes, references).ToList(); traversedTypes.Remove(effectiveTypeRef.CodeType.FullName); } return(result); } catch (InvalidCastException) { VSHelpers.WriteOnOutputWindow(string.Format("ERROR - Cannot find definition for {0}", typeName)); throw new ArgumentException(string.Format("Cannot find definition of {0}", typeName)); } }
protected void DefineForeignKeyNodes(string childForeignKeyPrefix, string childForeignKeyName, CodeProperty masterCodeProp, IList <PropertySelectorViewModel> list, string detailClassName, int currentNestedLevel) { CodeClass masterCodeClass = masterCodeProp.Type.CodeType as CodeClass; string masterCodePropName = masterCodeProp.Name; List <SolutionCodeElement> primKeyProps = GetPrimaryKeyProperties(masterCodeClass); // SolutionCodeElement.CodeElementRef holds 'CodeProperty' // collect ColumnAttributes to define order if (primKeyProps.Count < 1) { // throw an exception here return; } ////////////////////////////////////////////////// /// The 1st case: /// --------- /// public class DetailType { /// /// public int MasterRefId1 { get; set; } /// public int MasterRefId2 { get; set; } /// /// [ForeignKey("MasterRefId1")] /// [ForeignKey("MasterRefId2")] /// public MasterType MasterProp { get; set; } /// } ////////////////////////////////////////////////// foreach (CodeElement cea in masterCodeProp.Attributes) { string foreignKeyName = ""; CodeAttribute ca = cea as CodeAttribute; if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.Schema.ForeignKeyAttribute")) { foreach (CodeElement chld in ca.Children) { if (chld is CodeAttributeArgument) { foreignKeyName = (chld as CodeAttributeArgument).Value; } foreignKeyName = foreignKeyName.Replace("\"", ""); } foreach (ClassFiledSelectorViewModel itm in list) { if (foreignKeyName.Equals(itm.OriginalPropertyName)) { PropertySelectorViewModel fk = null; if (itm.ForeigKeyParentProperties == null) { itm.ForeigKeyParentProperties = new ObservableCollection <PropertySelectorViewModel>(); } else { fk = itm.ForeigKeyPPByForeignKN(masterCodePropName); } if (fk == null) { fk = new PropertySelectorViewModel() { ForeignKeyName = masterCodePropName }; itm.IsForeignKeyField = true; itm.ForeigKeyParentProperties.Add(fk); } } } } } ////////////////////////////////////////////////// /// The 2nd case: /// --------- /// public class DetailType { /// /// public int MasterRefId1 { get; set; } /// public int MasterRefId2 { get; set; } /// } /// public class MasterType { /// [ForeignKey("MasterRefId1")] /// [ForeignKey("MasterRefId2")] /// public ICollection<DetailType> DetailProps { get; set; } /// } ////////////////////////////////////////////////// if (!string.IsNullOrEmpty(detailClassName)) { foreach (CodeElement ce in masterCodeClass.Members) { if (ce.Kind != vsCMElement.vsCMElementProperty) { continue; } CodeProperty loopCodeProp = ce as CodeProperty; if (loopCodeProp.Access != vsCMAccess.vsCMAccessPublic) { continue; } if (loopCodeProp.Type == null) { continue; } if (loopCodeProp.Type.CodeType == null) { continue; } bool isNotMapped = false; foreach (CodeElement cea in loopCodeProp.Attributes) { CodeAttribute ca = cea as CodeAttribute; if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute")) { isNotMapped = true; break; } } if (isNotMapped) { continue; } CodeTypeRef ctRef = loopCodeProp.Type; if (ctRef.TypeKind == vsCMTypeRef.vsCMTypeRefArray) { continue; } if (ctRef.TypeKind != vsCMTypeRef.vsCMTypeRefCodeType) { continue; } if (ctRef.CodeType.Kind != vsCMElement.vsCMElementInterface) { continue; } string className = ctRef.CodeType.FullName.Replace("System.Collections.Generic.ICollection<", "").Replace(">", "").Trim(); if (!detailClassName.Equals(className, StringComparison.OrdinalIgnoreCase)) { continue; } // look for InversePropertyAttribute string inversePropertyName = ""; foreach (CodeElement cea in loopCodeProp.Attributes) { CodeAttribute ca = cea as CodeAttribute; if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.Schema.InversePropertyAttribute")) { foreach (CodeElement chld in ca.Children) { if (chld is CodeAttributeArgument) { inversePropertyName = (chld as CodeAttributeArgument).Value; } inversePropertyName = inversePropertyName.Replace("\"", ""); } } } if (!string.IsNullOrEmpty(inversePropertyName)) { if (!inversePropertyName.Equals(masterCodePropName, StringComparison.OrdinalIgnoreCase)) { continue; } } foreach (CodeElement cea in loopCodeProp.Attributes) { string foreignKeyName = ""; CodeAttribute ca = cea as CodeAttribute; if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.Schema.ForeignKeyAttribute")) { foreach (CodeElement chld in ca.Children) { if (chld is CodeAttributeArgument) { foreignKeyName = (chld as CodeAttributeArgument).Value; } foreignKeyName = foreignKeyName.Replace("\"", ""); } foreach (ClassFiledSelectorViewModel itm in list) { if (foreignKeyName.Equals(itm.OriginalPropertyName)) { PropertySelectorViewModel fk = null; if (itm.ForeigKeyParentProperties == null) { itm.ForeigKeyParentProperties = new ObservableCollection <PropertySelectorViewModel>(); } else { fk = itm.ForeigKeyPPByForeignKN(masterCodePropName); } if (fk == null) { fk = new PropertySelectorViewModel() { ForeignKeyName = masterCodePropName }; itm.ForeigKeyParentProperties.Add(fk); itm.IsForeignKeyField = true; } } } } } } } string[] names = masterCodeProp.Type.AsFullName.Split(new char[] { '.' }); string masterTypeName = names[names.Length - 1]; //masterCodePropName foreach (SolutionCodeElement primKeyProp in primKeyProps) { string primKeyPropName = primKeyProp.CodeElementName; if ("Id".Equals(primKeyPropName, StringComparison.OrdinalIgnoreCase)) { primKeyPropName = masterTypeName + primKeyPropName; } string fkNm = masterCodePropName + primKeyPropName; if (DefineForeigKeyNodeByForeigKeyFiledName(list, fkNm, masterCodePropName)) { continue; } fkNm = masterTypeName + primKeyPropName; if (DefineForeigKeyNodeByForeigKeyFiledName(list, fkNm, masterCodePropName)) { continue; } DefineForeigKeyNodeByForeigKeyFiledName(list, primKeyPropName, masterCodePropName); } // collect all foreign key fields for the given navigation property: masterCodePropName List <ClassFiledSelectorViewModel> fcflds = new List <ClassFiledSelectorViewModel>(); foreach (ClassFiledSelectorViewModel itm in list) { if (itm.ForeigKeyParentProperties == null) { continue; } if (itm.ForeigKeyPPByForeignKN(masterCodePropName) == null) { continue; } fcflds.Add(itm); } if (fcflds.Count > 1) { fcflds.Sort((x, y) => x.FieldOrder - y.FieldOrder); } if (primKeyProps.Count > 1) { foreach (SolutionCodeElement sce in primKeyProps) { CodeProperty cp = sce.CodeElementRef as CodeProperty; foreach (CodeElement cea in cp.Attributes) { bool OrderIsFound = false; CodeAttribute ca = cea as CodeAttribute; if (ca.FullName.Contains("System.ComponentModel.DataAnnotations.Schema.ColumnAttribute")) { foreach (CodeElement chld in ca.Children) { if ("Order".Equals(chld.Name, System.StringComparison.OrdinalIgnoreCase)) { if (chld is CodeAttributeArgument) { int val; if (int.TryParse((chld as CodeAttributeArgument).Value, out val)) { sce.Order = val; OrderIsFound = true; break; } } } } } if (OrderIsFound) { break; } } } primKeyProps.Sort((x, y) => x.Order - y.Order); } int Count = primKeyProps.Count; if (Count > fcflds.Count) { Count = fcflds.Count; } for (int i = 0; i < Count; i++) { ClassFiledSelectorViewModel cfsvm = fcflds[i]; PropertySelectorViewModel psvm = cfsvm.ForeigKeyPPByForeignKN(masterCodePropName); psvm.OriginalPropertyName = primKeyProps[i].CodeElementName; CodeProperty cp = primKeyProps[i].CodeElementRef as CodeProperty; psvm.TypeFullName = cp.Type.AsFullName; psvm.UnderlyingTypeName = cp.Type.AsFullName; psvm.TypeIsNullable = false; psvm.PocoName = masterCodeClass.Name; psvm.PocoFullName = masterCodeClass.FullName; if (currentNestedLevel + 1 <= this.MaxNestedLevel) { psvm.ForeigKeyParentProperties = new ObservableCollection <PropertySelectorViewModel>(); DoPrepareClassFiledSelectorData(psvm.ChildForeignKeyPrefix, psvm.ForeignKeyName, psvm.ForeigKeyParentProperties, masterCodeClass as CodeElement, primKeyProps, currentNestedLevel); } } }
/// <summary> /// Determines whether the supplied CodeTypeRef represents the specified .NET type. /// This requires that the CodeTypeRef be attached to a parent code element so we can detect /// what language it is written in; otherwise we'll throw an InvalidOperationException. /// </summary> public static bool IsType <T>(this CodeTypeRef codeTypeRef) { return(codeTypeRef.IsType(typeof(T))); }
private static IntellisenseType GetType(CodeClass rootElement, CodeTypeRef codeTypeRef, HashSet <string> traversedTypes, HashSet <string> references) { var isArray = codeTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefArray; var isCollection = codeTypeRef.AsString.StartsWith("System.Collections", StringComparison.Ordinal); var isDictionary = false; var effectiveTypeRef = codeTypeRef; if (isArray && codeTypeRef.ElementType != null) { effectiveTypeRef = effectiveTypeRef.ElementType; } else if (isCollection) { effectiveTypeRef = TryToGuessGenericArgument(rootElement, effectiveTypeRef); } if (isCollection) { isDictionary = codeTypeRef.AsString.StartsWith("System.Collections.Generic.Dictionary", StringComparison.Ordinal) || codeTypeRef.AsString.StartsWith("System.Collections.Generic.IDictionary", StringComparison.Ordinal); } string typeName = effectiveTypeRef.AsFullName; try { //VSHelpers.WriteOnBuildDebugWindow($"%{(effectiveTypeRef.CodeType as CodeInterface2) != null}%"); var codeInterface = effectiveTypeRef.CodeType as CodeInterface2; var codeClass = effectiveTypeRef.CodeType as CodeClass2; var codeEnum = effectiveTypeRef.CodeType as CodeEnum; var isPrimitive = IsPrimitive(effectiveTypeRef); //VSHelpers.WriteOnBuildDebugWindow($"###{effectiveTypeRef.CodeType.GetType().FullName}"); var result = new IntellisenseType { IsArray = !isDictionary && (isArray || isCollection), IsDictionary = isDictionary, CodeName = effectiveTypeRef.AsString }; //VSHelpers.WriteOnBuildDebugWindow($"#{result.CodeName}#{result.TypeScriptName}#{effectiveTypeRef.AsString}#{effectiveTypeRef.AsFullName}#{effectiveTypeRef.CodeType}"); //VSHelpers.WriteOnBuildDebugWindow($"##{effectiveTypeRef.TypeKind}##{vsCMTypeRef.vsCMTypeRefCodeType}##{effectiveTypeRef.CodeType.InfoLocation}##{vsCMInfoLocation.vsCMInfoLocationProject}"); result.ClientSideReferenceName = null; if (effectiveTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType) { var hasIntellisense = Options.IgnoreIntellisense; if (effectiveTypeRef.CodeType.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject) { if (codeClass != null) { hasIntellisense = HasIntellisense(codeClass.ProjectItem, references); } if (codeEnum != null) { hasIntellisense = HasIntellisense(codeEnum.ProjectItem, references); } } //VSHelpers.WriteOnBuildDebugWindow($"@{codeClass != null}@{codeEnum != null}@{hasIntellisense}@{Options.DeclareModule}"); result.ClientSideReferenceName = (codeClass != null && hasIntellisense ? (Options.DeclareModule ? GetNamespace(codeClass) + "." : "") + Utility.CamelCaseClassName(GetClassName(codeClass)) : null) ?? (codeEnum != null && hasIntellisense ? (Options.DeclareModule ? GetNamespace(codeEnum) + "." : "") + Utility.CamelCaseClassName(GetEnumName(codeEnum)) : null) ?? (codeInterface != null && hasIntellisense ? (Options.DeclareModule ? GetNamespace(codeInterface) + "." : "") + Utility.CamelCaseClassName(GetInterfaceName(codeInterface)) : null); } if (!isPrimitive && (codeClass != null || codeEnum != null) && !traversedTypes.Contains(effectiveTypeRef.CodeType.FullName) && !isCollection) { traversedTypes.Add(effectiveTypeRef.CodeType.FullName); result.Shape = GetProperties(effectiveTypeRef.CodeType.Members, traversedTypes, references).ToList(); traversedTypes.Remove(effectiveTypeRef.CodeType.FullName); } return(result); } catch (InvalidCastException) { VSHelpers.WriteOnOutputWindow(string.Format("ERROR - Cannot find definition for {0}", typeName)); throw new ArgumentException(string.Format("Cannot find definition of {0}", typeName)); } }
/// <summary> /// Determines whether the supplied CodeTypeRef represents a primitive .NET type, e.g., /// byte, bool, float, etc. /// </summary> public static bool IsPrimitive(this CodeTypeRef codeTypeRef) { // A possible optimization would be checking codeTypeRef.TypeKind for known primitive // types, e.g., vsCMTypeRef.vsCMTypeRefDouble. Consider adding this logic in future. return(_primitiveTypes.Any(primitiveType => codeTypeRef.IsType(primitiveType))); }
public VsBindingType(CodeTypeRef type) { FullName = type.AsFullName; int lastPeriodIndex = FullName.LastIndexOf('.'); Name = lastPeriodIndex >= 0 ? FullName.Substring(lastPeriodIndex + 1) : FullName; }
/// <summary> /// Had to use regex, getting it through CodeClass is too complicated /// </summary> /// <param name="setClassName"></param> /// <returns></returns> private static string GetDbsetGenericParameter(CodeTypeRef codeElement) { return _GetExistingSets_Regex.Replace(codeElement.AsFullName, _GetExistingSets_ReplacePattern); }
public string GetParamValue(CodeTypeRef member, string paramName, int depth) { var strippedMember = StripGenerics(member); // if (member.CodeType == null) return "Error"; if (member == null) { return("Error"); } AddNameSpace(member); if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefArray) { //array return(GetArrayParamValue(member, depth)); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType && strippedMember.AsString == "System.DateTime") { //DateTime var year = DateTime.Now.Year; var month = DateTime.Now.Month; var day = DateTime.Now.Day; return(string.Format("new DateTime({0}, {1}, {2})", year, month, day)); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType && strippedMember.CodeType != null && strippedMember.CodeType.Members != null && strippedMember.CodeType.Members.Count > 0 && strippedMember.CodeType.Kind == vsCMElement.vsCMElementEnum) { //Enums return(strippedMember.CodeType.Members.Item(1).FullName); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType && strippedMember.AsString == "System.Guid") { //Guid return(string.Format("new Guid(\"{0}\")", Guid.NewGuid())); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType && IsCodeTypeAList(strippedMember.CodeType.Name)) { return(GetListParamValue(member, depth)); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType) { var paramsInConstructorStr = string.Empty; if (strippedMember.CodeType.Members != null) { //var constructor = member.CodeType.Members.OfType<CodeFunction>().FirstOrDefault(x => x.FunctionKind == vsCMFunction.vsCMFunctionConstructor); var constructor = strippedMember.CodeType.Members.OfType <CodeFunction>().FirstOrDefault(x => x.FunctionKind == vsCMFunction.vsCMFunctionConstructor); if (constructor != null && constructor.Kind == vsCMElement.vsCMElementFunction) { paramsInConstructorStr = GenerateFunctionParamValues(constructor, false); } } var includedNewLineInParams = string.Empty; //var initializerStr = IterateMembers(member.CodeType, depth); var initializerStr = IterateMembers(strippedMember.CodeType, depth); if (string.IsNullOrWhiteSpace(initializerStr) == false) { includedNewLineInParams = "\r\n"; initializerStr += Spacing.Get(depth); } //defined types/objects we have created return(string.Format("new {0}({2}) {{{3}{1}}}", strippedMember.AsString, initializerStr, paramsInConstructorStr, includedNewLineInParams)); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefString) { //string return(string.Format("\"{0}\"", Words.Gen(_opts.WordsInStrings))); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefChar) { //char var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return("'" + chars[StaticRandom.Instance.Next(0, chars.Length)] + "'"); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefBool) { //bool return(StaticRandom.Instance.Next(0, 1) == 1 ? "true" : "false"); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefDecimal || strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefDouble || strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefFloat || strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefInt || strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefLong || strippedMember.AsString == "uint" || strippedMember.AsString == "ulong") { //numbers (except short) if (_opts.IntLength == 0) { return("0"); } return(StaticRandom.Instance.Next(_opts.GetMaxIntLength()).ToString()); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefShort) { //short if (_opts.IntLength == 0) { return("0"); } var maxRnd = _opts.IntLength > 4 ? 9999 : _opts.GetMaxIntLength(); return(StaticRandom.Instance.Next(maxRnd).ToString()); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefByte) { //byte return("new Byte()"); } else if (strippedMember.TypeKind == vsCMTypeRef.vsCMTypeRefObject) { //object return("new Object()"); } else if (strippedMember.AsString == "sbyte") { //sbyte return(StaticRandom.Instance.Next(-128, 127).ToString()); } else if (strippedMember.AsString == "ushort") //no, YOU'RE SHORT! { //ushort return(StaticRandom.Instance.Next(65535).ToString()); } else { //skip return(""); } }
private static void GetSerializeMethodAndDeserializeMethodName(CodeTypeRef codeTypeRef, string typeFullName, ref string serializeMethodName, ref string deserializeMethodName, string suffix = "", Dictionary<string, CodeClass2> dic = null, TyrantVSPackage package = null) { string fullName = codeTypeRef != null ? codeTypeRef.AsFullName : typeFullName; if (fullName == typeof(bool).FullName) { serializeMethodName = $"WriteBoolean{suffix}"; deserializeMethodName = $"ReadBoolean{suffix}"; } else if (fullName == typeof(double).FullName) { serializeMethodName = $"WriteDouble{suffix}"; deserializeMethodName = $"ReadDouble{suffix}"; } else if (fullName == typeof(sbyte).FullName) { serializeMethodName = $"WriteSByte{suffix}"; deserializeMethodName = $"ReadSByte{suffix}"; } else if (fullName == typeof(short).FullName) { serializeMethodName = $"WriteInt16{suffix}"; deserializeMethodName = $"ReadInt16{suffix}"; } else if (fullName == typeof(int).FullName) { serializeMethodName = $"WriteInt32{suffix}"; deserializeMethodName = $"ReadInt32{suffix}"; } else if (fullName == typeof(long).FullName) { serializeMethodName = $"WriteInt64{suffix}"; deserializeMethodName = $"ReadInt64{suffix}"; } else if (fullName == typeof(float).FullName) { serializeMethodName = $"WriteSingle{suffix}"; deserializeMethodName = $"ReadSingle{suffix}"; } else if (fullName == typeof(string).FullName) { serializeMethodName = $"WriteString{suffix}"; deserializeMethodName = $"ReadString{suffix}"; } else if (fullName == typeof(byte).FullName) { serializeMethodName = $"WriteByte{suffix}"; deserializeMethodName = $"ReadByte{suffix}"; } else if (fullName == typeof(char).FullName) { serializeMethodName = $"WriteChar{suffix}"; deserializeMethodName = $"ReadChar{suffix}"; } else if (fullName == typeof(ushort).FullName) { serializeMethodName = $"WriteUInt16{suffix}"; deserializeMethodName = $"ReadUInt16{suffix}"; } else if (fullName == typeof(uint).FullName) { serializeMethodName = $"WriteUInt32{suffix}"; deserializeMethodName = $"ReadUInt32{suffix}"; } else if (fullName == typeof(ulong).FullName) { serializeMethodName = $"WriteUInt64{suffix}"; deserializeMethodName = $"ReadUInt64{suffix}"; } else if (fullName == typeof(TimeSpan).FullName) { serializeMethodName = $"WriteTimeSpan{suffix}"; deserializeMethodName = $"ReadTimeSpan{suffix}"; } else if (fullName == typeof(DateTime).FullName) { serializeMethodName = $"WriteDateTime{suffix}"; deserializeMethodName = $"ReadDateTime{suffix}"; } else { bool b = false; if (codeTypeRef != null) b = IsSerializableClass(codeTypeRef.CodeType as CodeClass2) || IsMessageClass(codeTypeRef.CodeType as CodeClass2); else if (typeFullName != null) { if (dic == null) dic = CommunicationCodeInMenuCommand.GetClassElements(package); CodeClass2 classElement; dic.TryGetValue(typeFullName, out classElement); b = IsSerializableClass(classElement) || IsMessageClass(classElement); } if (b) { serializeMethodName = $"WriteSerializableObject{suffix}"; deserializeMethodName = $"ReadSerializableObject{suffix}<{fullName}>"; } } }
public string GenerateFunctionParamForClassInput(CodeTypeRef codeTypeRef) { var strippedCodeTypeRef = StripGenerics(codeTypeRef); var fullName = strippedCodeTypeRef.AsFullName.Replace("?", ""); var name = strippedCodeTypeRef.CodeType.Name.Replace("?", ""); if (ClassGenerator.IsCodeTypeAList(name)) { var baseType = TryToGuessGenericArgument(codeTypeRef); if (baseType == null) { return(null); } name = baseType.CodeType.Name + "List"; fullName = strippedCodeTypeRef.AsFullName.Replace("?", ""); } var exists = _parts.ParamsGenerated.FirstOrDefault(x => x.FullName == fullName); if (exists != null) { return(exists.GetFunctionName); //do not add a 2nd one } var functionName = string.Format("Get{0}", name); //if (functionName == "GetList") // { // var asdasdsad = 55; // } //_parts.ParamsGenerated keeps a list of functions that will get the value of the object we generated _parts.ParamsGenerated.Add(new ParamsGenerated() { FullName = fullName, GetFunctionName = functionName }); string innerCode; if (functionName == "GetTask") { innerCode = "new Task()"; } else { innerCode = GetParamValue(codeTypeRef, string.Empty, 3); } if (innerCode.Contains("Task")) { var asdasd = 444; } var gen = string.Format(@" private static {0} {1}() {{ return {2}; }} ", fullName, functionName, innerCode); _parts.ParamInputs += gen; return(functionName); }
private static CodeTypeRef TryToGuessGenericArgument(CodeClass rootElement, CodeTypeRef codeTypeRef) { var codeTypeRef2 = codeTypeRef as CodeTypeRef2; if (codeTypeRef2 == null || !codeTypeRef2.IsGeneric) return codeTypeRef; // There is no way to extract generic parameter as CodeTypeRef or something similar // (see http://social.msdn.microsoft.com/Forums/vstudio/en-US/09504bdc-2b81-405a-a2f7-158fb721ee90/envdte-envdte80-codetyperef2-and-generic-types?forum=vsx) // but we can make it work at least for some simple case with the following heuristic: // 1) get the argument's local name by parsing the type reference's full text // 2) if it's a known primitive (i.e. string, int, etc.), return that // 3) otherwise, guess that it's a type from the same namespace and same project, // and use the project CodeModel to retrieve it by full name // 4) if CodeModel returns null - well, bad luck, don't have any more guesses var typeNameAsInCode = codeTypeRef2.AsString.Split('<', '>').ElementAtOrDefault(1) ?? ""; CodeModel projCodeModel; try { projCodeModel = rootElement.ProjectItem.ContainingProject.CodeModel; } catch (COMException) { projCodeModel = ProjectHelpers.GetActiveProject().CodeModel; } var codeType = projCodeModel.CodeTypeFromFullName(TryToGuessFullName(typeNameAsInCode)); if (codeType != null) return projCodeModel.CreateCodeTypeRef(codeType); return codeTypeRef; }
public CodeTypeRef TryToGuessGenericArgument(CodeTypeRef member) { try { if (member.AsFullName.Contains("<") == false) { return(member); //No need to attempt to guess, this is not a generic class } //todo check if we need to cast to CodeTypeRef2 here var codeTypeRef2 = member as CodeTypeRef2; if (codeTypeRef2 == null || !codeTypeRef2.IsGeneric) { return(member); } // There is no way to extract generic parameter as CodeTypeRef or something similar // (see http://social.msdn.microsoft.com/Forums/vstudio/en-US/09504bdc-2b81-405a-a2f7-158fb721ee90/envdte-envdte80-codetyperef2-and-generic-types?forum=vsx) // but we can make it work at least for some simple case with the following heuristic: // 1) get the argument's local name by parsing the type reference's full text // 2) if it's a known primitive (i.e. string, int, etc.), return that // 3) otherwise, guess that it's a type from the same namespace and same project, // and use the project CodeModel to retrieve it by full name // 4) if CodeModel returns null - well, bad luck, don't have any more guesses var typeNameAsInCode = DTEHelper.RemoveTaskFromString(codeTypeRef2.AsFullName); // var typeNameAsInCode = codeTypeRef2.AsString.Replace("?", ""); //typeNameAsInCode = typeNameAsInCode.Split('<', '>').ElementAtOrDefault(1) ?? ""; typeNameAsInCode = typeNameAsInCode.Split('<', '>').ElementAtOrDefault(1) ?? typeNameAsInCode; try { CodeModel projCodeModel = ((CodeElement)member.Parent).ProjectItem.ContainingProject.CodeModel; if (projCodeModel == null) { return(member); } var codeType = projCodeModel.CodeTypeFromFullName(typeNameAsInCode); if (codeType != null) { return(projCodeModel.CreateCodeTypeRef(codeType)); } return(member); } catch (COMException ex) { var found = CheckForTypeInOtherPlaces(typeNameAsInCode); if (found != null) { return(found); } } if (member.AsFullName.Contains("Task<")) { return(null); //we failed, might as well throw error } if (member.AsFullName.Contains("List<")) { return(null); //we failed, might as well throw error } return(member); } catch (Exception ex) { return(member); } }
private static bool IsBindableType(CodeTypeRef type) { return(type.IsPrimitiveType() || bindableNonPrimitiveTypes.Any(x => type.IsMatchForReflectionType(x))); }
/// <summary> /// Returns CodeTypeRef.AsFullName, if null, returns CodeTypeRef.AsString /// </summary> /// <param name="ctr"></param> /// <returns></returns> /// <remarks> /// If there's compile error AsFullName will be null /// </remarks> public static string SafeFullName(this CodeTypeRef ctr) { return(ctr.AsFullName ?? ctr.AsString); }