Пример #1
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);
        }
Пример #2
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            DTE2 dte = GetDTE();

            try
            {
                Document activeDoc = dte.ActiveDocument;

                if (activeDoc != null && activeDoc.ProjectItem != null && activeDoc.ProjectItem.ContainingProject != null)
                {
                    TextDocument objTextDoc      = activeDoc.Object("TextDocument") as TextDocument;
                    EditPoint2   startPoint      = objTextDoc.StartPoint.CreateEditPoint() as EditPoint2;
                    EditPoint2   endPoint        = objTextDoc.EndPoint.CreateEditPoint() as EditPoint2;
                    string       wholeWindowText = startPoint.GetText(endPoint);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"^\s+${2,}", string.Empty, RegexOptions.Multiline);

                    wholeWindowText = Regex.Replace(wholeWindowText, @"\r\n\n\s*\}\r\n\s*$", "\r\n}\r\n", RegexOptions.Multiline);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"\r\n\n\s*\}", "\r\n}", RegexOptions.Multiline);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"\{\r\n\n", "{\r\n", RegexOptions.Multiline);
                    startPoint.ReplaceText(endPoint, wholeWindowText, 3);
                    startPoint.SmartFormat(endPoint);

                    dte.ActiveDocument.Activate();
                    dte.ExecuteCommand("Edit.FormatDocument");
                    dte.ExecuteCommand("Edit.SortUsings");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
        }
Пример #3
0
        private void AddMethodToClass(CodeElements codeElements, string className, string methodCode)
        {
            CodeClass featureReceiverClass = GetClassByName(codeElements, className);

            //add the method to the class
            if (featureReceiverClass != null)
            {
                EditPoint2 editPoint = (EditPoint2)featureReceiverClass.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

                StringReader reader = new StringReader(methodCode);
                string       line   = reader.ReadLine();
                while (line != null)
                {
                    editPoint.InsertNewLine(1);
                    editPoint.Indent(null, 2);
                    editPoint.Insert(line);
                    line = reader.ReadLine();
                }

                editPoint.InsertNewLine(1);

                Helpers.LogMessage(featureReceiverClass.DTE, featureReceiverClass.DTE, Helpers.GetFullPathOfProjectItem(featureReceiverClass.ProjectItem) + ": Added new method");
            }
            else
            {
                throw new Exception("Class " + className + " not found");
            }
        }
Пример #4
0
        private bool Find(EditPoint2 editPoint,
                          string text)
        {
            EditPoint  endPoint = null;
            TextRanges tags     = null;

            return(editPoint.FindPattern(text, (int)vsFindOptions.vsFindOptionsMatchInHiddenText,
                                         ref endPoint, ref tags));
        }
Пример #5
0
        public static void Run(DTE dte, VsError selectedError)
        {
            selectedError.Navigate();
            EditPoint2 ep = ErrorUtilities.GetEditPoint(dte);

            ep.LineDown();
            ep.StartOfLine();
            ep.InsertNewLine();
        }
Пример #6
0
        /// <summary>
        /// Create the text for a property using the property name and the accessors
        /// </summary>
        /// <param name="elem">Property we are updating</param>
        /// <param name="ep">The point we are inserting the text</param>
        private static void ProcessPropertyUpdate(CodeProperty elem, EditPoint2 ep)
        {
            string descriptionText = string.Empty;

            if (elem.Getter != null)
            {
                switch (elem.Getter.Access)
                {
                case vsCMAccess.vsCMAccessPrivate:
                    break;

                default:
                    descriptionText = "Gets";
                    break;
                }
            }

            if (elem.Setter != null)
            {
                switch (elem.Setter.Access)
                {
                case vsCMAccess.vsCMAccessPrivate:
                    break;

                default:
                    if (descriptionText.Length > 0)
                    {
                        descriptionText += " or sets";
                    }
                    else
                    {
                        descriptionText = "Sets";
                    }

                    break;
                }
            }

            descriptionText += " " + elem.Name;
            TextPoint tp = elem.GetStartPoint();

            ep.MoveToPoint(tp);
            string spacer = string.Empty;

            for (int i = 0; i < tp.LineCharOffset - 1; i++)
            {
                spacer += " ";
            }

            ep.LineUp();
            ep.Insert(Environment.NewLine);
            ep.Insert(spacer + "/// <summary>");
            ep.Insert(Environment.NewLine + spacer + string.Format("/// {0}", descriptionText));
            ep.Insert(Environment.NewLine + spacer + "/// </summary>");
            ep.Insert(spacer);
        }
