private CodeElement GetCodeElementAtTextPoint(vsCMElement eRequestedCodeElementKind,
            CodeElements colCodeElements, TextPoint objTextPoint)
        {

            //  CodeElement objCodeElement = default(CodeElement);
            CodeElement objResultCodeElement = default(CodeElement);
            CodeElements colCodeElementMembers = default(CodeElements);
            CodeElement objMemberCodeElement = default(CodeElement);


            if ((colCodeElements != null))
            {

                foreach (CodeElement objCodeElement in colCodeElements)
                {

                    if (objCodeElement.StartPoint.GreaterThan(objTextPoint))
                    {
                        // The code element starts beyond the point


                    }
                    else if (objCodeElement.EndPoint.LessThan(objTextPoint))
                    {
                        // The code element ends before the point

                        // The code element contains the point
                    }
                    else
                    {

                        if (objCodeElement.Kind == eRequestedCodeElementKind)
                        {
                            // Found
                            objResultCodeElement = objCodeElement;
                        }

                        // We enter in recursion, just in case there is an inner code element that also 
                        // satisfies the conditions, for example, if we are searching a namespace or a class
                        colCodeElementMembers = GetCodeElementMembers(objCodeElement);

                        objMemberCodeElement = GetCodeElementAtTextPoint(eRequestedCodeElementKind, colCodeElementMembers, objTextPoint);

                        if ((objMemberCodeElement != null))
                        {
                            // A nested code element also satisfies the conditions
                            objResultCodeElement = objMemberCodeElement;
                        }

                        break; // TODO: might not be correct. Was : Exit For

                    }

                }

            }

            return objResultCodeElement;

        }
