public string GetVerb(CodeFunction2 d)
        {
            List <CodeAttribute2> codeAttributes2 = d.Attributes.OfType <CodeAttribute2>().ToList();

            var attrs  = codeAttributes2.Select(attr => attr.Name).ToList();
            var result = "Get";

            if (attrs.Contains("HttpPost"))
            {
                result = "Post";
            }
            if (attrs.Contains("HttpPut"))
            {
                result = "Put";
            }

            if (attrs.Contains("HttpDelete"))
            {
                result = "Delete";
            }

            if (attrs.Contains("HttpPatch"))
            {
                result = "Patch";
            }

            if (attrs.Contains("HttpOption"))
            {
                result = "Option";
            }
            return(result);
        }
Exemplo n.º 2
0
        public string GenerateCode(CodeFunction2 method)
        {
            CodeParameter2 param = method.Parameters.Item(1) as CodeParameter2;
            CodeClass2 containingClass = method.Parent as CodeClass2;

            string returnType = method.Type.AsFullName;
            string paramType = param.Type.AsFullName;
            string paramName = param.Name;
            string returnVariableName = string.Empty;
            string codeToInsert = string.Empty;

            bool convertingToEntity = CodeModelUtils.IsEntityClass(method.Type.CodeType);

            // If we are converting to an entity
            if (convertingToEntity)
            {
                returnVariableName = "entity";
                codeToInsert += "// VO to entity conversion\n";
                // Add code to create a new entity with the Factory.NewInstance() method
                codeToInsert += returnType + " " + returnVariableName + " = " + returnType + ".Factory.NewInstance();\n\n";
            }
            else
            {
                returnVariableName = "valueObject";
                codeToInsert += "// Entity to VO conversion\n\n";
                // Add code to create a new VO with a new statement
                codeToInsert += returnType + " " + returnVariableName + " = new " + returnType + "();\n\n";
            }

            ArrayList unmappedProperties = new ArrayList();
            foreach (Property prop in m_properties)
            {
                if (prop.SourceProperty != null)
                {
                    if (prop.IsNullableType)
                    {
                        codeToInsert += "if (" + paramName + "." +prop.Name + ".HasValue)\n{\n";
                        codeToInsert += returnVariableName + "." + prop.Name + " = " + paramName + "." + prop.SourceProperty.Name + ".Value;\n}\n";
                    }
                    else
                    {
                        codeToInsert += returnVariableName + "." + prop.Name + " = " + paramName + "." + prop.SourceProperty.Name + ";\n";
                    }
                }
                else
                {
                    unmappedProperties.Add(prop);
                }
            }

            foreach (Property unmappedProp in unmappedProperties)
            {
                codeToInsert += "// " + returnVariableName + "." + unmappedProp.Name + "\n";
            }

            // Add the return statement
            codeToInsert += "\nreturn " + returnVariableName + ";\n\n";

            return codeToInsert;
        }
