internal static EnvDTE.CodeElements Create(
     CodeModelState state,
     CodeAttribute parent)
 {
     var collection = new AttributeArgumentCollection(state, parent);
     return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection);
 }
Exemplo n.º 2
0
        internal static EnvDTE80.CodeAttributeArgument Create(CodeModelState state, CodeAttribute parent, int index)
        {
            Debug.Assert(parent != null);
            Debug.Assert(index >= 0);

            var newElement = new CodeAttributeArgument(state, parent, index);
            return (EnvDTE80.CodeAttributeArgument)ComAggregate.CreateAggregatedObject(newElement);
        }
Exemplo n.º 3
0
        public CodeAttribute Serialize(BuildingContext context)
        {
            // Verify stack.
            if (ComputeMaxStackOnBuild)
            {
                MaxStack = ComputeMaxStack();
            }

            // Code.
            var result = new CodeAttribute
            {
                Code      = GenerateRawCode(context),
                MaxStack  = (ushort)MaxStack,
                MaxLocals = (ushort)Variables.Count
            };

            // Exception handlers.
            foreach (var info in GenerateExceptionHandlerInfos(context))
            {
                result.ExceptionHandlers.Add(info);
            }

            // Variables.
            if (Variables.Count > 0)
            {
                var localsAttribute = new LocalVariableTableAttribute();
                foreach (var variable in Variables)
                {
                    localsAttribute.LocalVariables.Add(new LocalVariableInfo
                    {
                        StartOffset     = (ushort)variable.Start.Offset,
                        Length          = (ushort)((variable.End?.Offset ?? result.Code.Length) - variable.Start.Offset),
                        NameIndex       = (ushort)context.Builder.ConstantPoolBuffer.GetUtf8Index(variable.Name),
                        DescriptorIndex = (ushort)context.Builder.ConstantPoolBuffer.GetDescriptorIndex(variable.Descriptor),
                        LocalIndex      = (ushort)variable.Index,
                    });
                }

                result.Attributes.Add(context.Builder.CreateAttribute(context, localsAttribute));
            }

            // Additional attributes.
            context.Builder.AddAttributes(context, result, this);

            return(result);
        }
Exemplo n.º 4
0
        /// <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(CodeInterface 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);
        }
Exemplo n.º 5
0
        internal MethodDefinition(JavaClassImage classImage, MethodInfo methodInfo)
        {
            // Name
            _name = new LazyValue <string>(() =>
                                           classImage.ClassFile.ConstantPool.ResolveString(methodInfo.NameIndex) ?? $"<<<INVALID({methodInfo.NameIndex})>>>");

            // Flags
            AccessFlags = methodInfo.AccessFlags;

            //Descriptor
            _descriptor = new LazyValue <MethodDescriptor>(() =>
                                                           classImage.ResolveMethodDescriptor(methodInfo.DescriptorIndex));

            // Attributes
            foreach (var attribute in methodInfo.Attributes)
            {
                string name = classImage.ClassFile.ConstantPool.ResolveString(attribute.NameIndex);
                switch (name)
                {
                // Code
                case CodeAttribute.AttributeName:
                    _body = new LazyValue <ByteCodeMethodBody>(() =>
                    {
                        var reader = new MemoryBigEndianReader(attribute.Contents);
                        return(new ByteCodeMethodBody(classImage, CodeAttribute.FromReader(reader)));
                    });
                    break;

                // Exceptions
                case ExceptionsAttribute.AttributeName:
                    _exceptions = new LazyValue <IList <ClassReference> >(() =>
                    {
                        var reader = new MemoryBigEndianReader(attribute.Contents);
                        var attr   = ExceptionsAttribute.FromReader(reader);
                        return(attr.Exceptions
                               .Select(index => classImage.ResolveClass(index))
                               .ToList());
                    });
                    break;

                default:
                    ExtraAttributes.Add(name, attribute.Clone());
                    break;
                }
            }
        }
Exemplo n.º 6
0
        protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element)
        {
            var node = LookupNode();

            foreach (var child in CodeModelService.GetAttributeNodes(node))
            {
                CodeModelService.GetAttributeNameAndOrdinal(node, child, out var childName, out var ordinal);
                if (childName == name)
                {
                    element = (EnvDTE.CodeElement)CodeAttribute.Create(State, FileCodeModel, this.ParentElement, childName, ordinal);
                    return(true);
                }
            }

            element = null;
            return(false);
        }