Esempio n. 2
0
 protected virtual void Visit(CodeElements elements)
 {
     foreach (CodeElement element in elements)
     {
         this.Visit(element);
     }
 }
        internal static IEnumerable<IEnumValueMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
        {
            var value = -1;

            foreach (var codeVariable in codeElements.OfType<CodeVariable2>())
            {
                if (codeVariable.InitExpression == null)
                    value++;
                else
                {
                    string initExpression = codeVariable.InitExpression.ToString();

                    if (int.TryParse(initExpression, out value) == false)
                    {
                        // Handle init expressions from char constants e.g. 'A' = 65
                        if (initExpression.Length == 3 && initExpression.StartsWith("'") && initExpression.EndsWith("'"))
                        {
                            value = initExpression[1];
                        }
                        else if (initExpression.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                        {
                            var convertedValue = _converter.ConvertFromString(initExpression);
                            value = (int?)convertedValue ?? -1;
                        }
                        else
                        {
                            value = -1;
                        }
                    }
                }

                yield return new CodeDomEnumValueMetadata(codeVariable, file, value);
            }
        }
Esempio n. 4
0
 private void Traverse(CodeElements members)
 {
     foreach (object elem in members)
     {
         if (elem is CodeClass)
             WithCodeClass((CodeClass)elem);
     }
 }
Esempio n. 5
0
 private void Traverse(CodeElements members)
 {
     foreach (var property in members)
     {
         if (property is CodeProperty)
             WithProperty((CodeProperty)property);
     }
 }
 void EditAppRegisterTypesForNavigation(CodeElements codeElements)
 {
     CodeFunction registerTypesFunction = GetRegisterTypesMethod(codeElements);
     if (registerTypesFunction != null)
     {
         TextPoint methodEndPoint = registerTypesFunction.GetEndPoint(vsCMPart.vsCMPartBody);
         EditPoint editPoint = methodEndPoint.CreateEditPoint();
         editPoint.Insert($"Container.RegisterTypeForNavigation<{_viewName}>();");
         editPoint.SmartFormat(methodEndPoint);
     }
 }
Esempio n. 7
0
 private void Traverse(CodeElements members)
 {
     var index = 0;
     foreach (var property in members.OfType<CodeVariable>())
     {
         WithVariable(property, index);
         if (property.InitExpression != null)
             index = Int32.Parse(property.InitExpression.ToString());
         index++;
     }
 }
 private void addItemFor(List<OnDemandRun> runs, CodeElements elements, string projectName)
 {
     var classes = new List<string>();
     foreach (CodeElement element in elements)
     {
         if (element.Kind == vsCMElement.vsCMElementNamespace)
             addItemFor(runs, element.Children, projectName);
         if (element.Kind == vsCMElement.vsCMElementClass)
             classes.Add(element.FullName);
     }
     if (classes.Count > 0)
         runs.Add(new OnDemandRun(projectName, new string[] { }, classes.ToArray(), new string[] { }));
 }
        private CodeElement GetCodeElement(DTE dte, SnapshotPoint  point, CodeElements codeElements, vsCMElement elementType)
        {
            foreach (CodeElement ce in codeElements)
            {
                if (ce.Kind.ToString() == "vsCMElementImportStmt")
                {
                    continue;
                }
                try
                {
                    _log.Debug("Searching " + ce.Name);
                    Debug.WriteLine(string.Format("Searching {0}:{1}", ce.Kind.ToString(), ce.Name));
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Exception getting object name: " + e.Message );
                }

                var sp = getStartPoint(ce);
                var pointLine = point.GetContainingLine().LineNumber;

                if (sp != null)
                {
                    if (sp.Line > pointLine )
                    {
                        // code element starts after the droplocation, ignore it
                    }
                    else if (ce.EndPoint.Line  < pointLine )
                    {
                        // code element finishes before the droplocation, ignore it
                    }
                    else
                    {

                        if (elementType == ce.Kind)
                        {

                            return ce;
                        }

                        var childElements = getCodeElements(ce);
                        if (childElements != null)
                        {
                            var ret = GetCodeElement(dte, point, childElements, elementType);
                            if (ret != null) return ret;
                        }
                    }
                }
            }
            return null;
        }
Esempio n. 10
0
        CodeFunction GetRegisterTypesMethod(CodeElements codeElements)
        {
            foreach (CodeElement codeElement in codeElements)
            {
                if (codeElement.Kind == vsCMElement.vsCMElementNamespace)
                {
                    CodeNamespace codeNamespace = (CodeNamespace)codeElement;
                    CodeClass codeClass = (CodeClass)codeNamespace.Children.Item("App");
                    return (CodeFunction)codeClass.Members.Item("RegisterTypes");
                }
            }

            return null;
        }
        internal static IEnumerable<IEnumValueMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
        {
            var value = -1;

            foreach (var codeVariable in codeElements.OfType<CodeVariable2>())
            {
                if (codeVariable.InitExpression == null)
                    value++;
                else
                    value = Convert.ToInt32(codeVariable.InitExpression);

                yield return new CodeDomEnumValueMetadata(codeVariable, file, value);
            }
        }
Esempio n. 12
0
      static public CodeElement FindInnerMostCodeElement(CodeElements elements, TextPoint p)
      {
         foreach (CodeElement ce in elements)
         {
            if (CodeElementContainsPoint(ce, p))
            {
               CodeElement ce2 = FindInnerMostCodeElement(ce.Children, p);

               if (ce2 == null) return ce;
               else return ce2;
            }
         }

         return null;
      }
Esempio n. 13
0
 /// <summary>
 /// 得到一个CodeElements下所有的元素
 /// </summary>
 /// <param name="elements"></param>
 /// <param name="allElements"></param>
 public void GetAllElements(CodeElements elements, List<CodeElement> allElements)
 {
     foreach (CodeElement element in elements)
     {
         try
         {
             allElements.Add(element);
             if (element.Children != null)
             {
                 GetAllElements(element.Children, allElements);
             }
         }
         catch
         {
         }
     }
 }
        /// <summary>
        /// Collect code elements information
        /// </summary>
        /// <param name="list"></param>
        /// <param name="elements"></param>
        /// <param name="filter"></param>
        public static void CollectElements(ICollection<CodeElement2> list, CodeElements elements, IEnumerable<vsCMElement> filter)
        {
            if (elements == null || elements.Count == 0)
            {
                return;
            }

            foreach (CodeElement2 p in elements)
            {
                Trace.WriteLine(String.Format("+ {0}", p.Kind));
                if (filter.Contains(p.Kind))
                {
                    list.Add(p);
                }

                CollectElements(list, p.Children, filter);
            }
        }
Esempio n. 15
0
        private static CodeElement GetCodeElementAtTextPoint(vsCMElement eRequestedCodeElementKind, CodeElements colCodeElements, EnvDTE.TextPoint objTextPoint)
        {
            CodeElement objResultCodeElement = null;

            if (colCodeElements == null) return null;
            foreach (var objCodeElement in colCodeElements.Cast<CodeElement>()) {

                if (objCodeElement.StartPoint.GreaterThan(objTextPoint)) {
                    // The code element starts beyond the point

                }
                else if (objCodeElement.EndPoint.LessThan(objTextPoint)) {
                    // The code element ends before the point

                    // The code element contains the point
                }
                else {

                    if (objCodeElement.Kind == eRequestedCodeElementKind) {
                        // Found
                        objResultCodeElement = objCodeElement;
                    }

                    // We enter in recursion, just in case there is an inner code element that also
                    // satisfies the conditions, for example, if we are searching a namespace or a class
                    var colCodeElementMembers = GetCodeElementMembers(objCodeElement);

                    var objMemberCodeElement = GetCodeElementAtTextPoint(eRequestedCodeElementKind, colCodeElementMembers, objTextPoint);

                    if ((objMemberCodeElement != null)) {
                        // A nested code element also satisfies the conditions
                        objResultCodeElement = objMemberCodeElement;
                    }

                    break;

                }

            }

            return objResultCodeElement;
        }
        CodeClass GetCodeClass(CodeElements codeElements)
        {
            foreach (CodeElement codeElement in codeElements)
            {
                if (codeElement.Kind == vsCMElement.vsCMElementNamespace)
                {
                    CodeNamespace codeNamespace = (CodeNamespace)codeElement;

                    foreach (CodeElement child in codeNamespace.Children)
                    {
                        if (child.Kind == vsCMElement.vsCMElementClass)
                        {
                            return (CodeClass)child;
                        }
                    }
                }
            }

            return null;
        }
        private CodeElement getCodeElementAtTextPoint(vsCMElement requestedElementKind, CodeElements codeElements, TextPoint cursor)
        {
            if (codeElements != null)
            {
                var c = cursor.CodeElement[vsCMElement.vsCMElementClass];
                if (c != null)
                {
                    Debug.WriteLine("Cursor is in " + c.FullName );
                }
                foreach (CodeElement e in codeElements)
                {
                    Debug.WriteLine("Searching..." + getEleentName(e) );
                    if (e.StartPoint.GreaterThan(cursor) || e.EndPoint.LessThan(cursor))
                    {
                        // ignore
                    }
                    else
                    {

                        var children = getMembers(e);
                        if (children != null)
                        {
                            var memberElement = getCodeElementAtTextPoint(requestedElementKind, children, cursor);
                            if (memberElement != null)
                            {
                                return memberElement;
                            }
                        }

                        if (e.Kind.Equals(requestedElementKind))
                        {
                            return e;
                        }
                    }
                }
            }
            Debug.WriteLine("Element not found");
            return null;

        }
        public IEnumerable<CodeElement> GetCodeElements(CodeElements elements, Predicate<CodeElement> match)
        {
            var ret = new List<CodeElement>();
            if (elements == null) return null;
            if (elements.Count == 0) return null;

            foreach (CodeElement ce in elements)
            {
                Debug.WriteLine("{0}: {1}", ce.SafeName(), ce.KindAsString());
                if(match(ce)) ret.Add(ce);

                var children = getCodeElements(ce);
                if (children != null)
                {
                    var inner = GetCodeElements(children, match);
                    if(inner!=null) ret.AddRange(inner);
                }

            }

            if (!ret.Any()) return null;
            return ret;
        }
Esempio n. 19
0
        private void CollapseElement(CodeElement element)
        {
            if (element.IsCodeType && (element.Kind != vsCMElement.vsCMElementDelegate))
            {
                System.Diagnostics.Debug.Print("got type but not a delegate, named : {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
                CodeType     ct   = element as EnvDTE.CodeType;
                CodeElements mems = ct.Members;
                foreach (CodeElement melt in mems)
                {
                    CollapseElement(melt);
                } //foreach
            }
            else if (element.Kind == vsCMElement.vsCMElementNamespace)
            {
                System.Diagnostics.Debug.Print("got a namespace, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
                CodeNamespace cns = element as EnvDTE.CodeNamespace;
                System.Diagnostics.Debug.Print("set cns = elt, named: {0}", cns.Name);

                CodeElements mems_ns = cns.Members;
                if (mems_ns.Count > 0)
                {
                    System.Diagnostics.Debug.Print("got cns.members");
                    foreach (CodeElement melt in mems_ns)
                    {
                        CollapseElement(melt);
                    } //foreach
                    System.Diagnostics.Debug.Print("end of cns.members");
                }     //if
            }
            else if (element.Kind == vsCMElement.vsCMElementFunction)
            {
                System.Diagnostics.Debug.Print("got a function, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
                CodeFunction cf = element as EnvDTE.CodeFunction;
                System.Diagnostics.Debug.Print("set cf = elt, named: {0}, fkind: {1}", cf.Name, cf.FunctionKind);

                CodeElements mems_f = cf.Children;
                if (mems_f.Count > 0)
                {
                    System.Diagnostics.Debug.Print("got cf.members");
                    foreach (CodeElement melt in mems_f)
                    {
                        CollapseElement(melt);
                    } //foreach
                    System.Diagnostics.Debug.Print("end of cf.members");
                }     //if
            }
            else if (element.Kind == vsCMElement.vsCMElementProperty)
            {
                System.Diagnostics.Debug.Print("got a property, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
                CodeProperty cp = element as EnvDTE.CodeProperty;
                System.Diagnostics.Debug.Print("set cp = elt, named: {0}", cp.Name);

                CodeElements mems_p = cp.Children;
                if (mems_p.Count > 0)
                {
                    System.Diagnostics.Debug.Print("got cp.members");
                    foreach (CodeElement melt in mems_p)
                    {
                        CollapseElement(melt);
                    } //foreach
                    System.Diagnostics.Debug.Print("end of cp.members");
                }     //if
            }
            else if (element.Kind == vsCMElement.vsCMElementVariable)
            {
                System.Diagnostics.Debug.Print("got a variable, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
                CodeVariable cv = element as EnvDTE.CodeVariable;
                System.Diagnostics.Debug.Print("set cv = elt, named: {0}", cv.Name);

                CodeElements mems_v = cv.Children;
                if (mems_v.Count > 0)
                {
                    System.Diagnostics.Debug.Print("got cv.members");
                    foreach (CodeElement melt in mems_v)
                    {
                        CollapseElement(melt);
                    } //foreach
                    System.Diagnostics.Debug.Print("end of cv.members");
                }     //if
            }
            else
            {
                System.Diagnostics.Debug.Print("kind = {0} in line {1} to {2}", element.Kind, element.StartPoint.Line, element.EndPoint.Line);
            }
        }
Esempio n. 20
0
 internal static IEnumerable <IFieldMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return(codeElements.OfType <CodeVariable2>().Where(v => v.Access == vsCMAccess.vsCMAccessPublic && v.IsConstant == false && v.IsShared == false).Select(v => new CodeDomFieldMetadata(v, file)));
 }
Esempio n. 21
0
        private void AddClassProperty(CodeElements codeElements, ref List <ClassProperty> classProperties)
        {
            foreach (CodeElement2 codeElement in codeElements)
            {
                if (codeElement.Kind == vsCMElement.vsCMElementProperty)
                {
                    ClassProperty classProperty = new ClassProperty();
                    CodeProperty2 property      = codeElement as CodeProperty2;
                    classProperty.Name = property.Name;
                    //获取属性类型
                    var propertyType = property.Type;
                    switch (propertyType.TypeKind)
                    {
                    case vsCMTypeRef.vsCMTypeRefString:
                        classProperty.PropertyType = "string";
                        break;

                    case vsCMTypeRef.vsCMTypeRefInt:
                        classProperty.PropertyType = "int";
                        break;

                    case vsCMTypeRef.vsCMTypeRefLong:
                        classProperty.PropertyType = "long";
                        break;

                    case vsCMTypeRef.vsCMTypeRefByte:
                        classProperty.PropertyType = "byte";
                        break;

                    case vsCMTypeRef.vsCMTypeRefChar:
                        classProperty.PropertyType = "char";
                        break;

                    case vsCMTypeRef.vsCMTypeRefShort:
                        classProperty.PropertyType = "short";
                        break;

                    case vsCMTypeRef.vsCMTypeRefBool:
                        classProperty.PropertyType = "bool";
                        break;

                    case vsCMTypeRef.vsCMTypeRefDecimal:
                        classProperty.PropertyType = "decimal";
                        break;

                    case vsCMTypeRef.vsCMTypeRefFloat:
                        classProperty.PropertyType = "float";
                        break;

                    case vsCMTypeRef.vsCMTypeRefDouble:
                        classProperty.PropertyType = "double";
                        break;

                    default:
                        classProperty.PropertyType = propertyType.AsFullName;
                        break;
                    }

                    classProperties.Add(classProperty);
                }
            }
        }
Esempio n. 22
0
 ///-------------------------------------------------------------------------------------------------------------
 /// <summary>
 ///	 Recursively searches the CodeElements for the specified class
 /// </summary>
 ///-------------------------------------------------------------------------------------------------------------
 public /*protected, but public for FSharp.Project.dll*/ virtual CodeClass FindClass(CodeElements codeElements, string className)
 {
     if (codeElements != null && !string.IsNullOrEmpty(className))
     {
         foreach (CodeElement codeElement in codeElements)
         {
             vsCMElement kind = codeElement.Kind;
             if (kind == vsCMElement.vsCMElementClass)
             {
                 CodeClass codeClass = codeElement as CodeClass;
                 if (codeClass != null && string.Compare(codeClass.FullName, className, StringComparison.Ordinal) == 0)
                 {
                     return(codeClass);
                 }
             }
             else if (kind == vsCMElement.vsCMElementNamespace)
             {
                 EnvDTE.CodeNamespace codeNamespace = codeElement as EnvDTE.CodeNamespace;
                 if (codeNamespace != null)
                 {
                     CodeClass codeClass = FindClass(codeNamespace.Children, className);
                     if (codeClass != null)
                     {
                         return(codeClass);
                     }
                 }
             }
         }
     }
     return(null);
 }
Esempio n. 23
0
        private CodeElement getCodeElementAtTextPoint(vsCMElement requestedElementKind, CodeElements codeElements, TextPoint cursor)
        {
            if (codeElements != null)
            {
                var c = cursor.CodeElement[vsCMElement.vsCMElementClass];
                if (c != null)
                {
                    Debug.WriteLine("Cursor is in " + c.FullName);
                }
                foreach (CodeElement e in codeElements)
                {
                    Debug.WriteLine("Searching..." + getEleentName(e));
                    if (e.StartPoint.GreaterThan(cursor) || e.EndPoint.LessThan(cursor))
                    {
                        // ignore
                    }
                    else
                    {
                        var children = getMembers(e);
                        if (children != null)
                        {
                            var memberElement = getCodeElementAtTextPoint(requestedElementKind, children, cursor);
                            if (memberElement != null)
                            {
                                return(memberElement);
                            }
                        }

                        if (e.Kind.Equals(requestedElementKind))
                        {
                            return(e);
                        }
                    }
                }
            }
            Debug.WriteLine("Element not found");
            return(null);
        }
Esempio n. 24
0
        //解析代码
        void parse()
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
            if (code_model_ == null)
            {
                throw new Exception("代码模型不能为空");
            }

            CodeElements codes = code_model_.CodeElements;

            //查找命名空间,只支持第一命名空间
            CodeNamespace codeNamespace = null;

            for (int i = 1; i <= codes.Count; i++)
            {
                if (codes.Item(i).Kind == vsCMElement.vsCMElementNamespace)
                {
                    codeNamespace = codes.Item(i) as CodeNamespace;
                    break;
                }
            }
            if (codeNamespace == null)
            {
                throw new Exception("未找到命名空间定义");
            }
            NamespaceName = codeNamespace.Name;

            //查找类或定义,只支持第一个类或接口定义
            CodeClass     codeClass     = null;
            CodeInterface codeInterface = null;

            for (int i = 1; i <= codeNamespace.Members.Count; i++)
            {
                if (codeNamespace.Members.Item(i).Kind == vsCMElement.vsCMElementClass)
                {
                    codeClass = codeNamespace.Members.Item(i) as CodeClass;
                    break;
                }
                else if (codeNamespace.Members.Item(i).Kind == vsCMElement.vsCMElementInterface)
                {
                    codeInterface = codeNamespace.Members.Item(i) as CodeInterface;
                    break;
                }
            }
            if (codeClass == null)
            {
                throw new Exception("未找到类或接口定义");
            }
            if (codeClass != null)
            {
                ShortClassName = codeClass.Name;
                ClassName      = codeClass.FullName.Replace($"{this.NamespaceName}.", "");
                IsAbstract     = codeClass.IsAbstract;
                if (ClassName.IndexOf("<") != -1)
                {
                    var s = ClassName.IndexOf("<") + 1;
                    var l = ClassName.Length - s - 1;
                    GenericTypeArguments = ClassName.Substring(s, l).Split(',').Select(it => it.Trim()).ToList();
                }
                parse_body(codeClass);
            }
            //else
            //{
            //    ClassName = codeInterface.Name;
            //    parse_body(codeInterface);
            //}
        }
 internal static IEnumerable <IAttributeMetadata> FromCodeElements(CodeElements codeElements)
 {
     return(codeElements.OfType <CodeAttribute2>().Select(a => new CodeDomAttributeMetadata(a)));
 }
Esempio n. 26
0
        private static List <Tuple <CodeElement2, List <CodeElement2> > > FindMembers(CodeElements codeElements, Predicate <CodeElement2> includeMember)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            List <Tuple <CodeElement2, List <CodeElement2> > > result = new();

            foreach (CodeElement2 element in codeElements)
            {
                switch (element.Kind)
                {
                case vsCMElement.vsCMElementNamespace:
                    result.AddRange(FindMembers(((CodeNamespace)element).Members, includeMember));
                    break;

                case vsCMElement.vsCMElementClass:
                case vsCMElement.vsCMElementModule:                         // No CodeModule type exists (for VB modules), but CodeClass2 works.
                    result.AddRange(FindMembers(element, ((CodeClass2)element).Members, includeMember));
                    break;

                case vsCMElement.vsCMElementStruct:
                    result.AddRange(FindMembers(element, ((CodeStruct2)element).Members, includeMember));
                    break;

                case vsCMElement.vsCMElementInterface:
                    result.AddRange(FindMembers(element, ((CodeInterface2)element).Members, includeMember));
                    break;

                case vsCMElement.vsCMElementEnum:
                    result.AddRange(FindMembers(element, ((CodeEnum)element).Members, includeMember));
                    break;
                }
            }

            return(result);
        }
Esempio n. 27
0
        private void CheckAndAddAlias(string nameSpace,
                                      string className,
                                      string aliasName)
        {
            string resourceAlias1 = $"using {aliasName} = ",
                   resourceAlias2 = $"global::{nameSpace}.{className}";

            CodeElements elements    = TextDocument.Parent.ProjectItem.FileCodeModel.CodeElements;
            CodeElement  lastElement = null;
            bool         isImport    = false;

            #region find alias or last using/Import element (return if alias found)
            foreach (CodeElement element in elements) //not really fast but more safe
            {
                if (!isImport)
                {
                    //find first using/import statement
                    if (element.Kind == vsCMElement.vsCMElementImportStmt)
                    {
                        isImport = true;
                    }
                }
                else
                {
                    //using/import statement was available so find next NON using/import statement
                    if (element.Kind != vsCMElement.vsCMElementImportStmt)
                    {
                        break;
                    }
                }

                if (element.Kind == vsCMElement.vsCMElementOptionStmt)
                {
                    //save last option statement
                    lastElement = element;
                }
                else if (element.Kind == vsCMElement.vsCMElementImportStmt)
                {
                    //save last using/import statement
                    lastElement = element;

                    //check if resource alias is already there
                    CodeImport importElement = element as CodeImport;
                    if ((importElement.Alias != null) && importElement.Alias.Equals(aliasName) && importElement.Namespace.Equals(resourceAlias2))
                    {
                        return;
                    }
                }
            }
            #endregion

            EditPoint insertPoint = null;

            if (lastElement == null)
            {
                insertPoint = TextDocument.CreateEditPoint(TextDocument.StartPoint); //beginning of text
            }
            else
            {
                //behind last element
                insertPoint = lastElement.EndPoint.CreateEditPoint();
                insertPoint.LineDown(1);
                insertPoint.StartOfLine();

                if (lastElement.Kind == vsCMElement.vsCMElementOptionStmt)
                {
                    insertPoint.Insert(Environment.NewLine);
                }
            }

            resourceAlias2 += ";";

            string alias = resourceAlias1 + resourceAlias2 + Environment.NewLine;

            insertPoint.Insert(alias);
        }
Esempio n. 28
0
 /// <summary>
 /// Initializes the iterator from a code element
 /// </summary>
 /// <param name="codeElement"></param>
 /// <remarks>
 /// The specified code element is not returned by the iterator
 /// </remarks>
 public CodeElementsIterator(CodeElement codeElement)
 {
     Guard.ArgumentNotNull(codeElement, "codeElement");
     elements = codeElement.Children;
 }
Esempio n. 29
0
        public override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeFunction originalClassCodeFuntion)
        {
            vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction;
            object       functionType = null;

            functionKind = vsCMFunction.vsCMFunctionSub;
            functionType = vsCMTypeRef.vsCMTypeRefVoid;

            string nextAvailableName = originalClassCodeFuntion.Name;

            if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass,
                                                                    nextAvailableName))
            {
                nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject);
            }

            CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction(
                nextAvailableName,
                functionKind,
                functionType,
                -1,
                originalClassCodeFuntion.Access,
                -1);

            bool tvIsStatic = originalClassCodeFuntion.IsShared;

            //add the NUnit attribute to the function
            unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1);

            try
            {
                unitTestCodeFunction.Comment    = originalClassCodeFuntion.Comment;
                unitTestCodeFunction.DocComment = originalClassCodeFuntion.DocComment;
            }
            catch (Exception ex)
            {
                //ignore, for some reason the doc throws in vb
                Logger.LogException(ex);
            }

            string tvFunctionCallTemplate   = string.Empty; //"iv{0}Type.{1}(";
            string tvFunctionReturnTemplate = string.Empty; //"{0} iv{1}Return = ";

            tvFunctionCallTemplate = "iv{0}Type.{1}(";

            if (tvIsStatic)
            {
                tvFunctionCallTemplate = "{0}.{1}(";
            }

            tvFunctionReturnTemplate = "Dim iv{1}Return As {0} = ";

            string tvTempParameterList = string.Empty;
            string tvFunctionCall      = tvFunctionCallTemplate;
            string tvFunctionReturn    = tvFunctionReturnTemplate;


            if (!originalClassCodeFuntion.FunctionKind.ToString().Equals("vsCMFunctionConstructor"))
            {
                CodeElements tvParameters = originalClassCodeFuntion.Parameters;

                foreach (CodeElement tvCodeElement in tvParameters)
                {
                    if (!tvFunctionCall.Equals(tvFunctionCallTemplate))
                    {
                        tvFunctionCall += ", ";
                    }

                    CodeParameter2 tvCodeParameter = (CodeParameter2)tvCodeElement;

                    string parameterName = tvCodeParameter.Name;

                    CodeTypeRef tvParameterType = tvCodeParameter.Type;

                    vsCMParameterKind tvParameterKind = tvCodeParameter.ParameterKind;

                    string parameterTypeAsString = tvParameterType.AsString;

                    tvTempParameterList += "Dim " + parameterName + " As " + parameterTypeAsString + " = New " + parameterTypeAsString + "()" + Environment.NewLine + StringHelper.GetTabString();

                    if (tvParameterKind == vsCMParameterKind.vsCMParameterKindRef)
                    {
                        tvFunctionCall += parameterName;
                    }
                    else if (tvParameterKind == vsCMParameterKind.vsCMParameterKindOut)
                    {
                        tvFunctionCall += parameterName;
                    }
                    else if (tvParameterKind == vsCMParameterKind.vsCMParameterKindIn)
                    {
                        tvFunctionCall += parameterName;
                    }
                    else
                    {
                        tvFunctionCall += parameterName;
                    }
                }

                tvFunctionCall = string.Format(tvFunctionCall + ")" + Environment.NewLine, ((CodeClass)originalClassCodeFuntion.Parent).Name, originalClassCodeFuntion.Name);
            }

            if (originalClassCodeFuntion.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid)
            {
                tvFunctionReturn = string.Format(tvFunctionReturn, originalClassCodeFuntion.Type.AsString, originalClassCodeFuntion.Name);
                tvFunctionCall   = tvFunctionReturn + tvFunctionCall;
            }

            TextPoint bodyStartingPoint =
                unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

            EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint();

            if (!originalClassCodeFuntion.FunctionKind.ToString().Equals("vsCMFunctionConstructor"))
            {
                boydEditPoint.Insert("\t\t\t' TODO: Update variable/s' defaults to meet test needs" + Environment.NewLine);

                boydEditPoint.Insert(StringHelper.GetTabString() + tvTempParameterList + Environment.NewLine);
                boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine);
            }

            if (originalClassCodeFuntion.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid)
            {
                string stringHolder = "iv{0}Return";
                stringHolder = string.Format(stringHolder, originalClassCodeFuntion.Name);
                //FIX ME (tabing)
                //boydEditPoint.Insert(string.Format("\t\t\tAssert.AreEqual({0}, default({1}));\r\n", stringHolder, originalClassCodeFuntion.Type.AsString));
            }


            boydEditPoint.Insert(Environment.NewLine);
            boydEditPoint.Insert("\t\t\t'TODO: Update Assert to meet test needs" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\t'Assert.AreEqual( , )" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\t" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\tThrow New Exception 'Not Implemented'" + Environment.NewLine);

            return(unitTestCodeFunction);
        }