Exemplo n.º 3
0
        public CodeMember(CodeElement2 element, CodeElement2 type, Language language)
        {
            this.element     = element;
            this.TypeElement = type;
            this.language    = language;

            this.Name = element.Name;
            this.RequiresSeparatorLine = element.Kind != vsCMElement.vsCMElementVariable;
            switch (element.Kind)
            {
            case vsCMElement.vsCMElementFunction:
                CodeFunction2 function = (CodeFunction2)element;
                MemberKind    kind;
                switch (function.FunctionKind)
                {
                case vsCMFunction.vsCMFunctionConstructor:
                    kind = MemberKind.Constructor;
                    break;

                case vsCMFunction.vsCMFunctionDestructor:
                    kind = MemberKind.Destructor;
                    break;

                case vsCMFunction.vsCMFunctionOperator:
                    kind = MemberKind.Operator;
                    break;

                default:
                    kind = MemberKind.Function;
                    break;
                }

                this.Initialize(
                    kind,
                    function.Access,
                    function.IsShared,
                    function.OverrideKind,
                    functionKind: function.FunctionKind,
                    parameters: function.Parameters);
                break;

            case vsCMElement.vsCMElementProperty:
                CodeProperty2 property = (CodeProperty2)element;
                this.Initialize(MemberKind.Property, property.Access, property.IsShared, property.OverrideKind, parameters: property.Parameters);
                break;

            case vsCMElement.vsCMElementVariable:
                CodeVariable2 variable = (CodeVariable2)element;
                this.Initialize(MemberKind.Variable, variable.Access, variable.IsShared, constKind: variable.ConstKind);
                break;

            case vsCMElement.vsCMElementEvent:
                CodeEvent evt = (CodeEvent)element;
                this.Initialize(MemberKind.Event, evt.Access, evt.IsShared, evt.OverrideKind);
                break;

            default:
                throw new NotSupportedException("Unsupported element kind: " + element.Kind);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public CodeFunctionInfo(BaseInfo parent, CodeFunction2 method)
            : base(parent, method as CodeElement2)
        {
            // Can be null when an custom ActionResult has no ctor
            if (method == null)
                return;

            _item = method;
            Summary = string.Empty;
            _signature = method.Name;
            this.IsGeneric = method.IsGeneric;

            try
            {
                BuildComment(_item.DocComment);
            }
            catch (Exception)
            {

            }

            this.Access = ObjectFactory.Convert(this._item.Access);

            Parameters.ToList();
        }
        protected override void OnUnitTestProjectCreated(Project unitTestProject, CodeFunction2 sourceMethod)
        {
            if (unitTestProject == null)
            {
                throw new ArgumentNullException("unitTestProject");
            }
            if (sourceMethod == null)
            {
                throw new ArgumentNullException("sourceMethod");
            }

            // TODO: Remove references to "MSTestFramework" and "MSTestFramework.Universal"

            // Add package reference for xUnit.net
            TraceLogger.LogInfo("XunitSolutionManager.OnUnitTestProjectCreated: Adding reference to NuGet packages 'xunit' and 'xunit.runner.visualstudion' (version {0})", xunitPackageVersion);
            EnsureNuGetReference(unitTestProject, "xunit", xunitPackageVersion);
            EnsureNuGetReference(unitTestProject, "xunit.runner.visualstudio", visualStudioRunnerPackageVersion);

            // Remove any *.cs/*.vb files from the root of the project (i.e., Class1.cs/Class1.vb)
            foreach (var projectItem in unitTestProject.ProjectItems.AsEnumerable())
            {
                var extension = Path.GetExtension(projectItem.Name).ToLowerInvariant();
                if (extension == ".cs" || extension == ".vb")
                {
                    TraceLogger.LogInfo("XunitSolutionManager.OnUnitTestProjectCreated: Removing project item {0}", projectItem.Name);
                    projectItem.Delete();
                }
            }
        }
        protected override void OnUnitTestProjectCreated(Project unitTestProject, CodeFunction2 sourceMethod)
        {
            if (unitTestProject == null)
                throw new ArgumentNullException("unitTestProject");
            if (sourceMethod == null)
                throw new ArgumentNullException("sourceMethod");

            // TODO: Remove references to "MSTestFramework" and "MSTestFramework.Universal"

            // Add package reference for xUnit.net
            TraceLogger.LogInfo("XunitSolutionManager.OnUnitTestProjectCreated: Adding reference to NuGet packages 'xunit' and 'xunit.runner.visualstudion' (version {0})", xunitPackageVersion);
            EnsureNuGetReference(unitTestProject, "xunit", xunitPackageVersion);
            EnsureNuGetReference(unitTestProject, "xunit.runner.visualstudio", visualStudioRunnerPackageVersion);

            // Remove any *.cs/*.vb files from the root of the project (i.e., Class1.cs/Class1.vb)
            foreach (var projectItem in unitTestProject.ProjectItems.AsEnumerable())
            {
                var extension = Path.GetExtension(projectItem.Name).ToLowerInvariant();
                if (extension == ".cs" || extension == ".vb")
                {
                    TraceLogger.LogInfo("XunitSolutionManager.OnUnitTestProjectCreated: Removing project item {0}", projectItem.Name);
                    projectItem.Delete();
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Finds the function code element.
        /// </summary>
        /// <param name="cc">The cc.</param>
        /// <param name="functionName">Name of the function.</param>
        /// <param name="arguments">The arguments.</param>
        /// <returns></returns>
        internal static CodeFunction2 FindFunctionCodeElement(CodeClass cc, string functionName,
                                                              List <Argument> arguments)
        {
            foreach (CodeElement ce in cc.Members)
            {
                if (ce is CodeFunction2 && functionName == ce.Name)
                {
                    CodeFunction2 cf = ce as CodeFunction2;

                    if (arguments == null)
                    {
                        return(cf);
                    }

                    if (cf.Parameters.Count == arguments.Count)
                    {
                        // On regarde si les paramètres correspondent
                        for (int i = 0; i < arguments.Count; i++)
                        {
                            CodeParameter param = (CodeParameter)cf.Parameters.Item(i + 1);
                            if (param.Name != arguments[i].Name)
                            {
                                return(null);
                            }
                        }
                        return(cf);
                    }
                }
            }
            return(null);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Adds missing access modifiers
        /// </summary>
        /// <param name="codeElement">The CodeElement to add missing access modifiers too. Includes children.</param>
        private void AddMissingAccessModifiers(CodeElement codeElement)
        {
            if (codeElement.Kind != vsCMElement.vsCMElementInterface && CodeElementBlockTypes.ContainsKey(codeElement.Kind))
            {
                for (int i = 1; i <= codeElement.Children.Count; i++)
                {
                    CodeElement element = codeElement.Children.Item(i) as CodeElement;

                    if (element.Kind != vsCMElement.vsCMElementImportStmt && element.Kind != vsCMElement.vsCMElementInterface && CodeElementBlockTypes.ContainsKey(codeElement.Kind))
                    {
                        // Get the element's access through reflection rather than a massive switch.
                        vsCMAccess access = (vsCMAccess)CodeElementTypes[element.Kind].InvokeMember("Access", BindingFlags.GetProperty, null, element, null);

                        if (element.Kind == vsCMElement.vsCMElementClass || element.Kind == vsCMElement.vsCMElementStruct)
                        {
                            AddMissingAccessModifiers(element);
                        }

                        EditPoint start;
                        EditPoint end;
                        string    declaration;

                        if (element.Kind == vsCMElement.vsCMElementFunction)
                        {
                            // method, constructor, or finalizer
                            CodeFunction2 function = element as CodeFunction2;

                            // Finalizers don't have access modifiers, neither do static constructors
                            if (function.FunctionKind == vsCMFunction.vsCMFunctionDestructor || (function.FunctionKind == vsCMFunction.vsCMFunctionConstructor && function.IsShared))
                            {
                                continue;
                            }
                        }

                        if (element.Kind == vsCMElement.vsCMElementProperty || element.Kind == vsCMElement.vsCMElementVariable || element.Kind == vsCMElement.vsCMElementEvent)
                        {
                            CodeElements attributes = (CodeElements)CodeElementTypes[element.Kind].InvokeMember("Attributes", BindingFlags.GetProperty, null, element, null);

                            start = attributes.Count > 0 ? element.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter).CreateEditPoint() : element.StartPoint.CreateEditPoint();
                        }
                        else
                        {
                            start = element.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint();
                        }

                        end = start.CreateEditPoint();
                        end.EndOfLine();
                        declaration = start.GetText(end);
                        if (!declaration.StartsWith(CodeAccessKeywords[access]) && !declaration.StartsWith("partial"))
                        {
                            object[] args = new object[1];
                            args.SetValue(access, 0);
                            CodeElementTypes[element.Kind].InvokeMember("Access", BindingFlags.SetProperty, null, element, args);
                        }

                        declaration = start.GetText(end);
                    }
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Performs any preparatory tasks that have to be done after a new unit test project has been created.
        /// </summary>
        /// <param name="unitTestProject">The <see cref="Project"/> of the unit test project that has just been created.</param>
        /// <param name="sourceMethod">The <see cref="CodeFunction2"/> of the source method that is to be unit tested.</param>
        protected override void OnUnitTestProjectCreated(Project unitTestProject, CodeFunction2 sourceMethod)
        {
            if (unitTestProject == null)
            {
                throw new ArgumentNullException(nameof(unitTestProject));
            }
            if (sourceMethod == null)
            {
                throw new ArgumentNullException(nameof(sourceMethod));
            }

            TraceLogger.LogInfo("xUnitSolutionManager.OnUnitTestProjectCreated: Adding reference to NUnit assemblies through nuget.");

            base.OnUnitTestProjectCreated(unitTestProject, sourceMethod);

            this.EnsureNuGetReference(unitTestProject, "xunit", "2.4.1");
            this.EnsureNuGetReference(unitTestProject, "xunit.runner.visualstudio", "2.4.1");


            var vsp       = unitTestProject.Object as VSProject2;
            var reference = vsp?.References.Find(GlobalConstants.MSTestAssemblyName);

            if (reference != null)
            {
                TraceLogger.LogInfo("xUnitSolutionManager.OnUnitTestProjectCreated: Removing reference to {0}", reference.Name);
                reference.Remove();
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Performs any preparatory tasks that have to be done after a new unit test project has been created.
        /// </summary>
        /// <param name="unitTestProject">The <see cref="Project"/> of the unit test project that has just been created.</param>
        /// <param name="sourceMethod">The <see cref="CodeFunction2"/> of the source method that is to be unit tested.</param>
        protected override void OnUnitTestProjectCreated(Project unitTestProject, CodeFunction2 sourceMethod)
        {
            if (unitTestProject == null)
            {
                throw new ArgumentNullException("unitTestProject");
            }

            TraceLogger.LogInfo("MSTestv2SolutionManager.OnUnitTestProjectCreated: Adding reference to MSTestv2 assemblies through nuget.");

            base.OnUnitTestProjectCreated(unitTestProject, sourceMethod);

            this.EnsureNuGetReference(unitTestProject, "MSTest.TestAdapter", "1.1.18");
            this.EnsureNuGetReference(unitTestProject, "MSTest.TestFramework", "1.1.18");

            VSProject2 vsp = unitTestProject.Object as VSProject2;

            if (vsp != null)
            {
                Reference reference = vsp.References.Find(GlobalConstants.MSTestAssemblyName);
                if (reference != null)
                {
                    TraceLogger.LogInfo("MSTestv2SolutionManager.OnUnitTestProjectCreated: Removing reference to {0}", reference.Name);
                    reference.Remove();
                }
            }
        }
Exemplo n.º 11
0
        public void initialize_constructor()
        {
            TextSelection selection    = studio.ActiveDocument.Selection as TextSelection;
            CodeClass2    class_object = (CodeClass2)selection.ActivePoint.get_CodeElement(vsCMElement.vsCMElementClass);
            CodeFunction2 constructor  = class_object.AddFunction(class_object.Name, vsCMFunction.vsCMFunctionConstructor,
                                                                  vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic, 0) as CodeFunction2;

            string text = "";

            foreach (CodeElement2 member in class_object.Members)
            {
                if (member.Kind == vsCMElement.vsCMElementVariable)
                {
                    CodeVariable2  variable  = member as CodeVariable2;
                    CodeParameter2 parameter = constructor.AddParameter("new_" + variable.Name, variable.Type, -1) as CodeParameter2;
                    text += "\r\n" + variable.Name + " = " + parameter.Name + ";";
                }
                else if (member.Kind == vsCMElement.vsCMElementProperty)
                {
                    var variable = member as CodeProperty;
                    // CodeTypeRef new_type =
                    CodeParameter2 parameter = constructor.AddParameter("new_" + variable.Name, variable.Type, -1) as CodeParameter2;
                    text += "\r\n" + variable.Name + " = " + parameter.Name + ";";
                }
            }

            EditPoint2 point = constructor.EndPoint.CreateEditPoint() as EditPoint2;

            point.LineUp(1);
            point.Insert(text);
            selection.MoveToPoint(constructor.StartPoint, false);
            selection.MoveToPoint(constructor.EndPoint, true);
            selection.SmartFormat();
            selection.MoveToPoint(point, false);
        }
Exemplo n.º 12
0
 public PropertyMapperDialog(CodeFunction2 currentMethod, AddInSettings settings)
 {
     InitializeComponent();
     m_currentMethod = currentMethod;
     this.KeyPreview = true;
     m_codeToInsert = string.Empty;
     m_addInSettings = settings;
 }
Exemplo n.º 13
0
 public PropertyMapperDialog(CodeFunction2 currentMethod, AddInSettings settings)
 {
     InitializeComponent();
     m_currentMethod = currentMethod;
     this.KeyPreview = true;
     m_codeToInsert  = string.Empty;
     m_addInSettings = settings;
 }
Exemplo n.º 14
0
        private string RenameMethod(CodeElement item)
        {
            //var sb = new StringBuilder();
            if (item.Kind == vsCMElement.vsCMElementFunction)
            {
                //Debug.WriteLine("RenameMethod.FullName:" + item.FullName);
                if (methodWhiteList.Contains(item.Name) || interFaceFunction.Contains(item.Name) || item.Name.Contains(alien))
                {
                    Print("WriteListFunction :" + item.Name);
                    return("");
                }
                try
                {
                    CodeFunction2 code3 = item as CodeFunction2;
                    PrintFunction2Info(code3);
                    if (code3.OverrideKind == vsCMOverrideKind.vsCMOverrideKindOverride ||
                        code3.OverrideKind == vsCMOverrideKind.vsCMOverrideKindNew ||
                        code3.OverrideKind == vsCMOverrideKind.vsCMOverrideKindAbstract ||
                        code3.OverrideKind == vsCMOverrideKind.vsCMOverrideKindVirtual)
                    {
                        PrintDetial("SpecialFunction :" + item.Name);
                        return("");
                    }
                    if (code3.IsShared)
                    {
                        PrintDetial("StaticFunction :" + item.Name);
                        return("");
                    }
                    if (item.Name.Contains(stringGlobal))
                    {
                        PrintDetial("GlobalFunction :" + item.Name);
                        return("");
                    }

                    CodeElement2 code2  = item as CodeElement2;
                    var          one    = nameCounter++;
                    var          alien2 = alien + nameCounter++;
                    var          three  = nameCounter++;
                    PrintDetial("RenameFunction :" + item.Name);
                    var randomOne   = GetRandomName(3, 5, useUpper: true);
                    var randomThree = GetRandomName(3, 5, useUpper: true);
                    var replacement = string.Format("{0}{1}{2}{3}{4}", randomOne, one, item.Name.Insert(item.Name.Length / 2, alien2), randomThree, three);
                    code2.RenameSymbol(replacement);

                    //sb += ("    " + code.Name + " " + code.IsCodeType + " " + code.Kind + "\n");
                }
                catch (Exception ex)
                {
                    //except += " error: " + ex.Message + "\n" + item.Name;
                    CodeFunction2 code3 = item as CodeFunction2;
                    PrintFunction2Info(code3);
                }
            }
            else
            {
            }
            return("");
        }
Exemplo n.º 15
0
 public static void InsertCodeInMethod(CodeFunction2 currentMethod, string codeToInsert)
 {
     TextPoint startPoint = currentMethod.GetStartPoint(vsCMPart.vsCMPartBody);
     // Batch insert the new code so it can be undone in 1 call to undo
     EditPoint pnt = startPoint.CreateEditPoint();
     pnt.Insert(codeToInsert);
     // Format the code (indent it properly)
     pnt.SmartFormat(startPoint);
 }
Exemplo n.º 16
0
        /// <inheritdoc />
        protected override IList <StaticParameterWrapper> GetFunctionParameters(StaticFunctionWrapper function)
        {
            CodeFunction2 functionHandle = (CodeFunction2)function.Handle;

            return(ConvertCodeElementsToArray <CodeParameter2, StaticParameterWrapper>(functionHandle.Parameters, delegate(CodeParameter2 parameter)
            {
                return new StaticParameterWrapper(this, parameter, function);
            }));
        }
Exemplo n.º 17
0
        /// <inheritdoc />
        protected override StaticParameterWrapper GetMethodReturnParameter(StaticMethodWrapper method)
        {
            CodeFunction2 methodHandle = (CodeFunction2)method.Handle;

            // TODO: This won't provide access to any parameter attributes.  How should we retrieve them?
            CodeTypeRef type = methodHandle.Type;

            return(type != null ? new StaticParameterWrapper(this, type, method) : null);
        }
Exemplo n.º 18
0
        public static void InsertCodeInMethod(CodeFunction2 currentMethod, string codeToInsert)
        {
            TextPoint startPoint = currentMethod.GetStartPoint(vsCMPart.vsCMPartBody);
            // Batch insert the new code so it can be undone in 1 call to undo
            EditPoint pnt = startPoint.CreateEditPoint();

            pnt.Insert(codeToInsert);
            // Format the code (indent it properly)
            pnt.SmartFormat(startPoint);
        }
Exemplo n.º 19
0
        /// <inheritdoc />
        protected override CallingConventions GetFunctionCallingConvention(StaticFunctionWrapper function)
        {
            CodeFunction2 functionHandle = (CodeFunction2)function.Handle;

            // FIXME: No way to determine VarArgs convention.
            CallingConventions flags = CallingConventions.Standard;

            ReflectorFlagsUtils.AddFlagIfTrue(ref flags, CallingConventions.HasThis, !functionHandle.IsShared);
            return(flags);
        }
Exemplo n.º 20
0
        void CreateMethod(DomRegion region)
        {
            AddCodeFile("class.cs", "class c {}");
            codeModelContext.DocumentLoader = documentLoader;

            IMethod method = MockRepository.GenerateStub <IMethod>();

            method.Stub(m => m.Region).Return(region);

            codeFunction = new CodeFunction2(codeModelContext, method);
        }
Exemplo n.º 21
0
        public void Members_ClassHasOneMethod_ReturnsOneMethod()
        {
            CreateProjectContent();
            CreatePublicClass("MyClass");
            AddMethodToClass("MyClass.MyMethod");

            global::EnvDTE.CodeElements codeElements = codeClass.Members;
            CodeFunction2 codeFunction = codeElements.FirstCodeFunction2OrDefault();

            Assert.AreEqual(1, codeElements.Count);
            Assert.AreEqual("MyMethod", codeFunction.Name);
        }
Exemplo n.º 22
0
            private void CreatePageMethod(CodeClass2 classModel, string name)
            {
                ParameterInfo[] parameters = _signature.GetParameters();
                CodeFunction2   method     = classModel.AddFunction(name, vsCMFunction.vsCMFunctionFunction, CreateCodeTypeRefName(_signature.ReturnType), -1, vsCMAccess.vsCMAccessPublic, null);

                method.IsShared = true;
                foreach (ParameterInfo param in parameters)
                {
                    method.AddParameter(param.Name, CreateCodeTypeRefName(param.ParameterType), -1);
                }
                method.AddAttribute(typeof(WebMethodAttribute).FullName, "", -1);
                method.AddAttribute(typeof(ScriptMethodAttribute).FullName, "", -1);
            }
        /// <summary>
        /// Determines if the specified code function is an explicit interface implementation.
        /// </summary>
        /// <param name="codeFunction">The code function.</param>
        /// <returns>True if an explicit interface implementation, otherwise false.</returns>
        public static bool IsExplicitInterfaceImplementation(CodeFunction2 codeFunction)
        {
            // In VS2013 and earlier, the name was reported including the interface name.
            if (codeFunction.Name.Contains("."))
            {
                return true;
            }

            var declaration = CodeElementHelper.GetMethodDeclaration(codeFunction);
            var matchString = @"\." + codeFunction.Name;

            return Regex.IsMatch(declaration, matchString);
        }
Exemplo n.º 24
0
        void CreateFunction(string code)
        {
            AddCodeFile("class.cs", code);

            IMethod method = assemblyModel
                             .TopLevelTypeDefinitions
                             .First()
                             .Members
                             .First()
                             .Resolve() as IMethod;

            codeFunction = new CodeFunction2(codeModelContext, method);
        }
Exemplo n.º 25
0
        void CreateCodeTypeRef2(string code)
        {
            AddCodeFile("class.cs", code);
            IMethod method = assemblyModel
                             .TopLevelTypeDefinitions
                             .First()
                             .Members
                             .First()
                             .Resolve() as IMethod;

            parent  = new CodeFunction2(codeModelContext, method);
            typeRef = parent.Type as CodeTypeRef2;
        }
Exemplo n.º 26
0
        public static void GenerateConstructor(CodeClass2 codeClass, CodeVariable2[] codeVariables, bool generateComments, vsCMAccess accessModifier)
        {
            CodeGenerator codeGenerator = CreateCodeGenerator(codeClass.Language);


            CodeFunction2 codeFunction = null;

            if (codeClass.Language == CodeModelLanguageConstants.vsCMLanguageCSharp)
            {
                codeFunction = (CodeFunction2)codeClass.AddFunction(codeClass.Name, vsCMFunction.vsCMFunctionConstructor, null, -1, accessModifier, null);
            }
            else if (codeClass.Language == CodeModelLanguageConstants.vsCMLanguageVB)
            {
                codeFunction = (CodeFunction2)codeClass.AddFunction("New", vsCMFunction.vsCMFunctionSub, vsCMTypeRef.vsCMTypeRefVoid, -1, accessModifier, null);
            }

            if (generateComments)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<doc>");
                sb.AppendLine("<summary>");
                sb.AppendLine("</summary>");
                foreach (CodeVariable2 codeVariable in codeVariables)
                {
                    sb.AppendLine(String.Format("<param name=\"{0}\"></param>", codeVariable.Name));
                }
                sb.Append("</doc>");

                codeFunction.DocComment = sb.ToString();
            }

            foreach (CodeVariable2 codeVariable in codeVariables)
            {
                codeFunction.AddParameter(codeVariable.Name, codeVariable.Type.AsString, -1);
            }

            EditPoint2 editPoint = (EditPoint2)codeFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

            foreach (CodeVariable2 codeVariable in codeVariables)
            {
                editPoint.Insert(codeGenerator.GenerateAssignStatement(codeVariable.Name, codeVariable.Name));
                editPoint.SmartFormat(editPoint);

                if (Array.IndexOf(codeVariables, codeVariable) < codeVariables.Length - 1)
                {
                    editPoint.InsertNewLine(1);
                }
            }

            editPoint.TryToShow(vsPaneShowHow.vsPaneShowCentered, codeFunction.StartPoint);
        }
Exemplo n.º 27
0
 private void ExpandSubCodeElement(CodeElement codeElement)
 {
     if (codeElement.Kind == vsCMElement.vsCMElementNamespace)
     {
         codeNamespace = (CodeNamespace)codeElement;
     }
     if (codeElement.Kind == vsCMElement.vsCMElementClass)
     {
         codeClass = (CodeClass2)codeElement;
     }
     if (codeElement.Kind == vsCMElement.vsCMElementFunction)
     {
         CodeFunction2 codeFunction = (CodeFunction2)codeElement;
         if (codeFunction.Name == "LoadContent")
         {
             loadContentFunction = codeFunction;
         }
         else if ((!open && codeFunction.Name == "Game1") /*ngikut template*/ || (open && codeFunction.Name == name))
         {
             constructorFunction = codeFunction;
         }
         else if (codeFunction.Name == "Draw")
         {
             drawFunction = codeFunction;
         }
         else if (codeFunction.Name == "Update")
         {
             updateFunction = codeFunction;
         }
     }
     if (codeElement.Kind == vsCMElement.vsCMElementImportStmt)
     {
         lastImportStatement = (CodeImport)codeElement;
         if (((CodeImport)codeElement).Namespace == "XleModel")
         {
             xleModelImportStmtExist = true;
         }
         if (((CodeImport)codeElement).Namespace == "Jitter")
         {
             jitterImportStmtExist = true;
         }
         if (((CodeImport)codeElement).Namespace == "Jitter.Collision")
         {
             jitterCollisionImportStmtExist = true;
         }
     }
     foreach (CodeElement child in codeElement.Children)
     {
         ExpandSubCodeElement(child);
     }
 }
Exemplo n.º 28
0
            private bool PageMethodNeedsRepair(CodeFunction2 method)
            {
                if (method == null || method.Reference == null)
                {
                    return(false);
                }

                ParameterInfo[] parameters = _signature.GetParameters();

                // Tweak the signature so it's appropriate
                if (!method.IsShared)
                {
                    return(true);
                }
                if (method.Access != vsCMAccess.vsCMAccessPublic)
                {
                    return(true);
                }

                int i = 0;

                foreach (object p in method.Parameters)
                {
                    CodeParameter2 parameter = new CodeParameter2(p);
                    if ((parameter.Reference == null) || (string.Compare(parameter.Name, parameters[i++].Name, StringComparison.Ordinal) != 0))
                    {
                        return(true);
                    }
                }

                // Add the necessary attributes
                bool hasWebMethod    = false;
                bool hasScriptMethod = false;

                foreach (object attr in method.Attributes)
                {
                    CodeAttribute2 attribute = new CodeAttribute2(attr);
                    if (attribute.Reference == null)
                    {
                        continue;
                    }
                    hasWebMethod    |= !string.IsNullOrEmpty(attribute.Name) && attribute.Name.Contains("WebMethod");
                    hasScriptMethod |= !string.IsNullOrEmpty(attribute.Name) && attribute.Name.Contains("ScriptMethod");
                    if (hasWebMethod && hasScriptMethod)
                    {
                        break;
                    }
                }
                return(!hasWebMethod || !hasScriptMethod);
            }
        /// <summary>
        /// Determines if the specified code function is an explicit interface implementation.
        /// </summary>
        /// <param name="codeFunction">The code function.</param>
        /// <returns>True if an explicit interface implementation, otherwise false.</returns>
        public static bool IsExplicitInterfaceImplementation(CodeFunction2 codeFunction)
        {
            // In some VS editions, the name may be reported including the interface name.
            if (codeFunction.Name.Contains("."))
            {
                return true;
            }

            // Otherwise, look for the element name with a preceding dot.
            var declaration = CodeElementHelper.GetMethodDeclaration(codeFunction);
            var matchString = @"\." + codeFunction.Name;

            return RegexNullSafe.IsMatch(declaration, matchString);
        }
Exemplo n.º 30
0
            private void RepairPageMethod(CodeFunction2 method)
            {
                if (method == null || method.Reference == null)
                {
                    return;
                }

                // Tweak the signature so it's appropriate
                method.IsShared = true;
                method.Access   = vsCMAccess.vsCMAccessPublic;
                int i = 0;

                ParameterInfo[] parameters = _signature.GetParameters();
                foreach (object p in method.Parameters)
                {
                    CodeParameter2 parameter = new CodeParameter2(p);
                    if (parameter.Reference != null)
                    {
                        parameter.Name = parameters[i++].Name;
                    }
                }

                // Add the necessary attributes
                bool hasWebMethod    = false;
                bool hasScriptMethod = false;

                foreach (object attr in method.Attributes)
                {
                    CodeAttribute2 attribute = new CodeAttribute2(attr);
                    if (attribute.Reference == null)
                    {
                        continue;
                    }

                    hasWebMethod    |= !string.IsNullOrEmpty(attribute.Name) && attribute.Name.Contains("WebMethod");
                    hasScriptMethod |= !string.IsNullOrEmpty(attribute.Name) && attribute.Name.Contains("ScriptMethod");
                    if (hasWebMethod && hasScriptMethod)
                    {
                        break;
                    }
                }
                if (!hasWebMethod)
                {
                    method.AddAttribute(typeof(WebMethodAttribute).FullName, "", -1);
                }
                if (!hasScriptMethod)
                {
                    method.AddAttribute(typeof(ScriptMethodAttribute).FullName, "", -1);
                }
            }
Exemplo n.º 31
0
        /// <summary>
        /// Visit given element.
        /// </summary>
        /// <param name="e">Element to visit.</param>
        public virtual void VisitFunction(CodeFunction2 e)
        {
            if (!RecursiveVisit)
            {
                //stop recursion
                visitUnhandled(e);
                return;
            }

            foreach (CodeElement child in e.Children)
            {
                VisitElement(child);
            }
        }
Exemplo n.º 32
0
        public void Members_ClassHasOneMethod_ReturnsOneMethod()
        {
            CreateClass(
                "public class MyClass {\r\n" +
                "    public void MyMethod() {}\r\n" +
                "}");

            global::EnvDTE.CodeElements codeElements = codeClass.Members;

            CodeFunction2 codeFunction = codeElements.FirstCodeFunction2OrDefault();

            Assert.AreEqual(1, codeElements.Count);
            Assert.AreEqual("MyMethod", codeFunction.Name);
        }
        /// <summary>
        /// Determines if the specified code function is an explicit interface implementation.
        /// </summary>
        /// <param name="codeFunction">The code function.</param>
        /// <returns>True if an explicit interface implementation, otherwise false.</returns>
        public static bool IsExplicitInterfaceImplementation(CodeFunction2 codeFunction)
        {
            // In some VS editions, the name may be reported including the interface name.
            if (codeFunction.Name.Contains("."))
            {
                return(true);
            }

            // Otherwise, look for the element name with a preceding dot.
            var declaration = CodeElementHelper.GetMethodDeclaration(codeFunction);
            var matchString = @"\." + codeFunction.Name;

            return(RegexNullSafe.IsMatch(declaration, matchString));
        }
Exemplo n.º 34
0
        public override void Exec(vsCommandExecOption executeOption, ref object varIn, ref object varOut)
        {
            CodeFunction2 currentMethod = CodeModelUtils.GetCurrentMethod(m_application);

            if (IsCommandAvailable(currentMethod))
            {
                AndroMDA.VS80AddIn.Dialogs.PropertyMapperDialog propertyMapper = new AndroMDA.VS80AddIn.Dialogs.PropertyMapperDialog(currentMethod, m_addInSettings);
                if (propertyMapper.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    // User clicked OK
                    AddInUtils.InsertCodeInMethod(currentMethod, propertyMapper.GeneratedCode);
                    m_application.StatusBar.Text = "Android/VS: Code inserted";
                }
            }
        }
Exemplo n.º 35
0
        private string getSignature(CodeFunction2 f)
        {
            var paramlist = new List <string>();

            foreach (CodeElement p in f.Parameters)
            {
                var cp = p as CodeParameter;
                if (cp != null)
                {
                    paramlist.Add(string.Format("{0}", cp.Name));
                }
            }


            return(getFunctionName(f) + "(" + string.Join(",", paramlist) + ")");
        }
Exemplo n.º 36
0
        /// <inheritdoc />
        protected override IEnumerable <StaticConstructorWrapper> GetTypeConstructors(StaticDeclaredTypeWrapper type)
        {
            CodeType typeHandle = (CodeType)type.Handle;

            foreach (CodeElement candidate in typeHandle.Members)
            {
                if (candidate.Kind == vsCMElement.vsCMElementFunction)
                {
                    CodeFunction2 function = (CodeFunction2)candidate;
                    if (function.FunctionKind == vsCMFunction.vsCMFunctionConstructor)
                    {
                        yield return(new StaticConstructorWrapper(this, function, type));
                    }
                }
            }
        }
Exemplo n.º 37
0
        private bool IsCommandAvailable(CodeFunction2 currentMethod, bool fullCheck)
        {
            if (
                // Ensure we found the current method
                currentMethod != null &&
                // That it has one parameter
                currentMethod.Parameters.Count == 1 &&

                /*
                 * // That it is an override
                 * currentMethod.OverrideKind == vsCMOverrideKind.vsCMOverrideKindOverride &&
                 */
                // That it is function (method)
                currentMethod.FunctionKind == vsCMFunction.vsCMFunctionFunction &&
                // That it exists inside a project
                currentMethod.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject &&
                // It's return type is not void
                currentMethod.Type.AsString != "void" &&
                // The return type does not equal the parameter type
                ((CodeParameter2)currentMethod.Parameters.Item(1)).Type.AsFullName != currentMethod.Type.AsFullName &&
                // And it's name is either ends with ToEntity or begins with To
                ((currentMethod.Name.EndsWith("ToEntity") || currentMethod.Name.StartsWith("To")) ||
                 !m_addInSettings.OnlyEnableCodeGenOnConversionMethods)
                )
            {
                if (!fullCheck)
                {
                    return(true);
                }

                CodeParameter2 param           = currentMethod.Parameters.Item(1) as CodeParameter2;
                CodeClass2     containingClass = currentMethod.Parent as CodeClass2;
                if (// Ensure we found the parameter and the parent class
                    param != null &&
                    containingClass != null &&

                    (!m_addInSettings.OnlyEnableCodeGenInDaoImpl ||
                     // Ensure we are in a DaoImpl class
                     containingClass.Name.Contains("DaoImpl"))

                    )
                {
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 38
0
        private bool IsCommandAvailable(CodeFunction2 currentMethod, bool fullCheck)
        {
            if (
                // Ensure we found the current method
                currentMethod != null &&
                // That it has one parameter
                currentMethod.Parameters.Count == 1 &&
                /*
                // That it is an override
                currentMethod.OverrideKind == vsCMOverrideKind.vsCMOverrideKindOverride &&
                */
                // That it is function (method)
                currentMethod.FunctionKind == vsCMFunction.vsCMFunctionFunction &&
                // That it exists inside a project
                currentMethod.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject &&
                // It's return type is not void
                currentMethod.Type.AsString != "void" &&
                // The return type does not equal the parameter type
                ((CodeParameter2)currentMethod.Parameters.Item(1)).Type.AsFullName != currentMethod.Type.AsFullName &&
                // And it's name is either ends with ToEntity or begins with To
                ((currentMethod.Name.EndsWith("ToEntity") || currentMethod.Name.StartsWith("To"))
                  || !m_addInSettings.OnlyEnableCodeGenOnConversionMethods)
                )
            {
                if (!fullCheck) return true;

                CodeParameter2 param = currentMethod.Parameters.Item(1) as CodeParameter2;
                CodeClass2 containingClass = currentMethod.Parent as CodeClass2;
                if (// Ensure we found the parameter and the parent class
                    param != null &&
                    containingClass != null &&

                    (!m_addInSettings.OnlyEnableCodeGenInDaoImpl ||
                    // Ensure we are in a DaoImpl class
                    containingClass.Name.Contains("DaoImpl"))

                    )
                {
                    return true;
                }

            }
            return false;
        }
        /// <summary>
        /// Performs any preparatory tasks that have to be done after a new unit test project has been created.
        /// </summary>
        /// <param name="unitTestProject">The <see cref="Project"/> of the unit test project that has just been created.</param>
        /// <param name="sourceMethod">The <see cref="CodeFunction2"/> of the source method that is to be unit tested.</param>
        protected override void OnUnitTestProjectCreated(Project unitTestProject, CodeFunction2 sourceMethod)
        {
            if (unitTestProject == null)
            {
                throw new ArgumentNullException(nameof(unitTestProject));
            }

            TraceLogger.LogInfo("NUnitSolutionManager.OnUnitTestProjectCreated: Adding reference to NUnit assemblies through nuget.");

            base.OnUnitTestProjectCreated(unitTestProject, sourceMethod);
            this.EnsureNuGetReference(unitTestProject, "NUnit", null);

            var vsp = unitTestProject.Object as VSProject2;
            var reference = vsp?.References.Find(GlobalConstants.MSTestAssemblyName);
            if (reference != null)
            {
                TraceLogger.LogInfo("NUnitSolutionManager.OnUnitTestProjectCreated: Removing reference to {0}", reference.Name);
                reference.Remove();
            }
        }
Exemplo n.º 40
0
 protected virtual bool AcceptConstructor(CodeFunction2 method)
 {
     return method.Name == this.Name
         && method.FunctionKind == vsCMFunction.vsCMFunctionConstructor;
 }
 internal NotifyPropertyChanged_GenAttribute(CodeFunction2 f)
     : base(f)
 {
     Init();
 }
Exemplo n.º 42
0
        /// <summary>
        /// Returns the parameters list from a function.
        /// </summary>
        /// <param name="element">A CodeFunction2 object.</param>
        /// <returns>A string with function parameters.</returns>
        private static string ExtractMethodParameters(CodeFunction2 element)
        {
            // Get the string holding the stub definition of this function.
            string temp = element.get_Prototype((int)vsCMPrototype.vsCMPrototypeParamTypes);
            int len = temp.Length;
            int index = temp.LastIndexOf('(');
            string str = null;
            try
            {
                str = temp.Substring(index, len - index);
            }
            catch (ArgumentNullException)
            {
                str = null;
            }

            return str;
        }
Exemplo n.º 43
0
 private CodeDomMethodMetadata(CodeFunction2 codeFunction, CodeDomFileMetadata file)
 {
     this.codeFunction = codeFunction;
     this.file = file;
 }
 internal GeneratorAttribute(CodeFunction2 f)
 {
     ParentFunction = f;
     Init(f.AsCodeElement());
 }
 public CodeConstructorInfo(BaseInfo parent, CodeFunction2 method)
     : base(parent, method)
 {
 }
 /// <summary>
 /// Determines if the specified code function is an explicit interface implementation.
 /// </summary>
 /// <param name="codeFunction">The code function.</param>
 /// <returns>True if an explicit interface implementation, otherwise false.</returns>
 public static bool IsExplicitInterfaceImplementation(CodeFunction2 codeFunction)
 {
     return codeFunction != null &&
            codeFunction.Name.Contains(".");
 }
Exemplo n.º 47
0
 protected virtual bool AcceptDestructor(CodeFunction2 method)
 {
     return method.FunctionKind == vsCMFunction.vsCMFunctionDestructor;
 }
Exemplo n.º 48
0
 internal AttributeProcessor(CodeFunction2 f)
 {
     ParentFunction = f;
     Init(f.AsCodeElement());
 }
Exemplo n.º 49
0
        public void SyncWithCode(bool forceRun = false)
        {
            var doc = ApplicationObject.ActiveDocument;
            if (doc == null) return;

            //
            // Fetch the selected bit of code
            //
            var sel = (TextSelection)doc.Selection;
            var p = sel.ActivePoint;
            var funcElm = (CodeFunction2)p.CodeElement[vsCMElement.vsCMElementFunction];

            if (funcElm == null) {
                var propElm = (CodeProperty2)p.CodeElement[vsCMElement.vsCMElementProperty];
                if (propElm != null) {
                    var getter = propElm.Getter;
                    var setter = propElm.Setter;
                    if (getter != null &&
                        p.GreaterThan (getter.StartPoint) &&
                        p.LessThan (getter.EndPoint)) {
                        funcElm = (CodeFunction2)getter;
                    }
                    else if (setter != null &&
                        p.GreaterThan (setter.StartPoint) &&
                        p.LessThan (setter.EndPoint)) {
                        funcElm = (CodeFunction2)setter;
                    }
                }
            }

            //
            // Make sure it's .NET (C# and VB)
            //
            if (funcElm != null) {
                if (funcElm.Language != CodeModelLanguageConstants.vsCMLanguageCSharp &&
                    funcElm.Language != CodeModelLanguageConstants.vsCMLanguageVB) {
                    funcElm = null;
                }
            }

            if (funcElm == null) return;

            //
            // Handle it
            //
            var newFunc = false;

            if (_funcElm == null || GetMemberName (funcElm) != _tests.Member) {
                _funcElm = funcElm;

                SetMember ();

                DisplayFunction ();

                newFunc = true;
            }

            if (forceRun || newFunc) {
                RunAllRows ();
            }
        }
Exemplo n.º 50
0
 public CodeMethodNodeFactory(CodeFunction2 element) : base(element as CodeElement)
 {
     _element = element;
 }
Exemplo n.º 51
0
 internal ShellCodeMethod(CodeFunction2 method) : base(method as CodeElement2)
 {
     _method = method;
 }
Exemplo n.º 52
0
 /// <summary>
 /// 
 /// </summary>
 protected virtual bool AcceptMethod(CodeFunction2 method)
 {
     return method.FunctionKind == vsCMFunction.vsCMFunctionFunction;
 }
 /// <summary>
 /// 
 /// </summary>
 public virtual CodeFunctionInfo CreateMethod(BaseInfo parent, CodeFunction2 item)
 {
     return new CodeFunctionInfo(parent, item);
 }
Exemplo n.º 54
0
        private Function ParseFunction(CodeFunction2 codeFunction, string currentFile)
        {
            var function = new Function {Name = codeFunction.Name, Type = codeFunction.Type.AsString, Access = codeFunction.Access.Convert(), FileName = currentFile};
            WriteLine("ParseFunction" + " " + function.Name + " " + function.Type);
            foreach (CodeAttribute2 codeElement in codeFunction.Attributes)
            {
                ParseAttribute(codeElement, function, currentFile);
            }


            foreach (var codeParameter in codeFunction.Parameters.Cast<CodeParameter2>())
            {
                var parmeter = ParseParameter(codeParameter);
                function.Parameters.Add(parmeter);
            }
            return function;
        }
 /// <summary>
 /// 
 /// </summary>
 public virtual CodeConstructorInfo CreateConstructor(BaseInfo parent, CodeFunction2 item)
 {
     return new CodeConstructorInfo(parent, item);
 }
 private bool IsCommandAvailable(CodeFunction2 currentMethod)
 {
     return IsCommandAvailable(currentMethod, true);
 }
Exemplo n.º 57
0
 public static ITypeMetadata FromCodeElement(CodeFunction2 codeVariable, CodeDomFileMetadata file)
 {
     return GetType(codeVariable, file);
 }