Exemplo n.º 7
0
        private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node, SyntaxNode parentNode)
        {
            CodeModelService.GetAttributeNameAndOrdinal(
                parentNode,
                node,
                out var name,
                out var ordinal
                );

            return((EnvDTE.CodeElement)CodeAttribute.Create(
                       this.State,
                       this.FileCodeModel,
                       this.ParentElement,
                       name,
                       ordinal
                       ));
        }
Exemplo n.º 8
0
        private void BuildCustomType(
            CodeClass codeClass,
            CodeAttribute originalTypeScriptInterfaceAttribute,
            TypeContext typeContext
            )
        {
            foreach (CodeClass baseClassCodeClass in codeClass.Bases)
            {
                BuildCustomType(baseClassCodeClass, originalTypeScriptInterfaceAttribute, typeContext);
            }
            var typeScriptInterfaceAttributeValues = GetInterfaceValues(codeClass, originalTypeScriptInterfaceAttribute);
            // Make sure an overridden name from originalTypeScriptInterfaceAttribute never overrides the name of "baseClass-interface", ie. a codeClass without a TypeScriptInterfaceAttribute of it's own.
            // typeScriptInterfaceAttributeValues.Name = codeClass.Name;
            // typeScriptInterfaceAttributeValues.NamePrefix = Settings.DefaultInterfaceNamePrefix ?? string.Empty;

            var customType = new CustomType(GetInterfaceName(typeScriptInterfaceAttributeValues), typeScriptInterfaceAttributeValues.Module);

            typeContext.AddCustomType(codeClass.FullName, customType);
        }
Exemplo n.º 9
0
        internal ByteCodeMethodBody(JavaClassImage classImage, CodeAttribute attribute)
        {
            MaxStack = attribute.MaxStack;

            // Read instructions.
            var disassembler = new ByteCodeDisassembler(new MemoryBigEndianReader(attribute.Code))
            {
                OperandResolver = new DefaultOperandResolver(classImage)
            };

            foreach (var instruction in disassembler.ReadInstructions())
            {
                Instructions.Add(instruction);
            }

            // Read exception handlers.
            foreach (var handler in attribute.ExceptionHandlers)
            {
                ExceptionHandlers.Add(new ExceptionHandler(classImage, this, handler));
            }

            // Read attributes.
            foreach (var attr in attribute.Attributes)
            {
                string name = classImage.ClassFile.ConstantPool.ResolveString(attr.NameIndex);
                switch (name)
                {
                // Local variables
                case LocalVariableTableAttribute.AttributeName:
                    var localsTable = LocalVariableTableAttribute.FromReader(new MemoryBigEndianReader(attr.Contents));
                    foreach (var info in localsTable.LocalVariables)
                    {
                        Variables.Add(new LocalVariable(classImage, this, info));
                    }
                    break;


                default:
                    ExtraAttributes.Add(name, attr.Clone());
                    break;
                }
            }
        }
Exemplo n.º 10
0
        public List <SymbolEnumItem> SearchEnumItem(string name)
        {
            List <SymbolEnumItem> list = new List <SymbolEnumItem>();

            foreach (var gcl in this.EnumTypes)
            {
                if (gcl is TktGcl)
                {
                    var fields = gcl.ForType.GetFields(BindingFlags.Static | BindingFlags.Public);
                    foreach (var fi in fields)
                    {
                        if (fi.Name == name)
                        {
                            object         value  = fi.GetValue(null);
                            SymbolEnumItem symbol = new SymbolEnumItem(fi.Name, value);
                            list.Add(symbol);
                        }
                    }
                }
                else
                {
                    var fields = gcl.ForType.GetFields(BindingFlags.Static | BindingFlags.Public);
                    foreach (var fi in fields)
                    {
                        object value      = fi.GetValue(null);
                        string rname      = fi.Name;
                        var    mapAttrObj = Attribute.GetCustomAttribute(fi, typeof(CodeAttribute));
                        if (mapAttrObj != null)
                        {
                            CodeAttribute mapAttr = mapAttrObj as CodeAttribute;
                            rname = mapAttr.Code;
                        }
                        if (rname == name)
                        {
                            SymbolEnumItem symbol = new SymbolEnumItem(rname, value);
                            list.Add(symbol);
                        }
                    }
                }
            }
            return(list);
        }
