Example #1
0
        public bool appParameters(ref CodeFunction cf, SqlParameterCollection spc)
        {
            CodeParameter cp = null;
            string        pname;

            foreach (SqlParameter p in spc)
            {
                pname = p.ParameterName.Remove(0, 1);
                if (p.Direction != System.Data.ParameterDirection.ReturnValue)
                {
                    if (p.Direction == ParameterDirection.Output)
                    {
                        cp = cf.AddParameter(pname, "out " + HandleTypes(p.SqlDbType), -1);
                    }
                    else
                    {
                        if (p.Direction == ParameterDirection.InputOutput)
                        {
                            cp = cf.AddParameter(pname, "ref " + HandleTypes(p.SqlDbType), -1);
                        }
                        else
                        {
                            cp = cf.AddParameter(pname, HandleTypes(p.SqlDbType), -1);
                        }
                    }
                }
            }
            return(true);
        }
Example #2
0
        /// <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;
        }
Example #3
0
        public bool ImpInterface(string intType, Project intPrj, CodeInterface intObj, ref CodeClass intCla)
        {
            Project prjObj = null;

            if (!prjCreate(intType, ref prjObj))
            {
                return(false);
            }
            // add the necessary references
            VSProject vsPrj = (VSProject)prjObj.Object;
            Reference vsref = vsPrj.References.AddProject(intPrj);



            string claName;

            claName = intObj.Name;
            CodeInterface[] Ints = new CodeInterface[1];
            Ints[0] = intObj;

            prjObj.ProjectItems.AddFromTemplate("C:\\Program Files\\Microsoft Visual Studio .NET\\VC#\\CSharpProjectItems\\NewCSharpFile.cs", claName + ".cs");


            ProjectItem   pi = prjObj.ProjectItems.Item(claName + ".cs");
            CodeNamespace cn = pi.FileCodeModel.AddNamespace(intType, 0);
            TextPoint     tp = cn.GetStartPoint(EnvDTE.vsCMPart.vsCMPartHeader);
            EditPoint     ep = tp.CreateEditPoint();

            ep.StartOfDocument();
            ep.Insert("using " + intObj.Namespace.FullName + ";\n");
            CodeClass cc = cn.AddClass(intObj.Name, 0, null, null, EnvDTE.vsCMAccess.vsCMAccessPublic);

            tp = cc.GetStartPoint(EnvDTE.vsCMPart.vsCMPartName);
            ep = tp.CreateEditPoint();
            ep.EndOfLine();
            ep.Insert(" : " + intObj.FullName);
            cc.Comment = intObj.Comment;
            foreach (CodeElement ce in intObj.Members)
            {
                if (ce.Kind == EnvDTE.vsCMElement.vsCMElementFunction)
                {
                    CodeFunction  cf   = (CodeFunction)ce;
                    CodeFunction  cf1  = cc.AddFunction(cf.Name, cf.FunctionKind, cf.Type, 0, cf.Access, 0);
                    CodeParameter cep1 = null;
                    foreach (CodeElement cep in cf.Parameters)
                    {
                        CodeParameter cp = (CodeParameter)cep;
                        cep1 = cf1.AddParameter(cp.Name, cp.Type, -1);
                    }
                }
            }


            intCla = cc;
            return(true);
        }
        private static void AddSpecialParam(CodeFunction implementationFunction, string parameter)
        {
            object paramType = vsCMTypeRef.vsCMTypeRefString;

            if (parameter.StartsWith("table:"))
            {
                paramType = typeof(Table).Name;
            }
            var paramValue         = GetParamName(parameter.Split(':').Last());
            var variableIdentifier = GenerateNewParameterIdentifier(implementationFunction, paramValue);

            implementationFunction.AddParameter(variableIdentifier, paramType);
        }