Пример #7
0
        public static void GeneratePropertyFromVariable(CodeVariable2 variable, bool generateGetter, bool generateSetter, bool generateComments)
        {
            CodeClass2    codeClass     = variable.Collection.Parent as CodeClass2;
            CodeGenerator codeGenerator = CreateCodeGenerator(codeClass.Language);

            string propertyName = ConvertVariableNameToPropertyName(variable.Name);

            if (!ContainsMember(codeClass, propertyName))
            {
                string getterName = String.Empty;
                string setterName = String.Empty;

                if (generateGetter)
                {
                    getterName = propertyName;
                }
                if (generateSetter)
                {
                    setterName = propertyName;
                }

                CodeProperty property = (CodeProperty)codeClass.AddProperty(getterName, setterName, variable.Type, -1, vsCMAccess.vsCMAccessPublic, null);
                if (generateComments)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("<doc>");
                    sb.AppendLine("<summary>");
                    sb.AppendLine();
                    sb.AppendLine("</summary>");
                    sb.Append("</doc>");

                    property.DocComment = sb.ToString();
                }

                if (generateGetter)
                {
                    EditPoint2 editPoint = (EditPoint2)property.Getter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                    editPoint.EndOfLine();
                    int position = editPoint.LineCharOffset;
                    editPoint.StartOfLine();
                    editPoint.Delete(position);
                    editPoint.Insert(codeGenerator.GenerateReturnStatement(variable.Name));
                    editPoint.SmartFormat(editPoint);
                }

                if (generateSetter)
                {
                    EditPoint2 editPoint = (EditPoint2)property.Setter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                    editPoint.Insert(codeGenerator.GenerateAssignStatement(variable.Name, "value"));
                    editPoint.SmartFormat(editPoint);
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Fix error SA1600
        /// </summary>
        /// <param name="dte">Current design environment</param>
        /// <param name="selectedError">Error selected by the user to fix.</param>
        public static void Run(DTE dte, VsError selectedError)
        {
            EditPoint2 ep = ErrorUtilities.GetEditPoint(dte);

            selectedError.Navigate();
            var selection       = (TextSelection)dte.ActiveDocument.Selection;
            var propertyElement = (CodeProperty)selection.ActivePoint.CodeElement[vsCMElement.vsCMElementProperty];

            if (propertyElement != null)
            {
                ProcessPropertyUpdate(propertyElement, ep);
            }
        }
Пример #9
0
        public static void Run(DTE dte, VsError error)
        {
            error.Navigate();
            EditPoint2 ep = ErrorUtilities.GetEditPoint(dte);

            ep.StartOfLine();
            string variableName  = error.Description.Split(" ".ToCharArray())[7];
            string replaceString = ep.GetLines(ep.Line, ep.Line + 1);

            replaceString = Regex.Replace(replaceString, string.Format(@"(\s|\(|\!)({0})(\W)", variableName), "$1this.$2$3",
                                          RegexOptions.None);
            ep.ReplaceText(ep.LineLength, replaceString, (int )vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
        }
Пример #10
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);
        }
Пример #11
0
        public static void Run(DTE dte, VsError selectedError)
        {
            selectedError.Navigate();
            EditPoint2 ep = ErrorUtilities.GetEditPoint(dte);

            ep.StartOfLine();
            string testString = ep.GetLines(ep.Line, ep.Line + 1);

            if (Regex.Match(testString, @"\t").Success)
            {
                testString = Regex.Replace(testString, @"\t", @"    ");
                ep.ReplaceText(ep.LineLength, testString, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
            }
        }
Пример #12
0
        public static void RegExUpdate(string findPattern, string replacePattern, VsError selectedError, DTE dte)
        {
            selectedError.Navigate();
            EditPoint2 ep = GetEditPoint(dte);

            ep.StartOfLine();
            string textToUpdate = ep.GetLines(ep.Line, ep.Line + 1);

            textToUpdate = Regex.Replace(textToUpdate, findPattern, replacePattern);

            // Using the Autoformat option is cheating a little but saves on a lot of work.  It basically formats
            // the text as if you were typing it in the IDE
            ep.ReplaceText(ep.LineLength, textToUpdate, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
        }
        /// <summary>Parses for strings by iterating through the text lines.</summary>
        /// <param name="element">The element.</param>
        /// <param name="stringResources">The string resources.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="isCSharp">If set to <c>true</c> it is CSharp code.</param>
        /// <param name="startLine">The start line.</param>
        /// <param name="endLine">The end line.</param>
        /// <returns>The last parsed line number or -1.</returns>
        private int ParseForStrings(CodeElement element,
                                    List <StringResource> stringResources,
                                    ISettings settings,
                                    bool isCSharp,
                                    int startLine,
                                    int endLine)
        {
            TextPoint startPoint = element.StartPoint;
            TextPoint endPoint   = element.EndPoint;

            try
            {
                if (element.Kind == vsCMElement.vsCMElementFunction)
                {
                    try
                    {
                        //we want to have the body only (throws COMException when inspecting an expression bodied function)
                        startPoint = element.GetStartPoint(vsCMPart.vsCMPartBody);
                        endPoint   = element.GetEndPoint(vsCMPart.vsCMPartBody);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.Print("ParseForStrings(vsCMElementFunction, line {0}): {1} - {2}", startPoint.Line, ex.GetType().Name, ex.Message);
                    }
                }

                EditPoint2 editPoint = startPoint.CreateEditPoint() as EditPoint2;

                int    editLine   = editPoint.Line;
                int    editColumn = editPoint.LineCharOffset;
                string text       = editPoint.GetText(endPoint);

                ICodeTools             codeTools        = ViewModelLocator.Instance.GetInstance <ICodeTools>();
                List <CodeTextElement> codeTextelements = codeTools.GetCodeElements(editLine, text);
                List <CodeTextLine>    textLines        = codeTools.GetFilteredLines(
                    codeTextelements, settings);

                bool isComment = false;

                FindStringsInCodeBlock(
                    textLines, editColumn, startLine, endLine, stringResources, settings, ref isComment);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print("### Error: ParseForStrings(): {0} - {1}", ex.GetType().Name, ex.Message);
            }

            return(endPoint?.Line ?? (-1));
        }
        protected bool makeSemicolon(TextSelection textSelection)
        {
            EditPoint2 epend   = textSelection.ActivePoint.CreateEditPoint() as EditPoint2;
            EditPoint2 epbegin = textSelection.ActivePoint.CreateEditPoint() as EditPoint2;

            epbegin.StartOfLine();

            String strOrgText = epbegin.GetText(epend);

            // Check for bracket pair
            int bOpen  = 0;
            int bClose = 0;

            foreach (char c in strOrgText.Trim())
            {
                if (c == '}')
                {
                    ++bClose;
                }
                if (c == '{')
                {
                    ++bOpen;
                }
            }

            if (bClose != bOpen)
            {
                m_logger.Log(String.Format("{0}: CodeBeautifier encounter error while parsing line ( bracket not equal ).", m_appOptions.name));
                return(false);
            }

            String strNewText = getLeadingWhiteSpace(strOrgText) + makeText(strOrgText, textSelection.Parent.Parent.FullName);

            if (String.IsNullOrEmpty(strOrgText) || String.IsNullOrEmpty(strNewText))
            {
                m_logger.Log(String.Format("{0}: CodeBeautifier encounter error while parsing document.", m_appOptions.name));
                return(false);
            }

            if (strNewText.Equals(strOrgText))
            {
                m_logger.Log(String.Format("{0}: No changes after document format.", m_appOptions.name), OptionsGeneral.LoggerPriority.Medium);
                return(true);
            }

            epbegin.ReplaceText(epend, strNewText, (int)(vsEPReplaceTextOptions.vsEPReplaceTextKeepMarkers | vsEPReplaceTextOptions.vsEPReplaceTextNormalizeNewlines));

            return(false);
        }
Пример #15
0
        private string GetTestsOutput()
        {
            Window       outputToolWindow = this.dte.Windows.Item(Constants.vsWindowKindOutput);
            OutputWindow outputWindow     = (OutputWindow)outputToolWindow.Object;

            OutputWindowPane outputWindowPane = outputWindow.OutputWindowPanes.Item("Tests");

            // Create a reference to the pane contents.
            // Select the Tests pane in the Output window.
            outputWindowPane.Activate();
            TextDocument outputWindowPaneTextDocument = outputWindowPane.TextDocument;

            // Retrieve the text contents of the pane.
            EditPoint2 strtPt = (EditPoint2)outputWindowPaneTextDocument.StartPoint.CreateEditPoint();

            return(strtPt.GetText(outputWindowPaneTextDocument.EndPoint));
        }
Пример #16
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
            string title   = "DeleteBlankLine";

            // Show a message box to prove we were here
            VsShellUtilities.ShowMessageBox(
                this.package,
                message,
                title,
                OLEMSGICON.OLEMSGICON_INFO,
                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

            DTE2 dte = GetDTE();

            try
            {
                Document activeDoc = dte.ActiveDocument;

                if (activeDoc != null && activeDoc.ProjectItem != null && activeDoc.ProjectItem.ContainingProject != null)
                {
                    TextDocument objTextDoc      = activeDoc.Object("TextDocument") as TextDocument;
                    EditPoint2   startPoint      = objTextDoc.StartPoint.CreateEditPoint() as EditPoint2;
                    EditPoint2   endPoint        = objTextDoc.EndPoint.CreateEditPoint() as EditPoint2;
                    string       wholeWindowText = startPoint.GetText(endPoint);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"^\s+${2,}", string.Empty, RegexOptions.Multiline);

                    wholeWindowText = Regex.Replace(wholeWindowText, @"\r\n\n\s*\}\r\n\s*$", "\r\n}\r\n", RegexOptions.Multiline);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"\r\n\n\s*\}", "\r\n}", RegexOptions.Multiline);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"\{\r\n\n", "{\r\n", RegexOptions.Multiline);
                    startPoint.ReplaceText(endPoint, wholeWindowText, 3);
                    startPoint.SmartFormat(endPoint);

                    dte.ActiveDocument.Activate();
                    dte.ExecuteCommand("Edit.FormatDocument");
                    dte.ExecuteCommand("Edit.SortUsings");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
        }
Пример #17
0
        /// <summary>
        /// Explores given variable initializer using C# lookuper
        /// </summary>
        protected virtual void Explore(AbstractBatchCommand parentCommand, CodeVariable2 codeVariable, CodeNamespace parentNamespace, CodeElement2 codeClassOrStruct, Predicate <CodeElement> exploreable, bool isLocalizableFalse)
        {
            if (codeVariable.InitExpression == null)
            {
                return;                                      // variable must have an initializer
            }
            if (codeClassOrStruct.Kind == vsCMElement.vsCMElementStruct && !codeVariable.IsShared)
            {
                return;                                                                                    // instance variable of structs cannot have initializers
            }
            if (!exploreable(codeVariable as CodeElement))
            {
                return;                                     // predicate must evaluate to true
            }
            string initExpression = codeVariable.GetText(); // get text of initializer

            if (string.IsNullOrEmpty(initExpression))
            {
                return;
            }

            TextPoint startPoint = codeVariable.StartPoint;

            // is variable decorated with Localizable(false)
            bool variableLocalizableFalse = (codeVariable as CodeElement).HasLocalizableFalseAttribute();

            // run lookuper using parent command
            var list = parentCommand.LookupInCSharp(initExpression, startPoint, parentNamespace, codeClassOrStruct, null, codeVariable.Name, isLocalizableFalse || variableLocalizableFalse);

            // add context to result items (surounding few lines of code)
            EditPoint2 editPoint = (EditPoint2)startPoint.CreateEditPoint();

            foreach (AbstractResultItem item in list)
            {
                item.IsConst         = codeVariable.ConstKind == vsCMConstKind.vsCMConstKindConst;
                item.CodeModelSource = codeVariable;
                AddContextToItem(item, editPoint);
            }
        }
        // add a class to the given namespace
        private void AddClassToNamespace(CodeNamespace ns)
        {
            // add a class
            CodeClass2 chess = (CodeClass2)ns.AddClass("Chess", -1, null, null, vsCMAccess.vsCMAccessPublic);

            // add a function with a parameter and a comment
            CodeFunction2 move = (CodeFunction2)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
            EditPoint2 editPoint = (EditPoint2)move.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

            editPoint.Indent(null, 0);
            editPoint.Insert("int a = 1;");
            editPoint.InsertNewLine(1);
            editPoint.Indent(null, 3);
            editPoint.Insert("int b = 3;");
            editPoint.InsertNewLine(2);
            editPoint.Indent(null, 3);
            editPoint.Insert("return a + b; //");
        }
Пример #19
0
        public static void Run(DTE dte, VsError selectedError)
        {
            selectedError.Navigate();
            EditPoint2 ep = ErrorUtilities.GetEditPoint(dte);

            ep.StartOfLine();
            string editLine = ep.GetLines(ep.Line, ep.Line + 1);

            editLine = editLine.Replace(";", "");
            string varName = string.Empty;

            if (editLine.IndexOf("=") > -1)
            {
                varName = editLine.Split("=".ToCharArray()).First().Split(" ".ToCharArray()).Where(item => item.Length > 0).Last();
            }
            else
            {
                varName = editLine.Split(" ".ToCharArray()).Last();
            }
            ep.Parent.Selection.CharRight(Count: editLine.IndexOf(varName));
            dte.ExecuteCommand("Refactor.Rename");
            //// todo
        }
Пример #20
0
        public static void Run(DTE dte, VsError selectedError)
        {
            selectedError.Navigate();
            EditPoint2 editPoint = ErrorUtilities.GetEditPoint(dte);

            editPoint.StartOfDocument();
            string fileName = selectedError.FileName.Substring(
                selectedError.FileName.LastIndexOf(@"\") + 1,
                selectedError.FileName.Length - (selectedError.FileName.LastIndexOf(@"\") + 1));

            editPoint.InsertNewLine();
            editPoint.StartOfDocument();
            editPoint.Insert(
                string.Format(
                    @"//-----------------------------------------------------------------------
// <copyright file=""{0}"" company=""{1}"">
//     {2}
// </copyright>
//-----------------------------------------------------------------------",
                    fileName,
                    StyleRepair.Properties.StyleRepair.Default.CompanyName,
                    StyleRepair.Properties.StyleRepair.Default.CopyrightMessage));
        }
Пример #21
0
        private void AddUsingStatement(FileCodeModel model, CodeElements codeElements, string usingStatement)
        {
            bool       usingStatementFound = false;
            CodeImport lastCodeElement     = null;

            foreach (CodeElement codeElement in codeElements)
            {
                if (codeElement.Kind == vsCMElement.vsCMElementImportStmt)
                {
                    CodeImport codeImport = codeElement as CodeImport;
                    if (codeImport.Namespace == usingStatement)
                    {
                        usingStatementFound = true;
                    }
                    lastCodeElement = codeImport;
                }

                AddUsingStatement(model, codeElement.Children, usingStatement);
            }

            if (!usingStatementFound)
            {
                if (lastCodeElement != null)
                {
                    //FileCodeModel2 model2 = model as FileCodeModel2;
                    //model2.AddImport(usingStatement);

                    EditPoint2 editPoint = (EditPoint2)lastCodeElement.GetEndPoint().CreateEditPoint();
                    editPoint.InsertNewLine(1);
                    editPoint.Indent(null, 1);
                    editPoint.Insert("using " + usingStatement + ";");

                    Helpers.LogMessage(model.DTE, model.DTE, Helpers.GetFullPathOfProjectItem(lastCodeElement.ProjectItem) + ": Added using statement '" + usingStatement + "'");
                }
            }
        }
        /// <summary>Parses for strings by iterating through the text lines.</summary>
        /// <param name="element">The element.</param>
        /// <param name="stringResources">The string resources.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="isCSharp">If set to <c>true</c> it is CSharp code.</param>
        /// <param name="startLine">The start line.</param>
        /// <param name="endLine">The end line.</param>
        /// <returns>The last parsed line number or -1.</returns>
        private static int ParseForStrings(CodeElement element,
                                           List <StringResource> stringResources,
                                           Settings settings,
                                           bool isCSharp,
                                           int startLine,
                                           int endLine)
        {
            TextPoint startPoint = element.StartPoint,
                      endPoint   = element.EndPoint;
            EditPoint2 editPoint = null;

            try
            {
                if (element.Kind == vsCMElement.vsCMElementFunction)
                {
#if DEBUG_OUTPUT
                    System.Diagnostics.Debug.Print("    function kind: {0}", (element as CodeFunction).FunctionKind);
#endif

                    try
                    {
                        //we want to have the body only (throws COMException when inspecting an expression bodied function)
                        startPoint = element.GetStartPoint(vsCMPart.vsCMPartBody);
                        endPoint   = element.GetEndPoint(vsCMPart.vsCMPartBody);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.Print("ParseForStrings(vsCMElementFunction, line {0}): {1} - {2}", startPoint.Line, ex.GetType().Name, ex.Message);
                    }
                }

                editPoint = startPoint.CreateEditPoint() as EditPoint2;

                int editLine       = editPoint.Line,
                    editColumn     = editPoint.LineCharOffset;
                string   text      = editPoint.GetText(endPoint);
                string[] txtLines  = text.Replace("\r", string.Empty).Split('\n');
                bool     isComment = false;
#if IGNORE_METHOD_ARGUMENTS
                bool isIgnoreMethodArguments = false;
#endif

                foreach (string txtLine in txtLines)
                {
                    if ((editLine >= startLine) && (editLine <= endLine))
                    {
                        //this is a changed text line in the block

#if !IGNORE_METHOD_ARGUMENTS
                        if (txtLine.Contains("\""))
                        {
                            ParseForStrings(txtLine, editLine, editColumn, stringResources, settings, isCSharp, ref isComment);
                        }
#else
                        if (line.Contains("\""))
                        {
                            ParseForStrings(line, editLine, editColumn, stringResources, settings, ref isComment, ref isIgnoreMethodArguments);
                        }
#endif
                    }

                    ++editLine;

                    //only for the first line of the text block LineCharOffset will be used
                    if (editColumn > 1)
                    {
                        editColumn = 1;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print("### Error: ParseForStrings(): {0} - {1}", ex.GetType().Name, ex.Message);
            }

            return(endPoint?.Line ?? (-1));
        }
Пример #23
0
        /// <summary>
        /// Explores given method using C# lookuper
        /// </summary>
        protected virtual void Explore(AbstractBatchCommand parentCommand, CodeFunction2 codeFunction, CodeNamespace parentNamespace, CodeElement2 codeClassOrStruct, Predicate <CodeElement> exploreable, bool isLocalizableFalse)
        {
            if (codeFunction.MustImplement)
            {
                return;                             // method must not be abstract or declated in an interface
            }
            if (!exploreable(codeFunction as CodeElement))
            {
                return;                                            // predicate must eval to true
            }
            // there is no way of knowing whether a function is not declared 'extern'. In that case, following will throw an exception.
            string functionText = null;

            try {
                functionText = codeFunction.GetText(); // get method text
            } catch (Exception) { }
            if (string.IsNullOrEmpty(functionText))
            {
                return;
            }

            TextPoint startPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

            // is method decorated with Localizable(false)
            bool functionLocalizableFalse = (codeFunction as CodeElement).HasLocalizableFalseAttribute();

            var list = parentCommand.LookupInCSharp(functionText, startPoint, parentNamespace, codeClassOrStruct, codeFunction.Name, null, isLocalizableFalse || functionLocalizableFalse);

            // add context to result items (surounding few lines of code)
            EditPoint2 editPoint = (EditPoint2)startPoint.CreateEditPoint();

            foreach (AbstractResultItem item in list)
            {
                item.CodeModelSource = codeFunction;
                AddContextToItem(item, editPoint);
            }

            // read optional arguments initializers (just to show them - they cannot be moved)
            TextPoint headerStartPoint = null;

            try {
                headerStartPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader);
            } catch (Exception) { }
            if (headerStartPoint == null)
            {
                return;
            }

            string headerText = codeFunction.GetHeaderText();

            // search method header
            var headerList = parentCommand.LookupInCSharp(headerText, headerStartPoint, parentNamespace, codeClassOrStruct, codeFunction.Name, null, isLocalizableFalse || functionLocalizableFalse);

            // add to list
            editPoint = (EditPoint2)startPoint.CreateEditPoint();
            foreach (AbstractResultItem item in headerList)
            {
                item.IsConst         = true;
                item.CodeModelSource = codeFunction;
                AddContextToItem(item, editPoint);
            }
        }
Пример #24
0
        /// <summary>
        /// Adds context to the result item, coming from code block starting at given position
        /// </summary>
        protected void AddContextToItem(AbstractResultItem item, EditPoint2 editPoint)
        {
            StringBuilder context = new StringBuilder();
            // indices +1 !!

            int topLines = 0;

            int currentLine         = item.ReplaceSpan.iStartLine;
            int contextRelativeLine = 0;

            // add NumericConstants.ContextLineRadius lines above the result item with at least 2 non-whitespace characters
            while (currentLine >= 1 && topLines < NumericConstants.ContextLineRadius)
            {
                editPoint.MoveToLineAndOffset(currentLine, 1);
                string lineText = editPoint.GetText(editPoint.LineLength);
                if (lineText.Trim().Length > 0)
                {
                    context.Insert(0, lineText + Environment.NewLine);
                    contextRelativeLine++;
                    if (lineText.Trim().Length > 1)
                    {
                        topLines++;
                    }
                }
                currentLine--;
            }

            editPoint.MoveToLineAndOffset(item.ReplaceSpan.iStartLine + 1, 1);
            context.Append(editPoint.GetText(item.ReplaceSpan.iStartIndex));

            context.Append(StringConstants.ContextSubstituteText); // add text that will be displayed instead of actual result item

            editPoint.MoveToLineAndOffset(item.ReplaceSpan.iEndLine + 1, item.ReplaceSpan.iEndIndex + 1);
            context.Append(editPoint.GetText(editPoint.LineLength - item.ReplaceSpan.iEndIndex + 1));

            int botLines = 0;

            currentLine = item.ReplaceSpan.iEndLine + 2;
            // add NumericConstants.ContextLineRadius lines below the result item with at least 2 non-whitespace characters
            while (botLines < NumericConstants.ContextLineRadius)
            {
                editPoint.MoveToLineAndOffset(currentLine, 1);
                string lineText = editPoint.GetText(editPoint.LineLength);
                if (lineText.Trim().Length > 0)
                {
                    context.Append(Environment.NewLine + lineText);
                    if (lineText.Trim().Length > 1)
                    {
                        botLines++;
                    }
                }
                editPoint.EndOfLine();
                if (editPoint.AtEndOfDocument)
                {
                    break;
                }
                currentLine++;
            }

            item.Context             = context.ToString();
            item.ContextRelativeLine = contextRelativeLine; // index of "middle" line
        }
Пример #25
0
        protected bool makeBracketClose(TextSelection textSelection)
        {
            EditPoint2 epend   = textSelection.ActivePoint.CreateEditPoint() as EditPoint2;
            EditPoint2 epbegin = textSelection.ActivePoint.CreateEditPoint() as EditPoint2;

            String bracketOpen;
            int    otherbracket = 0;

            do
            {
                EditPoint2 last = epbegin.CreateEditPoint() as EditPoint2;
                epbegin.CharLeft();
                bracketOpen = epbegin.GetText(last);

                if (bracketOpen.CompareTo("}") == 0)
                {
                    ++otherbracket;
                }
                if (bracketOpen.CompareTo("{") == 0)
                {
                    --otherbracket;
                }

                if (epbegin.AtStartOfDocument &&
                    (bracketOpen.CompareTo("{") != 0 || otherbracket != 0))
                {
                    return(false);
                }
            } while(bracketOpen.CompareTo("{") != 0 || otherbracket != 0);

            epbegin.StartOfLine();

            String strOrgText = epbegin.GetText(epend);
            String strNewText = makeText(strOrgText, textSelection.Parent.Parent.FullName);

            if (String.IsNullOrEmpty(strOrgText) || String.IsNullOrEmpty(strNewText))
            {
                m_logger.Log(String.Format("{0}: CodeBeautifier encounter error while parsing document.", m_appOptions.name));
                return(false);
            }

            // Insert leading white space to each line
            String strNewIdentText   = String.Empty;
            String leadingWhiteSpace = getLeadingWhiteSpace(strOrgText);

            using (StringReader reader = new StringReader(strNewText))
            {
                string line = reader.ReadLine();
                do
                {
                    strNewIdentText += leadingWhiteSpace + line;

                    line = reader.ReadLine();
                    if (line != null)
                    {
                        strNewIdentText += Environment.NewLine;
                    }
                } while(line != null);
            }

            if (strNewIdentText.Equals(strOrgText))
            {
                m_logger.Log(String.Format("{0}: No changes after document format.", m_appOptions.name), OptionsGeneral.LoggerPriority.Medium);
                return(true);
            }

            epbegin.ReplaceText(epend, strNewIdentText, (int)(vsEPReplaceTextOptions.vsEPReplaceTextKeepMarkers | vsEPReplaceTextOptions.vsEPReplaceTextNormalizeNewlines));

            return(true);
        }
        /// <summary>Parses for strings by iterating through the text lines.</summary>
        /// <param name="element">The element.</param>
        /// <param name="stringResources">The string resources.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="isCSharp">If set to <c>true</c> it is CSharp code.</param>
        /// <param name="startLine">The start line.</param>
        /// <param name="endLine">The end line.</param>
        /// <returns>The last parsed line number or -1.</returns>
        private static int ParseForStrings(CodeElement element,
                                           List <StringResource> stringResources,
                                           Settings settings,
                                           bool isCSharp,
                                           int startLine,
                                           int endLine)
        {
            TextPoint startPoint = element.StartPoint,
                      endPoint   = element.EndPoint;
            EditPoint2 editPoint = null;

            try
            {
                if (element.Kind == vsCMElement.vsCMElementFunction)
                {
#if DEBUG_OUTPUT
                    System.Diagnostics.Debug.Print("    function kind: {0}", (element as CodeFunction).FunctionKind);
#endif

                    try
                    {
                        //we want to have the body only (throws COMException when inspecting an expression bodied function)
                        startPoint = element.GetStartPoint(vsCMPart.vsCMPartBody);
                        endPoint   = element.GetEndPoint(vsCMPart.vsCMPartBody);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.Print("ParseForStrings(vsCMElementFunction, line {0}): {1} - {2}", startPoint.Line, ex.GetType().Name, ex.Message);
                    }
                } //if

                editPoint = startPoint.CreateEditPoint() as EditPoint2;

                //if ((element.Kind == vsCMElement.vsCMElementVariable) && (startPoint.LineCharOffset > 1))
                //  editPoint.CharLeft(startPoint.LineCharOffset - 1);

//#if DEBUG
//        if (element.Kind == vsCMElement.vsCMElementFunction)
//          System.Diagnostics.Debug.Print("got a function, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
//        else
//          System.Diagnostics.Debug.Print("got a variable, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
//#endif
                //if (element.Children.Count > 0)
                //  editPoint = element.Children.Item(element.Children.Count).EndPoint.CreateEditPoint() as EditPoint2;
                //else
                //  editPoint = element.StartPoint.CreateEditPoint() as EditPoint2;
//#if DEBUG
//        if (element.Children.Count > 0) System.Diagnostics.Debug.Print("      line {0} to {1}", editPoint.Line, element.EndPoint.Line);
//#endif

                #region veeeeeery sloooooow
                //int endPoint      = element.EndPoint.Line,
                //    endColumn     = element.EndPoint.LineCharOffset,
                //    absoluteEnd   = element.EndPoint.AbsoluteCharOffset,
                //    editLine      = editPoint.Line,
                //    editColumn    = editPoint.LineCharOffset,
                //    absoluteStart = editPoint.AbsoluteCharOffset,
                //    editLength    = (editLine == endPoint) ? (absoluteEnd - absoluteStart + 1)
                //                                           : (editPoint.LineLength - editColumn + 1);

                //while ((editLine < endPoint) || ((editLine == endPoint) && (editColumn <= endColumn)))
                //{
                //  string textLine = editPoint.GetText(editLength);

                //  //System.Diagnostics.Debug.Print(">>>{0}<<<", textLine);

                //  if (!string.IsNullOrEmpty(textLine.Trim()))
                //    ParseForStrings(textLine, editLine, editColumn, stringResources, settings);

                //  editPoint.LineDown(1);
                //  editPoint.StartOfLine();

                //  editLine      = editPoint.Line;
                //  editColumn    = editPoint.LineCharOffset;
                //  absoluteStart = editPoint.AbsoluteCharOffset;
                //  editLength    = (editLine == endPoint) ? (absoluteEnd - absoluteStart + 1)
                //                                         : (editPoint.LineLength - editColumn + 1);
                //} //while
                #endregion

                //this is much faster (by factors)!!!
                int editLine       = editPoint.Line,
                    editColumn     = editPoint.LineCharOffset;
                string   text      = editPoint.GetText(endPoint);
                string[] txtLines  = text.Replace("\r", string.Empty).Split('\n');
                bool     isComment = false;
#if IGNORE_METHOD_ARGUMENTS
                bool isIgnoreMethodArguments = false;
#endif

                foreach (string txtLine in txtLines)
                {
                    if ((editLine >= startLine) && (editLine <= endLine))
                    {
                        //this is a changed text line in the block

#if !IGNORE_METHOD_ARGUMENTS
                        if (txtLine.Contains("\""))
                        {
                            ParseForStrings(txtLine, editLine, editColumn, stringResources, settings, isCSharp, ref isComment);
                        }
#else
                        if (line.Contains("\""))
                        {
                            ParseForStrings(line, editLine, editColumn, stringResources, settings, ref isComment, ref isIgnoreMethodArguments);
                        }
#endif
                    } //if

                    ++editLine;

                    //only for the first line of the text block LineCharOffset will be used
                    if (editColumn > 1)
                    {
                        editColumn = 1;
                    }
                } //foreach
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print("### Error: ParseForStrings(): {0} - {1}", ex.GetType().Name, ex.Message);
            }

            return(endPoint?.Line ?? (-1));
        }
Пример #27
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);
        }