Exemplo n.º 11
0
        private static IEnumerable <CodeAttribute> GetAttributes(SyntaxList <AttributeListSyntax> attributeLists)
        {
            var attributes = new List <CodeAttribute>();

            foreach (var attributeList in attributeLists)
            {
                foreach (var attribute in attributeList.Attributes)
                {
                    var temp = new CodeAttribute
                    {
                        Identifier = attribute.Name.ToString()
                    };

                    if (attribute.ArgumentList != null)
                    {
                        temp.Param = attribute.ArgumentList.Arguments.Select(x => x.ToString());
                    }

                    attributes.Add(temp);
                }
            }
            return(attributes);
        }
Exemplo n.º 12
0
        public ExPropertyInfo SearchExProperty(string name)
        {
            var propertyArray = MType.GetProperties(/*BindingFlags.DeclaredOnly*/);

            foreach (var property in propertyArray)
            {
                if (ReflectionUtil.IsDeclare(MType, property))
                {
                    CodeAttribute propertyAttr = Attribute.GetCustomAttribute(property, typeof(CodeAttribute)) as CodeAttribute;
                    if (propertyAttr == null)
                    {
                        if (property.Name == name)
                        {
                            //return ForType.GetExProperty(property.Name);
                            return(GclUtil.CreatExPropertyInfo(ForType.GetProperty(property.Name), ForType));
                        }
                    }
                    else
                    {
                        if (propertyAttr.Code == name)
                        {
                            //return ForType.GetExProperty(property.Name);
                            return(GclUtil.CreatExPropertyInfo(ForType.GetProperty(property.Name), ForType));
                        }
                    }
                }
            }
            if (isRootMapping())
            {
                return(null);
            }
            else
            {
                ExPropertyInfo property = ParentMapping.SearchExProperty(name);
                return(property);
            }
        }
Exemplo n.º 13
0
        public static object GetValueFromAttribute <T>(this CodeAttribute graph, string PropertyName)
        {
            var formattedValue = graph.Value.Replace("\r", "").Replace("\n", "").Replace("\t", "");
            var valueStrings   = formattedValue.Split(',');

            foreach (var value in valueStrings)
            {
                var parameterStrings = value.Split('=');

                if (parameterStrings[0].Trim() == PropertyName)
                {
                    var parameterValue = parameterStrings[1].Trim();

                    if (PropertyName.Trim() == "Type")
                    {
                        var typeName = parameterValue.Replace("typeof(", "").Replace(")", "").Trim();

                        return(Type.GetType(typeName));
                    }
                }
            }

            throw new Exception(string.Format("Property '{0}' not found", PropertyName));
        }
Exemplo n.º 14
0
        private Dictionary <string, string> GetAttributeValues(CodeAttribute codeAttribute)
        {
            var values = new Dictionary <string, string>();

            foreach (CodeElement child in codeAttribute.Children)
            {
                var property = (EnvDTE80.CodeAttributeArgument)child;
                if (property == null || property.Value == null)
                {
                    continue;
                }

                // remove quotes if the property is a string
                string val = property.Value ?? string.Empty;
                if (val.StartsWith("\"") && val.EndsWith("\""))
                {
                    val = val.Substring(1, val.Length - 2);
                }

                values.Add(property.Name, val);
            }

            return(values);
        }
Exemplo n.º 15
0
        private void AddConfigurationElementTypeAttribute(CodeClass codeClass, ProjectItem customProvider)
        {
            CodeAttribute codeAttribute  = GetConfigurationElementTypeAttirbute(codeClass);
            string        attributeValue = null;

            if (!string.IsNullOrEmpty(Namespace))
            {
                attributeValue = string.Format(GetTypeOfDependingOnProjectTypeCSharpOrVisualBasic(), Namespace + NamespaceHelper.NamespaceSeparator + ConfigurationNamespacePart + NamespaceHelper.NamespaceSeparator + ConfigurationClassname);
            }
            else
            {
                attributeValue = string.Format(GetTypeOfDependingOnProjectTypeCSharpOrVisualBasic(), string.Concat(ConfigurationNamespacePart, NamespaceHelper.NamespaceSeparator, ConfigurationClassname));
            }

            if (codeAttribute != null)
            {
                RuntimeConfigurationBaseType = GetTypeFrom(codeAttribute);
                codeAttribute.Value          = attributeValue;
            }
            else
            {
                codeClass.AddAttribute(ConfigurationElementTypeAttributeName, attributeValue, 0);
            }
        }
