/// <summary> /// Inserts the method at end of class. /// </summary> /// <param name="instance">The instance.</param> /// <param name="snippetPath">The snippet path.</param> public static void InsertMethod( this ProjectItem instance, string snippetPath) { CodeClass codeClass = instance.GetFirstClass(); if (codeClass != null) { CodeFunction codeFunction = codeClass.AddFunction("temp", vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic, null); TextPoint startPoint = codeFunction.StartPoint; EditPoint editPoint = startPoint.CreateEditPoint(); codeClass.RemoveMember(codeFunction); editPoint.Insert("\n\n"); editPoint.InsertFromFile(snippetPath); } }
private void AddConstructorToRequestHandler(CodeClass codeClass, CreateMessage model) { var constructor = codeClass.AddFunction( Name: codeClass.Name, Kind: vsCMFunction.vsCMFunctionConstructor, Type: vsCMTypeRef.vsCMTypeRefVoid, Position: 0, Access: vsCMAccess.vsCMAccessPublic); var constructorParameters = model.ConstructorParameters .Select(x => { x.Type = x.Type.Replace("$self$", model.MessageHandlerName.Name); return(x); }) .ToList(); constructorParameters.ForEach(x => constructor.AddParameter(x.Name, x.Type, -1)); constructorParameters.ForEach(x => { var variable = codeClass.AddVariable(x.Name, x.Type, 0); variable.StartPoint.CreateEditPoint().Insert(model.ServicesAcces); }); var constructorEditPoit = constructor.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); constructorParameters.ForEach(x => constructorEditPoit.Insert(model.RequestHandlerIndent + "this." + x.Name + " = " + x.Name + ";" + Environment.NewLine)); }
/// <summary> /// 克隆一个方法 /// </summary> /// <param name="cloneFunction">要克隆的方法</param> /// <param name="codeClass">添加到类中</param> private void CloneFunction(CodeFunction cloneFunction, CodeClass codeClass) { CodeFunction codeFunction = codeClass.AddFunction(cloneFunction.Name, cloneFunction.FunctionKind, cloneFunction.Type, -1, cloneFunction.Access, null); //添加参数 for (int i = 1; i <= cloneFunction.Parameters.Count; i++) { CodeParameter2 parameter = cloneFunction.Parameters.Item(i) as CodeParameter2; CodeParameter2 cloneParameter = codeFunction.AddParameter(parameter.FullName, parameter.Type.AsFullName, i) as CodeParameter2; cloneParameter.DefaultValue = parameter.DefaultValue; cloneParameter.ParameterKind = parameter.ParameterKind; } //添加属性 for (int i = 1; i <= cloneFunction.Attributes.Count; i++) { CodeAttribute attribute = cloneFunction.Attributes.Item(i) as CodeAttribute; codeFunction.AddAttribute(attribute.Name, attribute.Value, i); } //方法注释 codeFunction.Comment = cloneFunction.Comment; //方法说明 codeFunction.DocComment = cloneFunction.DocComment; //静态修饰 codeFunction.IsShared = cloneFunction.IsShared; //抽象修饰 codeFunction.MustImplement = cloneFunction.MustImplement; //重载修饰 codeFunction.CanOverride = cloneFunction.CanOverride; }
protected void AddDefaultConstructor(CodeClass codeClass) { if (null == GetDefaultConstructor(codeClass)) { CodeFunction constructor = null; if (ReferenceUtil.IsCSharpProject(CustomProvider)) { constructor = codeClass.AddFunction(string.Empty, vsCMFunction.vsCMFunctionConstructor, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic, null); } else if (EntlibReferences.ReferenceUtil.IsVisualBasicProject(CustomProvider)) { constructor = codeClass.AddFunction(VisualBasicConstructorKeyWord, vsCMFunction.vsCMFunctionSub, vsCMTypeRef.vsCMTypeRefVoid, 0, vsCMAccess.vsCMAccessPublic, null); } constructor.AddParameter(ConfigurationParameterName, NamespaceHelper.GenerateFullTypeName(Namespace, ConfigurationNamespacePart, ConfigurationClassname), -1); } }
/// <summary> /// add a default constructor. /// </summary> /// <param name="instance">The instance.</param> /// <param name="moveToCorrectPosition">if set to <c>true</c> [move to correct position].</param> /// <returns>The constructor.</returns> public static CodeFunction AddDefaultConstructor( this CodeClass instance, bool moveToCorrectPosition) { TraceService.WriteLine("CodeClassExtensions::AddDefaultConstructor file=" + instance.Name); CodeFunction codeFunction = instance.AddFunction( instance.Name, vsCMFunction.vsCMFunctionConstructor, vsCMTypeRef.vsCMTypeRefVoid, 0, vsCMAccess.vsCMAccessPublic, null); codeFunction.GetEndPoint().CreateEditPoint().InsertNewLine(); string comment = "<doc><summary>\r\nInitializes a new instance of the " + instance.Name + " class.\r\n</summary></doc>\r\n"; codeFunction.DocComment = comment; if (moveToCorrectPosition) { TraceService.WriteLine("Move to correct position"); IEnumerable <CodeVariable> variables = instance.GetVariables(); CodeVariable lastVariable = variables.LastOrDefault(); if (lastVariable != null) { EditPoint startPoint = codeFunction.StartPoint.CreateEditPoint(); EditPoint endPoint = codeFunction.EndPoint.CreateEditPoint(); string text = startPoint.GetText(endPoint); //// remove current code Function text instance.RemoveMember(codeFunction); if (endPoint.GetText(1) == Environment.NewLine) { TraceService.WriteLine("Delete line"); endPoint.Delete(1); } EditPoint editPoint = lastVariable.EndPoint.CreateEditPoint(); editPoint.Insert(string.Format("{0}{1}{2}", Environment.NewLine, Environment.NewLine, text)); //// we need to re find the function as we have deleted this one! codeFunction = instance.GetFunction(instance.Name); codeFunction.DocComment = comment; } } return(codeFunction); }
private void AddMethodToClass(CodeClass serviceClass, string name, bool async) { string parameter = string.Format("{0}Input", name); var returnName = string.Format(async ? "Task<{0}Output>" : "{0}Output", 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); }
/// <summary> /// 生成方法定义到类中 /// </summary> /// <param name="serviceClass"></param> /// <param name="methodName"></param> /// <param name="async"></param> private void AddMethodToClass(CodeClass serviceClass, string methodName, string doccoment, bool async) { var returnName = string.Format(async ? "Task<{0}>" : "{0}", GetDtoClassName(methodName, DtoType.Output)); var function = serviceClass.AddFunction(methodName, vsCMFunction.vsCMFunctionFunction, returnName, -1, vsCMAccess.vsCMAccessPublic); function.AddParameter("input", GetDtoClassName(methodName, DtoType.Input)); function.Comment = doccoment; 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); }
private static void AddFunctionToClass(Project targetProject, CodeClass cls, string interfaceName) { CodeClass targetClass = null; int tryCount = 0; do { try { targetClass = (CodeClass)targetProject.CodeModel.CodeElements.Item(interfaceName); System.Threading.Thread.Sleep(10); } catch { } } while (targetClass == null && tryCount < 1024); if (targetClass == null) { return; } foreach (CodeElement elem in cls.Members) { if (elem.Kind == vsCMElement.vsCMElementFunction) { if (elem.Name != cls.Name && elem.Name != "~" + cls.Name) { CodeFunction originalFunction = (CodeFunction)elem; if (originalFunction.Access == vsCMAccess.vsCMAccessPublic) { CodeFunction newFunction = targetClass.AddFunction(elem.Name, vsCMFunction.vsCMFunctionPure | vsCMFunction.vsCMFunctionVirtual, originalFunction.Type, -1); int paramIdx = 0; foreach (CodeParameter param in originalFunction.Parameters) { string oldParamsName = param.Name; newFunction.AddParameter(oldParamsName, param.Type, ++paramIdx); } } } } } return; }
private void AddHandlerFunctionToRequestHandler(CodeClass codeClass, CreateMessage model) { var handler = codeClass.AddFunction( Name: "Handle", Kind: vsCMFunction.vsCMFunctionFunction, Type: model.HandlerHandleReturnValueName, Position: -1); handler.AddParameter("request", model.MessageName.Name, -1); if (model.ProcessingType == ProcessingType.Async) { handler.AddParameter("cancellationToken", "CancellationToken", -1); } handler.StartPoint.CreateEditPoint().ReplaceText(0, model.HandlerHandleAcces, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); handler.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint().Insert(model.RequestHandlerIndent + "throw new NotImplementedException();"); }
/// <summary> /// add a default constructor. /// </summary> /// <param name="instance">The instance.</param> /// <returns> /// The constructor. /// </returns> public static CodeFunction AddDefaultConstructor(this CodeClass instance) { TraceService.WriteLine("CodeClassExtensions::AddDefaultConstructor file=" + instance.Name); CodeFunction codeFunction = instance.AddFunction( instance.Name, vsCMFunction.vsCMFunctionConstructor, vsCMTypeRef.vsCMTypeRefVoid, 0, vsCMAccess.vsCMAccessPublic, null); codeFunction.GetEndPoint().CreateEditPoint().InsertNewLine(); string comment = "<doc><summary>\r\nInitializes a new instance of the " + instance.Name + " class.\r\n</summary></doc>\r\n"; codeFunction.DocComment = comment; return(codeFunction); }
/// <summary> /// Implements the function. /// </summary> /// <param name="instance">The instance.</param> /// <param name="codeSnippet">The code snippet.</param> public static void ImplementFunction( this CodeClass instance, CodeSnippet codeSnippet) { TraceService.WriteLine("CodeClassExtensions::ImplementFunction file=" + instance.Name); CodeFunction codeFunction = instance.AddFunction( "temp", vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic, null); TextPoint startPoint = codeFunction.StartPoint; EditPoint editPoint = startPoint.CreateEditPoint(); instance.RemoveMember(codeFunction); editPoint.Insert(codeSnippet.Code); }
// add a class to the given namespace private void AddClassToNamespace(CodeNamespace ns) { // add a class CodeClass chess = (CodeClass)ns.AddClass("Chess", -1, null, null, vsCMAccess.vsCMAccessPublic); // add a function with a parameter and a comment CodeFunction move = (CodeFunction)chess.AddFunction("Move", vsCMFunction.vsCMFunctionFunction, "int", -1, vsCMAccess.vsCMAccessPublic, null); move.AddParameter("IsOK", "bool", -1); move.Comment = "This is the move function"; // add some text to the body of the function EditPoint editPoint = (EditPoint)move.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.Indent(null, 0); editPoint.Insert("int a = 1;"); editPoint.Insert(Environment.NewLine); editPoint.Indent(null, 3); editPoint.Insert("int b = 3;"); editPoint.Insert(Environment.NewLine); editPoint.Indent(null, 3); editPoint.Insert("return a + b; //"); }
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 override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeProperty originalClassCodeProperty) { vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction; object functionType = null; functionKind = vsCMFunction.vsCMFunctionSub; functionType = vsCMTypeRef.vsCMTypeRefVoid; string nextAvailableName = originalClassCodeProperty.Name; if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass, nextAvailableName)) { nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject); } CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction( nextAvailableName, functionKind, functionType, -1, originalClassCodeProperty.Access, -1); unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1); try { unitTestCodeFunction.Comment = originalClassCodeProperty.Comment; unitTestCodeFunction.DocComment = originalClassCodeProperty.DocComment; } catch (Exception ex) { Logger.LogException(ex); //ignore } TextPoint bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint(); //Stop here if not read-write type property now... if (originalClassCodeProperty.Setter == null) { boydEditPoint = bodyStartingPoint.CreateEditPoint(); boydEditPoint.Insert(StringHelper.GetTabString() + "' Property is not read-write please add your own code here." + Environment.NewLine); return(unitTestCodeFunction); } string tvFunctionCallTemplate = string.Empty; // "iv{0}Type.{1} = default({2});"; tvFunctionCallTemplate = "iv{0}Type.{1} = New {2}()" + Environment.NewLine; string tvFunctionCall = tvFunctionCallTemplate; CodeTypeRef tvPropertyType = originalClassCodeProperty.Type; string tvPropertyTypeAsString = tvPropertyType.AsString; tvFunctionCall = string.Format(tvFunctionCall, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString); bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody); boydEditPoint = bodyStartingPoint.CreateEditPoint(); //FIX ME (tabing) boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine); //FIX ME (tabbing) string tvTempString = string.Empty; // "iv{0}Type.{1}, default({2})"; tvTempString = "iv{0}Type.{1}, New {2}()"; tvTempString = string.Format(tvTempString, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString); boydEditPoint.Insert(Environment.NewLine); boydEditPoint.Insert("\t\t\t'TODO: Update Assert to meet test needs" + Environment.NewLine); boydEditPoint.Insert("\t\t\t'Assert.AreEqual(" + tvTempString + ")" + Environment.NewLine); boydEditPoint.Insert("\t\t\t" + Environment.NewLine); boydEditPoint.Insert("\t\t\tThrow New Exception 'Not Implemented'" + Environment.NewLine); return(unitTestCodeFunction); }
/// <summary> /// Help method to modify KeyinCommands.cs or KeyinCommands.vb. /// </summary> /// <param name="projectItem"></param> /// <param name="keyinCommandFunctionCS"></param> /// <param name="keyinCommandFunctionvb"></param> private void ModifyKeyinsCommands(ProjectItem projectItem, string keyinCommandFunctionCS, string keyinCommandFunctionvb, string keyinCommandFunctionCPP) { Document activeDoc = projectItem.Document; if (activeDoc == null) { return; } ProjectItem activeDocumentProjectItem = activeDoc.ProjectItem; if (activeDocumentProjectItem == null) { return; } FileCodeModel fileCodeModel = activeDocumentProjectItem.FileCodeModel; if (fileCodeModel == null) { return; } CodeElements codeElements = fileCodeModel.CodeElements; CodeClass codeClass = null; // look for the namespace in the active document CodeNamespace codeNamespace = null; foreach (CodeElement codeElement in codeElements) { if (codeElement.Kind == vsCMElement.vsCMElementNamespace) { codeNamespace = codeElement as CodeNamespace; break; } } if (codeNamespace == null) { if (IsVBProject) { codeElements = fileCodeModel.CodeElements; } else { return; } } else { codeElements = codeNamespace.Members; } if (codeElements == null) { return; } // look for the first class foreach (CodeElement codeElement in codeElements) { if (codeElement.Kind == vsCMElement.vsCMElementClass) { codeClass = codeElement as CodeClass; break; } } if (codeClass == null) { return; } if (IsCSProject) { CodeFunction codeFunction = codeClass.AddFunction(FunctionName + "Keyin", vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic); codeFunction.AddParameter("unparsed", vsCMTypeRef.vsCMTypeRefString, -1); TextPoint textPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint editPoint = textPoint.CreateEditPoint(); EditPoint objMovePt = textPoint.CreateEditPoint(); EditPoint UtilEditPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint(); UtilEditPoint.ReplaceText(6, "public static", 0); editPoint.Insert ( keyinCommandFunctionCS ); editPoint.StartOfDocument(); objMovePt.EndOfDocument(); editPoint.SmartFormat(objMovePt); } else if (IsVBProject) { CodeFunction codeFunction = codeClass.AddFunction(FunctionName + "Keyin", vsCMFunction.vsCMFunctionSub, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic); codeFunction.AddParameter("unparsed", vsCMTypeRef.vsCMTypeRefString, -1); TextPoint textPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint editPoint = textPoint.CreateEditPoint(); EditPoint objMovePt = textPoint.CreateEditPoint(); EditPoint UtilEditPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint(); UtilEditPoint.ReplaceText(6, "Public Shared", 0); editPoint.Insert ( keyinCommandFunctionvb ); editPoint.StartOfDocument(); objMovePt.EndOfDocument(); editPoint.SmartFormat(objMovePt); } else if (IsVCProject) { TextDocument editDoc = (TextDocument)activeDoc.Object("TextDocument"); EditPoint objEditPt = editDoc.CreateEditPoint(); EditPoint objMovePt = editDoc.EndPoint.CreateEditPoint(); objEditPt.StartOfDocument(); activeDoc.ReadOnly = false; if (objEditPt.FindPattern("#include")) { objEditPt.LineDown(1); objEditPt.Insert("#include \"" + FunctionName + ".h\"\n"); } else if ((objEditPt.FindPattern("#using"))) { objEditPt.LineUp(1); objEditPt.Insert("#include \"" + FunctionName + ".h\"\n"); } else { objEditPt.FindPattern("namespace"); objEditPt.LineUp(1); objEditPt.Insert("#include \"" + FunctionName + ".h\"\n"); } CodeFunction codeFunction = codeClass.AddFunction(FunctionName + "Keyin", vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic); codeFunction.AddParameter("unparsed", "System::String^", -1); TextPoint textPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint editPoint = textPoint.CreateEditPoint(); objMovePt = textPoint.CreateEditPoint(); EditPoint UtilEditPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint(); UtilEditPoint.ReplaceText(4, "public:static", 0); editPoint.Insert(keyinCommandFunctionCPP); if (objEditPt.FindPattern("throw gcnew System::NotImplementedException();")) { editPoint.Delete(52); } editPoint.StartOfDocument(); objMovePt.EndOfDocument(); editPoint.SmartFormat(objMovePt); } }
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; }
public bool TryGenerateMethodStub(string selectedClass, ITextSnapshotLine containingLine, out CodeClass targetClass, out CodeFunction implementationFunction) { targetClass = null; implementationFunction = null; try { targetClass = _project.FindOrCreateClass(selectedClass); } catch (ArgumentException ex) { StatusBarLogger.Log(ex.Message); return(false); } if (targetClass == null) { return(false); } EnsureGaugeImport(targetClass); var functionName = _step.Text.ToMethodIdentifier(); var functionCount = _project.GetFunctionsForClass(targetClass) .Count(element => string.CompareOrdinal(element.Name, functionName) == 0); functionName = functionCount == 0 ? functionName : functionName + functionCount; try { implementationFunction = targetClass.AddFunction(functionName, vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic, null); var parameterList = _step.Parameters; parameterList.Reverse(); if (_step.HasInlineTable) { implementationFunction.AddParameter("table", typeof(Table).Name); parameterList.RemoveAt(0); } foreach (var parameter in parameterList) { if (IsSpecialParameter(parameter)) { AddSpecialParam(implementationFunction, parameter); } else { var newName = GenerateNewParameterIdentifier(implementationFunction, parameter); implementationFunction.AddParameter(newName, vsCMTypeRef.vsCMTypeRefString); } } AddStepAttribute(implementationFunction, _step.Text); } catch { if (implementationFunction != null) { targetClass.RemoveMember(implementationFunction); } return(false); } finally { targetClass.ProjectItem.Save(); } return(true); }
protected bool AddSynchWrapperMember(CodeClass synch, CodeFunction cf) { if (cf != null && (cf.FunctionKind & FunctionsThatCantBeAnnotatedAsVirtual) == 0 && cf.CanOverride == true && cf.IsShared == false) { //add prototype and parameters CodeFunction synchFunction = synch.AddFunction(cf.Name, cf.FunctionKind, cf.Type, -1, cf.Access, null); foreach (CodeParameter param in cf.Parameters) { synchFunction.AddParameter(param.Name, param.Type, -1); } synchFunction.CanOverride = true; EditPoint replaceVirtual = synchFunction.StartPoint.CreateEditPoint(); TextRanges tr = null; replaceVirtual.ReplacePattern(synchFunction.EndPoint, "virtual", "override", (int)EnvDTE.vsFindOptions.vsFindOptionsMatchWholeWord, ref tr); //remove default return EditPoint editPt = synchFunction.EndPoint.CreateEditPoint(); editPt.LineUp(1); editPt.StartOfLine(); string returnType = cf.Type.AsString; if (returnType != "void") { EditPoint startOfLastLine = synchFunction.EndPoint.CreateEditPoint(); startOfLastLine.LineUp(1); startOfLastLine.EndOfLine(); editPt.Delete(startOfLastLine); } //generate method body System.Text.StringBuilder methodBody = new System.Text.StringBuilder(100); if (returnType != "void") { methodBody.Append(cf.Type.AsString + " ret;\n"); } methodBody.Append( "System.Threading.Monitor.Enter(_root);" + "\ntry{"); if (returnType != "void") { methodBody.Append("\nret = _parent." + cf.Name + "("); } else { methodBody.Append("\n_parent." + cf.Name + "("); } bool first = true; foreach (CodeParameter p in cf.Parameters) { if (!first) { methodBody.Append(", "); } first = false; int typeSpaceLocation = p.Type.AsString.IndexOf(' '); if (typeSpaceLocation != -1) //append out or ref to parameter { methodBody.Append(p.Type.AsString.Substring(0, typeSpaceLocation + 1)); } methodBody.Append(p.Name); } methodBody.Append(");"); methodBody.Append( "\n}" + "\nfinally{System.Threading.Monitor.Exit(_root);}"); if (returnType != "void") { methodBody.Append("\nreturn ret;"); } //add new body to method editPt.Insert(methodBody.ToString()); editPt.MoveToPoint(synchFunction.StartPoint); editPt.SmartFormat(synchFunction.EndPoint); } return(true); }
public override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeProperty originalClassCodeProperty) { vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction; object functionType = null; functionKind = vsCMFunction.vsCMFunctionSub; functionType = vsCMTypeRef.vsCMTypeRefVoid; string nextAvailableName = originalClassCodeProperty.Name; if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass, nextAvailableName)) { nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject); } CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction( nextAvailableName, functionKind, functionType, -1, originalClassCodeProperty.Access, -1); unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1); try { unitTestCodeFunction.Comment = originalClassCodeProperty.Comment; unitTestCodeFunction.DocComment = originalClassCodeProperty.DocComment; } catch (Exception ex) { Logger.LogException(ex); //ignore } TextPoint bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint(); //Stop here if not read-write type property now... if (originalClassCodeProperty.Setter == null) { boydEditPoint = bodyStartingPoint.CreateEditPoint(); boydEditPoint.Insert(StringHelper.GetTabString() + "' Property is not read-write please add your own code here." + Environment.NewLine); return unitTestCodeFunction; } string tvFunctionCallTemplate = string.Empty; // "iv{0}Type.{1} = default({2});"; tvFunctionCallTemplate = "iv{0}Type.{1} = New {2}()" + Environment.NewLine; string tvFunctionCall = tvFunctionCallTemplate; CodeTypeRef tvPropertyType = originalClassCodeProperty.Type; string tvPropertyTypeAsString = tvPropertyType.AsString; tvFunctionCall = string.Format(tvFunctionCall, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString); bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody); boydEditPoint = bodyStartingPoint.CreateEditPoint(); //FIX ME (tabing) boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine); //FIX ME (tabbing) string tvTempString = string.Empty; // "iv{0}Type.{1}, default({2})"; tvTempString = "iv{0}Type.{1}, New {2}()"; tvTempString = string.Format(tvTempString, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString); boydEditPoint.Insert(Environment.NewLine); boydEditPoint.Insert("\t\t\t'TODO: Update Assert to meet test needs" + Environment.NewLine); boydEditPoint.Insert("\t\t\t'Assert.AreEqual(" + tvTempString + ")" + Environment.NewLine); boydEditPoint.Insert("\t\t\t" + Environment.NewLine); boydEditPoint.Insert("\t\t\tThrow New Exception 'Not Implemented'" + Environment.NewLine); return unitTestCodeFunction; }
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); }
/// <summary> /// 克隆一个方法 /// </summary> /// <param name="cloneFunction">要克隆的方法</param> /// <param name="codeClass">添加到类中</param> private void CloneFunction(CodeFunction cloneFunction, CodeClass codeClass) { CodeFunction codeFunction = codeClass.AddFunction(cloneFunction.Name, cloneFunction.FunctionKind, cloneFunction.Type, -1, cloneFunction.Access, null); //添加参数 for (int i = 1; i <= cloneFunction.Parameters.Count; i++) { CodeParameter2 parameter = cloneFunction.Parameters.Item(i) as CodeParameter2; CodeParameter2 cloneParameter = codeFunction.AddParameter(parameter.FullName, parameter.Type.AsFullName, i) as CodeParameter2; cloneParameter.DefaultValue = parameter.DefaultValue; cloneParameter.ParameterKind = parameter.ParameterKind; } //添加属性 for (int i = 1; i <= cloneFunction.Attributes.Count; i++) { CodeAttribute attribute = cloneFunction.Attributes.Item(i) as CodeAttribute; codeFunction.AddAttribute(attribute.Name, attribute.Value, i); } //方法注释 codeFunction.Comment = cloneFunction.Comment; //方法说明 codeFunction.DocComment = cloneFunction.DocComment; //静态修饰 codeFunction.IsShared = cloneFunction.IsShared; //抽象修饰 codeFunction.MustImplement = cloneFunction.MustImplement; //重载修饰 codeFunction.CanOverride = cloneFunction.CanOverride; }
/// <summary> /// Generates the DTOs of the EDMX Document provided using the parameters received. /// </summary> /// <param name="parameters">Parameters for the generation of DTOs.</param> /// <param name="worker">BackgroundWorker reference.</param> public static List <DTOEntity> GenerateDTOs(GenerateDTOsParams parameters, BackgroundWorker worker) { LogManager.LogMethodStart(); if (parameters.DTOsServiceReady) { VisualStudioHelper.AddReferenceToProject(parameters.TargetProject, Resources.AssemblySystemRuntimeSerialization, Resources.AssemblySystemRuntimeSerialization); } if (GeneratorManager.CheckCancellationPending()) { return(null); } EditPoint objEditPoint; // EditPoint to reuse CodeParameter objCodeParameter; // CodeParameter to reuse CodeNamespace objNamespace = null; // Namespace item to add Classes ProjectItem sourceFileItem = null; // Source File Item to save int dtosGenerated = 0; List <EnumType> enums = DTOGenerator.GetEnumTypes(parameters); PropertyHelper.SetEnumTypes(enums); List <DTOEntity> entitiesDTOs = DTOGenerator.GetEntityDTOs(parameters); if (GeneratorManager.CheckCancellationPending()) { return(null); } worker.ReportProgress(0, new GeneratorOnProgressEventArgs(0, string.Format(Resources.Text_DTOsGenerated, dtosGenerated, entitiesDTOs.Count))); TemplateClass.CreateFile(); // Imports to add to the Source File var importList = new List <SourceCodeImport>(); // EnumTypes defined in the EDMX ? if (enums.Exists(e => e.IsExternal == false)) { importList.Add(new SourceCodeImport(parameters.EntitiesNamespace)); VisualStudioHelper.AddReferenceToProject(parameters.TargetProject, parameters.EDMXProject); } // Include imports of external enums. foreach (string externalEnumNamespace in enums.Where(e => e.IsExternal).Select(e => e.Namespace).Distinct()) { importList.Add(new SourceCodeImport(externalEnumNamespace)); } // Generate Source File if type is One Source File if (parameters.SourceFileGenerationType == SourceFileGenerationType.OneSourceFile) { sourceFileItem = null; // Generate Source and Get the Namespace item objNamespace = VisualStudioHelper.GenerateSourceAndGetNamespace( parameters.TargetProject, parameters.TargetProjectFolder, parameters.SourceFileName, parameters.SourceFileHeaderComment, parameters.SourceNamespace, parameters.DTOsServiceReady, out sourceFileItem); // Add Imports to Source File VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList); } // Check Cancellation Pending if (GeneratorManager.CheckCancellationPending()) { return(null); } // Loop through Entities DTOs foreach (DTOEntity entityDTO in entitiesDTOs) { // Generate Source File if type is Source File per Class if (parameters.SourceFileGenerationType == SourceFileGenerationType.SourceFilePerClass) { sourceFileItem = null; // Generate Source and Get the Namespace item objNamespace = VisualStudioHelper.GenerateSourceAndGetNamespace( parameters.TargetProject, parameters.TargetProjectFolder, entityDTO.NameDTO, parameters.SourceFileHeaderComment, parameters.SourceNamespace, parameters.DTOsServiceReady, out sourceFileItem); // Add Imports to Source File VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList); } // Add Class CodeClass objCodeClass = objNamespace.AddClassWithPartialSupport(entityDTO.NameDTO, entityDTO.NameBaseDTO, entityDTO.DTOClassAccess, entityDTO.DTOClassKind); // Set IsAbstract objCodeClass.IsAbstract = entityDTO.IsAbstract; // Set Class Attributes foreach (DTOAttribute classAttr in entityDTO.Attributes) { objCodeClass.AddAttribute(classAttr.Name, classAttr.Parameters, AppConstants.PLACE_AT_THE_END); } // Set Class Properties foreach (DTOClassProperty entityProperty in entityDTO.Properties) { // Add Property CodeProperty objCodeProperty = objCodeClass.AddProperty(entityProperty.PropertyName, entityProperty.PropertyName, entityProperty.PropertyType, AppConstants.PLACE_AT_THE_END, entityProperty.PropertyAccess, null); // Get end of accessors auto-generated code objEditPoint = objCodeProperty.Setter.EndPoint.CreateEditPoint(); objEditPoint.LineDown(); objEditPoint.EndOfLine(); var getSetEndPoint = objEditPoint.CreateEditPoint(); // Move to the start of accessors auto-generated code objEditPoint = objCodeProperty.Getter.StartPoint.CreateEditPoint(); objEditPoint.LineUp(); objEditPoint.LineUp(); objEditPoint.EndOfLine(); // Replace accessors auto-generated code with a more cleaner one objEditPoint.ReplaceText(getSetEndPoint, Resources.CSharpCodeGetSetWithBrackets, Convert.ToInt32(vsEPReplaceTextOptions.vsEPReplaceTextAutoformat)); // Set Property Attributes foreach (DTOAttribute propAttr in entityProperty.PropertyAttributes) { objCodeProperty.AddAttribute(propAttr.Name, propAttr.Parameters, AppConstants.PLACE_AT_THE_END); } objEditPoint = objCodeProperty.StartPoint.CreateEditPoint(); objEditPoint.SmartFormat(objEditPoint); } if (parameters.GenerateDTOConstructors) { // Add empty Constructor CodeFunction emptyConstructor = objCodeClass.AddFunction(objCodeClass.Name, vsCMFunction.vsCMFunctionConstructor, null, AppConstants.PLACE_AT_THE_END, vsCMAccess.vsCMAccessPublic, null); // Does this DTO have a Base Class ? if (entityDTO.BaseDTO != null) { // Add call to empty Base Constructor objEditPoint = emptyConstructor.StartPoint.CreateEditPoint(); objEditPoint.EndOfLine(); objEditPoint.Insert(Resources.Space + Resources.CSharpCodeBaseConstructor); } // Does this DTO have properties ? if (entityDTO.Properties.Count > 0) { // Add Constructor with all properties as parameters CodeFunction constructorWithParams = objCodeClass.AddFunction(objCodeClass.Name, vsCMFunction.vsCMFunctionConstructor, null, AppConstants.PLACE_AT_THE_END, vsCMAccess.vsCMAccessPublic, null); foreach (DTOClassProperty entityProperty in entityDTO.Properties) { // Add Constructor parameter objCodeParameter = constructorWithParams.AddParameter( Utils.SetFirstLetterLowercase(entityProperty.PropertyName), entityProperty.PropertyType, AppConstants.PLACE_AT_THE_END); // Add assignment objEditPoint = constructorWithParams.EndPoint.CreateEditPoint(); objEditPoint.LineUp(); objEditPoint.EndOfLine(); objEditPoint.Insert(Environment.NewLine + AppConstants.TAB + AppConstants.TAB + AppConstants.TAB); objEditPoint.Insert(string.Format(Resources.CSharpCodeAssignmentThis, entityProperty.PropertyName, objCodeParameter.Name)); } // Does this DTO have a Base Class ? if (entityDTO.BaseDTO != null) { // Get the Base Class properties (includes the properties of the base recursively) List <DTOClassProperty> baseProperties = DTOGenerator.GetPropertiesForConstructor(entityDTO.BaseDTO); // Base Constructor parameters var sbBaseParameters = new StringBuilder(); foreach (DTOClassProperty entityProperty in baseProperties) { // Add Constructor parameter objCodeParameter = constructorWithParams.AddParameter( Utils.SetFirstLetterLowercase(entityProperty.PropertyName), entityProperty.PropertyType, AppConstants.PLACE_AT_THE_END); // Add parameter separation if other parameters exists if (sbBaseParameters.Length > 0) { sbBaseParameters.Append(Resources.CommaSpace); } // Add to Base Constructor parameters sbBaseParameters.Append(objCodeParameter.Name); } // Add call to Base Constructor with parameters objEditPoint = constructorWithParams.StartPoint.CreateEditPoint(); objEditPoint.EndOfLine(); objEditPoint.Insert( Environment.NewLine + AppConstants.TAB + AppConstants.TAB + AppConstants.TAB); objEditPoint.Insert( string.Format(Resources.CSharpCodeBaseConstructorWithParams, sbBaseParameters.ToString())); } // END if DTO has a Base Class } // END if DTO has properties } // END if Generate DTO Constructor methods // Save changes to Source File Item sourceFileItem.Save(); // Count DTO generated dtosGenerated++; // Report Progress int progress = ((dtosGenerated * 100) / entitiesDTOs.Count); if (progress < 100) { worker.ReportProgress(progress, new GeneratorOnProgressEventArgs(progress, string.Format(Resources.Text_DTOsGenerated, dtosGenerated, entitiesDTOs.Count))); } // Check Cancellation Pending if (GeneratorManager.CheckCancellationPending()) { return(null); } } // END Loop through Entities DTOs // Save Target Project parameters.TargetProject.Save(); // Delete Template Class File TemplateClass.Delete(); // Report Progress worker.ReportProgress(100, new GeneratorOnProgressEventArgs(100, string.Format(Resources.Text_DTOsGenerated, dtosGenerated, entitiesDTOs.Count))); LogManager.LogMethodEnd(); // Return the DTOs generated return(entitiesDTOs); }
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); }
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); }