Esempio n. 30
0
 internal static IEnumerable <IPropertyMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return(codeElements.OfType <CodeProperty2>().Where(p => p.Access == vsCMAccess.vsCMAccessPublic && p.IsShared == false).Select(p => new CodeDomPropertyMetadata(p, file)));
 }
Esempio n. 31
0
        private bool Refactor(IList <CodeVariable> vars, IList <CodeVariable> disabledVars, string codeClassName, string languageGUID, CodeElements codeMembers, EditPoint insertLocation, out int gotoLine)
        {
            IList <CodeVariable> toDisable;
            IList <CodeProperty> props;
            IList <string>       varNames;
            IList <string>       propNames;

            // set invalid goto-line:
            gotoLine = -1;

            if (vars != null)
            {
                // get the language and a list of currently available properties:
                CodeModelLanguages language = CodeHelper.GetCodeLanguage(languageGUID);
                props = EditorHelper.GetList <CodeProperty>(codeMembers, vsCMElement.vsCMElementProperty);

                // remove the variables from the list for which the properties exist:
                FindExistingProperties(vars, props, language, out toDisable, false);

                // add additional disabled variables:
                if (disabledVars != null)
                {
                    if (toDisable == null)
                    {
                        toDisable = disabledVars;
                    }
                    else
                    {
                        foreach (CodeVariable v in disabledVars)
                        {
                            if (!toDisable.Contains(v))
                            {
                                toDisable.Add(v);
                            }
                        }
                    }
                }

                if (cfgDialog == null)
                {
                    cfgDialog = new PropertyRefactorForm();
                    cfgDialog.GeneratorOptions = PropertyGeneratorOptions.GetterAndSetter | PropertyGeneratorOptions.ForcePropertyPublic | PropertyGeneratorOptions.ForceVarDontChange | PropertyGeneratorOptions.SuppressComment;
                    cfgDialog.RegionName       = RegionName;
                }

                // show dialog with possibility to change:
                cfgDialog.InitializeInterface(vars, toDisable, language);

                if (cfgDialog.ShowDialog() == DialogResult.OK && cfgDialog.ReadInterface(out vars, out varNames, out propNames))
                {
                    // generate code based on user modifications:
                    string code = GenerateSourceCodeOutput(codeClassName, vars, varNames, propNames, language, cfgDialog.GeneratorOptions, cfgDialog.RegionName);

                    // insert code to the editor:
                    if (!string.IsNullOrEmpty(code))
                    {
                        insertLocation.ReplaceText(insertLocation, code, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);

                        // jump without selection to the insertion place:
                        gotoLine = insertLocation.Line;
                        return(true);
                    }
                }
            }

            return(false);
        }
