/// <summary> /// 解析出实体的命令空间。 /// </summary> /// <param name="repo"></param> /// <returns></returns> private static bool ParseDomainNamespace(CodeClass repo, string entityName, IList<CodeClass> entities, out string domainNamespace) { domainNamespace = null; //如果实体和仓库都是在这同一个项目中时,直接在实体列表中找到对应实体的命令空间。 if (entities.Count > 0) { var entity = entities.FirstOrDefault(c => c.Name == entityName); if (entity != null) { domainNamespace = entity.Namespace.FullName; return true; } } //实体不在同一个项目中,则通过约定查找实体的命名空间: //Repository.g.cs 文件中的最后一个命名空间,即是实体的命名空间。 var item = repo.ProjectItem; var fileName = item.get_FileNames(1); var gFileName = Path.GetFileNameWithoutExtension(fileName) + ".g.cs"; var gFile = Path.Combine(Path.GetDirectoryName(fileName), gFileName); //Repository 的层基类是没有 .g.cs 文件的,这时不需要为它生成。 if (File.Exists(gFile)) { var code = File.ReadAllText(gFile); var match = Regex.Match(code, @"using (?<domainNamespace>\S+?);\s+namespace"); domainNamespace = match.Groups["domainNamespace"].Value; return !string.IsNullOrWhiteSpace(domainNamespace); } return false; }
protected override void VisitClass(CodeClass codeClass) { if (codeClass.FullName == _classFullName) { _result = codeClass.ProjectItem; } }
/// <summary> /// Adds the property. /// </summary> /// <param name="codeClass">The code class.</param> /// <param name="var">The var.</param> /// <returns></returns> public static CodeProperty AddProperty(CodeClass codeClass, CodeVariable var) { CodeProperty prop = null; try { prop = codeClass.AddProperty( FormatPropertyName(var.Name), FormatPropertyName(var.Name), var.Type.AsFullName, -1, vsCMAccess.vsCMAccessPublic, null); EditPoint editPoint = prop.Getter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); //Delete return default(int); added by codeClass.AddProperty editPoint.Delete(editPoint.LineLength); editPoint.Indent(null, 4); editPoint.Insert(string.Format(CultureInfo.InvariantCulture, "return {0};", var.Name)); editPoint = prop.Setter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.Indent(null, 1); editPoint.Insert(string.Format(CultureInfo.InvariantCulture, "{0} = value;", var.Name)); editPoint.SmartFormat(editPoint); return prop; } catch { //Property already exists return null; } }
/// <summary> /// Gets the declaration of the specified code class as a string. /// </summary> /// <param name="codeClass">The code class.</param> /// <returns>The string declaration.</returns> internal static string GetClassDeclaration(CodeClass codeClass) { // Get the start point after the attributes. var startPoint = codeClass.GetStartPoint(vsCMPart.vsCMPartHeader); return TextDocumentHelper.GetTextToFirstMatch(startPoint, @"\{"); }
/// <summary> /// Adds the attribute. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="attributeValue">The attribute value.</param> public static void AddAttribute(CodeClass element, string attributeName, string attributeValue) { if(!HasAttribute(element, attributeName)) { element.AddAttribute(attributeName, attributeValue, 0); } }
internal static bool CanGenerateHandleCodeProperty(string testClassFixturePostFix, CodeClass parentCodeClass, CodeProperty codeProperty, Project unitTestProject) { foreach (ProjectItem projectItem in unitTestProject.ProjectItems) { List<CodeClass> lstProjectCodeClasses = UTGManagerAndExaminor.ProjectItemExaminor.GetCodeClasses(projectItem.FileCodeModel); foreach (CodeClass codeClass in lstProjectCodeClasses) { if ((parentCodeClass.Name + testClassFixturePostFix).Equals(codeClass.Name)) { foreach (CodeElement codeElement in codeClass.Members) { if (codeElement is CodeProperty) { if (codeProperty.Name.Equals(((CodeProperty)codeElement).Name)) return false; } } } } } return true; }
// Methods public static bool HaveAClass(object target, out CodeClass codeClass) { ProjectItem projectItem = null; if (target is SelectedItems) { SelectedItems items = (SelectedItems)target; if ((items.Count > 1) && (items.Item(1).ProjectItem != null)) { projectItem = items.Item(1).ProjectItem; } } else if (target is ProjectItem) { projectItem = (ProjectItem)target; } if ((projectItem != null) && (projectItem.FileCodeModel != null)) { foreach (CodeElement element in projectItem.FileCodeModel.CodeElements) { if (element is CodeNamespace) { CodeNamespace namespace2 = (CodeNamespace)element; if ((namespace2.Members.Count > 0) && (namespace2.Members.Item(1) is CodeClass)) { codeClass = (CodeClass)namespace2.Members.Item(1); return true; } } } } codeClass = null; return false; }
public override bool CanExecute(IDictionary<string, object> parameter) { _document = _dte.ActiveDocument; if (_document == null || _document.ProjectItem == null || _document.ProjectItem.FileCodeModel == null) { MessageBox(ErrMessage); return false; } _serviceClass = GetClass(_document.ProjectItem.FileCodeModel.CodeElements); if (_serviceClass == null) { MessageBox(ErrMessage); return false; } _serviceInterface = GetServiceInterface(_serviceClass as CodeElement); if (_serviceInterface == null) { MessageBox(ErrMessage); return false; } _serviceName = _serviceClass.Name.Replace("AppService", ""); return true; }
private void ProcessCodeFunctions(CodeClass codeClass, BindingSourceType bindingSourceType, IdeBindingSourceProcessor bindingSourceProcessor) { foreach (var codeFunction in codeClass.Children.OfType<CodeFunction>()) { var bindingSourceMethod = CreateBindingSourceMethod(codeFunction, bindingSourceType, bindingSourceProcessor); if (bindingSourceMethod != null) bindingSourceProcessor.ProcessMethod(bindingSourceMethod); } }
protected override void VisitClass(CodeClass codeClass) { this.ShowName(codeClass, "Class"); _level++; base.VisitClass(codeClass); _level--; }
public ClassTraverser(CodeClass codeClass, Action<CodeProperty> withProperty) { if (codeClass == null) throw new ArgumentNullException("codeClass"); if (withProperty == null) throw new ArgumentNullException("withProperty"); CodeClass = codeClass; WithProperty = withProperty; if (codeClass.Members != null) Traverse(codeClass.Members); }
static public bool IsBindingClass(CodeClass codeClass) { try { return codeClass.Attributes.Cast<CodeAttribute>().Any(attr => "TechTalk.SpecFlow.BindingAttribute".Equals(attr.FullName)); } catch(Exception) { return false; } }
static public bool IsBindingClass(CodeClass codeClass) { try { return codeClass.Attributes.Cast<CodeAttribute>().Any(attr => typeof(BindingAttribute).FullName.Equals(attr.FullName)); } catch(Exception) { return false; } }
static internal bool IsPotentialBindingClass(CodeClass codeClass) { try { var filteredAttributes = codeClass.Attributes.OfType<CodeAttribute2>(); return BindingSourceProcessor.IsPotentialBindingClass(filteredAttributes.Select(attr => attr.FullName)); } catch(Exception) { return false; } }
protected override void VisitClass(CodeClass codeClass) { if (Helper.IsEntity(codeClass)) { _fileFinised = true; } else if (Helper.IsRepository(codeClass)) { _result.Add(codeClass); _fileFinised = true; } }
private static bool DerivedFromBaseTest(CodeClass classElement) { if (classElement.Name == "BaseTest") { return true; } return classElement.Bases .Cast<CodeElement>() .Where(e => e.Kind == vsCMElement.vsCMElementClass) .Count(c => DerivedFromBaseTest((CodeClass)c)) > 0; }
internal static string GetEntityNameForRepository(CodeClass repo) { ////使用 Attribute 来进行获取实体类名。 //foreach (CodeAttribute attri in repo.Attributes) //{ // //RootEntity or ChildEntity // if (attri.FullName == Consts.RepositoryForAttributeClassFullName) // { // } //} return repo.Name.Substring(0, repo.Name.Length - Consts.RepositorySuffix.Length); }
public static string GetNextAvailableCopyName(CodeClass codeClass, ref string codeFunctionName, Project project) { codeFunctionName = "CopyOf" + codeFunctionName; if (!CodeSelectionHandler.CanGenerateHandleCodeFunction( codeClass, codeFunctionName)) { return GetNextAvailableCopyName(codeClass, ref codeFunctionName, project); } return codeFunctionName; }
internal static bool CanGenerateHandleCodeFunction(CodeClass parentCodeClass, string codeFunctionName) { foreach (CodeElement codeElement in parentCodeClass.Members) { if (codeElement is CodeFunction) { if (codeFunctionName.Equals(((CodeFunction)codeElement).Name)) return false; } } return true; }
private bool IsProcessableBaseClass(CodeClass codeClass) { try { if (codeClass.FullName == "System.Object") return false; if (codeClass.ProjectItem == null) return false; if (codeClass.Children == null) return false; return true; } catch (Exception) { return false; } }
private void ProcessCodeClass(CodeClass codeClass, IdeBindingSourceProcessor bindingSourceProcessor, params CodeClass[] classParts) { var filteredAttributes = classParts .SelectMany(cc => cc.Attributes.Cast<CodeAttribute2>().Where(attr => CanProcessTypeAttribute(bindingSourceProcessor, attr))).ToArray(); if (!bindingSourceProcessor.PreFilterType(filteredAttributes.Select(attr => attr.FullName))) return; var bindingSourceType = bindingReflectionFactory.CreateBindingSourceType(classParts, filteredAttributes); //TODO: merge info from parts if (!bindingSourceProcessor.ProcessType(bindingSourceType)) return; ProcessCodeFunctions(codeClass, bindingSourceType, bindingSourceProcessor); bindingSourceProcessor.ProcessTypeDone(); }
protected void SelectObjectClass( CodeClass cc ) { ProjectItem p = cc.ProjectItem; // Open the file as a source code file EnvDTE.Window theWindow = p.Open(Constants.vsViewKindCode); //Get a handle to the new document in the open window TextDocument objTextDoc = (TextDocument)theWindow.Document.Object("TextDocument"); EditPoint objEditPoint = (EditPoint)objTextDoc.StartPoint.CreateEditPoint(); theWindow.Visible = true; TextSelection ts = (TextSelection) theWindow.Selection; ts.StartOfDocument(false); objEditPoint.MoveToLineAndOffset(cc.StartPoint.Line,1); ts.MoveToPoint( objEditPoint, false ); }
private void ProcessCodeClass(CodeClass codeClass, IdeBindingSourceProcessor bindingSourceProcessor) { var filteredAttributes = codeClass.Attributes.Cast<CodeAttribute2>().Where(attr => bindingSourceProcessor.CanProcessTypeAttribute(attr.FullName)).ToArray(); if (!bindingSourceProcessor.PreFilterType(filteredAttributes.Select(attr => attr.FullName))) return; var bindingSourceType = bindingReflectionFactory.CreateBindingSourceType(codeClass, filteredAttributes); if (!bindingSourceProcessor.ProcessType(bindingSourceType)) return; foreach (var codeFunction in codeClass.Children.OfType<CodeFunction>()) { bindingSourceProcessor.ProcessMethod(CreateBindingSourceMethod(codeFunction, bindingSourceType, bindingSourceProcessor)); } bindingSourceProcessor.ProcessTypeDone(); }
/// <summary> /// 获取某个类的基类。 /// 有时会找不到对应的对象、或者没有基类,则返回 null。 /// </summary> /// <param name="codeClass"></param> /// <returns></returns> internal static CodeClass GetBaseClass(CodeClass codeClass) { //查找基类的方式检测可能会出现以下问题,原因不详: //如果基类不在同一程序集时,codeClass.Bases 中的元素的类型(Kind)不是 CodeClass,而是 Other。 //所以会查找基类失败。 foreach (CodeElement item in codeClass.Bases) { if (item.Kind == vsCMElement.vsCMElementOther) { throw new InvalidOperationException(string.Format("无法读取类型 {0} 的基类,请先编译程序集。", codeClass.Name)); } if (item is CodeClass) { return item as CodeClass; } } return null; }
private static string GetSummary(CodeClass property) { return GetSummary(property.InfoLocation, property.DocComment, property.Comment, property.FullName); }
private static IntellisenseType GetType(CodeClass rootElement, CodeTypeRef codeTypeRef, HashSet<string> traversedTypes, HashSet<string> references) { var isArray = codeTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefArray; var isCollection = codeTypeRef.AsString.StartsWith("System.Collections", StringComparison.Ordinal); var effectiveTypeRef = codeTypeRef; if (isArray && codeTypeRef.ElementType != null) effectiveTypeRef = effectiveTypeRef.ElementType; else if (isCollection) effectiveTypeRef = TryToGuessGenericArgument(rootElement, effectiveTypeRef); var codeClass = effectiveTypeRef.CodeType as CodeClass2; var codeEnum = effectiveTypeRef.CodeType as CodeEnum; var isPrimitive = IsPrimitive(effectiveTypeRef); var result = new IntellisenseType { IsArray = isArray || isCollection, CodeName = effectiveTypeRef.AsString, ClientSideReferenceName = effectiveTypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefCodeType && effectiveTypeRef.CodeType.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject ? (codeClass != null && HasIntellisense(codeClass.ProjectItem, Ext.TypeScript, references) ? (GetNamespace(codeClass) + "." + codeClass.Name) : null) ?? (codeEnum != null && HasIntellisense(codeEnum.ProjectItem, Ext.TypeScript, references) ? (GetNamespace(codeEnum) + "." + codeEnum.Name) : null) : null }; if (!isPrimitive && codeClass != null && !traversedTypes.Contains(effectiveTypeRef.CodeType.FullName) && !isCollection) { traversedTypes.Add(effectiveTypeRef.CodeType.FullName); result.Shape = GetProperties(effectiveTypeRef.CodeType.Members, traversedTypes, references).ToList(); traversedTypes.Remove(effectiveTypeRef.CodeType.FullName); } return result; }
public async Task GetStartPoint_Attributes() { CodeClass testObject = await GetCodeClassAsync("Bar"); AssertEx.Throws <NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes)); }
public override void Execute() { CodeClass codeClass = _target as CodeClass; if (codeClass == null && !ReferenceUtil.HaveAClass(_target, out codeClass)) { return; } if (codeClass != null) { TextPoint tp = codeClass.StartPoint; EditPoint ep = tp.CreateEditPoint(); ep.StartOfDocument(); int lastUsing = -1; string keyword = string.Empty; string patternText = string.Empty; switch (codeClass.Language) { case CodeModelLanguageConstants.vsCMLanguageCSharp: keyword = "using"; patternText = String.Concat(keyword, " {0};"); break; case CodeModelLanguageConstants.vsCMLanguageVB: keyword = "Imports"; patternText = String.Concat(keyword, " {0}"); break; default: throw new NotSupportedException("Language not supported"); } string usingText = String.Format(patternText, _usingNamespace); //string usingText = String.Format("using {0}", usingNamespace); while (!ep.AtEndOfDocument) { int length = ep.LineLength; string line = ep.GetText(ep.LineLength); //if (line.Contains("using")) return; if (line.Contains(usingText)) { return; } if (line.StartsWith(keyword)) { lastUsing = ep.Line; } ep.LineDown(1); } ep.StartOfDocument(); if (lastUsing > 0) { ep.LineDown(lastUsing); } ep.Insert(usingText); //ep.Insert(";"); ep.Insert(Environment.NewLine); if (ep.LineLength != 0) { ep.Insert(Environment.NewLine); } } }
private BindingScopeNew[] GetClassScopes(CodeClass codeClass) { return(codeClass.Attributes.Cast <CodeAttribute2>().Select(GetBingingScopeFromAttribute).Where(s => s != null).ToArray()); }
public async Task KindTest() { CodeClass cc = await GetCodeClassAsync("Foo"); Assert.Equal(vsCMElement.vsCMElementClass, cc.Kind); }
private void SortFunctionsWithinClass(CodeElement codeElement) { EditPoint fieldInsertionPoint; EditPoint constructorInsertionPoint; EditPoint finalizerInsertionPoint; EditPoint delegateInsertionPoint; EditPoint eventInsertionPoint; EditPoint enumInsertionPoint; EditPoint interfaceInsertionPoint; EditPoint propertyInsertionPoint; EditPoint methodInsertionPoint; EditPoint structInsertionPoint; EditPoint classInsertionPoint; EditPoint origin = codeElement.StartPoint.CreateEditPoint(); EditPoint classPoint = codeElement.StartPoint.CreateEditPoint(); TextRanges trs = null; if (origin.FindPattern("{", (int)vsFindOptions.vsFindOptionsMatchCase, ref classPoint, ref trs)) { classPoint.Insert("\r\n"); origin = classPoint.CreateEditPoint(); fieldInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); constructorInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); finalizerInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); delegateInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); eventInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); enumInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); interfaceInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); propertyInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); methodInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); structInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); classInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); Array accessLevels = Enum.GetValues(typeof(vsCMAccess)); foreach (vsCMAccess accessLevel in accessLevels) { for (int i = 1; i <= codeElement.Children.Count; i++) { CodeElement element = codeElement.Children.Item(i); EditPoint elementStartPoint = element.StartPoint.CreateEditPoint(); switch (element.Kind) { case vsCMElement.vsCMElementVariable: CodeVariable variable = element as CodeVariable; if (variable != null) { if (variable.Access == accessLevel) { MoveCodeBlock(codeElement, element, fieldInsertionPoint); } } else { Debug.WriteLine("CodeVariable " + element.Name + " null"); } break; case vsCMElement.vsCMElementFunction: // method, constructor, or finalizer CodeFunction function = element as CodeFunction; if (function != null) { if (function.Access == accessLevel) { if (function.FunctionKind == vsCMFunction.vsCMFunctionConstructor) { MoveCodeBlock(codeElement, element, constructorInsertionPoint); } else if (function.FunctionKind == vsCMFunction.vsCMFunctionDestructor) { MoveCodeBlock(codeElement, element, finalizerInsertionPoint); } else { MoveCodeBlock(codeElement, element, methodInsertionPoint); } } } else { Debug.WriteLine("CodeFunction " + element.Name + " null"); } break; case vsCMElement.vsCMElementDelegate: CodeDelegate delegateElement = element as CodeDelegate; if (delegateElement != null) { if (delegateElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, delegateInsertionPoint); } } else { Debug.WriteLine("CodeDelegate " + element.Name + " null"); } break; case vsCMElement.vsCMElementEvent: MoveCodeBlock(codeElement, element, eventInsertionPoint); break; case vsCMElement.vsCMElementEnum: CodeEnum enumElement = element as CodeEnum; if (enumElement != null) { if (enumElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, enumInsertionPoint); } } else { Debug.WriteLine("CodeEnum " + element.Name + " null"); } break; case vsCMElement.vsCMElementInterface: CodeInterface interfaceElement = element as CodeInterface; if (interfaceElement != null) { if (interfaceElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, interfaceInsertionPoint); } } else { Debug.WriteLine("CodeInterface " + element.Name + " null"); } break; case vsCMElement.vsCMElementProperty: CodeProperty propertyElement = element as CodeProperty; if (propertyElement != null) { if (propertyElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, propertyInsertionPoint); } } else { Debug.WriteLine("CodeProperty " + element.Name + " null"); } break; case vsCMElement.vsCMElementStruct: CodeStruct structElement = element as CodeStruct; if (structElement != null) { if (structElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, structInsertionPoint); } } else { Debug.WriteLine("CodeStruct " + element.Name + " null"); } break; case vsCMElement.vsCMElementClass: CodeClass classElement = element as CodeClass; if (classElement != null) { if (classElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, classInsertionPoint); } } else { Debug.WriteLine("CodeStruct " + element.Name + " null"); } break; default: Debug.WriteLine("unknown element: " + element.Name + " - " + element.Kind); break; } } for (int i = 1; i <= codeElement.Children.Count; i++) { CodeElement element = codeElement.Children.Item(i); if (element.Kind == vsCMElement.vsCMElementClass || element.Kind == vsCMElement.vsCMElementInterface || element.Kind == vsCMElement.vsCMElementStruct) { SortFunctionsWithinClass(element); } } } origin.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); classInsertionPoint.CreateEditPoint().DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); } }
public static CustomAttributeData GetCustomAttribute(this CodeClass cc, Type attrType) { return(cc.GetCustomAttributes().FirstOrDefault(x => x.AttributeType == attrType)); }
public bool IsPrimaryKey(CodeClass codeClass, CodeProperty codeProperty) { return(CodePropertyHasAttributeWithArgValue(codeProperty, typeof(ColumnAttribute), "IsPrimaryKey", bool.TrueString, StringComparison.OrdinalIgnoreCase)); }
public bool IsPrimaryKey(CodeClass codeClass, CodeProperty codeProperty) { return(codeProperty.Attributes.OfType <CodeAttribute2>().Any(x => x.FullName == typeof(KeyAttribute).FullName)); }
public bool IsPrimaryKey(CodeClass codeClass, CodeProperty codeProperty) { return(string.Equals(codeClass.Name + "id", codeProperty.Name, StringComparison.OrdinalIgnoreCase)); }
private static bool IsPrimaryKey(CodeClass codeClass, CodeProperty codeProperty) { return(PrimaryKeyLocators.Any(x => x.IsPrimaryKey(codeClass, codeProperty))); }
public static string GetParents(CodeClass c) { var parent = c.Parent as CodeClass; return(GetParents((CodeElement)c, parent)); }
//OK internal static void OnCodeClassSelection(AbstractTestFramework testFramework, CodeClass codeClass, DTE2 applicationObject, UnitTestCodeType codeType) { //We can only test public methods if (codeClass.Access != vsCMAccess.vsCMAccessPublic) return; Project parentProject = ProjectExaminar.GetCodeClassParentProject(codeClass); Project unitTestProject = ProjectExaminar.GetUnitTestProject(parentProject.Name, applicationObject, testFramework.TestProjectPostFix); if (unitTestProject != null && !CanGenerateHandleCodeClass(testFramework.TestClassFixturePostFix, codeClass, unitTestProject)) { UTGHelper.ErrorHandler.ShowMessage(CommonUserMessages.MSG_TEST_ALREADY_EXISTS); OnGenerationFaliure(applicationObject); return; } string path = ProjectManager.GetUnitTestProjectPath(parentProject.Name, applicationObject, testFramework.TestProjectPostFix); path = UTGHelper.IO.GetFilePath(path); System.IO.DirectoryInfo newDirectoryInfo; string fullPath = System.IO.Path.Combine(path, parentProject.Name + testFramework.TestProjectPostFix); try{ //Another way of doing this would be to try and find this project in current open solution saving us the exception newDirectoryInfo = System.IO.Directory.CreateDirectory(fullPath); } catch (Exception ex){ Logger.LogException(ex); } finally{ //Either case we have one by now so lets get its directory information newDirectoryInfo = new System.IO.DirectoryInfo(fullPath); } //If for whatever reason we are still failing then simply quit this if (newDirectoryInfo == null) { OnGenerationFaliure(applicationObject); throw new Exception(string.Format("Unable to create new Directory {0}", System.IO.Path.Combine(path, parentProject.Name + testFramework.TestProjectPostFix))); } if (unitTestProject == null) { try{ unitTestProject = ProjectManager.CreateAndAddUnitTestProject((Solution2)applicationObject.Solution, parentProject.Name + testFramework.TestProjectPostFix, newDirectoryInfo.FullName, codeType/*, license*/); } catch (Exception ex){ Logger.LogException(ex); OnGenerationFaliure(applicationObject); throw; } } //Rethink this bit //Since above operation fails in either case then try getting the new Unit Test Project if created and added ok.. if (unitTestProject == null) { unitTestProject = ProjectExaminar.GetUnitTestProject(parentProject.Name, applicationObject, testFramework.TestProjectPostFix); } if (unitTestProject == null) { OnGenerationFaliure(applicationObject); throw new Exception("Can not create new UnitTest Project"); } AbstractTestClassFactory testClassFactory = new NUnitTestClassFactory(); AbstractTestClass nunitClass = null; if (codeType == UnitTestCodeType.CSharp) { nunitClass = testClassFactory.CreateCSharpTestClass(codeClass.Namespace.FullName, codeClass.Name, codeClass.IsAbstract); } else if (codeType == UnitTestCodeType.VB) { nunitClass = testClassFactory.CreateVBTestClass(codeClass.Namespace.FullName, codeClass.Name, codeClass.IsAbstract); } if (!nunitClass.write(newDirectoryInfo.FullName, testFramework.TestClassFixturePostFix)) { OnGenerationFaliure(applicationObject); return; } //add new class to project ProjectItem projectItem = ProjectManager.AddClassToProject(applicationObject, unitTestProject, null, nunitClass.FullName); List<CodeClass> lstCodeClasses = ProjectItemExaminor.GetCodeClasses(projectItem.FileCodeModel); if (lstCodeClasses == null || lstCodeClasses.Count == 0) { OnGenerationFaliure(applicationObject); return; } CodeClass unitTestCodeClass = lstCodeClasses[0]; //passed this point the actual object will take care of it self. nunitClass.GenerateTest(unitTestCodeClass, codeClass); //To consider: this should be handled by an object that inherits from project type copyReferences(testFramework, parentProject, unitTestProject); applicationObject.ItemOperations.OpenFile(nunitClass.FullName, EnvDTE.Constants.vsViewKindAny); }
internal static bool CanGenerateHandleCodeClass(string testClassFixturePostFix, CodeClass ce, Project unitTestProject) { foreach (ProjectItem projectItem in unitTestProject.ProjectItems) { List<CodeClass> lstProjectCodeClasses = UTGManagerAndExaminor.ProjectItemExaminor.GetCodeClasses(projectItem.FileCodeModel); foreach (CodeClass codeClass in lstProjectCodeClasses) { if ((ce.Name + testClassFixturePostFix).Equals(codeClass.Name)) return false; } } return true; }
public static IEnumerable <CodeVariable> GetVariables(this CodeClass cls) { return(cls.Children.OfType <CodeVariable>()); }
/// <summary> /// Creates <see cref="TypeDescriptor" /> from given typeNode. /// </summary> /// <param name="typeNode">Type node which descriptor is created.</param> /// <returns>Created <see cref="TypeDescriptor" />.</returns> public TypeDescriptor CreateDescriptor(CodeClass typeNode) { var fullname = typeNode.FullName; return(ConvertToDescriptor(fullname, true)); }
public static Type ToType(this CodeClass cc) { return(cc.ProjectItem.GetTypeFromProject(cc.FullName)); }
public static IEnumerable <CodeFunction> GetFunctions(this CodeClass codeClass) { return(codeClass.Children.OfType <CodeFunction>()); }
protected void WalkElements(CodeElement cein, AbstractComponent parent) { CodeElements ces; switch (cein.Kind) { // Handle namespaces case EnvDTE.vsCMElement.vsCMElementNamespace: { CodeNamespace cn = (CodeNamespace)cein; ces = cn.Members; foreach (CodeElement ce in ces) { WalkElements(ce, parent); } break; } // Handle classes case EnvDTE.vsCMElement.vsCMElementClass: { CodeClass cc = (CodeClass)cein; ClassComponent cls = new ClassComponent(cc.FullName, cc.Name); cls.CodeClass = cc; parent.Visit(cls); ces = cc.Members; foreach (CodeElement ce in ces) { WalkElements(ce, cls); } break; } // Handle interfaces case EnvDTE.vsCMElement.vsCMElementInterface: { CodeInterface ci = (CodeInterface)cein; // nothing for now. break; } // Handle methods (functions) case EnvDTE.vsCMElement.vsCMElementFunction: { CodeFunction cf = (CodeFunction)cein; MethodComponent mc = new MethodComponent(cf.FullName, cf.Name); parent.Visit(mc); mc.CreateRepresentation(GetFunctionText(cf)); mc.CodeFunction = cf; break; } // Handle properties case EnvDTE.vsCMElement.vsCMElementProperty: { CodeProperty cp = (CodeProperty)cein; PropertyComponent pc = new PropertyComponent(cp.FullName, cp.Name); parent.Visit(pc); break; } // Handle fields (variables) case EnvDTE.vsCMElement.vsCMElementVariable: { CodeVariable cv = (CodeVariable)cein; FieldComponent fc = new FieldComponent(cv.FullName, cv.Name); parent.Visit(fc); break; } } }
private IEnumerable <StepBindingNew> GetStepsFromClass(CodeClass codeClass, BindingScopeNew[] classScopes) { return(codeClass.Children.OfType <CodeFunction>().SelectMany(codeFunction => GetSuggestionsFromCodeFunction(codeFunction, classScopes))); }
public IBindingType CreateBindingType(CodeClass codeClass) { return(new BindingType(codeClass.Name, codeClass.FullName)); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.mylayout1); var createDbBtn = FindViewById <Button>(Resource.Id.mydbbutton1); var tblBtn = FindViewById <Button>(Resource.Id.mytablebutton2); var txt = FindViewById <EditText>(Resource.Id.myentertaskeditText1); var insertBtn = FindViewById <Button>(Resource.Id.myinsertbutton3); var updateBtn = FindViewById <Button>(Resource.Id.myupdatebutton4); var deleteBtn = FindViewById <Button>(Resource.Id.mydeletebutton5); var showAllDataBtn = FindViewById <Button>(Resource.Id.myshowalldatabutton6); var getById = FindViewById <Button>(Resource.Id.mygetbyidbutton7); //create database createDbBtn.Click += delegate { CodeClass obj = new CodeClass(); var v = obj.createDatabaseMethod(); Toast.MakeText(this, v, ToastLength.Short).Show(); }; //create table tblBtn.Click += delegate { CodeClass obj = new CodeClass(); var v = obj.createTableMethod(); Toast.MakeText(this, v, ToastLength.Short).Show(); }; //insert data into table insertBtn.Click += delegate { CodeClass obj = new CodeClass(); string v = obj.insertMethod(txt.Text); Toast.MakeText(this, v, ToastLength.Short).Show(); }; //delete data krny k lye deleteBtn.Click += delegate { CodeClass obj = new CodeClass(); string v = obj.deleteMethod(int.Parse(txt.Text)); Toast.MakeText(this, v, ToastLength.Short).Show(); }; //show all records showAllDataBtn.Click += delegate { CodeClass obj = new CodeClass(); var v = obj.showAllRecordMethod(); Toast.MakeText(this, v, ToastLength.Short).Show(); }; //get by id getById.Click += delegate { CodeClass obj = new CodeClass(); var v = obj.getByIdMethod(int.Parse(txt.Text)); }; //now show all record showAllDataBtn.Click += delegate { CodeClass obj = new CodeClass(); string v = obj.showAllRecordMethod(); Toast.MakeText(this, v, ToastLength.Short).Show(); }; }
private List <ListItemData> FillElements(CodeElement startElement) { List <ListItemData> result = new List <ListItemData>(); try { string s = ""; switch (startElement.Kind) { case vsCMElement.vsCMElementNamespace: CodeNamespace cn = (CodeNamespace)startElement; foreach (CodeElement element in cn.Members) { result.AddRange(FillElements(element)); } break; case vsCMElement.vsCMElementClass: CodeClass cc = (CodeClass)startElement; result.Add(new ListItemData(startElement.Name, 0, String.Format("{0} ({1})", cc.Name, "class"), "class", startElement)); foreach (CodeElement element in cc.Members) { result.AddRange(FillElements(element)); } break; case vsCMElement.vsCMElementInterface: CodeInterface ci = (CodeInterface)startElement; result.Add(new ListItemData(startElement.Name, 0, String.Format("{0} ({1})", ci.Name, "interface"), "interface", startElement)); foreach (CodeElement element in ci.Members) { result.AddRange(FillElements(element)); } break; case vsCMElement.vsCMElementFunction: result.Add(new ListItemData(startElement.Name, 0, FunctionToString((CodeFunction)startElement), ParseComment((startElement as CodeFunction).DocComment), startElement)); break; case vsCMElement.vsCMElementProperty: result.Add(new ListItemData(startElement.Name, 1, PropertyToString((CodeProperty)startElement), ParseComment((startElement as CodeProperty).DocComment), startElement)); break; case vsCMElement.vsCMElementEvent: result.Add(new ListItemData(startElement.Name, 2, (startElement as CodeEvent).Name, ParseComment((startElement as CodeEvent).DocComment), startElement)); break; case vsCMElement.vsCMElementDelegate: result.Add(new ListItemData(startElement.Name, 3, DelegateToString((CodeDelegate)startElement), ParseComment((startElement as CodeDelegate).DocComment), startElement)); break; case vsCMElement.vsCMElementEnum: result.Add(new ListItemData(startElement.Name, 4, EnumToString((CodeEnum)startElement), ParseComment((startElement as CodeEnum).DocComment), startElement)); break; case vsCMElement.vsCMElementStruct: result.Add(new ListItemData(startElement.Name, 5, s, ParseComment((startElement as CodeStruct).DocComment), startElement)); CodeStruct cs = (CodeStruct)startElement; foreach (CodeElement element in cs.Members) { result.AddRange(FillElements(element)); } break; } } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.Message, "AS VS Expert: FillElements"); } return(result); }
private static string GetSummary(CodeClass property) { return(GetSummary(property.InfoLocation, property.DocComment, property.Comment, property.FullName)); }
/// <summary> /// Implements the code snippet. /// </summary> /// <param name="instance">The instance.</param> /// <param name="codeSnippet">The code snippet.</param> /// <param name="formatFunctionParameters">if set to <c>true</c> [format function parameters].</param> public static void ImplementCodeSnippet( this CodeClass instance, CodeSnippet codeSnippet, bool formatFunctionParameters) { TraceService.WriteLine("CodeClassExtensions::ImplementCodeSnippet file" + instance.Name); if (codeSnippet.Variables != null) { foreach (string[] parts in codeSnippet.Variables .Select(variable => variable.Split(' '))) { //// variable could already exist! try { instance.ImplementVariable(parts[1], parts[0], false); } catch (Exception exception) { TraceService.WriteError("Error adding variable exception=" + exception.Message + " variable=" + parts[1]); //// if variable already exists get out - code snippet will already have been applied. return; } } } if (codeSnippet.MockVariables != null) { foreach (string[] parts in codeSnippet.MockVariables .Select(variable => variable.Split(' '))) { //// variable could already exist! try { instance.ImplementMockVariable(parts[1], parts[0], codeSnippet.MockingVariableDeclaration); } catch (Exception exception) { TraceService.WriteError("Error adding mock variable exception=" + exception.Message + " variable=" + parts[1]); //// if variable already exists get out - code snippet will already have been applied. return; } } } if (string.IsNullOrEmpty(codeSnippet.Code) == false) { instance.ImplementFunction(codeSnippet); } if (codeSnippet.Interfaces != null && codeSnippet.Interfaces.Count > 0) { IEnumerable <CodeFunction> constructors = instance.GetConstructors(); CodeFunction constructor = constructors.FirstOrDefault() ?? instance.AddDefaultConstructor(true); foreach (string variable in codeSnippet.Interfaces) { instance.ImplementInterface(constructor, variable); } if (formatFunctionParameters) { constructor.FormatParameters(); } } if (string.IsNullOrEmpty(codeSnippet.GetMockInitCode()) == false || string.IsNullOrEmpty(codeSnippet.GetMockConstructorCode()) == false) { instance.ImplementMockCode(codeSnippet); } }
private static CodeTypeRef TryToGuessGenericArgument(CodeClass rootElement, CodeTypeRef codeTypeRef) { var codeTypeRef2 = codeTypeRef as CodeTypeRef2; if (codeTypeRef2 == null || !codeTypeRef2.IsGeneric) return codeTypeRef; // There is no way to extract generic parameter as CodeTypeRef or something similar // (see http://social.msdn.microsoft.com/Forums/vstudio/en-US/09504bdc-2b81-405a-a2f7-158fb721ee90/envdte-envdte80-codetyperef2-and-generic-types?forum=vsx) // but we can make it work at least for some simple case with the following heuristic: // 1) get the argument's local name by parsing the type reference's full text // 2) if it's a known primitive (i.e. string, int, etc.), return that // 3) otherwise, guess that it's a type from the same namespace and same project, // and use the project CodeModel to retrieve it by full name // 4) if CodeModel returns null - well, bad luck, don't have any more guesses var typeNameAsInCode = codeTypeRef2.AsString.Split('<', '>').ElementAtOrDefault(1) ?? ""; CodeModel projCodeModel; try { projCodeModel = rootElement.ProjectItem.ContainingProject.CodeModel; } catch (COMException) { projCodeModel = ProjectHelpers.GetActiveProject().CodeModel; } var codeType = projCodeModel.CodeTypeFromFullName(TryToGuessFullName(typeNameAsInCode)); if (codeType != null) return projCodeModel.CreateCodeTypeRef(codeType); return codeTypeRef; }
/// <summary> /// Gets the variables. /// </summary> /// <param name="instance">The instance.</param> /// <returns>The variables.</returns> public static IEnumerable <CodeVariable> GetVariables(this CodeClass instance) { TraceService.WriteLine("CodeClassExtensions::GetVariables file=" + instance.Name); return(instance.Members.OfType <CodeVariable>()); }
private static string GetDataContractName(CodeClass cc, string attrName) { IEnumerable <CodeAttribute> dataContractAttribute = cc.Attributes.Cast <CodeAttribute>().Where(a => a.Name == "DataContract"); return(GetDataContractNameInner(dataContractAttribute, attrName)); }
public override bool run(TestFixturOption testFixturOption, DTE2 applicationObject) { try { string output = string.Empty; string tvTestFixtureOptions = string.Empty; string tvOutputFileFullname = string.Empty; if (testFixturOption.CClass != null) { tvTestFixtureOptions = " /fixture:"; tvTestFixtureOptions += testFixturOption.CClass.FullName; tvOutputFileFullname = UTGManagerAndExaminor.ProjectExaminar.GetProjectOutputFullAssemblyName(testFixturOption.CClass.ProjectItem.ContainingProject); tvTestFixtureOptions += " \"" + tvOutputFileFullname + "\""; if (testFixturOption.ConfigurationFile != string.Empty) { tvTestFixtureOptions += " /config:\"" + tvOutputFileFullname + ".config\""; } } else if (testFixturOption.CFunction != null) { tvTestFixtureOptions = " /run:"; CodeClass parentClass = testFixturOption.CFunction.Parent as CodeClass; tvTestFixtureOptions += testFixturOption.CFunction.FullName; tvOutputFileFullname = UTGManagerAndExaminor.ProjectExaminar.GetProjectOutputFullAssemblyName(parentClass.ProjectItem.ContainingProject); tvTestFixtureOptions += " \"" + tvOutputFileFullname + "\""; if (tvTestFixtureOptions.Length > 0) { if (testFixturOption.ConfigurationFile != string.Empty) { tvTestFixtureOptions += " /config:\"" + tvOutputFileFullname + ".config\""; } } } else { if (tvOutputFileFullname.Equals(string.Empty)) { tvOutputFileFullname = UTGManagerAndExaminor.ProjectExaminar.GetProjectOutputFullAssemblyName(testFixturOption.Project); tvTestFixtureOptions = "\"" + tvOutputFileFullname + "\""; } if (testFixturOption.ConfigurationFile != string.Empty) { tvTestFixtureOptions += " /config:\"" + tvOutputFileFullname + ".config\""; } } tvTestFixtureOptions += " /xmlConsole"; ProjectExaminar.GetProjectOutputType(testFixturOption.Project); ProjectItem projectItem = ProjectExaminar.GetProjectConfigurationFile(testFixturOption.Project); Project project = testFixturOption.Project; if (this.binariesDirectory == null || this.binariesDirectory == string.Empty) { BrowseForUnitLibraries tvLocateNUnitBinaries = new BrowseForUnitLibraries( UTGHelper.CommonErrors.ERR_UNABLE_TO_LOCATE_NUNIT_INSTALL_FOLDER, BrowseForUnitLibraries.BrowseForNunitDialogType.libraries, this); tvLocateNUnitBinaries.Show(); return(false); } if (this.consoleDirectory == null || this.consoleDirectory == string.Empty) { BrowseForUnitLibraries tvLocateNUnitBinaries = new BrowseForUnitLibraries( UTGHelper.CommonErrors.ERR_UNABLE_TO_LOCATE_NUNIT_CONSOLE, BrowseForUnitLibraries.BrowseForNunitDialogType.console, this); tvLocateNUnitBinaries.Show(); return(false); } string processFullPath = System.IO.Path.Combine(this.consoleDirectory, this.ConsoleName); if (TestStarted != null) { TestStarted(); } #if _PROCESS_START_WIN32_ ProcessTypes.StartupInfo startInfo = new ProcessTypes.StartupInfo(); ProcessTypes.ProcessInfo processInfo = new ProcessTypes.ProcessInfo(); IntPtr ThreadHandle = IntPtr.Zero; string commandLine = (arguments != null ? libraryPath + arguments : libraryPath); //string commandLine = @"C:\Users\Sam\documents\visual studio 2010\Projects\MyClassLibrary\MyClassLibrary.nunit\bin\Debug\MyClassLibrary.nunit.dll"; bool success = CreateProcess(processFullPath, commandLine, IntPtr.Zero, IntPtr.Zero, false, ProcessTypes.ProcessCreationFlags.CREATE_SUSPENDED, IntPtr.Zero, null, ref startInfo, out processInfo); if (!success) { UTGHelper.Logger.LogMessage("Failed to start unit test process"); return(false); } ThreadHandle = processInfo.hThread; uint PID = processInfo.dwProcessId; ResumeThread(ThreadHandle); return(true); #else System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(processFullPath, tvTestFixtureOptions); //we choose to redirect output, but we could also just use the TestResult.xml file psi.RedirectStandardOutput = true; psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; psi.UseShellExecute = false; psi.CreateNoWindow = true; //this is the one that works System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi); if (testFixturOption.IsDebugging) { AttachToProcessThread(applicationObject); } System.IO.StreamReader myOutput = process.StandardOutput; process.WaitForExit(60000); if (!process.HasExited) { UTGHelper.ErrorHandler.ShowMessage(UTGHelper.CommonErrors.ERR_UNABLE_TO_RUN_UNITTEST + " " + "Failed to exit process"); return(false); } output += myOutput.ReadToEnd(); #endif //This should be fixed by simple passing the argument that suppresses the copyright text /nologo output = PatchFunctionMessageTestOutput(output); if (output.Equals(string.Empty)) { UTGHelper.ErrorHandler.ShowMessage(UTGHelper.CommonErrors.ERR_UNABLE_TO_RUN_UNITTEST); return(false); } System.Xml.XmlDocument xmlTestResultDoc = NUnitXmlResultProccessor.ToXmlDoc(output); System.Xml.XmlNodeList xmlTestResultsNodeList = NUnitXmlResultProccessor.GetTestCases(xmlTestResultDoc); List <System.Xml.XmlNode> successfulTestSuites = NUnitXmlResultProccessor.GetSuccessfulTestSuites(xmlTestResultsNodeList); List <System.Xml.XmlNode> failedTestSuites = NUnitXmlResultProccessor.GetFailedTestSuites(xmlTestResultsNodeList); List <System.Xml.XmlNode> failedExecutionSuites = NUnitXmlResultProccessor.GetFailedExecutionSuites(xmlTestResultsNodeList); List <UnitTestError> lstUnitTestPassed = NUnitXmlResultProccessor.GetSuccessfulTestSuitesAsUnitTestErrors(successfulTestSuites); List <UnitTestError> lstUnitTestErrors = NUnitXmlResultProccessor.GetFailedTestSuitesAsUnitTestErrors(failedTestSuites); List <UnitTestError> lstUnitTestsFialedToExecute = NUnitXmlResultProccessor.GetFailedExecutionsAsUnitTestErrors(failedExecutionSuites); if (TestEnded != null) { TestEnded(testFixturOption.Project, lstUnitTestPassed, lstUnitTestErrors, lstUnitTestsFialedToExecute); } return(true); } catch (Exception ex) { Logger.LogException(ex); } return(false); }
public async Task GetEndPoint_BodyWithDelimiter() { CodeClass testObject = await GetCodeClassAsync("Bar"); Assert.Throws <NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); }
public async Task GetEndPoint_Whole() { CodeClass testObject = await GetCodeClassAsync("Bar"); Assert.Throws <NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole)); }
private void AddMethodToClass(CodeClass serviceClass, string name, bool async) { string parameter = string.Format("{0}Input", _serviceName + name); var returnName = string.Format(async ? "Task<{0}Output>" : "{0}Output", _serviceName + name); var function = serviceClass.AddFunction(name, vsCMFunction.vsCMFunctionFunction, returnName, -1, vsCMAccess.vsCMAccessPublic); function.AddParameter("input", parameter); if (async) { function.StartPoint.CreateEditPoint().ReplaceText(6, "public async", (int) vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); } function.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint().ReplaceText(0, "throw new System.NotImplementedException();", (int) vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); }
public async Task IsAbstract() { CodeClass cc = await GetCodeClassAsync("Foo"); Assert.True(cc.IsAbstract); }
public static IEnumerable <CodeProperty2> GetProperties(this CodeClass cls) { return(cls.Children.OfType <CodeProperty2>()); }
protected override CodeElement CreateCodeElement(string name, string fullName, CodeLocation location, CodeElement parent) { CodeClass element = new CodeClass(name, fullName, location, parent); return(element); }