Exemplo n.º 16
0
        private bool TryGetAttribute(CodeElements attributes, string attributeFullName, out CodeAttribute attribute)
        {
            foreach (CodeAttribute attr in attributes)
            {
                if (attr.FullName == attributeFullName)
                {
                    attribute = attr;
                    return(true);
                }
            }

            attribute = null;
            return(false);
        }
Exemplo n.º 17
0
        /// <summary>
        /// A recursively used method which builds interfaces out of CodeClasses *and* their base-class -CodeClasses
        /// (if instructed with [TypeScriptInterface(CreateTypeScriptInterfacesAlsoForBaseClasses = true)]).
        /// </summary>
        /// <param name="codeClass">The CodeClass for which to create a TypeScriptInterface.</param>
        /// <param name="typeContext"></param>
        /// <param name="originalTypeScriptInterfaceAttribute"></param>
        /// <param name="tsMap">The tsMap in which the created TypeScriptInterface will be stored.</param>
        /// <param name="module">The module in which the created TypeScriptInterface will be stored.</param>
        /// <param name="indirectlyMarkedInterface">A marker to indicate that a CodeClass with [TypeScriptInterface(CreateTypeScriptInterfacesAlsoForBaseClasses = true)] has been hit somewhere in previous recursion.</param>
        private void BuildInterface(
            CodeClass codeClass,
            TypeContext typeContext,
            CodeAttribute originalTypeScriptInterfaceAttribute,
            Dictionary <CodeClass, TypeScriptInterface> tsMap,
            TypeScriptModule module,
            bool indirectlyMarkedInterface = false
            )
        {
            var interfaceAlreadyExists = tsMap.ContainsKey(codeClass) || tsMap.Keys.Any(x => x.FullName == codeClass.FullName);
            // There's no need to display the properties of System.Object, ie. the grand-base-class of all classes.
            var codeClassIsIrrelevant = codeClass.FullName == typeof(Object).FullName;

            if (interfaceAlreadyExists || codeClassIsIrrelevant)
            {
                return;
            }

            CodeAttribute specificTypeScriptInterfaceAttribute;
            var           directlyMarkedInterface = TryGetAttribute(
                codeClass.Attributes,
                InterfaceAttributeFullName,
                out specificTypeScriptInterfaceAttribute
                );

            TypeScriptInterfaceAttributeValues typeScriptInterfaceAttributeValues;

            if (directlyMarkedInterface)
            {
                typeScriptInterfaceAttributeValues = GetInterfaceValues(codeClass, specificTypeScriptInterfaceAttribute);
                // This will set all the baseClasses of this class to be indirectlyMarked.
                indirectlyMarkedInterface =
                    indirectlyMarkedInterface ||
                    typeScriptInterfaceAttributeValues.CreateTypeScriptInterfacesAlsoForBaseClasses;
            }
            else
            {
                // If no specific attribute was available, use the originalTypeScriptInterfaceAttribute as source for typeScriptInterfaceAttributeValues.
                typeScriptInterfaceAttributeValues = GetInterfaceValues(codeClass, originalTypeScriptInterfaceAttribute);
                // Make sure an overridden name from originalTypeScriptInterfaceAttribute never overrides the name of "baseClass-interface", ie. a codeClass without a TypeScriptInterfaceAttribute of it's own.
                typeScriptInterfaceAttributeValues.Name       = codeClass.Name;
                typeScriptInterfaceAttributeValues.NamePrefix = Settings.DefaultInterfaceNamePrefix ?? string.Empty;
            }

            // Only indirectlyMarkedInterfaces build also their base-class -interfaces.
            if (indirectlyMarkedInterface)
            {
                // First, create interfaces for the baseCodeClasses.
                foreach (CodeClass baseClassCodeClass in codeClass.Bases)
                {
                    BuildInterface(
                        baseClassCodeClass,
                        typeContext,
                        originalTypeScriptInterfaceAttribute,
                        tsMap,
                        module,
                        true
                        );
                }
            }

            // Second, create interfaces for the CodeClass itself.
            var tsInterface = BuildInterface(
                codeClass,
                typeScriptInterfaceAttributeValues,
                typeContext,
                directlyMarkedInterface,
                indirectlyMarkedInterface
                );

            tsMap.Add(codeClass, tsInterface);
            tsInterface.Module = module;
            module.Interfaces.Add(tsInterface);
        }
 private static bool HasRequiredAttribute(CodeAttribute attribute)
 {
     return(attribute.FullName == "System.ComponentModel.DataAnnotations.RequiredAttribute" ||
            attribute.FullName == "Newtonsoft.Json.JsonRequiredAttribute");
 }