Esempio n. 32
0
 internal static IEnumerable <IDelegateMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return(codeElements.OfType <CodeDelegate2>().Where(d => d.Access == vsCMAccess.vsCMAccessPublic).Select(d => FromCodeDelegate(d, file)));
 }
Esempio n. 33
0
 internal static IEnumerable <IInterfaceMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return(codeElements.OfType <CodeInterface2>().Where(i => i.Access == vsCMAccess.vsCMAccessPublic).Select(i => new CodeDomInterfaceMetadata(i, file)));
 }
        /// <summary>Parses for strings by evaluating the element kind.</summary>
        /// <param name="element">The element.</param>
        /// <param name="progressWorker">The progress worker.</param>
        /// <param name="stringResources">The string resources.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="isCSharp">If set to <c>true</c> it is CSharp code.</param>
        /// <param name="startLine">The start line.</param>
        /// <param name="endLine">The end line.</param>
        private static void ParseForStrings(CodeElement element,
                                            Action <int> progressWorker,
                                            List <StringResource> stringResources,
                                            Settings settings,
                                            bool isCSharp,
                                            int startLine,
                                            int endLine)
        {
            if (element == null)
            {
                return;
            }

            try
            {
                if (element.StartPoint.Line > endLine)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                //element.StartPoint not implemented in VS2017 15.2 (26430.6) for expression bodied property getters (before no getter element was available)
                System.Diagnostics.Debug.Print("### Error: ParseForStrings({0}): element.StartPoint.Line > endLine? {1} - {2}", element.Kind, ex.GetType().Name, ex.Message);
                return;
            }

            try
            {
                if (element.EndPoint.Line < startLine)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                //element.EndPoint invalid when deleting or cutting text
                System.Diagnostics.Debug.Print("### Error: ParseForStrings(): element.EndPoint < startLine? {0} - {1}", ex.GetType().Name, ex.Message);
                return;
            }

#if DEBUG_OUTPUT
            string elementName = string.Empty;
            if (!isCSharp || (element.Kind != vsCMElement.vsCMElementImportStmt))
            {
                try { elementName = element.Name; } catch {}
            }
            System.Diagnostics.Debug.Print("  > ParseForStrings({0} '{1}')", element.Kind, elementName);
#endif

            if (element.IsCodeType &&
                ((element.Kind == vsCMElement.vsCMElementClass) ||
                 (element.Kind == vsCMElement.vsCMElementStruct)))
            {
                CodeElements elements = (element as CodeType).Members;

                foreach (CodeElement element2 in elements)
                {
                    ParseForStrings(element2, progressWorker, stringResources, settings, isCSharp, startLine, endLine);
                }
            }
            else if (element.Kind == vsCMElement.vsCMElementNamespace)
            {
                CodeElements elements = (element as CodeNamespace).Members;

                foreach (CodeElement element2 in elements)
                {
                    ParseForStrings(element2, progressWorker, stringResources, settings, isCSharp, startLine, endLine);
                }
            }
            else if (element.Kind == vsCMElement.vsCMElementProperty)
            {
                CodeProperty prop = element as CodeProperty;

                //CodeElement.StartPoint not implemented in VS2017 15.2 (26430.6) for expression bodied property getters
                //because before the expression bodied properties had Getter and Setter == null
                bool getterHasStartPoint = (prop.Getter != null) && (prop.Getter as CodeElement).HasStartPoint(),
                     setterHasStartPoint = (prop.Setter != null) && (prop.Setter as CodeElement).HasStartPoint();

                if (getterHasStartPoint)
                {
                    ParseForStrings(prop.Getter as CodeElement, progressWorker, stringResources, settings, isCSharp, startLine, endLine);
                }

                if (setterHasStartPoint)
                {
                    ParseForStrings(prop.Setter as CodeElement, progressWorker, stringResources, settings, isCSharp, startLine, endLine);
                }

                if (!getterHasStartPoint && !setterHasStartPoint)
                {
                    //expression bodied property
                    int lineNo = ParseForStrings(element, stringResources, settings, isCSharp, startLine, endLine);
                    if (lineNo > -1)
                    {
                        progressWorker(lineNo);
                    }
                } //if
            }
            else if ((element.Kind == vsCMElement.vsCMElementFunction) ||
                     (element.Kind == vsCMElement.vsCMElementVariable))
            {
                if ((element.Kind == vsCMElement.vsCMElementFunction) && settings.IgnoreMethod(element.Name))
                {
                    return;
                }

                int lineNo = ParseForStrings(element, stringResources, settings, isCSharp, startLine, endLine);
                if (lineNo > -1)
                {
                    progressWorker(lineNo);
                }
            } //else if
        }
