protected override void Visit(CodeProperty property) { if (property.XmlDoc != null) { Visit(property.XmlDoc); } VisitList(property.CustomAttributes); Visit(property.Type); Visit(property.Name); if (property.Getter != null) { VisitList(property.Getter); } if (property.Setter != null) { VisitList(property.Setter); } if (property.Initializer != null) { Visit(property.Initializer); } if (property.TrailingComment != null) { Visit(property.TrailingComment); } }
public async Task ParsesQueryParametersWithSpaces() { using var request = new HttpRequestMessage(HttpMethod.Get, $"{ServiceRootUrl}/roleManagement/directory/roleAssignments?$filter=roleDefinitionId eq '62e90394-69f5-4237-9190-012177145e10'&$expand=principal"); var snippetModel = new SnippetModel(request, ServiceRootUrl, await GetV1TreeNode()); var result = new SnippetCodeGraph(snippetModel); Assert.True(result.HasParameters()); Assert.Equal(2, result.Parameters.Count()); var expectedProperty1 = new CodeProperty { Name = "filter", Value = "roleDefinitionId eq '62e90394-69f5-4237-9190-012177145e10'", PropertyType = PropertyType.String }; var actualParam1 = result.Parameters.First(); Assert.Equal(expectedProperty1, actualParam1); var expectedProperty2 = new CodeProperty { Value = "principal", PropertyType = PropertyType.String }; var actualParam2 = result.Parameters.Skip(1).First(); Assert.Equal("expand", actualParam2.Name); Assert.Equal(expectedProperty2, actualParam2.Children[0]); }
private void AddDataFieldAttribute(CodeProperty prop, DBObject obj, Column v) { string propType = v.IsPrimaryKey ? "DataAccess.Core.Attributes.Key" : "DataAccess.Core.Attributes.DataField"; string propValue = string.Format("FieldName=\"{0}\"{1}{2}", v.Name, GetDefaultValueString(v), GetFieldTypeString(v)); prop.AddAttribute(propType, propValue); }
public async Task ArrayParametersSplitOnExternalCommas() { using var requestPayload = new HttpRequestMessage(HttpMethod.Get, $"{ServiceRootUrl}/groups?$expand=members($select=id,displayName),teams($select=id,displayName)"); var result = new SnippetCodeGraph(requestPayload, ServiceRootUrl, await GetV1TreeNode()); Assert.True(result.HasParameters()); Assert.Single(result.Parameters); var param = result.Parameters.First(); Assert.Equal("expand", param.Name); Assert.Equal(PropertyType.Array, param.PropertyType); Assert.Equal(2, param.Children.Count); var expectedProperty1 = new CodeProperty { Value = "members($select=id,displayName)", PropertyType = PropertyType.String }; Assert.Equal(param.Children.First(), expectedProperty1); var expectedProperty2 = new CodeProperty { Value = "teams($select=id,displayName)", PropertyType = PropertyType.String }; Assert.Equal(param.Children.Skip(1).First(), expectedProperty2); }
/// <summary> /// Adds the attribute. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="attributeValue">The attribute value.</param> public static void AddAttribute(CodeProperty element, string attributeName, string attributeValue) { if (!HasAttribute(element, attributeName)) { element.AddAttribute(attributeName, attributeValue, 0); } }
/// <summary> /// Adds the property. /// </summary> /// <param name="codeClass">The code class.</param> /// <param name="var">The var.</param> /// <returns></returns> public static CodeProperty AddProperty(CodeClass codeClass, CodeVariable var) { CodeProperty prop = null; try { prop = codeClass.AddProperty( FormatPropertyName(var.Name), FormatPropertyName(var.Name), var.Type.AsFullName, -1, vsCMAccess.vsCMAccessPublic, null); EditPoint editPoint = prop.Getter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); //Delete return default(int); added by codeClass.AddProperty editPoint.Delete(editPoint.LineLength); editPoint.Indent(null, 4); editPoint.Insert(string.Format(CultureInfo.InvariantCulture, "return {0};", var.Name)); editPoint = prop.Setter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.Indent(null, 1); editPoint.Insert(string.Format(CultureInfo.InvariantCulture, "{0} = value;", var.Name)); editPoint.SmartFormat(editPoint); return(prop); } catch { //Property already exists return(null); } }
private static void AddDocCommentToProperty(CodeProperty codeProperty) { if (AddGhostDogCommand(codeProperty as CodeElement)) { RemoveValueTagFromDocComment(codeProperty); } }
private void GeneratePropertyCode(CodeProperty propDecl) { foreach (CodeComment commentDecl in propDecl.Comments) { GenerateCommentCode(commentDecl); } WriteAttributes(propDecl.Attributes); Output.Write(GetClrTypeName(propDecl.Type.Type)); Output.Write(" "); Output.Write(propDecl.Name); WriteBlockStart(CodeGenBlockType.Method); if (propDecl.GetterBody != null) { WriteIndent(); Output.Write("get"); WriteBlockStart(CodeGenBlockType.Method); GenerateMethodBodyCode(propDecl.GetterBody); WriteBlockEnd(CodeGenBlockType.Method); } if (propDecl.SetterBody != null) { WriteIndent(); Output.Write("set"); WriteBlockStart(CodeGenBlockType.Method); GenerateMethodBodyCode(propDecl.SetterBody); WriteBlockEnd(CodeGenBlockType.Method); } WriteBlockEnd(CodeGenBlockType.Method); }
public static MemberDeclarationSyntax Generate(CodeProperty codeProperty) { var fieldDeclaration = GenerateFieldMember(codeProperty.Type, codeProperty.Name); var currentCode = ((SyntaxNode)fieldDeclaration).NormalizeWhitespace().ToFullString(); return(fieldDeclaration); }
public RelatedEntityInfo(RelationType relationType, string relationName, CodeProperty relationProperty, CodeType relatedEntityType, string relatedEntityPrimaryKeyName, CodeProperty lazyLoadingProperty) { if (string.IsNullOrEmpty(relationName)) { throw new ArgumentException("'relationName' cannot be null or empty."); } if (relationProperty == null) { throw new ArgumentNullException("relationProperty"); } if (relatedEntityType == null) { throw new ArgumentNullException("relatedEntityType"); } if ((relationType == RelationType.Parent) && string.IsNullOrEmpty(relatedEntityPrimaryKeyName)) { throw new ArgumentException("'relatedEntityPrimaryKeyName' cannot be null or empty for parent entities."); } RelationType = relationType; RelationName = relationName; RelationNamePlural = Pluralize(relationName); RelationProperty = relationProperty; RelatedEntityType = relatedEntityType; RelatedEntityTypeNamePlural = Pluralize(relatedEntityType.Name); RelatedEntityPrimaryKeyName = relatedEntityPrimaryKeyName; LazyLoadingProperty = lazyLoadingProperty; }
internal static bool IsDSAClass(CodeClass codeClass) { bool hasOnlineProxyType = false; bool hasEndpoint = false; foreach (CodeElement element in codeClass.Members) { CodeProperty property = element as CodeProperty; if (property != null && property.Access == vsCMAccess.vsCMAccessPublic && property.Name == "OnlineProxyType") { hasOnlineProxyType = true; } if (property != null && property.Access == vsCMAccess.vsCMAccessPublic && property.Name == "Endpoint") { hasEndpoint = true; } if (hasOnlineProxyType && hasEndpoint) { return(true); } } return(false); }
private void AssosiatedTypes(CodeElement codeElement) { CodeElements ces = null; if (codeElement is CodeClass) { ces = (codeElement as CodeClass).Members; } else if (codeElement is CodeInterface) { ces = (codeElement as CodeInterface).Members; } else { return; } foreach (CodeElement property in ces) { CodeProperty prop = property as CodeProperty; if (prop != null) { Debug.WriteLine(prop.Type.CodeType); string i = string.Format(associationExpression, codeElement.Name, prop.Type.CodeType.Name); AppendExpression(i); } } }
public CodePropertyWriterTests() { writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.CSharp, DefaultPath, DefaultName); tw = new StringWriter(); writer.SetTextWriter(tw); var root = CodeNamespace.InitRootNamespace(); parentClass = new CodeClass { Name = "parentClass" }; root.AddClass(parentClass); property = new CodeProperty { Name = PropertyName, Type = new CodeType { Name = TypeName }, }; parentClass.AddProperty(property, new() { Name = "pathParameters", Kind = CodePropertyKind.PathParameters, }, new() { Name = "requestAdapter", Kind = CodePropertyKind.RequestAdapter, }); }
private string PropertyToString(CodeProperty codeProperty) { try { string s = codeProperty.Type.AsString; try { if (codeProperty.Getter != null) { s = s + " get{} "; } } catch { } try { if (codeProperty.Setter != null) { s = s + " set{} "; } } catch { } return(s); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.Message, "AS VS Expert: PropertyToString"); return(""); } }
public void WriteDeserializer(CodeProperty property, string expected) { parentClass.Kind = CodeClassKind.Model; var deserializerMethod = new CodeMethod() { Name = "getDeserializationFields", Kind = CodeMethodKind.Deserializer, Description = "Just some random method", ReturnType = new CodeType { IsNullable = false, CollectionKind = CodeTypeBase.CodeTypeCollectionKind.Array, Name = "array" } }; parentClass.AddMethod(deserializerMethod); parentClass.AddProperty(property); _refiner.Refine(parentClass.Parent as CodeNamespace); languageWriter.Write(deserializerMethod); if (property.ExistsInBaseType) { Assert.DoesNotContain(expected, stringWriter.ToString()); } else { Assert.Contains(expected, stringWriter.ToString()); } }
internal static bool CanGenerateHandleCodeProperty(string testClassFixturePostFix, CodeClass parentCodeClass, CodeProperty codeProperty, Project unitTestProject) { foreach (ProjectItem projectItem in unitTestProject.ProjectItems) { List<CodeClass> lstProjectCodeClasses = UTGManagerAndExaminor.ProjectItemExaminor.GetCodeClasses(projectItem.FileCodeModel); foreach (CodeClass codeClass in lstProjectCodeClasses) { if ((parentCodeClass.Name + testClassFixturePostFix).Equals(codeClass.Name)) { foreach (CodeElement codeElement in codeClass.Members) { if (codeElement is CodeProperty) { if (codeProperty.Name.Equals(((CodeProperty)codeElement).Name)) return false; } } } } } return true; }
private static bool IsScaffoldColumn(CodeProperty propertyType) { bool flag; IEnumerator enumerator = propertyType.Attributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CodeAttribute current = (CodeAttribute)enumerator.Current; if (!string.Equals(current.FullName, TypeNames.ScaffoldColumnAttributeTypeName, StringComparison.Ordinal)) { continue; } flag = CodeModelPropertyMetadata.IsPropertyValuePresent(current, string.Empty, "true"); return(flag); } return(true); } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } return(flag); }
private void setPropWithAttributes(CodeProperty property) { foreach (var ele in property.Attributes) { var prop = ele as CodeAttribute; if (prop.Name == "Required") { this.Required = true; this.Nullable = false; } if (prop.Name == "MaxLength") { int v = 0; int.TryParse(prop.Value, out v); this.MaxLength = v; } if (prop.Name == "Range") { var arr = prop.Value.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); int n1 = 0, n2 = 0; int.TryParse(arr[0], out n1); int.TryParse(arr[1], out n2); this.RangeMin = n1; this.RangeMax = n2; } } }
private bool Evaluate(out object newValue) { newValue = null; CodeClass currentDSAClass = ExpressionEvaluationHelper.EvaluateExpression((IDictionaryService)GetService(typeof(IDictionaryService)), currentDSAClassExpression) as CodeClass; if (currentDSAClass != null) { CodeProperty onlineProxyTypeProperty = CodeModelHelper.GetProperty(currentDSAClass, "OnlineProxyType", vsCMAccess.vsCMAccessPublic); if (onlineProxyTypeProperty != null) { CodeFunction getMethod = onlineProxyTypeProperty.Getter; EditPoint edit = getMethod.StartPoint.CreateEditPoint(); EditPoint endpoint = null; TextRanges tags = null; if (edit.FindPattern(@"(typeof|GetType)\((.+)\)", (int)vsFindOptions.vsFindOptionsRegularExpression, ref endpoint, ref tags)) { EditPoint begin = edit.CreateEditPoint(); string proxyTypeName = begin.GetText(endpoint); Regex extractRegex = new Regex(@"(typeof|GetType)\((.+)\)"); if (extractRegex.IsMatch(proxyTypeName) && extractRegex.Match(proxyTypeName).Groups.Count == 3) { proxyTypeName = extractRegex.Match(proxyTypeName).Groups[2].Value; newValue = proxyTypeName; return(true); } } } } return(false); }
//public MetaColumnInfo() { } //public MetaColumnInfo(Microsoft.AspNet.Scaffolding.Core.Metadata.PropertyMetadata property) // : this(property.PropertyName, property.PropertyName, property.ShortTypeName, (property.RelatedModel != null)) //{ //} //public MetaColumnInfo(CodeParameter property) // : this(property.Name, property.DocComment, property.Type.AsString, false) //{ //} //public MetaColumnInfo(CodeProperty property) // : this(property.Name, property.DocComment, property.Type.AsString, false) //{ //} //private MetaColumnInfo(string strName, string strDisplayName, string strType, bool relatedModel) //{ // this.Name = strName; // this.ShortTypeName = strType; // this.strDataType = strType.Replace("?", "").Replace("System.", "").ToLower(); // if (!relatedModel) // { // this.DataType = GetColumnType(this.strDataType); // IsVisible = true; // } // else // { // this.DataType = euColumnType.RelatedModel; // IsVisible = false; //不勾选导航属性 // } // DisplayName = strDisplayName ?? this.Name; // Nullable = true; //} public MetaColumnInfo(CodeProperty property) { string strName = property.Name; string strType = property.Type.AsString; string strDisplayName = VmUtils.getCName(property); this.Name = property.Name; this.ShortTypeName = property.Type.AsString; //this.strDataType = strType.Replace("?", "").Replace("System.", "").ToLower(); //this.strDataType = strType.Replace("System.", ""); this.strDataType = strType.Split('.').Last(); this.DataType = GetColumnType(strType); DisplayName = strDisplayName ?? this.Name; Nullable = true; Required = false; setPropWithAttributes(property); if (strDataType.ToLower() == "int" || strDataType.ToLower() == "guid") { Nullable = false; } this.ControlType = GetControlType(); //放在setPropWithAttributes之后 IsDtoVisible = IsDtoVisibleMember(); IsItemVisible = IsItemVisibleMember(); }
/// <summary> /// Determine if property is auto generated. /// </summary> /// <param name="prop">Property to be tested.</param> /// <returns>True if prop is auto generated property.</returns> public static bool IsAutoProperty(this CodeProperty prop) { try { var pGetter = prop.Getter as CodeFunction; var pSetter = prop.Setter as CodeFunction; if (pGetter == null || pSetter == null) { //auto generated property has to have both setter, getter return(false); } if (pGetter.Language == CSharpSyntax.LanguageID) { //C# can determine auto properties faster than by throwing exceptions var start = pGetter.StartPoint.CreateEditPoint(); var text = start.GetText(pGetter.EndPoint); return(!text.Contains("{")); } if ((pGetter as CodeElement).GetBody() == null) { return(true); } return(false); } catch (COMException) { //we cant access to property -> will be autogenerated. return(true); } }
private static string GetName(CodeProperty property) { foreach (CodeAttribute attr in property.Attributes) { var className = Path.GetExtension(attr.Name); if (string.IsNullOrEmpty(className)) { className = attr.Name; } string[] argumentNames; if (!nameAttributes.TryGetValue(className, out argumentNames)) { continue; } var value = attr.Children.OfType <CodeAttributeArgument>().FirstOrDefault(a => argumentNames.Contains(a.Name)); if (value == null) { break; } // Strip the leading & trailing quotes return(value.Value.Substring(1, value.Value.Length - 2)); } return(property.Name); }
/// <summary> /// Adds a new type to the types and localizables cache, examinig given CodeProperty for the Localizable attribute /// </summary> public void AddType(string typeName, string propertyName, CodeProperty property) { if (typeName == null) { throw new ArgumentNullException("typeName"); } if (propertyName == null) { throw new ArgumentNullException("propertyName"); } bool hasLocalizableFalseSet = false; Type propertyType = null; try { propertyType = Type.GetType(property.Type.AsFullName, false, false); // get its name and save it in cache hasLocalizableFalseSet = (property as CodeElement).HasLocalizableFalseAttribute(); } catch (Exception) { } string fullName = typeName + "." + propertyName; if (!Types.ContainsKey(fullName)) { Types.Add(fullName, propertyType); Localizables.Add(fullName, hasLocalizableFalseSet); } else { Types[fullName] = propertyType; Localizables[fullName] = hasLocalizableFalseSet; } }
private bool TryGetMember( TypeScriptInterface interfaceContext, CodeProperty property, TypeContext typeContext, out TypeScriptMember member) { member = null; if (!this.settings.MemberAccessTypes.Contains(property.Access)) { return(false); } var getter = property.Getter; if (getter == null) { return(false); } string name = property.Name; if (name.StartsWith("@")) { name = name.Substring(1); } member = new TypeScriptMember { Name = name, Type = typeContext.GetTypeReference( TypeName.ParseDte(getter.Type.AsFullName), interfaceContext) }; return(true); }
/// <summary> /// Retrieves the properties. /// </summary> /// <param name="entity">The entity.</param> /// <param name="members">The members.</param> private static void RetrieveProperties(Entity entity, CodeElements members) { foreach (CodeElement codeElement in members) { CodeProperty prop = codeElement as CodeProperty; if (prop == null) { continue; } if (prop.Access != vsCMAccess.vsCMAccessPublic) { continue; } // Operation Property p = FindProperty(entity, prop); if (p == null) { p = new Property(entity.Store); p.Name = prop.Name; p.ColumnName = prop.Name; p.Comment = ImportInterfaceHelper.NormalizeComment(prop.DocComment); p.Type = prop.Type.AsString; p.IsCollection = prop.Type.TypeKind == vsCMTypeRef.vsCMTypeRefArray; entity.Properties.Add(p); } } }
private bool IsItemExpandable(ListViewItem item) { int index = item.Index; if (item.ImageIndex != 2) { return(false); } CodeProperty prop = (CodeProperty)item.SubItems[1].Tag; if (prop.Type == null) { return(false); } if (prop.Type.TypeKind != vsCMTypeRef.vsCMTypeRefCodeType) { return(false); } if (prop.Type.CodeType == null) { return(false); } if (prop.Type.CodeType.Namespace.FullName == "System") { return(false); } //if (prop.Type.CodeType.Namespace.FullName == "Iesi.Collections") return false; if (prop.Type.CodeType.Kind == vsCMElement.vsCMElementEnum) { return(false); } return(true); }
private static RelatedEntityInfo GetRelatedParentEntityInfo(CodeProperty property, IEnumerable<CodeProperty> allCandidateProperties, Project project, IProjectTypeLocator projectTypeLocator) { // First, we need to be able to extract "SomeType" from properties called "SomeTypeID" // "SomeType" is the name of the relation, and either corresponds to an entity type, or to another property whose type is an entity if (!property.Name.EndsWith(PropertySuffix, StringComparison.OrdinalIgnoreCase)) return null; var relationName = property.Name.Substring(0, property.Name.Length - PropertySuffix.Length); if (string.IsNullOrEmpty(relationName)) return null; // Next, "SomeType" needs to correspond to plausible entity or be the name of another property whose type is a plausible entity List<CodeType> foundRelatedEntityTypes; var propertyNameComparison = VsConstants.VbCodeModelLanguageGuid.Equals(property.Language, StringComparison.OrdinalIgnoreCase) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; var matchesOtherCandidateProperty = allCandidateProperties.FirstOrDefault(x => string.Equals(x.Name, relationName, propertyNameComparison)); if ((matchesOtherCandidateProperty != null) && (matchesOtherCandidateProperty.Type != null) && (matchesOtherCandidateProperty.Type.CodeType != null)) foundRelatedEntityTypes = new[] { matchesOtherCandidateProperty.Type.CodeType }.ToList(); else foundRelatedEntityTypes = projectTypeLocator.FindTypes(project, relationName).Distinct().ToList(); // Get the primary key info for each possible type match so we can check it's a plausible entity. var foundRelatedEntityTypesPlusPrimaryKeyInfo = (from relatedEntityType in foundRelatedEntityTypes select new { type = relatedEntityType, primaryKeys = PrimaryKeyLocation.GetPrimaryKeys(relatedEntityType).ToList() }).ToList(); // It's only a plausible entity if it has a single primary key, so filter out ones that don't, then ensure we're left with an unambiguous match foundRelatedEntityTypesPlusPrimaryKeyInfo.RemoveAll(x => x.primaryKeys.Count != 1); if (foundRelatedEntityTypesPlusPrimaryKeyInfo.Count != 1) return null; return new RelatedEntityInfo(RelationType.Parent, relationName, property, foundRelatedEntityTypesPlusPrimaryKeyInfo.Single().type, foundRelatedEntityTypesPlusPrimaryKeyInfo.Single().primaryKeys.Single().Name, matchesOtherCandidateProperty); }
public void WriteConstructorBody() { var constructor = new CodeMethod() { Name = "constructor", Access = AccessModifier.Public, Description = "The constructor for this class", ReturnType = new CodeType() { Name = "void" }, Kind = CodeMethodKind.Constructor }; parentClass.AddMethod(constructor); var propWithDefaultValue = new CodeProperty() { Name = "type", DefaultValue = "\"#microsoft.graph.entity\"", Kind = CodePropertyKind.Custom }; parentClass.AddProperty(propWithDefaultValue); _codeMethodWriter.WriteCodeElement(constructor, languageWriter); var result = stringWriter.ToString(); Assert.Contains("public function __construct", result); Assert.Contains("$this->setType('#microsoft.graph.entity')", result); }
private bool TryGetMember(CodeProperty property, TypeContext typeContext, out TypeScriptInterfaceMember member) { member = null; if (property.Access != vsCMAccess.vsCMAccessPublic) { return(false); } var getter = property.Getter; if (getter == null) { return(false); } var values = GetMemberValues(property, typeContext); member = new TypeScriptInterfaceMember { Name = values.Name ?? property.Name, FullName = property.FullName, Optional = values.Optional, Type = (string.IsNullOrWhiteSpace(values.Type)) ? typeContext.GetTypeScriptType(getter.Type) : new CustomType(values.Type) }; if (values.CamelCase && values.Name == null) { member.Name = member.Name.Substring(0, 1).ToLowerInvariant() + member.Name.Substring(1); } return(true); }
private TypeScriptMemberAttributeValues GetMemberValues(CodeProperty property, TypeContext typeContext) { bool? attributeOptional = null; bool? attributeCamelCase = null; string attributeName = null; string attributeType = null; CodeAttribute attribute; if (TryGetAttribute(property.Attributes, MemberAttributeFullName, out attribute)) { var values = GetAttributeValues(attribute); if (values.ContainsKey("Optional")) { attributeOptional = values["Optional"] == "true"; } if (values.ContainsKey("CamelCase")) { attributeCamelCase = values["CamelCase"] == "true"; } values.TryGetValue("Name", out attributeName); values.TryGetValue("Type", out attributeType); } return(new TypeScriptMemberAttributeValues { Optional = attributeOptional.HasValue ? attributeOptional.Value : Settings.DefaultOptional, Name = attributeName, Type = attributeType, CamelCase = attributeCamelCase ?? Settings.DefaultCamelCaseMemberNames }); }
public static PropertyViewModel ToViewModel(this CodeProperty property, EntityViewModel entityModel = null) { PropertyViewModel model = IoC.Get <PropertyViewModel>(); model = property.MapTo(model); model.Entity = entityModel; return(model); }
public PropertyNode(CodeProperty cp, CodeModelEditorForm context) : base(CodeModelEditor.BrowseKind.ClassProperty, context) { base.Tag = cp; base.ImageKey = "Property"; base.SelectedImageKey = "Property"; SetText(cp.Name); }
private static bool CodePropertyHasAttributeWithArgValue(CodeProperty codeProperty, Type attributeType, string argName, string value, StringComparison valueComparer) { return (from attrib in codeProperty.Attributes.OfType<CodeAttribute2>() where attrib.FullName == attributeType.FullName from arg in attrib.Arguments.OfType<CodeAttributeArgument>() where arg.Name.Equals(argName, valueComparer) && arg.Value.Equals(value, valueComparer) select arg).Any(); }
/// <summary> /// Determines if the specified code property is an explicit interface implementation. /// </summary> /// <param name="codeProperty">The code property.</param> /// <returns>True if an explicit interface implementation, otherwise false.</returns> public static bool IsExplicitInterfaceImplementation(CodeProperty codeProperty) { // In VS2013 and earlier, the name was reported including the interface name. if (codeProperty.Name.Contains(".")) { return true; } var declaration = CodeElementHelper.GetPropertyDeclaration(codeProperty); var matchString = @"\." + codeProperty.Name; return Regex.IsMatch(declaration, matchString); }
/// <summary> /// Determines if the specified code property is an explicit interface implementation. /// </summary> /// <param name="codeProperty">The code property.</param> /// <returns>True if an explicit interface implementation, otherwise false.</returns> public static bool IsExplicitInterfaceImplementation(CodeProperty codeProperty) { // In some VS editions, the name may be reported including the interface name. if (codeProperty.Name.Contains(".")) { return true; } // Otherwise, look for the element name with a preceding dot. var declaration = CodeElementHelper.GetPropertyDeclaration(codeProperty); var matchString = @"\." + codeProperty.Name; return RegexNullSafe.IsMatch(declaration, matchString); }
public CodeModelPropertyMetadata(CodeProperty property) { if (property == null) { throw new ArgumentNullException("property"); } PropertyName = property.Name; TypeName = property.Type.AsFullName; ShortTypeName = property.Type.AsString; IsPrimaryKey = IsPropertyPrimaryKey(property); IsAutoGenerated = IsPrimaryKey; IsReadOnly = !property.HasPublicSetter(); Scaffold = IsScaffoldColumn(property); }
public RelatedEntityInfo(RelationType relationType, string relationName, CodeProperty relationProperty, CodeType relatedEntityType, string relatedEntityPrimaryKeyName, CodeProperty lazyLoadingProperty) { if (string.IsNullOrEmpty(relationName)) throw new ArgumentException("'relationName' cannot be null or empty."); if (relationProperty == null) throw new ArgumentNullException("relationProperty"); if (relatedEntityType == null) throw new ArgumentNullException("relatedEntityType"); if ((relationType == RelationType.Parent) && string.IsNullOrEmpty(relatedEntityPrimaryKeyName)) throw new ArgumentException("'relatedEntityPrimaryKeyName' cannot be null or empty for parent entities."); RelationType = relationType; RelationName = relationName; RelationNamePlural = Pluralize(relationName); RelationProperty = relationProperty; RelatedEntityType = relatedEntityType; RelatedEntityTypeNamePlural = Pluralize(relatedEntityType.Name); RelatedEntityPrimaryKeyName = relatedEntityPrimaryKeyName; LazyLoadingProperty = lazyLoadingProperty; }
/// <summary> /// This function verifies if the specified property is a primary key based on common conventions. The result /// returned by this function may not be accurate. In order to get accurate results for primary key properties /// <see cref="EntityMetadata"/> should be used. /// </summary> private static bool IsPropertyPrimaryKey(CodeProperty propertyType) { if (String.Equals(propertyType.Name, "id", StringComparison.OrdinalIgnoreCase)) { // EF Code First convention return true; } if (String.Equals(propertyType.Name, propertyType.Parent.Name + "id", StringComparison.OrdinalIgnoreCase)) { // EF Code First convention return true; } foreach (CodeAttribute attribute in propertyType.Attributes) { // WCF RIA Services and EF Code First explicit if (String.Equals(attribute.FullName, TypeNames.KeyAttributeTypeName, StringComparison.Ordinal)) { return true; } // EF traditional if (String.Equals(attribute.FullName, TypeNames.EdmScalarPropertyAttributeTypeName, StringComparison.Ordinal)) { if (IsPropertyValuePresent(attribute: attribute, name: "EntityKeyProperty", value: "true")) { return true; } } // LINQ to SQL if (String.Equals(attribute.FullName, TypeNames.ColumnAttributeTypeName, StringComparison.Ordinal)) { if (IsPropertyValuePresent(attribute: attribute, name: "IsPrimaryKey", value: "true")) { return true; } } } return false; }
private static CodeType ExtractFirstGenericArgOfCollectionType(CodeProperty property, Project project, IProjectTypeLocator projectTypeLocator) { // This is difficult for VB types because the API won't let us know the generic args when scanning the type hierarchy. // We can see if a type implements ICollection<T>, but there's no way to know what T is. So, try to spot some // common collection types at the CodeTypeRef level where VB gives us a string representation of the closed generic type. var genericArg = ExtractFirstGenericArgOfSpecificCollectionType(property.Type, property.Language, typeof (List<>), typeof (IList<>), typeof(Collection<>), typeof (ICollection<>), typeof (EntitySet<>)); // If this failed, then for C# types at least, we can scan up the inheritance hierarchy looking for something that implements ICollection<T> if (string.IsNullOrEmpty(genericArg)) { if (!string.Equals(property.Language, VsConstants.VbCodeModelLanguageGuid, StringComparison.OrdinalIgnoreCase)) genericArg = ExtractFirstGenericArgOfImplementedICollectionInterface(property.Type.CodeType as CodeClass); } // Convert the string representation of the collection element type to a project-local CodeType if (string.IsNullOrEmpty(genericArg)) return null; var foundTypes = projectTypeLocator.FindTypes(project, genericArg).ToList(); if (foundTypes.Count != 1) // Only accept unambiguous match return null; return foundTypes.Single(); }
public bool IsPrimaryKey(CodeClass codeClass, CodeProperty codeProperty) { return codeProperty.Attributes.OfType<CodeAttribute2>().Any(x => x.FullName == typeof(KeyAttribute).FullName); }
// External items throw an exception from the DocComment getter private static string GetSummary(CodeProperty property) { return property.InfoLocation != vsCMInfoLocation.vsCMInfoLocationProject ? null : GetSummary(property.InfoLocation, property.DocComment, property.Comment, property.FullName); }
private static string GetName(CodeProperty property) { foreach (CodeAttribute attr in property.Attributes) { var className = Path.GetExtension(attr.Name); if (string.IsNullOrEmpty(className)) className = attr.Name; string[] argumentNames; if (!nameAttributes.TryGetValue(className, out argumentNames)) continue; var value = attr.Children.OfType<CodeAttributeArgument>().FirstOrDefault(a => argumentNames.Contains(a.Name)); if (value == null) break; // Strip the leading & trailing quotes return value.Value.Substring(1, value.Value.Length - 2); } return property.Name; }
/// <summary> /// Gets the declaration of the specified code property as a string. /// </summary> /// <param name="codeProperty">The code property.</param> /// <returns>The string declaration.</returns> internal static string GetPropertyDeclaration(CodeProperty codeProperty) { // Get the start point at the end of the attributes if there are any (vsCMPartHeader is // not available for properties). var startPoint = codeProperty.Attributes.Count > 0 ? codeProperty.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter) : codeProperty.StartPoint; return TextDocumentHelper.GetTextToFirstMatch(startPoint, @"\{"); }
private bool TryGetMember(CodeProperty property, TypeContext typeContext, out TypeScriptInterfaceMember member) { member = null; if (property.Access != vsCMAccess.vsCMAccessPublic) return false; var getter = property.Getter; if (getter == null) return false; var values = GetMemberValues(property, typeContext); string name; if (values.Name != null) { name = values.Name; } else { name = property.Name; if (name.StartsWith("@")) name = name.Substring(1); } member = new TypeScriptInterfaceMember { Name = name, //FullName = property.FullName, Optional = values.Optional, Ignore = values.Ignore, Type = (string.IsNullOrWhiteSpace(values.Type)) ? typeContext.GetTypeScriptType(getter.Type) : new InterfaceType(values.Type) }; if (member.Ignore) return false; if (values.CamelCase && values.Name == null) member.Name = member.Name.Substring(0, 1).ToLowerInvariant() + member.Name.Substring(1); return true; }
private static RelatedEntityInfo GetRelatedChildEntityInfo(CodeProperty property, Project project, IProjectTypeLocator projectTypeLocator) { // We are only interested in properties that implement ICollection<TEntity> var collectionElementType = ExtractFirstGenericArgOfCollectionType(property, project, projectTypeLocator); if (collectionElementType == null) return null; // The element type has to be plausibly an entity, meaning that it has a single primary key var collectionElementTypePrimaryKeys = PrimaryKeyLocation.GetPrimaryKeys(collectionElementType).ToList(); if (collectionElementTypePrimaryKeys.Count != 1) return null; return new RelatedEntityInfo(RelationType.Child, property.Name, property, collectionElementType, collectionElementTypePrimaryKeys.Single().Name, property); }
internal static void HandelCodeClassSelection(AbstractTestFramework testFramework, CodeProperty property, DTE2 applicationObject, UnitTestCodeType codeType) { Project parentProject = ProjectExaminar.GetCodeClassParentProject((CodeClass)property.Parent); Project unitTestProject = ProjectExaminar.GetUnitTestProject(parentProject.Name, applicationObject, testFramework.TestProjectPostFix); //We might or might not use this factory, we don't know at this point AbstractTestClassFactory testClassFactory = new NUnitTestClassFactory(); foreach (ProjectItem projectItem in unitTestProject.ProjectItems) { System.Collections.Generic.List<CodeClass> lstCodeClasses = ProjectItemExaminor.GetCodeClasses(projectItem.FileCodeModel); foreach (CodeClass codeClass in lstCodeClasses) { if (codeClass.Name.Equals(((CodeClass)property.Parent).Name + testFramework.TestClassFixturePostFix)) { //if found AbstractTestClass nunitClass = null; if (codeType == UnitTestCodeType.CSharp) { nunitClass = testClassFactory.CreateCSharpTestClass(codeClass.Namespace.FullName, codeClass.Name, codeClass.IsAbstract); } else if (codeType == UnitTestCodeType.VB) { nunitClass = testClassFactory.CreateVBTestClass(codeClass.Namespace.FullName, codeClass.Name, codeClass.IsAbstract); } nunitClass.GenerateTest(codeClass, property); //we sure expect just one class, the first class we find matching return; } } } //if we have reached this point then it means that we have not been able to locate a parent class in our //unit test project, then we simply create a class unit test OnCodeClassSelection(testFramework, (CodeClass)property.Parent, (CodeElement)property, applicationObject, unitTestProject, codeType); }
internal ShellCodeProperty(CodeProperty property) : base(property as CodeElement) { _property = property; }
private static bool IsPrimaryKey(CodeClass codeClass, CodeProperty codeProperty) { return PrimaryKeyLocators.Any(x => x.IsPrimaryKey(codeClass, codeProperty)); }
public bool IsPrimaryKey(CodeClass codeClass, CodeProperty codeProperty) { return CodePropertyHasAttributeWithArgValue(codeProperty, typeof(EdmScalarPropertyAttribute), "EntityKeyProperty", bool.TrueString, StringComparison.OrdinalIgnoreCase); }
public bool IsPrimaryKey(CodeClass codeClass, CodeProperty codeProperty) { return string.Equals("id", codeProperty.Name, StringComparison.OrdinalIgnoreCase); }
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 void OnCodeClassSelection(AbstractTestFramework testFramework, CodeProperty ce, DTE2 applicationObject, UnitTestCodeType codeType) { Project parentProject = ProjectExaminar.GetCodeClassParentProject((CodeClass)ce.Parent); Project unitTestProject = ProjectExaminar.GetUnitTestProject(parentProject.Name, applicationObject, testFramework.TestProjectPostFix); if (unitTestProject == null) { OnCodeClassSelection(testFramework, (CodeClass)ce.Parent, (CodeElement)ce, applicationObject, codeType); return; } //In cases where we can not simply generate automatically (definition already exists) we will //ask the user for input, wait on input, then async back to the function actual useful handler //HandelCodeClassSelection if (!CanGenerateHandleCodeProperty(testFramework.TestClassFixturePostFix, (CodeClass)ce.Parent, ce, unitTestProject)) { UTGHelper.UserAlertActionRequired tvUserAlertActionRequired = new UserAlertActionRequired( "Property definition already exits! What would you like to do?", typeof(CodeProperty), (CodeElement)ce, ref applicationObject, codeType, testFramework); if (!tvUserAlertActionRequired.IsDisposed) { tvUserAlertActionRequired.FormClosed += new System.Windows.Forms.FormClosedEventHandler(tvUserAlertActionRequired_FormClosed); tvUserAlertActionRequired.Show(); } else { HandelCodeClassSelection(testFramework, ce, applicationObject, codeType); } return; } //otherwise simply call HandelCodeClassSelection HandelCodeClassSelection(testFramework, ce, applicationObject, codeType); }
private static string GetName(CodeProperty property) { foreach (CodeAttribute attr in property.Attributes) { if (attr.Name != "DataMember" && !attr.Name.EndsWith(".DataMember")) continue; var value = attr.Children.OfType<CodeAttributeArgument>().FirstOrDefault(p => p.Name == "Name"); if (value == null) break; // Strip the leading & trailing quotes return value.Value.Substring(1, value.Value.Length - 2); } return property.Name; }
public abstract CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeProperty originalClassCodeProperty);
private TypeScriptMemberAttributeValues GetMemberValues(CodeProperty property, TypeContext typeContext) { bool? attributeOptional = null; bool? attributeCamelCase = null; bool attributeIgnore = false; string attributeName = null; string attributeType = null; CodeAttribute attribute; if (TryGetAttribute(property.Attributes, MemberAttributeFullName, out attribute)) { var values = GetAttributeValues(attribute); bool parsedProperty; if (values.ContainsKey("Optional") && bool.TryParse(values["Optional"], out parsedProperty)) attributeOptional = parsedProperty; if (values.ContainsKey("CamelCase") && bool.TryParse(values["CamelCase"], out parsedProperty)) attributeCamelCase = parsedProperty; if (values.ContainsKey("Ignore") && bool.TryParse(values["Ignore"], out parsedProperty)) attributeIgnore = parsedProperty; values.TryGetValue("Name", out attributeName); values.TryGetValue("Type", out attributeType); } return new TypeScriptMemberAttributeValues { Optional = attributeOptional.HasValue ? attributeOptional.Value : Settings.DefaultOptional, Name = attributeName, Type = attributeType, CamelCase = attributeCamelCase ?? Settings.DefaultCamelCaseMemberNames, Ignore = attributeIgnore }; }
/// <summary> /// Determines if the specified code property is an explicit interface implementation. /// </summary> /// <param name="codeProperty">The code property.</param> /// <returns>True if an explicit interface implementation, otherwise false.</returns> public static bool IsExplicitInterfaceImplementation(CodeProperty codeProperty) { return codeProperty != null && codeProperty.Name.Contains("."); }
/// <summary> /// Determines whether the specified element has attribute. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <returns> /// <c>true</c> if the specified element has attribute; otherwise, <c>false</c>. /// </returns> public static bool HasAttribute(CodeProperty element, string attributeName) { if(element.Attributes.Count > 0) { foreach(CodeElement att in element.Attributes) { CodeAttribute codeAttribute = (CodeAttribute)att; if(att.Name.Equals(attributeName, StringComparison.InvariantCultureIgnoreCase)) { return true; } } } return false; }
private static bool CheckIfCodeClassInheritsProperty(CodeClass codeClass, CodeProperty codeProperty) { List<CodeInterface> implementedInterfaces = codeClass.GetImplementedInterfaces(); if ( SearchService.SearchInCodeElements<CodeProperty>(implementedInterfaces.OfType<CodeElement>()) .Any( p => p.Name == codeProperty.Name && p.Kind == codeProperty.Kind && p.Type.AsFullName == codeProperty.Type.AsFullName && p.Access == codeClass.Access)) { return true; } return false; }
private static string GetSummary(CodeProperty property) { if (string.IsNullOrWhiteSpace(property.DocComment)) return null; try { return XElement.Parse(property.DocComment) .Descendants("summary") .Select(x => x.Value) .FirstOrDefault(); } catch (Exception ex) { Logger.Log("Couldn't parse XML Doc Comment for " + property.FullName + ":\n" + ex); return null; } }