Exemplo n.º 19
0
        protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element)
        {
            var node          = LookupNode();
            var parentElement = !IsRootNamespace ? (AbstractCodeElement)Parent : null;

            // Option statements
            foreach (var child in CodeModelService.GetOptionNodes(node))
            {
                CodeModelService.GetOptionNameAndOrdinal(
                    node,
                    child,
                    out var childName,
                    out var ordinal
                    );
                if (childName == name)
                {
                    element = CodeOptionsStatement.Create(State, FileCodeModel, childName, ordinal);
                    return(true);
                }
            }

            // Imports/using statements
            foreach (var child in CodeModelService.GetImportNodes(node))
            {
                var childName = CodeModelService.GetImportNamespaceOrType(child);
                if (childName == name)
                {
                    element = CodeImport.Create(State, FileCodeModel, parentElement, childName);
                    return(true);
                }
            }

            // Attributes
            foreach (var child in CodeModelService.GetAttributeNodes(node))
            {
                CodeModelService.GetAttributeNameAndOrdinal(
                    node,
                    child,
                    out var childName,
                    out var ordinal
                    );
                if (childName == name)
                {
                    element = (EnvDTE.CodeElement)CodeAttribute.Create(
                        State,
                        FileCodeModel,
                        parentElement,
                        childName,
                        ordinal
                        );
                    return(true);
                }
            }

            // Members
            foreach (var child in CodeModelService.GetLogicalSupportedMemberNodes(node))
            {
                var childName = CodeModelService.GetName(child);
                if (childName == name)
                {
                    element = FileCodeModel.GetOrCreateCodeElement <EnvDTE.CodeElement>(child);
                    return(true);
                }
            }

            element = null;
            return(false);
        }
Exemplo n.º 20
0
        private Dictionary<string, string> GetAttributeValues(CodeAttribute codeAttribute)
        {
            var values = new Dictionary<string, string>();
            foreach (CodeElement child in codeAttribute.Children)
            {
                var property = (EnvDTE80.CodeAttributeArgument)child;
                if (property == null || property.Value == null)
                    continue;

                // remove quotes if the property is a string
                string val = property.Value ?? string.Empty;
                if (val.StartsWith("\"") && val.EndsWith("\""))
                    val = val.Substring(1, val.Length - 2);

                values.Add(property.Name, val);
            }

            return values;
        }
Exemplo n.º 21
0
 private AttributeArgumentCollection(
     CodeModelState state,
     CodeAttribute parent)
     : base(state, parent)
 {
 }
Exemplo n.º 22
0
 /// <summary>
 /// Get fullname of given attribute, without throwing excpetions.
 /// </summary>
 /// <param name="attribute">Attribute which fullname fill be returned.</param>
 /// <returns>Null if excpetion occur, otherwise attributes fullname.</returns>
 public static string SafeFullname(this CodeAttribute attribute)
 {
     return((attribute as CodeElement).SafeFullname());
 }
Exemplo n.º 23
0
        private bool TryGetAttribute(CodeElements attributes, string attributeFullName, out CodeAttribute attribute)
        {
            foreach (CodeAttribute attr in attributes)
            {
                if (attr.FullName == attributeFullName)
                {
                    attribute = attr;
                    return true;
                }
            }

            attribute = null;
            return false;
        }
