private string ExtractMember(CodeElement element) { var memberStart = element.GetStartPoint().CreateEditPoint(); var memberText = string.Empty; memberText += memberStart.GetText(element.GetEndPoint()); memberStart.Delete(element.GetEndPoint()); return(memberText); }
/// <summary> /// Adds missing access modifiers /// </summary> /// <param name="codeElement">The CodeElement to add missing access modifiers too. Includes children.</param> private void AddMissingAccessModifiers(CodeElement codeElement) { if (codeElement.Kind != vsCMElement.vsCMElementInterface && CodeElementBlockTypes.ContainsKey(codeElement.Kind)) { for (int i = 1; i <= codeElement.Children.Count; i++) { CodeElement element = codeElement.Children.Item(i) as CodeElement; if (element.Kind != vsCMElement.vsCMElementImportStmt && element.Kind != vsCMElement.vsCMElementInterface && CodeElementBlockTypes.ContainsKey(codeElement.Kind)) { // Get the element's access through reflection rather than a massive switch. vsCMAccess access = (vsCMAccess)CodeElementTypes[element.Kind].InvokeMember("Access", BindingFlags.GetProperty, null, element, null); if (element.Kind == vsCMElement.vsCMElementClass || element.Kind == vsCMElement.vsCMElementStruct) { AddMissingAccessModifiers(element); } EditPoint start; EditPoint end; string declaration; if (element.Kind == vsCMElement.vsCMElementFunction) { // method, constructor, or finalizer CodeFunction2 function = element as CodeFunction2; // Finalizers don't have access modifiers, neither do static constructors if (function.FunctionKind == vsCMFunction.vsCMFunctionDestructor || (function.FunctionKind == vsCMFunction.vsCMFunctionConstructor && function.IsShared)) { continue; } } if (element.Kind == vsCMElement.vsCMElementProperty || element.Kind == vsCMElement.vsCMElementVariable || element.Kind == vsCMElement.vsCMElementEvent) { CodeElements attributes = (CodeElements)CodeElementTypes[element.Kind].InvokeMember("Attributes", BindingFlags.GetProperty, null, element, null); start = attributes.Count > 0 ? element.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter).CreateEditPoint() : element.StartPoint.CreateEditPoint(); } else { start = element.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint(); } end = start.CreateEditPoint(); end.EndOfLine(); declaration = start.GetText(end); if (!declaration.StartsWith(CodeAccessKeywords[access]) && !declaration.StartsWith("partial")) { object[] args = new object[1]; args.SetValue(access, 0); CodeElementTypes[element.Kind].InvokeMember("Access", BindingFlags.SetProperty, null, element, args); } declaration = start.GetText(end); } } } }
/// <summary> /// Deletes the name space using statements. /// </summary> /// <param name="instance">The instance.</param> public static void DeleteNameSpaceUsingStatements(this ProjectItem instance) { bool continueLoop = true; do { CodeElement codeElement = instance.FileCodeModel.CodeElements.Item(1); if (codeElement != null) { if (codeElement.Kind == vsCMElement.vsCMElementImportStmt) { EditPoint editPoint = codeElement.GetStartPoint().CreateEditPoint(); TextPoint textPoint = codeElement.GetEndPoint(); editPoint.Delete(textPoint); //// should get rid of the blank line! editPoint.Delete(1); } else { continueLoop = false; } } else { continueLoop = false; } }while (continueLoop); }
public string GetMethodText(vsCMPart part) { TextPoint startPoint = m_method.GetStartPoint(); int endLine = m_method.GetEndPoint().Line; m_textSelection.MoveToPoint(startPoint); StringBuilder sb = new StringBuilder(); int count = 99999; while (count-- != 0 && m_textSelection.CurrentLine != endLine) { m_textSelection.SelectLine(); sb.Append(m_textSelection.Text); } return(sb.ToString()); }
/// <summary> /// Inserts the routes. /// </summary> /// <param name="utilFolder">The util folder.</param> /// <param name="mvcCodeFilePath">The MVC code file path.</param> /// <param name="isConnectToQuickBookAlreadyThere">if set to <c>true</c> [is connect to quick book already there].</param> /// <param name="isLoginAlreadyThere">if set to <c>true</c> [is login already there].</param> /// <param name="isBlueDotMenyAlreadyThere">if set to <c>true</c> [is blue dot meny already there].</param> /// <param name="isDisconnetThere">if set to <c>true</c> [is disconnet there].</param> internal static void InsertRoutes(ProjectItem utilFolder, string mvcCodeFilePath, bool isConnectToQuickBookAlreadyThere, bool isLoginAlreadyThere, bool isBlueDotMenyAlreadyThere, bool isDisconnetThere, bool isLogoutThere) { ProjectItem fileProjectItem; if (Common.IsProjectItemExist(utilFolder.ProjectItems, "IntuitRegisterRoutes.cs", out fileProjectItem)) { CodeElement registerIntuitAnywhereRoutes = null; foreach (CodeElement codeElement in fileProjectItem.FileCodeModel.CodeElements) { if (codeElement.Kind == vsCMElement.vsCMElementClass) { foreach (CodeElement classChildElelement in codeElement.Children) { if (classChildElelement.Kind == vsCMElement.vsCMElementFunction && classChildElelement.Name == "RegisterIntuitAnywhereRoutes") { registerIntuitAnywhereRoutes = classChildElelement; break; } } } } if (registerIntuitAnywhereRoutes != null) { EditPoint ep = registerIntuitAnywhereRoutes.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); if (isConnectToQuickBookAlreadyThere == true) { string oauth = File.ReadAllText(mvcCodeFilePath + "oAuth.txt"); ep.Insert(oauth); } if (isLoginAlreadyThere) { string openId = File.ReadAllText(mvcCodeFilePath + "openID.txt"); ep.Insert(openId); } if (isBlueDotMenyAlreadyThere) { string blueDot = File.ReadAllText(mvcCodeFilePath + "blueDot.txt"); ep.Insert(blueDot); } if (isDisconnetThere) { string blueDot = File.ReadAllText(mvcCodeFilePath + "disconnect.txt"); ep.Insert(blueDot); } if (isLogoutThere) { string logout = File.ReadAllText(mvcCodeFilePath + "logout.txt"); ep.Insert(logout); } } } }
/// <summary> /// Replaces a code element with the supplied source code, which should be valid code in the target project's language. /// </summary> public static void ReplaceWithSourceCode(this CodeElement codeElement, string sourceCode, vsEPReplaceTextOptions replaceTextOptions = vsEPReplaceTextOptions.vsEPReplaceTextAutoformat) { if (codeElement == null) { throw new ArgumentNullException("codeElement"); } var startPoint = codeElement.GetStartPoint(); startPoint.CreateEditPoint().ReplaceText(codeElement.GetEndPoint(), IndentAllButFirstLine(sourceCode ?? string.Empty, startPoint.LineCharOffset - 1), (int)replaceTextOptions); }
/// <summary> /// Refreshes the cached position and name fields on this item. /// </summary> /// <remarks> /// Similar to BaseCodeItemElement's implementation, except ignores the Name property which /// is not available for using statements. /// </remarks> public override void RefreshCachedPositionAndName() { var startPoint = CodeElement.GetStartPoint(); var endPoint = CodeElement.GetEndPoint(); StartLine = startPoint.Line; StartOffset = startPoint.AbsoluteCharOffset; EndLine = endPoint.Line; EndOffset = endPoint.AbsoluteCharOffset; }
/// <summary> /// Removes whitespace immediately inside a block /// </summary> /// <param name="element">The current code element</param> private void RemoveInternalBlockPadding(CodeElement element) { EditPoint start = element.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); EditPoint end = element.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); end.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); end.CharLeft(1); start.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); end.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); }
string UpdateBodyCode(CodeUIItem item,CodeElement codeElement) { if (codeElement == null || item == null || !item.IsFunction()) { return(""); } var funcStart = codeElement.GetStartPoint(vsCMPart.vsCMPartBody); var funcEnd = codeElement.GetEndPoint(vsCMPart.vsCMPartBody); var funcEditPnt = funcStart.CreateEditPoint(); string funcText = funcEditPnt.GetText(funcEnd).Replace("\r\n","\n"); item.m_bodyCode = funcText; return(funcText); }
/// <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)); }
/// <summary> /// Checks to see if there should be additional blank lines after the end of a block. /// </summary> /// <param name="element">The current element to check</param> private void CheckBlockEnd(CodeElement element) { EditPoint endBlock = element.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes).CreateEditPoint(); EditPoint startBlock = element.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes).CreateEditPoint(); string original = startBlock.GetText(endBlock); EditPoint endOfEnd = endBlock.CreateEditPoint(); endOfEnd.EndOfLine(); string endOfBlockLine = endBlock.GetText(endOfEnd).Trim(); if (element.Kind == vsCMElement.vsCMElementAttribute || element.Kind == vsCMElement.vsCMElementOther) { if (endOfBlockLine != "]" && endOfBlockLine != ")]" && !endOfBlockLine.StartsWith(",")) { endOfEnd = endBlock.CreateEditPoint(); endOfEnd.EndOfLine(); endOfBlockLine = endBlock.GetText(endOfEnd).Trim(); if (endOfBlockLine != string.Empty) { endBlock.Insert(Environment.NewLine); endBlock.SmartFormat(endOfEnd); } } } else if (endOfBlockLine != string.Empty) { endBlock.Insert(Environment.NewLine); endBlock.SmartFormat(endOfEnd); } if (element.Kind != vsCMElement.vsCMElementImportStmt && element.Kind != vsCMElement.vsCMElementAttribute && element.Kind != vsCMElement.vsCMElementOther) { endOfEnd.LineDown(1); endOfEnd.EndOfLine(); string lineAfterBlock = endBlock.GetText(endOfEnd).Trim(); if (lineAfterBlock != string.Empty && !lineAfterBlock.StartsWith("else") && !lineAfterBlock.StartsWith("}")) { endBlock.Insert(Environment.NewLine); endBlock.SmartFormat(endOfEnd); } } }
/// <summary> /// Refresh Start,End offsets /// return true, if offsets differs from stored ones, else return false. /// </summary> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> private bool refreshOffset() { vsCMPart partS, partE; int nStart, nEnd; try { switch (Element.Kind) { case vsCMElement.vsCMElementFunction: partS = vsCMPart.vsCMPartBody; partE = vsCMPart.vsCMPartWholeWithAttributes; //to get whole end var f2 = Element as CodeFunction2; if (f2.MustImplement) { return(false); //doesn't have body } break; default: partE = partS = vsCMPart.vsCMPartWholeWithAttributes; break; } nStart = Element.GetStartPoint(partS).AbsoluteCharOffset; nEnd = Element.GetEndPoint(partE).AbsoluteCharOffset; } catch { nEnd = nStart = Start + 1; //because of returning true, until position will be available _owner.VS.Log.Warning("Cannot resolve position of {0}", Element.FullName); } if (nStart != Start || nEnd != End) { Start = nStart; End = nEnd; return(true); } return(false); }
/// <summary> /// Checks to see if there should be additional blank lines immediately after starting a block /// </summary> /// <param name="element">The current element to check</param> private void CheckBlockStart(CodeElement element) { EditPoint start = element.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); EditPoint end = element.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); EditPoint beginStart = start.CreateEditPoint(); beginStart.StartOfLine(); string beginningStartText = beginStart.GetText(start).Trim(); if (beginningStartText != string.Empty) { EditPoint endStart = start.CreateEditPoint(); endStart.EndOfLine(); string restofStartText = start.GetText(endStart).Trim(); if (!restofStartText.StartsWith("get;")) { start.Insert(Environment.NewLine); start.SmartFormat(endStart); } } }
public TextPoint GetEndPoint(vsCMPart Part) { return(_element.GetEndPoint(Part)); }
/// <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)); }
/// <summary> /// Inserts the method call in global ASAX file. /// </summary> /// <param name="selProject">The sel project.</param> internal static void InsertMethodCallInGlobalASAXFile(Project selProject) { ProjectItem fileProjectItem; bool registerRootsFound = false; bool registerGlobalFiltersFound = false; if (Common.IsProjectItemExist(selProject.ProjectItems, "Global.asax", out fileProjectItem)) { CodeElement registerRoutes = null; CodeElement registerGlobalFilters = null; FileCodeModel codeModel = fileProjectItem.ProjectItems.Item(1).FileCodeModel; foreach (CodeElement codeElement in codeModel.CodeElements) { if (codeElement.Kind == vsCMElement.vsCMElementNamespace) { foreach (CodeElement namespacechildElement in codeElement.Children) { if (namespacechildElement.Kind == vsCMElement.vsCMElementClass) { foreach (CodeElement functionElement in namespacechildElement.Children) { if (functionElement.Kind == vsCMElement.vsCMElementFunction && (functionElement.Name == "RegisterRoutes" || functionElement.Name == "RegisterGlobalFilters")) { if (functionElement.Name == "RegisterRoutes") { registerRoutes = functionElement; registerRootsFound = true; } if (functionElement.Name == "RegisterGlobalFilters") { registerGlobalFilters = functionElement; registerGlobalFiltersFound = true; } if (registerRootsFound && registerGlobalFiltersFound) { break; } } } } } } } if (registerRoutes != null) { EditPoint startEp = registerRoutes.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); if (!startEp.FindPattern("IntuitRegisterRoutes.RegisterIntuitAnywhereRoutes(routes);")) { EditPoint endEP = registerRoutes.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); endEP.Insert(Environment.NewLine + Environment.NewLine + "IntuitRegisterRoutes.RegisterIntuitAnywhereRoutes(routes);"); } } if (registerGlobalFilters != null) { EditPoint startEp = registerGlobalFilters.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); if (!startEp.FindPattern("filters.Add(new IntuitSampleMVC.utils.IppTag());")) { EditPoint endEP = registerGlobalFilters.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); endEP.Insert(Environment.NewLine + Environment.NewLine + "filters.Add(new IntuitSampleMVC.utils.IppTag());"); } } } }
/// <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)); }