Example #5
0
        /// <summary>
        /// Implements the interface.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="constructor">The constructor.</param>
        /// <param name="variable">The variable.</param>
        public static void ImplementInterface(
            this CodeClass instance,
            CodeFunction constructor,
            string variable)
        {
            TraceService.WriteLine("CodeClassExtensions::ImplementInterface file=" + variable);

            //// now add in the interfaces!

            //// split the variable string
            string[] parts = variable.Split(' ');

            constructor.AddParameter(parts[1], parts[0]);

            //// we need to add the variable.
            //// variable could already exist!
            try
            {
                instance.ImplementVariable(parts[1], parts[0], true);
            }
            catch (Exception)
            {
                TraceService.WriteError("variable already exists " + parts[1]);
            }

            //// now do the wiring up of the interface and variable!
            EditPoint editPoint = constructor.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

            string code = string.Format("this.{0} = {1};", parts[1], parts[1]);

            editPoint.InsertCodeLine(code);

            //// now update the constructor document comments.
            string paramComment   = string.Format("<param name=\"{0}\">The {0}.</param>{1}", parts[1], Environment.NewLine);
            string currentComment = constructor.DocComment;

            int index = currentComment.LastIndexOf("</summary>", StringComparison.Ordinal);

            StringBuilder sb = new StringBuilder();

            if (index != -1)
            {
                sb.Append(currentComment.Substring(0, index + 10));
                sb.Append(paramComment);
                sb.Append(currentComment.Substring(index + 10));

                TraceService.WriteLine("comment added=" + paramComment);
            }

            constructor.DocComment = sb.ToString();
        }
        public virtual void UiBtnCommandAction(Object param)
        {
            if (SelectedCodeElement == null)
            {
                UiCommandButtonClicked.DoNotify(this);
            }
            else
            {
                CodeClass cc = SelectedCodeElement.CodeElementRef as CodeClass;
                if (cc == null)
                {
                    return;
                }
                CodeFunction cf = cc.AddMethodHelper("OnModelCreating", vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, vsCMAccess.vsCMAccessDefault);
                if (cf == null)
                {
                    return;
                }
                string modelBuilderType = "System.Data.Entity.DbModelBuilder";
                if (cc.IsDerivedFrom["Microsoft.EntityFrameworkCore.DbContext"])
                {
                    modelBuilderType = "Microsoft.EntityFrameworkCore.ModelBuilder";
                }
                cf.AddParameter("modelBuilder", modelBuilderType, null);
                EditPoint editPoint = cf.StartPoint.CreateEditPoint();
                editPoint.Insert("protected override ");
                if (cc.ProjectItem != null)
                {
                    if (cc.ProjectItem.IsDirty)
                    {
                        cc.ProjectItem.Save();
                    }
                }
                DoAnaliseDbContext();

                //foreach(CodeElement ce in cf.Children)
                //{
                //    string nm = ce.FullName;
                //    vsCMElement kind = ce.Kind;
                //    if (nm == "") nm = null;
                //}

                //DoAnaliseDbContext();
                //editPoint = cf.EndPoint.CreateEditPoint();
                //editPoint.CharLeft(1);
                //editPoint.Insert("\n\r int i = 0; \n\r");
                //editPoint.SmartFormat(cf.StartPoint);
            }
        }
Example #7
0
        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;
        }
Example #8
0
 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);
     }
 }
Example #9
0
        /// <summary>
        /// 重构方法
        /// </summary>
        /// <param name="replacedFunction"></param>
        /// <param name="newFunction"></param>
        private void RefactorMethod(CodeFunction replacedFunction, CodeFunction newFunction)
        {
            //清除方法参数
            while (replacedFunction.Parameters.Count > 0)
            {
                replacedFunction.RemoveParameter(replacedFunction.Parameters.Count);
            }

            //清除方法属性
            while (replacedFunction.Attributes.Count > 0)
            {
                ((CodeAttribute)replacedFunction.Attributes.Item(replacedFunction.Attributes.Count)).Delete();
            }

            //添加参数
            for (int i = 1; i <= newFunction.Parameters.Count; i++)
            {
                CodeParameter2 parameter      = newFunction.Parameters.Item(i) as CodeParameter2;
                CodeParameter2 cloneParameter = replacedFunction.AddParameter(parameter.FullName, parameter.Type.AsFullName, i) as CodeParameter2;
                cloneParameter.DefaultValue  = parameter.DefaultValue;
                cloneParameter.ParameterKind = parameter.ParameterKind;
            }

            //添加属性
            for (int i = 1; i <= newFunction.Attributes.Count; i++)
            {
                CodeAttribute2 attribute = newFunction.Attributes.Item(i) as CodeAttribute2;
                replacedFunction.AddAttribute(attribute.Name, attribute.Value, i);
            }

            //方法名
            replacedFunction.Name = newFunction.Name;
            //方法注释
            replacedFunction.Comment = newFunction.Comment;
            //方法说明
            replacedFunction.DocComment = newFunction.DocComment;
            //静态修饰
            replacedFunction.IsShared = newFunction.IsShared;
            //抽象修饰
            replacedFunction.MustImplement = newFunction.MustImplement;
            //重载修饰
            replacedFunction.CanOverride = newFunction.CanOverride;
        }
Example #10
0
        public void Invoke(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            try
            {
                CodeFunction addedFunction = _interface.AddFunction(_srcFunction.Name, vsCMFunction.vsCMFunctionFunction, _srcFunction.Type, -1);

                var parameters = _srcFunction.Parameters.Cast <CodeParameter>().Reverse().ToList();

                foreach (var parameter in parameters)
                {
                    addedFunction.AddParameter(parameter.Name, parameter.Type);
                }
            }
            catch { }
        }