Exemplo n.º 24
0
        public TKTProcDesc SearchProc(TKTProcDesc procDesc)
        {
            var methodArray = MType.GetMethods();

            foreach (var method in methodArray)
            {
                if (ReflectionUtil.IsDeclare(MType, method))
                {
                    CodeAttribute procAttr = Attribute.GetCustomAttribute(method, typeof(CodeAttribute)) as CodeAttribute;
                    if (procAttr == null)
                    {
                        ExMethodInfo exMethod     = GclUtil.CreatExMethodInfo(method, this.ForType);
                        TKTProcDesc  typeProcDesc = ProcDescHelper.CreateProcDesc(exMethod);
                        if (typeProcDesc.Eq(procDesc))
                        {
                            MethodInfo rmethod = method;
                            if (rmethod.IsAbstract)
                            {
                                rmethod = searchMethodByMethod(method);
                            }
                            if (rmethod == null)
                            {
                                throw new RTException("方法与被翻译类型的方法不一致");
                            }
                            else
                            {
                                TKTProcDesc rdesc = ProcDescHelper.CreateProcDesc(exMethod);
                                return(rdesc);
                            }
                        }
                    }
                    else
                    {
                        ParameterInfo[] paramArray = method.GetParameters();

                        parser.InitType(ForType, method);
                        TKTProcDesc typeProcDesc = parser.Parser(WordDict, procAttr.Code);
                        if (method.IsStatic && !method.IsAbstract && typeProcDesc.HasSubject() && typeProcDesc.GetSubjectArg().ArgType == this.ForType)
                        {
                            typeProcDesc = typeProcDesc.CreateTail();
                        }
                        if (typeProcDesc.Eq(procDesc))
                        {
                            MethodInfo rmethod = method;
                            if (rmethod.IsAbstract)
                            {
                                rmethod = searchMethodByMethod(method);
                            }
                            if (rmethod == null)
                            {
                                throw new RTException("过程描述标注错误");
                            }
                            else
                            {
                                ExMethodInfo exMethod = GclUtil.CreatExMethodInfo(rmethod, this.ForType);
                                typeProcDesc.ExMethod = exMethod;
                                return(typeProcDesc);
                            }
                        }
                    }
                }
            }
            if (isRootMapping())
            {
                return(null);
            }
            else
            {
                return(ParentMapping.SearchProc(procDesc));
            }
        }
Exemplo n.º 25
0
        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);
                }
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Get <see cref="CodeProperty"/> where given attribute is defined
 /// </summary>
 /// <param name="attribute">Attribute which property is needed</param>
 /// <returns><see cref="CodeProperty"/> where given attribute is defined, <c>null</c> if there is no such property</returns>
 private CodeProperty getProperty(CodeAttribute attribute)
 {
     return(attribute.Parent as CodeProperty);
 }
Exemplo n.º 27
0
 /// <summary>
 /// Get <see cref="CodeProperty"/> where given attribute is defined
 /// </summary>
 /// <param name="attribute">Attribute which property is needed</param>
 /// <returns><see cref="CodeProperty"/> where given attribute is defined, <c>null</c> if there is no such property</returns>
 private CodeFunction getMethod(CodeAttribute attribute)
 {
     return(attribute.Parent as CodeFunction);
 }
        /// <summary>
        /// Updates the code attribute argument.
        /// </summary>
        /// <param name="codeAttribute">The code attribute.</param>
        /// <param name="argumentName">Name of the argument.</param>
        /// <param name="argumentValue">The argument value.</param>
        /// <param name="createIfNew">if set to <c>true</c> [create if new].</param>
        /// <returns></returns>
        public static bool UpdateCodeAttributeArgument(
            CodeAttribute codeAttribute,
            string argumentName,
            string argumentValue,
            bool createIfNew)
        {
            Guard.ArgumentNotNull(codeAttribute, "codeAttribute");
            Guard.ArgumentNotNullOrEmptyString(argumentName, "argumentName");

            bool result = false;

            EnvDTE80.CodeAttribute2 attribute2 = (EnvDTE80.CodeAttribute2)codeAttribute;
            EnvDTE80.CodeAttributeArgument argumentMatch = null;
            foreach (EnvDTE80.CodeAttributeArgument argument in attribute2.Arguments)
            {
                if (argument.Name.Equals(argumentName, StringComparison.InvariantCultureIgnoreCase))
                {
                    argumentMatch = argument;
                    break;
                }
            }
            if (argumentMatch != null)
            {
                argumentMatch.Value = argumentValue;
                result = true;
            }
            else if (createIfNew)
            {
                attribute2.AddArgument(argumentValue, argumentName, attribute2.Arguments.Count);
                result = true;
            }

            return result;
        }
Exemplo n.º 29
0
        private TypeScriptInterfaceAttributeValues GetInterfaceValues(CodeClass codeClass, CodeAttribute interfaceAttribute)
        {
            var values = GetAttributeValues(interfaceAttribute);

            return(new TypeScriptInterfaceAttributeValues
            {
                Name = values.ContainsKey("Name") ? values["Name"] : codeClass.Name,
                Module = values.ContainsKey("Module") ? values["Module"] : Settings.DefaultModule ?? "T4TS",
                NamePrefix = values.ContainsKey("NamePrefix") ? values["NamePrefix"] : Settings.DefaultInterfaceNamePrefix ?? string.Empty,
                CreateTypeScriptInterfacesAlsoForBaseClasses =
                    values.ContainsKey("CreateTypeScriptInterfacesAlsoForBaseClasses") ?
                    bool.Parse(values["CreateTypeScriptInterfacesAlsoForBaseClasses"]) :
                    Settings.DefaultCreateTypeScriptInterfacesAlsoForBaseClasses
            });
        }
