private void Button1Click(object sender, RoutedEventArgs e) { result = ""; TextBox1.Text = ""; // Get DTE DTE dte = (DTE)Package.GetGlobalService(typeof(DTE)); // Get Full Path to Document string docPath = dte.ActiveDocument.FullName; // Get File Content fileContent = File.ReadAllLines(path: Path.GetFullPath(dte.ActiveDocument.FullName)); // Get File Code Model FileCodeModel fcm = dte.ActiveDocument.ProjectItem.FileCodeModel; CodeElements elts = null; elts = fcm.CodeElements; CodeElement elt = null; for (int i = 1; i <= fcm.CodeElements.Count; i++) { elt = elts.Item(i); SearchForFun(elt, elts, i); } }
private void PopulateRecursively(TreeNodeCollection nodes, CodeElements elements) { for (int i = 1; i <= elements.Count; i++) { VCCodeElement element = elements.Item(i) as VCCodeElement; if (IsElementAcceptableType(element)) { TreeNode node = new TreeNode(); node.Text = element.Name; node.Tag = element; IPicture picture = (IPicture)element.Picture; Icon icon = Icon.FromHandle(new IntPtr(picture.Handle)); imageList.Images.Add(icon); node.ImageIndex = node.SelectedImageIndex = imageList.Images.Count - 1; node.Checked = true; nodes.Add(node); PopulateRecursively(node.Nodes, element.Children); } } }
public List <CodeElement> GetCodeElementList(ProjectItem codeProjectItem) { // TODO: 增加对codeProjectItem 参数的检查, 以确保其对应的是代码文件 List <CodeElement> codeElementList = new List <CodeElement>(); Debug.Assert(codeProjectItem != null); Debug.Assert(codeProjectItem.FileCodeModel != null); if (codeProjectItem.FileCodeModel != null) { CodeElements ces = codeProjectItem.FileCodeModel.CodeElements; for (int i = 1; i <= ces.Count; i++) { CodeElement ce = ces.Item(i); if (ce.IsCodeType) { codeElementList.Add(ce); } for (int j = 1; j <= ce.Children.Count; j++) { CodeElement ce2 = ce.Children.Item(j); if (ce2.IsCodeType) { codeElementList.Add(ce2); } } } } return(codeElementList); }
public IEnumerable <TypeScriptModule> GetAllInterfaces() { var typeContext = BuildContext(); var byModuleName = new Dictionary <string, TypeScriptModule>(); var tsMap = new Dictionary <CodeClass, TypeScriptInterface>(); new SolutionTraverser(this.Solution, (ns) => { new NamespaceTraverser(ns, (codeClass) => { InterfaceType interfaceType; if (!typeContext.TryGetInterfaceType(codeClass.FullName, out interfaceType)) { return; } var values = interfaceType.AttributeValues; TypeScriptModule module; if (!byModuleName.TryGetValue(values.Module, out module)) { module = new TypeScriptModule { QualifiedName = values.Module }; byModuleName.Add(values.Module, module); } var tsInterface = BuildInterface(codeClass, values, typeContext); tsMap.Add(codeClass, tsInterface); tsInterface.Module = module; module.Interfaces.Add(tsInterface); }); }); var tsInterfaces = tsMap.Values.ToList(); tsMap.Keys.ToList().ForEach(codeClass => { CodeElements baseClasses = codeClass.Bases; if (baseClasses != null && baseClasses.Count > 0) { CodeElement baseClass = baseClasses.Item(1); if (baseClass != null) { ///since this is traversing project files, a class's base class can be defined in multiple files, if that is a partial class. ///SingleOrDefault fails if it finds multiple files ==> That's why use FirstOrDefault var parent = tsInterfaces.FirstOrDefault(intf => intf.FullName == baseClass.FullName); if (parent != null) { tsMap[codeClass].Parent = parent; } } } }); return(byModuleName.Values .OrderBy(m => m.QualifiedName) .ToList()); }
public void Arguments_GetArgumentByItemIndexWhenTwoPositionalArguments_ReturnsArgumentAtIndex() { CreateMSBuildAttribute("Test.MyAttribute"); helper.AddPositionalArguments("StringValue", false); CreateAttribute(); CodeElements args = codeAttribute.Arguments; CodeAttributeArgument arg = args.Item(2) as CodeAttributeArgument; Assert.AreEqual("False", arg.Value); }
public void SearchForFun(CodeElement elt, CodeElements elts, long loc) { switch (elt.Kind) { case vsCMElement.vsCMElementNamespace: { CodeNamespace cns = null; cns = (CodeNamespace)elt; CodeElements memsVb = null; memsVb = cns.Members; for (int j = 1; j <= cns.Members.Count; j++) { SearchForFun(memsVb.Item(j), memsVb, j); } break; } case vsCMElement.vsCMElementClass: { //result += elem.Name + Environment.NewLine; break; CodeClass cns = null; cns = (CodeClass)elt; CodeElements memsVb = null; memsVb = cns.Members; for (int j = 1; j <= cns.Members.Count; j++) { SearchForFun(memsVb.Item(j), memsVb, j); } break; } case vsCMElement.vsCMElementFunction: { int startLine = elt.StartPoint.Line; int endLine = elt.EndPoint.Line; int linesEmpty = 0; int linesComments = 0; int amountKeyWords = 0; string test = ""; FunctionHandler(startLine, endLine, ref linesEmpty, ref linesComments, ref amountKeyWords, ref test); result += elt.Name + Environment.NewLine + "Total Lines: " + (endLine - startLine + 1).ToString() + Environment.NewLine + "Empty Lines: " + linesEmpty.ToString() + Environment.NewLine + "Comment Lines: " + linesComments.ToString() + Environment.NewLine + "Key Words: " + amountKeyWords.ToString() + Environment.NewLine + Environment.NewLine; break; } default: break; } TextBox1.Text = result; }
public void Arguments_GetArgumentByItemNameWhenTwoNamedArguments_ReturnsArgument() { CreateMSBuildAttribute("Test.MyAttribute"); helper.AddNamedArgument("One", "OneValue"); helper.AddNamedArgument("Two", false); CreateAttribute(); CodeElements args = codeAttribute.Arguments; CodeAttributeArgument arg = args.Item("Two") as CodeAttributeArgument; Assert.AreEqual("False", arg.Value); }
public void Attributes_PropertyHasOneAttribute_ReturnsOneAttribute() { helper.CreateProperty("MyProperty"); helper.AddAttribute("Tests.TestAttribute", "TestAttribute"); CreateCodeProperty2(); CodeElements attributes = property.Attributes; CodeAttribute2 attribute = attributes.Item(1) as CodeAttribute2; Assert.AreEqual(1, attributes.Count); Assert.AreEqual("Tests.TestAttribute", attribute.FullName); }
/// <summary> /// return CodeClass of classname indicated /// </summary> /// <param name="prj"></param> /// <param name="className"></param> /// <returns></returns> public static CodeClass GetClassFromProject(Project prj, string className) { CodeClass someclass = null; try { if (prj != null) { ProjectItem prjItem; for (int i = 1; i <= prj.ProjectItems.Count; ++i) { prjItem = prj.ProjectItems.Item(i); FileCodeModel codeModel = prjItem.FileCodeModel; if (codeModel == null) { continue; } 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) && (melemt.Name.Equals(className))) { someclass = (CodeClass)melemt; break; } } } if (someclass != null) { break; } } if (someclass != null) { break; } } } } catch (Exception) { /* insert your message here */ } return(someclass); }
public void Attributes_ClassHasOneAttribute_ReturnsOneAttribute() { CreateProjectContent(); CreateClass("TestClass"); AddAttributeToClass("TestAttribute"); CreateCodeType(); CodeElements attributes = codeType.Attributes; CodeAttribute2 attribute = attributes.Item(1) as CodeAttribute2; Assert.AreEqual(1, attributes.Count); Assert.AreEqual("Test", attribute.Name); }
private void fillNamespaces(CodeElements elements, TreeNode node) { for (int i = 1; i <= elements.Count; ++i) { var name = elements.Item(i) as CodeNamespace; if (name == null) { continue; } fillNamespaces(name.Members, node); fillTypes(name.Members, node); } }
private static TOutput[] ConvertCodeElementsToArray <TInput, TOutput>(CodeElements codeElements, Converter <TInput, TOutput> converter) { int count = codeElements.Count; if (count == 0) { return(EmptyArray <TOutput> .Instance); } TOutput[] result = new TOutput[count]; for (int i = 0; i < count; i++) { result[i] = converter((TInput)codeElements.Item(i + 1)); } return(result); }
/** * Checks a method inside a test suite class to determine if it * is a valid test method (void return value, no arguments, name * begins with "test"). If so, it is added to the suite's list of * tests. * * @param element the method handle to be checked. */ private void CheckMethod(VCCodeFunction function) { string name = function.Name; int lineNum = function.StartPoint.Line; bool isStatic = function.IsShared; if (name.StartsWith("Test") || name.StartsWith("test")) { if (function.Type.AsString == "void" && IsMethodParameterless(function)) { testCases.Add(new TestCase(function)); } } else if (name == "createSuite") { if (isStatic && function.Type.AsString.IndexOf('*') >= 0 && IsMethodParameterless(function)) { createLineNumber = lineNum; } } else if (name == "destroySuite") { CodeElements parameters = function.Parameters; if (parameters.Count == 1) { VCCodeParameter parameter = (VCCodeParameter)parameters.Item(1); if (isStatic && parameter.Type.AsString.IndexOf('*') >= 0 && function.Type.AsString == "void") { destroyLineNumber = lineNum; } } } }
public IEnumerable <TypeScriptModule> GetAllInterfaces() { TypeContext typeContext = BuildContext(); var byModuleName = new Dictionary <string, TypeScriptModule>(); var tsMap = new Dictionary <CodeClass, TypeScriptInterface>(); var tsEnumMap = new Dictionary <CodeEnum, TypeScriptEnum>(); new SolutionTraverser(Solution, ns => { new NamespaceTraverser(ns, codeClass => ProcessCodeClass(typeContext, tsMap, byModuleName, codeClass), codeEnum => ProcessCodeEnum(typeContext, tsEnumMap, byModuleName, codeEnum) ); }); List <TypeScriptInterface> tsInterfaces = tsMap.Values.ToList(); tsMap.Keys.ToList().ForEach(codeClass => { CodeElements baseClasses = codeClass.Bases; if (baseClasses.Count > 0) { CodeElement baseClass = baseClasses.Item(1); if (baseClass != null) { // We must remove all text after < char, to compare generic types. // It's not really correct, but must work in common cases. var baseClassNonGenericFullName = baseClass.FullName.Split('<')[0]; TypeScriptInterface parent = tsInterfaces.FirstOrDefault(intf => baseClassNonGenericFullName == intf.FullName.Split('<')[0]); if (parent != null) { tsMap[codeClass].Parent = parent; } } } }); return(byModuleName.Values .OrderBy(m => m.QualifiedName) .ToList()); }
/// <inheritdoc /> protected override int GetParameterPosition(StaticParameterWrapper parameter) { if (parameter.Handle is CodeTypeRef) { return(-1); } CodeParameter2 parameterHandle = (CodeParameter2)parameter.Handle; CodeElements codeElements = parameterHandle.Collection; for (int i = 0; i < codeElements.Count; i++) { if (codeElements.Item(i) == parameterHandle) { return(i); } } throw new InvalidOperationException("Could not obtain position of parameter."); }
private void fillTypes(CodeElements elements, TreeNode node) { for (int i = 1; i <= elements.Count; ++i) { var type = elements.Item(i) as CodeClass; if (type == null) { continue; } TreeNode child; var name = type.Name; if (node.Nodes.ContainsKey(type.Namespace.FullName)) { child = node.Nodes[type.Namespace.FullName]; } else { child = node.Nodes.Add(type.Namespace.FullName, type.Namespace.FullName); child.ImageKey = "namespace"; child.SelectedImageKey = child.ImageKey; child.StateImageKey = "collapsed"; } if (type.Parent is CodeClass) { name = string.Format("{0}.{1}", (type.Parent as CodeClass).Name, type.Name); } child = child.Nodes.Add(name); child.ImageKey = "class"; child.SelectedImageKey = child.ImageKey; child.StateImageKey = "none"; child.Tag = type; fillTypes(type.Members, node); } }
private bool InternalHasAttributePropertyValue(CodeElement element, string attributeFullName, string propertyName, object propertyValue) { EnvDTE80.CodeAttribute2 attribute; if (element is CodeAttribute) { attribute = (EnvDTE80.CodeAttribute2)element; } else if (element.IsCodeType) { attribute = (EnvDTE80.CodeAttribute2)((CodeType)element).Attributes.Item(attributeFullName); } else { return(false); } // Accessing item by name if that item is not contained in the collection // will crash VS; not even an exception, just GONE. Therefore, rather than // try to go directly to the named argument, we loop through them all looking // for the one we want. CodeElements arguments = attribute.Arguments; int numArguments = arguments.Count; for (int argNum = 1; argNum <= numArguments; ++argNum) { CodeAttributeArgument argument = (CodeAttributeArgument)arguments.Item(argNum); string argName = argument.Name; if (argName == propertyName) { return(argument.Value.Contains(propertyValue.ToString())); } } return(false); }
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); } } } } } } } } } }
public bool MakeBaseClassCompatiableWithSyncPattern() { CodeType ct = (CodeType)_cc; bool isSynchronizedFound = false; bool syncRootFound = false; bool synchronizedFound = false; //check base class for non-virtual functions for (CodeElements baseClasses = _cc.Bases; baseClasses != null;) { if (baseClasses.Count == 0) { break; } CodeClass baseClass = baseClasses.Item(1) as CodeClass; if (baseClass.Name == "Object") { break; } foreach (CodeElement ceBase in baseClass.Members) { CodeFunction cfBase = ceBase as CodeFunction; if (cfBase != null) { if (!cfBase.IsShared && !cfBase.CanOverride && cfBase.FunctionKind != EnvDTE.vsCMFunction.vsCMFunctionConstructor && cfBase.Name != "Finalize") { System.Windows.Forms.MessageBox.Show("The selected class contains base classes with non-virtual member functions." + " Please change these to virtual to allow synchronized wrapper creation."); return(false); } } CodeProperty cpBase = ceBase as CodeProperty; if (cpBase != null) { try{ if (!cpBase.Getter.IsShared && !cpBase.Getter.CanOverride) { System.Windows.Forms.MessageBox.Show("The selected class contains base classes with non-virtual member properties." + " Please change these to virtual to allow synchronized wrapper creation."); return(false); } }catch (Exception) {} try{ if (!cpBase.Setter.IsShared && !cpBase.Setter.CanOverride) { System.Windows.Forms.MessageBox.Show("The selected class contains base classes with non-virtual member properties." + " Please change these to virtual to allow synchronized wrapper creation."); return(false); } }catch (Exception) {} } } baseClasses = baseClass.Bases; } //check current clas foreach (CodeElement member in ct.Members) { CodeFunction cf = member as CodeFunction; if (!CheckFunctionIsVirtualAndFixIfOK(cf)) { return(false); } if (cf != null && cf.Name == "Synchronized") { synchronizedFound = true; } CodeProperty cp = member as CodeProperty; if (cp != null) { if (cp.Name == "SyncRoot") { syncRootFound = true; } if (cp.Name == "IsSynchronized") { isSynchronizedFound = true; } //Getter and Setter throw if property lacks these methods try{ if (!CheckFunctionIsVirtualAndFixIfOK(cp.Getter)) { return(false); } }catch (Exception) {} try{ if (!CheckFunctionIsVirtualAndFixIfOK(cp.Setter)) { return(false); } }catch (Exception) {} } } if (!isSynchronizedFound) { CodeProperty isSynchProp = _cc.AddProperty("IsSynchronized", "", EnvDTE.vsCMTypeRef.vsCMTypeRefBool, -1, EnvDTE.vsCMAccess.vsCMAccessPublic, null); CodeFunction isSynchPropGetter = isSynchProp.Getter; isSynchPropGetter.CanOverride = true; AddOneLineImpl("return false;", isSynchPropGetter, true); } if (!syncRootFound) { CodeProperty syncRootProp = _cc.AddProperty("SyncRoot", "", EnvDTE.vsCMTypeRef.vsCMTypeRefObject, -1, EnvDTE.vsCMAccess.vsCMAccessPublic, null); CodeFunction syncRootGetter = syncRootProp.Getter; syncRootGetter.CanOverride = true; AddOneLineImpl("return this;", syncRootGetter, true); } if (!synchronizedFound) { CodeFunction synchronizedStatic = _cc.AddFunction("Synchronized", EnvDTE.vsCMFunction.vsCMFunctionFunction, _cc.FullName, -1, EnvDTE.vsCMAccess.vsCMAccessPublic, null); synchronizedStatic.IsShared = true; synchronizedStatic.AddParameter("inst", _cc.FullName, -1); AddOneLineImpl("return new Synch" + _cc.Name + "(inst);", synchronizedStatic, true); } _cc.StartPoint.CreateEditPoint().SmartFormat(_cc.EndPoint); return(true); }
private void PopulateRecursively(TreeNodeCollection nodes, CodeElements elements) { for (int i = 1; i <= elements.Count; i++) { VCCodeElement element = elements.Item(i) as VCCodeElement; if (IsElementAcceptableType(element)) { TreeNode node = new TreeNode(); node.Text = element.Name; node.Tag = element; IPicture picture = (IPicture) element.Picture; Icon icon = Icon.FromHandle(new IntPtr(picture.Handle)); imageList.Images.Add(icon); node.ImageIndex = node.SelectedImageIndex = imageList.Images.Count - 1; node.Checked = true; nodes.Add(node); PopulateRecursively(node.Nodes, element.Children); } } }
//解析代码 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); //} }
/// <summary> /// /// </summary> public static List<AttributeInfo> GetAttributes(CodeElements attributes) { List<AttributeInfo> _result = new List<AttributeInfo>(); for (int i = 1; i <= attributes.Count; i++) { try { var attrib = (CodeAttribute2)attributes.Item(i); _result.Add(ObjectFactory.Instance.CreateAttribute(attrib)); } catch { continue; } } return _result; }