Example #11
0
        public CodeFunction CreateEventHandler(string codeBehindFile, string className, string objectTypeName, string eventName, string eventHandlerName)
        {
            var codeClass = FindClass(className);

            if (codeClass != null)
            {
                if (!string.IsNullOrEmpty(eventHandlerName))
                {
                    string   str;
                    string[] strArray;
                    string[] strArray2;

                    Type objectType = ResolveType(objectTypeName);
                    GetEventHandlerSignature(objectType, eventName, out str, out strArray2, out strArray);

                    if (string.IsNullOrEmpty(str))
                    {
                        str = "System.Void";
                    }

                    vsCMFunction vsCMFunctionFunction = vsCMFunction.vsCMFunctionFunction;
                    if (str == "System.Void")
                    {
                        vsCMFunctionFunction = vsCMFunction.vsCMFunctionSub;
                    }

                    CodeFunction codeFunction = codeClass.AddFunction(eventHandlerName, vsCMFunctionFunction, str, -1, vsCMAccess.vsCMAccessProtected, codeBehindFile);
                    if ((codeFunction != null) && (strArray2 != null))
                    {
                        for (int i = 0; i < strArray2.Length; i++)
                        {
                            codeFunction.AddParameter("_" + strArray[i], strArray2[i], -1);
                        }
                    }

                    return(codeFunction);
                }
            }

            return(null);
        }
        // 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; //");
        }
Example #13
0
        /// <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);
            }
        }
        /// <summary>
        /// Implements the interface.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="constructor">The constructor.</param>
        /// <param name="variable">The variable.</param>
        public static void ImplementInterface(
            this CodeClass instance, 
            CodeFunction constructor, 
            string variable)
        {
            TraceService.WriteLine("CodeClassExtensions::ImplementInterface file=" + variable);

            //// now add in the interfaces!

            //// split the variable string
            string[] parts = variable.Split(' ');

            constructor.AddParameter(parts[1], parts[0]);

            //// we need to add the variable.
            //// variable could already exist!
            try
            {
                instance.ImplementVariable(parts[1], parts[0], true);
            }
            catch (Exception)
            {
                TraceService.WriteError("variable already exists " + parts[1]);
            }

            //// now do the wiring up of the interface and variable!
            EditPoint editPoint = constructor.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

            string code = string.Format("this.{0} = {1};", parts[1], parts[1]);
            editPoint.InsertCodeLine(code);

            //// now update the constructor document comments.
            string paramComment = string.Format("<param name=\"{0}\">The {0}.</param>{1}", parts[1], Environment.NewLine);
            string currentComment = constructor.DocComment;

            int index = currentComment.LastIndexOf("</summary>", StringComparison.Ordinal);

            StringBuilder sb = new StringBuilder();

            if (index != -1)
            {
                sb.Append(currentComment.Substring(0, index + 10));
                sb.Append(paramComment);
                sb.Append(currentComment.Substring(index + 10));

                TraceService.WriteLine("comment added=" + paramComment);
            }

            constructor.DocComment = sb.ToString();
        }
Example #15
0
        /// <summary>
        /// 重构方法
        /// </summary>
        /// <param name="replacedFunction"></param>
        /// <param name="newFunction"></param>
        private void RefactorMethod(CodeFunction replacedFunction, CodeFunction newFunction)
        {
            //清除方法参数
            while (replacedFunction.Parameters.Count > 0)
            {
                replacedFunction.RemoveParameter(replacedFunction.Parameters.Count);
            }

            //清除方法属性
            while (replacedFunction.Attributes.Count > 0)
            {
                ((CodeAttribute)replacedFunction.Attributes.Item(replacedFunction.Attributes.Count)).Delete();
            }

            //添加参数
            for (int i = 1; i <= newFunction.Parameters.Count; i++)
            {
                CodeParameter2 parameter = newFunction.Parameters.Item(i) as CodeParameter2;
                CodeParameter2 cloneParameter = replacedFunction.AddParameter(parameter.FullName, parameter.Type.AsFullName, i) as CodeParameter2;
                cloneParameter.DefaultValue = parameter.DefaultValue;
                cloneParameter.ParameterKind = parameter.ParameterKind;
            }

            //添加属性
            for (int i = 1; i <= newFunction.Attributes.Count; i++)
            {
                CodeAttribute2 attribute = newFunction.Attributes.Item(i) as CodeAttribute2;
                replacedFunction.AddAttribute(attribute.Name, attribute.Value, i);
            }

            //方法名
            replacedFunction.Name = newFunction.Name;
            //方法注释
            replacedFunction.Comment = newFunction.Comment;
            //方法说明
            replacedFunction.DocComment = newFunction.DocComment;
            //静态修饰
            replacedFunction.IsShared = newFunction.IsShared;
            //抽象修饰
            replacedFunction.MustImplement = newFunction.MustImplement;
            //重载修饰
            replacedFunction.CanOverride = newFunction.CanOverride;
        }
        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);
        }
Example #17
0
        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);
        }
Example #18
0
        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);
        }
Example #19
0
        /// <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);
        }
Example #20
0
        private bool AddMethodCall(CodeElements codeElements, string className, string targetMethodName, string methodCall)
        {
            CodeClass    featureReceiverClass = GetClassByName(codeElements, className);
            CodeFunction function             = null;
            bool         result = false;

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

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

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

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

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

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

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

                    result = true;
                }
            }
            else
            {
                throw new Exception("Class " + className + " not found");
            }
            return(result);
        }
Example #21
0
 public bool appDTParameter(ref CodeFunction cf)
 {
     cf.AddParameter("ReturnedDataTable", "ref System.Data.DataTable", -1);
     return(true);
 }