Exemplo n.º 30
0
        private static string GetAttributeValue(CodeAttribute attribute, CodeClass codeClass)
        {
            var value = attribute.Value;
            if (!string.IsNullOrEmpty(value))
            {
                if (value[0] != '"' && value[0] != '@')
                {
                    var variable = codeClass.GetIEnumerable<CodeVariable>()
                        .Where(v => v.IsConstant && v.Name == value)
                        .FirstOrDefault();

                    if (variable != null)
                    {
                        var initExpression = variable.InitExpression as string;
                        if (initExpression != null)
                        {
                            value = initExpression;
                        }
                    }
                }
            }
            return value;
        }
Exemplo n.º 31
0
        // Helper function to verify if the specified attribute contains a property with the specified name and value
        private static bool IsPropertyValuePresent(CodeAttribute attribute, string name, string value)
        {
            foreach (CodeAttributeArgument property in attribute.Children)
            {
                if (String.Equals(property.Name, name, StringComparison.Ordinal) &&
                    String.Equals(property.Value, value, StringComparison.Ordinal))
                {
                    return true;
                }
            }

            return false;
        }
Exemplo n.º 32
0
        private void AddStep(CodeAttribute attribute, CodeClass codeClass)
        {
            if (!STEP_ATTRIBUTES.Contains(attribute.FullName))
                return;

            var attributeValue = GetAttributeValue(attribute, codeClass);

            _stepDefinitions.Add(new StepDefinition(Unescape(attributeValue))
                                     {
                                         ProjectItem = attribute.ProjectItem,
                                         StartPoint = attribute.StartPoint,
                                         EndPoint = attribute.EndPoint,
                                         Function = attribute.Parent as CodeFunction,
                                         ClassName = codeClass.FullName
                                     });

            Debug.Print("Attribute FullName={0}, Value={1}, Unescaped={4} at {2}:{3}",
                        attribute.FullName, attribute.Value, attribute.StartPoint.Line, attribute.StartPoint.DisplayColumn,
                        Unescape(attribute.Value));
        }
Exemplo n.º 33
0
 private bool TryGetAttribute(CodeElements attributes, string attributeFullName, out CodeAttribute attribute, bool useShortAttributeName = false)
 {
     try
     {
         foreach (CodeAttribute attr in attributes)
         {
             var attrName = attr.FullName ?? "";
             if (useShortAttributeName)
             {
                 attrName = attrName.Split('.').Last().Split('+').Last();
             }
             if (attrName == attributeFullName)
             {
                 attribute = attr;
                 return(true);
             }
         }
     }
     catch
     {
     }
     attribute = null;
     return(false);
 }
Exemplo n.º 34
0
        protected CodeAttribute GetConfigurationElementTypeAttirbute(CodeClass codeClass)
        {
            CodeAttribute codeAttribute = GetAttribute(codeClass, ConfigurationElementTypeAttributeName);

            return(codeAttribute);
        }
Exemplo n.º 35
0
        private TypeScriptInterfaceAttributeValues GetInterfaceValues(CodeClass codeClass, CodeAttribute interfaceAttribute)
        {
            Dictionary <string, string> values = GetAttributeValues(interfaceAttribute);

            return(new TypeScriptInterfaceAttributeValues
            {
                Name = values.ContainsKey("Name") ? values["Name"] : codeClass.Name,
                Module = values.ContainsKey("Module") ? values["Module"] : Settings.DefaultModule ?? "T4TS",
                NamePrefix = values.ContainsKey("NamePrefix")
                        ? values["NamePrefix"]
                        : Settings.DefaultInterfaceNamePrefix ?? string.Empty
            });
        }
Exemplo n.º 36
0
        private TypeScriptInterfaceAttributeValues GetInterfaceValues(CodeClass codeClass, CodeAttribute interfaceAttribute)
        {
            var values = GetAttributeValues(interfaceAttribute);

            return new TypeScriptInterfaceAttributeValues
            {
                Name = values.ContainsKey("Name") ? values["Name"] : codeClass.Name,
                Module = values.ContainsKey("Module") ? values["Module"] : Settings.DefaultModule ?? "T4TS",
                NamePrefix = values.ContainsKey("NamePrefix") ? values["NamePrefix"] : Settings.DefaultInterfaceNamePrefix ?? string.Empty
            };
        }