Esempio n. 35
0
        ///-------------------------------------------------------------------------------------------------------------
        /// <summary>
        ///	 Returns field names in the specified class using code model.
        ///	 If publicOnly is true only public fields are returned.
        /// </summary>
        ///-------------------------------------------------------------------------------------------------------------
        public /*protected, but public for FSharp.Project.dll*/ void GetFieldNames(CodeClass codeClass, bool caseSensitive, bool onlyBaseClasses, int depth, int maxDepth, ref FieldDataDictionary fields)
        {
            if (codeClass != null && depth <= maxDepth)
            {
                if (!(onlyBaseClasses && depth == 0))
                {
                    foreach (CodeElement codeElement in codeClass.Members)
                    {
                        //vsCMElement kind = codeElement.Kind; //vsCMElementVariable
                        CodeVariable codeVariable = codeElement as CodeVariable;
                        if (codeVariable != null)
                        {
                            FieldData field = new FieldData(codeClass, codeVariable, depth);

                            if (field != null && !string.IsNullOrEmpty(field.Name))
                            {
                                if (fields == null)
                                {
                                    fields = new FieldDataDictionary(caseSensitive);
                                }

                                try
                                {
                                    if (!fields.ContainsKey(field.Name))
                                    {
                                        fields.Add(field.Name, field);
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }

                foreach (CodeElement baseCodeElement in codeClass.Bases)
                {
                    CodeClass baseCodeClass = baseCodeElement as CodeClass;
                    if (baseCodeClass != null)
                    {
                        CodeElements partCodeElements = null;
                        CodeClass2   baseCodeClass2   = baseCodeClass as CodeClass2;
                        if (baseCodeClass2 != null)
                        {
                            vsCMClassKind classKind = baseCodeClass2.ClassKind;
                            if ((classKind | vsCMClassKind.vsCMClassKindPartialClass) == vsCMClassKind.vsCMClassKindPartialClass)
                            {
                                try
                                {
                                    partCodeElements = baseCodeClass2.Parts;
                                }
                                catch
                                {
                                }
                            }
                        }

                        if (partCodeElements != null && partCodeElements.Count > 1)
                        {
                            foreach (CodeElement partCodeElement in partCodeElements)
                            {
                                CodeClass partCodeClass = partCodeElement as CodeClass;
                                if (partCodeClass != null)
                                {
                                    GetFieldNames(partCodeClass, caseSensitive, onlyBaseClasses, depth + 1, maxDepth, ref fields);
                                }
                            }
                        }
                        else
                        {
                            GetFieldNames(baseCodeClass, caseSensitive, onlyBaseClasses, depth + 1, maxDepth, ref fields);
                        }
                    }
                }
            }
        }
        /// <summary>Parses for strings by iterating through the FileCodeModel.</summary>
        /// <param name="startPoint">The start point.</param>
        /// <param name="endPoint">The end point.</param>
        /// <param name="lastDocumentLength">Last length of the document.</param>
        private void ParseForStrings(TextPoint startPoint,
                                     TextPoint endPoint,
                                     int lastDocumentLength)
        {
            //0.35-0.06 seconds (threaded: 2.47-1.77 seconds)
            List <StringResource> stringResources = new List <StringResource>();

            bool isFullDocument          = startPoint.AtStartOfDocument && endPoint.AtEndOfDocument,
                 isTextWithStringLiteral = true;
            int startLine      = startPoint.Line,
                startCol       = startPoint.LineCharOffset,
                endLine        = endPoint.Line,
                endCol         = endPoint.LineCharOffset,
                documentLength = endPoint.Parent.EndPoint.Line,
                insertIndex    = 0;

            if (isFullDocument)
            {
                m_StringResources.Clear();
            }
            else
            {
                #region document manipulated -> adapt string resources and locations

                //determine whether the text between startLine and endLine (including) contains double quotes
                EditPoint editPoint = startPoint.CreateEditPoint() as EditPoint2;
                if (!startPoint.AtStartOfLine)
                {
                    editPoint.StartOfLine();
                }
                isTextWithStringLiteral = editPoint.GetLines(startLine, endLine + 1).Contains("\"");

                //move trailing locations behind changed lines if needed and
                //remove string resources on changed lines

                int lineOffset = documentLength - lastDocumentLength;
#if DEBUG_OUTPUT
                System.Diagnostics.Debug.Print("  Line offset is {0}", lineOffset);
#endif

                for (int i = m_StringResources.Count - 1; i >= 0; --i)
                {
                    StringResource stringResource = m_StringResources[i];
                    int            lineNo         = stringResource.Location.X;

                    if (lineNo + lineOffset > endLine)
                    {
                        if (lineOffset != 0)
                        {
#if DEBUG_OUTPUT
                            System.Diagnostics.Debug.Print("  Move string literal from line {0} to {1}", lineNo, lineNo + lineOffset);
#endif
                            stringResource.Offset(lineOffset, 0); //move
                        } //if
                    }
                    else if (lineNo >= startLine)
                    {
#if DEBUG_OUTPUT
                        System.Diagnostics.Debug.Print("  Remove string literal {0} ({1}): {2}", i, stringResource.Location, stringResource.Text);
#endif
                        m_StringResources.RemoveAt(i); //remove changed line
                    }
                    else if (insertIndex == 0)
                    {
#if DEBUG_OUTPUT
                        System.Diagnostics.Debug.Print("  List insert index is {0} / {1}", i + 1, m_StringResources.Count - 1);
#endif
                        insertIndex = i + 1;
                    } //else if
                }     //for

                #endregion
            } //else

#if DEBUG_OUTPUT
            System.Diagnostics.Debug.Print("  Text has{0} string literals.", isTextWithStringLiteral ? string.Empty : " no");
#endif

            if (isTextWithStringLiteral)
            {
                CodeElements elements = m_Window.Document.ProjectItem.FileCodeModel.CodeElements;

                foreach (CodeElement element in elements)
                {
                    ParseForStrings(element, m_DoProgress, stringResources, m_Settings, m_IsCSharp, startLine, endLine);

#if DEBUG
                    if (element.Kind == vsCMElement.vsCMElementProperty)
                    {
                        CodeProperty prop = element as CodeProperty;

                        if ((prop.Getter == null) && (prop.Setter == null))
                        {
                            //here we have an expression bodied property
                            //if (m_IVsTextView != null)
                            //{
                            //  m_IVsTextView.
                            //}
                        }
                    }
#endif
                } //foreach

#if DEBUG_OUTPUT
                System.Diagnostics.Debug.Print("  Found {0} string literals", stringResources.Count);
#endif

                if (isFullDocument)
                {
                    m_StringResources.AddRange(stringResources);
                }
                else if (stringResources.Count > 0)
                {
                    m_StringResources.InsertRange(insertIndex, stringResources);
                }
            } //if

            m_DoCompleted(isFullDocument || (stringResources.Count > 0));
        }
Esempio n. 37
0
 internal static IEnumerable <IClassMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return(codeElements.OfType <CodeClass2>().Where(c => c.Access == vsCMAccess.vsCMAccessPublic && c.FullName != "System.Object").Select(c => new CodeDomClassMetadata(c, file)));
 }
        private void AddUsingStatement(FileCodeModel model, CodeElements codeElements, string usingStatement)
        {
            bool usingStatementFound = false;
            CodeImport lastCodeElement = null;

            foreach (CodeElement codeElement in codeElements)
            {
                if (codeElement.Kind == vsCMElement.vsCMElementImportStmt)
                {
                    CodeImport codeImport = codeElement as CodeImport;
                    if (codeImport.Namespace == usingStatement)
                    {
                        usingStatementFound = true;
                    }
                    lastCodeElement = codeImport;
                }

                AddUsingStatement(model, codeElement.Children, usingStatement);
            }

            if (!usingStatementFound)
            {
                if (lastCodeElement != null)
                {
                    //FileCodeModel2 model2 = model as FileCodeModel2;
                    //model2.AddImport(usingStatement);

                    EditPoint2 editPoint = (EditPoint2)lastCodeElement.GetEndPoint().CreateEditPoint();
                    editPoint.InsertNewLine(1);
                    editPoint.Indent(null, 1);
                    editPoint.Insert("using " + usingStatement + ";");

                    Helpers.LogMessage(model.DTE, model.DTE, Helpers.GetFullPathOfProjectItem(lastCodeElement.ProjectItem) + ": Added using statement '" + usingStatement + "'");
                }
            }
        }
Esempio n. 39
0
 public IEnumerator GetEnumerator() => CodeElements.GetEnumerator();
        /// <summary>
        /// Recursively scan to extract all CodeType elements. But since the CodeModel contains *all*
        /// referenced types (including the whole of System.*), it would be too slow to consider them all. 
        /// We're only interested in types defined in the project itself, so we disregard namespaces that 
        /// contain one or more type with InfoLocation != vsCMInfoLocation.vsCMInfoLocationProject
        /// </summary>
        private static IEnumerable<CodeType> GetCodeTypesFromLocalCodeElements(CodeElements codeElements)
        {
            var results = new List<CodeType>();
            foreach (CodeElement codeElement in codeElements) {
                if ((codeElement is CodeType) && (codeElement.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject)) {
                    results.Add((CodeType)codeElement);
                }

                CodeElements childrenToSearch = null;
                if ((codeElement is CodeClass) && (codeElement.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject)) {
                    childrenToSearch = ((CodeClass)codeElement).Members;
                } else if (codeElement is CodeNamespace) {
                    var codeNamespace = (CodeNamespace)codeElement;
                    if (!ExcludedNamespaces.Contains(codeNamespace.FullName, StringComparer.Ordinal))
                        childrenToSearch = codeNamespace.Members;
                }
                if (childrenToSearch != null) {
                    var childResults = GetCodeTypesFromLocalCodeElements(childrenToSearch);
                    results.AddRange(childResults);
                }
            }
            return results;
        }
Esempio n. 41
0
        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            itemsFunc.Clear();

            //Get DTE
            DTE2 dte = (DTE2)Package.GetGlobalService(typeof(DTE));

            if (dte == null)
            {
                return;
            }

            //Get Document name(path)
            Document ActiveDoc = dte.ActiveDocument;

            if (ActiveDoc == null)
            {
                return;
            }


            ProjectItem DocItem = ActiveDoc.ProjectItem;

            if (DocItem == null)
            {
                return;
            }

            FileCodeModel DocModel = DocItem.FileCodeModel;

            if (DocModel == null || DocModel.CodeElements == null)
            {
                return;
            }

            foreach (CodeElement CodeElem in DocModel.CodeElements)
            {
                if (CodeElem.Kind == vsCMElement.vsCMElementFunction)
                {
                    StatisticSetFunc SSF = ParseFunction(CodeElem, false);
                    itemsFunc.Add(SSF);
                }

                else if (CodeElem.Kind == vsCMElement.vsCMElementClass)
                {
                    CodeClass    cClass      = CodeElem as CodeClass;
                    CodeElements all_methods = cClass.Members;
                    foreach (CodeElement method in all_methods)
                    {
                        StatisticSetFunc SSF = ParseFunction(method, true);
                        if (SSF != null)
                        {
                            itemsFunc.Add(SSF);
                        }
                    }
                }
            }

            Stat.Items.Refresh();
        }
        private bool AddMethodCall(CodeElements codeElements, string className, string targetMethodName, string methodCall)
        {
            CodeClass featureReceiverClass = GetClassByName(codeElements, className);
            CodeFunction function = null;
            bool result = false;

            if (featureReceiverClass != null)
            {

                //try to find the targetMethodName and if found then add the methodCall at the end
                foreach (CodeElement codeElement in featureReceiverClass.Members)
                {
                    if (codeElement.Kind == vsCMElement.vsCMElementFunction)
                    {
                        if (codeElement.Name == targetMethodName)
                        {
                            function = codeElement as CodeFunction;
                        }
                    }
                }

                if (function == null)
                {
                    //method not found (SPFeatureReceiverProperties properties)
                    function = featureReceiverClass.AddFunction(targetMethodName, vsCMFunction.vsCMFunctionFunction, "void", 0, vsCMAccess.vsCMAccessPublic, null);
                    CodeFunction2 function2 = function as CodeFunction2;
                    function2.OverrideKind = vsCMOverrideKind.vsCMOverrideKindOverride;
                    function.AddParameter("properties", "SPFeatureReceiverProperties", -1);
                    function.AddAttribute("SharePointPermission", "(SecurityAction.LinkDemand, ObjectModel = true)");
                    Helpers.LogMessage(function.DTE, function.DTE,  Helpers.GetFullPathOfProjectItem(function.ProjectItem) + ": Added method '" + methodCall + "'");

                }

                if (function != null)
                {
                    EditPoint2 editPoint = (EditPoint2)function.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

                    //get indent of editpoint (at the end of the function
                    int charsBefore = editPoint.AbsoluteCharOffset;
                    int lineAdded = editPoint.Line;

                    if (!methodCall.StartsWith("this."))
                    {
                        //add this. to be StyleCop conform
                        methodCall = "this." + methodCall;
                    }

                    editPoint.InsertNewLine(1);
                    editPoint.Insert("// Call to method " + methodCall);
                    editPoint.InsertNewLine(1);
                    editPoint.Indent(null, 2);
                    editPoint.Insert(methodCall);
                    editPoint.InsertNewLine(1);
                    editPoint.Indent(null, 2);

                    Helpers.LogMessage(function.DTE, function.DTE, Helpers.GetFullPathOfProjectItem(function.ProjectItem) + "(" + lineAdded.ToString() + ",0): Added code to method '" + methodCall + "'");

                    result = true;
                }
            }
            else
            {
                throw new Exception("Class " + className + " not found");
            }
            return result;
        }
Esempio n. 43
0
 internal static IEnumerable <IEnumMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return(codeElements.OfType <CodeEnum>().Where(e => e.Access == vsCMAccess.vsCMAccessPublic).Select(e => new CodeDomEnumMetadata(e, file)));
 }
Esempio n. 44
0
 internal static IEnumerable <IParameterMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return(codeElements.OfType <CodeParameter2>().Select(p => new CodeDomParameterMetadata(p, file)));
 }
Esempio n. 45
0
        private static CodeElement GetCodeElementAtTextPoint(vsCMElement eRequestedCodeElementKind, CodeElements colCodeElements, EnvDTE.TextPoint objTextPoint)
        {
            CodeElement objResultCodeElement = null;


            if (colCodeElements == null)
            {
                return(null);
            }
            foreach (var objCodeElement in colCodeElements.Cast <CodeElement>())
            {
                if (objCodeElement.StartPoint.GreaterThan(objTextPoint))
                {
                    // The code element starts beyond the point
                }
                else if (objCodeElement.EndPoint.LessThan(objTextPoint))
                {
                    // The code element ends before the point

                    // The code element contains the point
                }
                else
                {
                    if (objCodeElement.Kind == eRequestedCodeElementKind)
                    {
                        // Found
                        objResultCodeElement = objCodeElement;
                    }

                    // We enter in recursion, just in case there is an inner code element that also
                    // satisfies the conditions, for example, if we are searching a namespace or a class
                    var colCodeElementMembers = GetCodeElementMembers(objCodeElement);

                    var objMemberCodeElement = GetCodeElementAtTextPoint(eRequestedCodeElementKind, colCodeElementMembers, objTextPoint);

                    if ((objMemberCodeElement != null))
                    {
                        // A nested code element also satisfies the conditions
                        objResultCodeElement = objMemberCodeElement;
                    }

                    break;
                }
            }

            return(objResultCodeElement);
        }
Esempio n. 46
0
 internal static IEnumerable <IEventMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return(codeElements.OfType <CodeEvent>().Where(f => f.Access == vsCMAccess.vsCMAccessPublic && f.IsShared == false).Select(f => new CodeDomEventMetadata(f, file)));
 }