Exemplo n.º 37
0
        public MethodInfo(ref ReadOnlySpan <byte> data, ClassFile classFile)
        {
            AccessFlags = data.ReadTwo();

            NameIndex = data.ReadTwo();
            Name      = ((CUtf8Info)classFile.Constants[NameIndex]).String;

            DescriptorIndex = data.ReadTwo();
            Descriptor      = ((CUtf8Info)classFile.Constants[DescriptorIndex]).String;

            AttributesCount = data.ReadTwo();
            Attributes      = new AttributeInfo[AttributesCount];
            for (int i = 0; i < AttributesCount; i++)
            {
                ushort nameIndexNonSwapped = MemoryMarshal.Cast <byte, ushort>(data)[0];
                ushort nameIndex           = nameIndexNonSwapped.SwapEndian();
                string name = ((CUtf8Info)classFile.Constants[nameIndex]).String;
                switch (name)
                {
                case "Code":
                    CodeAttribute code = new CodeAttribute(ref data, classFile.Constants);
                    Attributes[i] = code;
                    MaxStack      = code.MaxStack;
                    MaxLocals     = code.MaxLocals;
                    CodeAttribute = code;
                    break;

                case "Exceptions":
                    ExceptionsAttribute exceptionsAttribute = new ExceptionsAttribute(ref data, classFile.Constants);
                    Attributes[i]       = exceptionsAttribute;
                    ExceptionsAttribute = exceptionsAttribute;
                    break;

                case "Deprecated":
                    Attributes[i] = new DeprecatedAttribute(ref data, classFile.Constants);
                    Deprecated    = true;
                    break;

                case "RuntimeVisibleAnnotations":
                    Attributes[i] = new RuntimeVisibleAnnotationsAttribute(ref data, classFile.Constants);
                    break;

                case "Synthetic":
                    Attributes[i] = new SyntheticAttribute(ref data, classFile.Constants);
                    break;

                case "Signature":
                    Attributes[i] = new SignatureAttribute(ref data, classFile.Constants);
                    break;

                case "RuntimeInvisibleAnnotations":
                case "RuntimeVisibleParameterAnnotations":
                case "RuntimeInvisibleParameterAnnotations":
                case "AnnotationDefault":
                    throw new NotImplementedException();

                default:
                    Attributes[i] = new AttributeInfo(ref data, classFile.Constants);
                    break;
                }
            }

            ClassFile = classFile;
        }
Exemplo n.º 38
0
 protected virtual void VisitAttribute(CodeAttribute codeAttribute)
 {
 }
Exemplo n.º 39
0
        private bool TryGetAttribute(CodeElements attributes, string attributeFullName, out CodeAttribute attribute, bool useShortAttributeName = false)
        {
            foreach (CodeAttribute attr in attributes)
            {
                var attrName = attr.FullName ?? "";
                if (useShortAttributeName)
                    attrName = attrName.Split('.').Last().Split('+').Last();
                if (attrName == attributeFullName)
                {
                    attribute = attr;
                    return true;
                }
            }

            attribute = null;
            return false;
        }
Exemplo n.º 40
0
 private static bool HasIgnoreAttribute(CodeAttribute attribute)
 {
     return(attribute.FullName == "System.Runtime.Serialization.IgnoreDataMemberAttribute" ||
            attribute.FullName == "Newtonsoft.Json.JsonIgnoreAttribute" ||
            attribute.FullName == "System.Web.Script.Serialization.ScriptIgnoreAttribute");
 }
Exemplo n.º 41
0
 /// <summary>
 /// Add custom attribute to method.
 /// </summary>
 /// <param name="attribute">Custom attribute.</param>
 /// <returns>Method builder instance.</returns>
 public MethodBuilder AddAttribute(CodeAttribute attribute)
 {
     Method.AddAttribute(attribute);
     return(this);
 }
Exemplo n.º 42
0
 private CodeAttributeArgument(CodeModelState state, CodeAttribute parent, int index)
     : base(state, parent.FileCodeModel)
 {
     _parentHandle = new ParentHandle<CodeAttribute>(parent);
     _index = index;
 }
Exemplo n.º 43
0
 protected virtual void VisitAttribute(CodeAttribute codeAttribute)
 {
 }