Esempio n. 47
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;
        }
Esempio n. 48
0
        static void GetAllClassFromProjectRaw(ProjectItems prjItems, List <CodeClass>
                                              someclass, List <string> interfaceNames, List <string> attributeNames)
        {
            ProjectItem prjItem = null;

            for (int i = 1; i <= prjItems.Count; ++i)
            {
                prjItem = prjItems.Item(i);
                FileCodeModel codeModel = prjItem.FileCodeModel;
                if (codeModel == null)
                {
                    if (prjItem.ProjectItems == null || prjItem.ProjectItems.Count < 1)
                    {
                        continue;
                    }
                    GetAllClassFromProjectRaw(prjItem.ProjectItems, someclass, interfaceNames,
                                              attributeNames);
                }
                else
                {
                    CodeElements elements = codeModel.CodeElements;
                    for (int j = 1; j <= elements.Count; ++j)
                    {
                        CodeElement element = elements.Item(j);
                        if (element.Kind == vsCMElement.vsCMElementNamespace)
                        {
                            CodeNamespace cns       = (CodeNamespace)element;
                            CodeElements  melements = cns.Members;
                            for (int k = 1; k <= melements.Count; ++k)
                            {
                                CodeElement melemt = melements.Item(k);
                                if (melemt.Kind == vsCMElement.vsCMElementClass)
                                {
                                    if (!melemt.Name.EndsWith("Resources") && !
                                        melemt.Name.EndsWith("Settings"))
                                    {
                                        if (interfaceNames.Count == 0 && attributeNames.Count == 0)
                                        {
                                            someclass.Add((CodeClass)melemt);
                                        }
                                        else
                                        {
                                            CodeClass c      = (CodeClass)melemt;
                                            bool      bToAdd = false;
                                            if (interfaceNames.Count > 0)
                                            {
                                                CodeElements ce = c.ImplementedInterfaces;
                                                foreach (CodeElement cel in ce)
                                                {
                                                    if (interfaceNames.Contains(cel.Name))
                                                    {
                                                        if (!someclass.Contains(c))
                                                        {
                                                            bToAdd = true;
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                            // remove comment if you want i'll be able to controll
                                            // attribute presence
                                            //if (bToAdd && attributeNames.Count > 0)
                                            //{
                                            // CodeElements cea = c.Attributes;
                                            // foreach (CodeElement cel in cea)
                                            // if (attributeNames.Contains((cel.Name)))
                                            // {
                                            // if (!someclass.Contains(c))
                                            // bToAdd = true;
                                            // break;
                                            // }
                                            //}
                                            if (bToAdd)
                                            {
                                                someclass.Add(c);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
 internal static IEnumerable<IInterfaceMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return codeElements.OfType<CodeInterface2>().Where(i => i.Access == vsCMAccess.vsCMAccessPublic).Select(i => new CodeDomInterfaceMetadata(i, file));
 }
        private static string GetNamespace(CodeElements attrs)
        {
            if (attrs == null) return DefaultModuleName;
            var namespaceFromAttr = from a in attrs.Cast<CodeAttribute2>()
                                    where a.Name.EndsWith(ModuleNameAttributeName, StringComparison.OrdinalIgnoreCase)
                                    from arg in a.Arguments.Cast<CodeAttributeArgument>()
                                    let v = (arg.Value ?? "").Trim('\"')
                                    where !string.IsNullOrWhiteSpace(v)
                                    select v;

            return namespaceFromAttr.FirstOrDefault() ?? DefaultModuleName;
        }
        private void AddMethodToClass(CodeElements codeElements, string className, string methodCode)
        {
            CodeClass featureReceiverClass = GetClassByName(codeElements, className);

            //add the method to the class
            if (featureReceiverClass != null)
            {
                EditPoint2 editPoint = (EditPoint2)featureReceiverClass.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

                StringReader reader = new StringReader(methodCode);
                string line = reader.ReadLine();
                while (line != null)
                {
                    editPoint.InsertNewLine(1);
                    editPoint.Indent(null, 2);
                    editPoint.Insert(line);
                    line = reader.ReadLine();
                }

                editPoint.InsertNewLine(1);

                Helpers.LogMessage(featureReceiverClass.DTE, featureReceiverClass.DTE,  Helpers.GetFullPathOfProjectItem(featureReceiverClass.ProjectItem) + ": Added new method");

            }
            else
            {
                throw new Exception("Class " + className + " not found");
            }
        }
 private CodeClass GetClass(CodeElements codeElements)
 {
     var elements = codeElements.Cast<CodeElement>().ToList();
     var result = elements.FirstOrDefault(codeElement => codeElement.Kind == vsCMElement.vsCMElementClass) as CodeClass;
     if (result != null)
     {
         return result;
     }
     foreach (var codeElement in elements)
     {
         result = GetClass(codeElement.Children);
         if (result != null)
         {
             return result;
         }
     }
     return null;
 }
        private CodeClass GetClassByName(CodeElements codeElements, string className)
        {
            //if className is empty we will take the first class in the file

            CodeClass result = null;

            //add the method to the class
            foreach (CodeElement codeElement in codeElements)
            {
                if (codeElement.Kind == vsCMElement.vsCMElementClass)
                {
                    CodeClass featureReceiverClass = codeElement as CodeClass;
                    if ((featureReceiverClass.Name == className) || (className == ""))
                    {
                        result = featureReceiverClass;
                    }
                }
                if (result == null)
                {
                    result = GetClassByName(codeElement.Children, className);
                }
            }
            return result;
        }
Esempio n. 54
0
        private bool AddMethodCall(CodeElements codeElements, string className, string targetMethodName, string methodCall)
        {
            CodeClass    featureReceiverClass = GetClassByName(codeElements, className);
            CodeFunction function             = null;
            bool         result = false;

            if (featureReceiverClass != null)
            {
                //try to find the targetMethodName and if found then add the methodCall at the end
                foreach (CodeElement codeElement in featureReceiverClass.Members)
                {
                    if (codeElement.Kind == vsCMElement.vsCMElementFunction)
                    {
                        if (codeElement.Name == targetMethodName)
                        {
                            function = codeElement as CodeFunction;
                        }
                    }
                }

                if (function == null)
                {
                    //method not found (SPFeatureReceiverProperties properties)
                    function = featureReceiverClass.AddFunction(targetMethodName, vsCMFunction.vsCMFunctionFunction, "void", 0, vsCMAccess.vsCMAccessPublic, null);
                    CodeFunction2 function2 = function as CodeFunction2;
                    function2.OverrideKind = vsCMOverrideKind.vsCMOverrideKindOverride;
                    function.AddParameter("properties", "SPFeatureReceiverProperties", -1);
                    function.AddAttribute("SharePointPermission", "(SecurityAction.LinkDemand, ObjectModel = true)");
                    Helpers.LogMessage(function.DTE, function.DTE, Helpers.GetFullPathOfProjectItem(function.ProjectItem) + ": Added method '" + methodCall + "'");
                }

                if (function != null)
                {
                    EditPoint2 editPoint = (EditPoint2)function.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

                    //get indent of editpoint (at the end of the function
                    int charsBefore = editPoint.AbsoluteCharOffset;
                    int lineAdded   = editPoint.Line;

                    if (!methodCall.StartsWith("this."))
                    {
                        //add this. to be StyleCop conform
                        methodCall = "this." + methodCall;
                    }

                    editPoint.InsertNewLine(1);
                    editPoint.Insert("// Call to method " + methodCall);
                    editPoint.InsertNewLine(1);
                    editPoint.Indent(null, 2);
                    editPoint.Insert(methodCall);
                    editPoint.InsertNewLine(1);
                    editPoint.Indent(null, 2);

                    Helpers.LogMessage(function.DTE, function.DTE, Helpers.GetFullPathOfProjectItem(function.ProjectItem) + "(" + lineAdded.ToString() + ",0): Added code to method '" + methodCall + "'");

                    result = true;
                }
            }
            else
            {
                throw new Exception("Class " + className + " not found");
            }
            return(result);
        }
 private static IEnumerable<IntellisenseProperty> GetProperties(CodeElements props, HashSet<string> traversedTypes, HashSet<string> references = null)
 {
     return from p in props.OfType<CodeProperty>()
            where !p.Attributes.Cast<CodeAttribute>().Any(a => a.Name == "IgnoreDataMember")
            where p.Getter != null && !p.Getter.IsShared && p.Getter.Access == vsCMAccess.vsCMAccessPublic
            select new IntellisenseProperty
            {
                Name = GetName(p),
                Type = GetType(p.Parent, p.Type, traversedTypes, references),
                Summary = GetSummary(p)
            };
 }
Esempio n. 56
0
 internal static IEnumerable <IMethodMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return(codeElements.OfType <CodeFunction2>().Where(f => f.Access == vsCMAccess.vsCMAccessPublic && f.FunctionKind != vsCMFunction.vsCMFunctionConstructor && f.IsShared == false).Select(f => new CodeDomMethodMetadata(f, file)));
 }
 internal static IEnumerable<IDelegateMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return codeElements.OfType<CodeDelegate2>().Where(d => d.Access == vsCMAccess.vsCMAccessPublic).Select(d => FromCodeDelegate(d, file));
 }
        public bool Start()
        {
            try
            {
                if (!ProjectItem.IsOpen)
                {
                    ProjectItem.Open();
                }

                Document     document           = ProjectItem.Document;
                TextDocument textDocument       = document.Object(Constants.TEXT_DOCUMENT) as TextDocument;
                TextPoint    startPoint         = textDocument.StartPoint;
                TextPoint    endPoint           = textDocument.EndPoint;
                int          lastDocumentLength = textDocument.EndPoint.Line;

                logger.Debug("Start - parsing document: " + FileName);

                List <StringResource> stringResources = new List <StringResource>();

                bool isFullDocument          = startPoint.AtStartOfDocument && endPoint.AtEndOfDocument,
                     isTextWithStringLiteral = true;
                int startLine      = startPoint.Line;
                int startCol       = startPoint.LineCharOffset;
                int endLine        = endPoint.Line;
                int endCol         = endPoint.LineCharOffset;
                int documentLength = endPoint.Parent.EndPoint.Line;
                int insertIndex    = 0;

                if (isFullDocument)
                {
                    StringResources.Clear();
                }
                else
                {
                    //determine whether the text between startLine and endLine (including) contains double quotes
                    EditPoint editPoint = startPoint.CreateEditPoint() as EditPoint2;
                    if (!startPoint.AtStartOfLine)
                    {
                        editPoint.StartOfLine();
                    }
                    isTextWithStringLiteral = editPoint.GetLines(startLine, endLine + 1).Contains("\"");

                    //move trailing locations behind changed lines if needed and
                    //remove string resources on changed lines
                    int lineOffset = documentLength - lastDocumentLength;

                    for (int i = StringResources.Count - 1; i >= 0; --i)
                    {
                        StringResource stringResource = StringResources[i];
                        int            lineNo         = stringResource.Location.X;

                        if (lineNo + lineOffset > endLine)
                        {
                            if (lineOffset != 0)
                            {
                                stringResource.Offset(lineOffset, 0); //move
                            }
                        }
                        else if (lineNo >= startLine)
                        {
                            StringResources.RemoveAt(i); //remove changed line
                        }
                        else if (insertIndex == 0)
                        {
                            insertIndex = i + 1;
                        }
                    }
                }

                if (isTextWithStringLiteral)
                {
                    CodeElements elements = ProjectItem.FileCodeModel.CodeElements;

                    foreach (CodeElement element in elements)
                    {
                        ParseForStrings(element, stringResources, isCsharp, m_Settings, startLine, endLine);
                    }

                    if (isFullDocument)
                    {
                        StringResources.AddRange(stringResources);
                    }
                    else if (stringResources.Count > 0)
                    {
                        StringResources.InsertRange(insertIndex, stringResources);
                    }
                }

                logger.Debug("End - parsing document: " + FileName);

                return(true);
            } catch (Exception e)
            {
                logger.Warn(e, "An error occurred while parsing file: " + FileName);
                return(false);
            }
        }
Esempio n. 59
0
 internal static IEnumerable<IEventMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file)
 {
     return codeElements.OfType<CodeEvent>().Where(f => f.Access == vsCMAccess.vsCMAccessPublic && f.IsShared == false).Select(f => new CodeDomEventMetadata(f, file));
 }
Esempio n. 60
0
 public static IEnumerable <CodeElement> GetClasses(this CodeElements codeElements)
 {
     return(codeElements.GetCodeElements(vsCMElement.vsCMElementClass, vsCMElement.vsCMElementNamespace, vsCMElement.vsCMElementClass));
 }