public CodeVariable GetVariable(FileLinePositionSpan location) { m_textSelection.MoveToLineAndOffset(location.StartLinePosition.Line + this.StartLineNumber - 1, 1); m_textSelection.SelectLine(); CodeVariable var = (CodeVariable)m_textSelection.ActivePoint.get_CodeElement( vsCMElement.vsCMElementVariable); return(var); }
/// <summary> /// Extract document information. Such as namespace, class or interface. /// </summary> /// <param name="textSelection">TextSelection object of a document</param> /// <returns>Basic Information object</returns> private DocumentInformation ExtractDocumentInformation(TextSelection textSelection) { textSelection.StartOfDocument(); string @namespace = string.Empty; string @class = string.Empty; string @interface = string.Empty; int previousLine = -1; while (previousLine != textSelection.CurrentLine) { if (textSelection.Text.Contains("//")) { previousLine = textSelection.CurrentLine; textSelection.SelectLine(); continue; } string[] split = textSelection.Text.Split(' '); if (@namespace == string.Empty) { @namespace = FindName(split, "namespace"); } if (@class == string.Empty) { @class = FindName(split, "class"); } if (@interface == string.Empty) { @interface = FindName(split, "interface"); } if (@namespace != string.Empty && (@class != string.Empty || @interface != string.Empty)) { break; } previousLine = textSelection.CurrentLine; textSelection.SelectLine(); } return(new DocumentInformation { Namespace = @namespace, Class = @class, Interface = @interface }); }
/// <summary> /// Runs custom wizard logic when the wizard has completed all tasks. /// </summary> public void RunFinished() { try { // The interface implmentation inserted in the ProjectFinishedGenerating event has its Region twistie open // This code is to close the interface implmentation twistie so that the region appears like the common methods and support code twisties TL.Enabled = true; TL.LogMessage("RunFinished", "Start"); Diagnostics.Enter(); if (myProjectItem != null) // We do have a project item to work on { myProjectItem.Open(); // Open the item for editing TL.LogMessage("RunFinished", "Done Open"); Document itemDocument = myProjectItem.Document; // Get the open file's document object TL.LogMessage("RunFinished", "Created Document"); itemDocument.Activate(); // Make this the current document TL.LogMessage("RunFinished", "Activated Document"); TextSelection documentSelection = (TextSelection)itemDocument.Selection; // Create a document selection TL.LogMessage("RunFinished", "Created Selection object"); documentSelection.StartOfDocument(); // GO to the top of the document TL.LogMessage("RunFinished", "Done StartOfDocument Region"); string pattern = "[Rr]egion \"*I" + DeviceClass; // Cerate a regular expression string that works for region in both VB and C# TL.LogMessage("", "RegEx search pattern: " + pattern); if (documentSelection.FindText(pattern, (int)vsFindOptions.vsFindOptionsRegularExpression)) // Search for the interface implemnetation start of region { // Found the interface implementation region so toggle its twistie closed documentSelection.SelectLine(); TL.LogMessage("RunFinished", "Found region I" + DeviceClass + " - " + documentSelection.Text); // Log the line actuall found myDTE.ExecuteCommand("Edit.ToggleOutliningExpansion"); // Toggle the twistie closed TL.LogMessage("RunFinished", "Done ToggleOutliningExpansion Region"); } itemDocument.Close(vsSaveChanges.vsSaveChangesYes); // SAve changes and close the file TL.LogMessage("RunFinished", "Done Save"); } else // No project item so just report this (happens when a test project is being created) { TL.LogMessage("RunFinished", "Project item is null, no action taken"); } TL.LogMessage("RunFinished", "End"); Diagnostics.Exit(); } catch (Exception ex) { TL.LogMessageCrLf(" RunFinished Exception", ex.ToString()); // Log any error message MessageBox.Show(ex.ToString(), "RunFinished Wizard Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // Show an error message } }
void onShowInAtlas(object[] param) { Document doc = m_applicationObject.ActiveDocument; TextSelection ts = doc.Selection as TextSelection; int lineOffset = ts.AnchorPoint.LineCharOffset; int lineNum = ts.AnchorPoint.Line; ts.SelectLine(); string lineText = ts.Text; ts.MoveToLineAndOffset(lineNum, lineOffset); Regex rx = new Regex(@"\b(?<word>\w+)\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); MatchCollection matches = rx.Matches(lineText); // Report on each match. string token = null; foreach (Match match in matches) { string word = match.Groups["word"].Value; int startIndex = match.Index; int endIndex = startIndex + word.Length - 1; int lineIndex = lineOffset - 1; if (startIndex <= lineIndex && endIndex + 1 >= lineIndex) { token = word; break; } } if (token != null) { string docPath = doc.FullName; m_socket.remoteCall("showInAtlas", new object[] { token, "*", docPath, lineNum }); } // TextDocument txtDoc = doc.Object("TextDocument") as TextDocument; // ProjectItem projectItem = doc.ProjectItem; // FileCodeModel fileCodeModel = projectItem.FileCodeModel; // // if (true || fileCodeModel.Language == CodeModelLanguageConstants.vsCMLanguageCSharp) // { // EnvDTE.TextSelection txtSelection = m_applicationObject.ActiveDocument.Selection as EnvDTE.TextSelection; // CodeElement codeEmelemt = null; // try // { // codeEmelemt = fileCodeModel.CodeElementFromPoint(txtSelection.TopPoint, vsCMElement.vsCMElementFunction); // string codeName = codeEmelemt.Name; // } // catch { } // } }
private void HandleException(string ExceptionType, string Name, int Code, string Description, ref dbgExceptionAction ExceptionAction) { ExceptionEvent ex = new ExceptionEvent(); int depthCounter = 0; EnvDTE90a.Debugger4 debugger = dte.Debugger as EnvDTE90a.Debugger4; if (debugger != null) { //not sure when the current thread could be NULL, but you never know with //the DTE. if (debugger.CurrentThread != null) { foreach (EnvDTE.StackFrame dteFrame in debugger.CurrentThread.StackFrames) { EnvDTE90a.StackFrame2 frame = (StackFrame2)dteFrame; Models.StackFrame modelFrame = new Models.StackFrame(frame); modelFrame.Depth = depthCounter; ex.StackFrames.Add(modelFrame); depthCounter++; } } } //the stuff inside this try will be null if there isn't an open document //window (rare, but possible) try { TextSelection debugSelection = dte.ActiveDocument.Selection; debugSelection.SelectLine(); ex.LineContent = debugSelection.Text; ex.LineNumber = debugSelection.CurrentLine; ex.DocumentName = dte.ActiveDocument.Name; } catch (Exception) { ex.LineContent = ""; ex.LineNumber = 0; ex.DocumentName = dte.Solution.FullName; } ex.EventDate = DateTime.UtcNow; ex.ExceptionAction = (int)ExceptionAction; ex.ExceptionCode = Code; ex.ExceptionDescription = Description; ex.ExceptionName = Name; ex.ExceptionType = ExceptionType; ex.SolutionName = dte.Solution.FullName; NotifyEventCreated(this, new EventCreatedArgs(ex)); }
private static string GetCurrentLine(TextSelection sel) { if (sel == null) { return(""); } if (sel.Text.Length == 0) { sel.SelectLine(); } return(sel.Text.Trim()); }
private void HandleException(string exceptionType, string name, int code, string description, ref dbgExceptionAction exceptionAction) { var ex = new ExceptionEvent(); var debugger = Dte.Debugger as Debugger4; if (debugger != null) { //not sure when the current thread could be NULL, but you never know with //the DTE. if (debugger.CurrentThread != null) { foreach (StackFrame dteFrame in debugger.CurrentThread.StackFrames) { ex.StackFrames.Add(TypeConverters.VsStackFrameToStackFrame(dteFrame)); } } } //the stuff inside this try will be null if there isn't an open document //window (rare, but possible) try { TextSelection debugSelection = Dte.ActiveDocument.Selection; debugSelection.SelectLine(); ex.LineContent = debugSelection.Text; ex.LineNumber = debugSelection.CurrentLine; ex.DocumentName = Dte.ActiveDocument.Name; } catch (Exception) { ex.LineContent = string.Empty; ex.LineNumber = 0; ex.DocumentName = Dte.Solution.FullName; } ex.ExceptionAction = (int)exceptionAction; ex.ExceptionCode = code; ex.ExceptionDescription = description; ex.ExceptionName = name; ex.ExceptionType = exceptionType; ex.SolutionName = Dte.Solution.FullName; NotifyEventCreated(this, new EventCreatedArgs(ex)); if (EnableInterventionWindow) { CheckInterventionStatus(); } }
public static void navigate(KnowledgeController controller, Object tag, String sourceFile) { try { log.Debug(" navigation ... "); string regExpression = getRegExpr(tag); if (regExpression == null) { return; } string actualString = getActualString(sourceFile, regExpression); if (actualString == null) { return; } Window textEditor = controller.environment.ApplicationObject.OpenFile(Constants.vsViewKindCode, sourceFile); TextSelection textSelection = (TextSelection)textEditor.Document.Selection; textSelection.StartOfDocument(false); textSelection.EndOfDocument(false); // TODO: textSelection.findPattern doesn't work for some reason if (textSelection.FindText(actualString, (int)vsFindOptions.vsFindOptionsFromStart)) { textSelection.SelectLine(); } else { log.Debug("log. actualString is not found in text file, actualString=" + actualString); } textEditor.Visible = true; textEditor.Activate(); // TODO: save of the document } catch (Exception e0) { MessageBox.Show(e0.Message); } }
public void Execute(object sender, EventArgs args) { var dte2 = (DTE2)Package.GetGlobalService(typeof(SDTE)); if (dte2 != null && dte2.ActiveDocument != null) { var launcher = new PowerShellProjectLauncher(); TextSelection sel = (TextSelection)dte2.ActiveDocument.Selection; if (sel.TopPoint.EqualTo(sel.ActivePoint)) { sel.SelectLine(); launcher.LaunchSelection(sel.Text); } else { launcher.LaunchSelection(sel.Text); } } }
public void Execute(object sender, EventArgs args) { var dte2 = (DTE2)Package.GetGlobalService(typeof(SDTE)); var launcher = new PowerShellProjectLauncher(_validator.Validate()); var file = GetTargetFile(dte2); if (String.IsNullOrEmpty(file)) { return; } Utilities.SaveDirtyFiles(); TextSelection selection = (TextSelection)dte2.ActiveDocument.Selection; // If the selection is completely empty, selected current line and run that. if (string.IsNullOrEmpty(selection.Text)) { selection.SelectLine(); } launcher.LaunchSelection(selection.Text); }
public RequestKeys GetKeys(TextSelection selection) { //Example key //@ApiKey:f568d28a-8280-459d-a21d-80fd82b6cab2,Bot:24@ selection.StartOfDocument(false); selection.SelectLine(); var selectedText = selection.Text; var firstIndex = selectedText.IndexOf('@'); var lastIndex = selectedText.IndexOf('@', firstIndex + 1); var keysPart = selectedText.Substring(firstIndex + 1, lastIndex - (firstIndex + 1)); var keysArray = keysPart.Split(','); var keysList = new List<string>(); for (int i = 0; i < keysArray.Length; i++) { var kvp = keysArray[i].Split(':'); keysList.Add(kvp[1]); } return new RequestKeys { Key = keysList[0], Bot = keysList[1] }; }
public static IActivityEvent FromCommand(string commandName, DTE2 dte) { IActivityEvent oEvent = null; //debugging events if (DebugCommands.Contains(commandName)) { var action = (DebugActions)Enum.Parse(typeof(DebugActions), commandName.Split('.')[1]); var debug = new DebugEvent { SolutionName = dte.Solution.FullName, }; //sometimes document name can be null try { debug.DocumentName = dte.ActiveDocument.Name; } catch (Exception) { debug.DocumentName = dte.Solution.FullName; } //add line number if applicable if (action == DebugActions.StepInto || action == DebugActions.StepOut || action == DebugActions.StepOver ) { //line number can be null if there is no document open try { TextSelection debugSelection = dte.ActiveDocument.Selection; debugSelection.SelectLine(); var lineNumber = debugSelection.CurrentLine; debug.LineNumber = lineNumber; debug.DebugOutput = debugSelection.Text; } catch (Exception) { debug.LineNumber = 0; } } //kind of reappropriating this for our current use. Consider refactoring. debug.ExecutionAction = (int)action; //throw the content of the output window into the event if we just stopped debugging if (action == DebugActions.StopDebugging) { var debugWindow = dte.ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug"); if (debugWindow != null) { var text = debugWindow.TextDocument; var selection = text.Selection; selection.StartOfDocument(); selection.EndOfDocument(true); debug.DebugOutput = selection.Text; selection.EndOfDocument(); } } oEvent = debug; } else if (CutCopyPasteCommands.Contains(commandName)) { var ccp = new CutCopyPasteEvent { SolutionName = dte.Solution.FullName, EventActionId = (int)Enum.Parse(typeof(CutCopyPasteActions), commandName.Split('.')[1]), Content = Clipboard.GetText() }; //sometimes document name can be null try { ccp.DocumentName = dte.ActiveDocument.Name; } catch (Exception) { ccp.DocumentName = dte.Solution.FullName; } oEvent = ccp; } return(oEvent); }
private void _Do_0(Func <string, bool> doneToConfirmContinue = null) { if (string.IsNullOrEmpty(_Namespace)) { MessageBox.Show("Please provide a namespace"); return; } Func <MBColumn, string> _getType = c => { switch (c.Type) { case _Types.t_bit: if (c.Spec.Contains("(1)")) { return((c.Nullable) ? "Nullable<bool>" : "bool"); } return((c.Nullable) ? "Nullable<bool>" : "bool"); case _Types.t_boolean: return((c.Nullable) ? "Nullable<bool>" : "bool"); case _Types.t_tinyint: if (c.Spec.EndsWith("unsigned")) { return((c.Nullable) ? "Nullable<byte>" : "byte"); } return((c.Nullable) ? "Nullable<sbyte>" : "sbyte"); case _Types.t_smallint: if (c.Spec.EndsWith("unsigned")) { return((c.Nullable) ? "Nullable<int>" : "int"); } return((c.Nullable) ? "Nullable<short>" : "short"); case _Types.t_year: return((c.Nullable) ? "Nullable<short>" : "short"); case _Types.t_int: if (c.Spec.EndsWith("unsigned")) { return((c.Nullable) ? "Nullable<long>" : "long"); } return((c.Nullable) ? "Nullable<int>" : "int"); case _Types.t_integer: if (c.Spec.EndsWith("unsigned")) { return((c.Nullable) ? "Nullable<long>" : "long"); } return((c.Nullable) ? "Nullable<int>" : "int"); case _Types.t_mediumint: return((c.Nullable) ? "Nullable<int>" : "int"); case _Types.t_bigint: if (c.Spec.EndsWith("unsigned")) { return((c.Nullable) ? "Nullable<decimal>" : "decimal"); } return((c.Nullable) ? "Nullable<long>" : "long"); case _Types.t_float: if (c.Spec.EndsWith("unsigned")) { return((c.Nullable) ? "Nullable<decimal>" : "decimal"); } return((c.Nullable) ? "Nullable<float>" : "float"); case _Types.t_double: if (c.Spec.EndsWith("unsigned")) { return((c.Nullable) ? "Nullable<decimal>" : "decimal"); } return((c.Nullable) ? "Nullable<double>" : "double"); case _Types.t_real: return((c.Nullable) ? "Nullable<double>" : "double"); case _Types.t_rowversion: return("byte[]"); case _Types.t_numeric: case _Types.t_decimal: case _Types.t_dec: case _Types.t_fixed: case _Types.t_serial: return((c.Nullable) ? "Nullable<decimal>" : "decimal"); case _Types.t_date: case _Types.t_datetime: case _Types.t_datetime2: return((c.Nullable) ? "Nullable<DateTime>" : "DateTime"); case _Types.t_timestamp: if (_Context.IsMySql) { return((c.Nullable) ? "Nullable<DateTime>" : "DateTime"); } return("byte[]"); case _Types.t_datetimeoffset: return((c.Nullable) ? "Nullable<System.DateTimeOffset>" : "System.DateTimeOffset"); case _Types.t_time: return((c.Nullable) ? "Nullable<System.TimeSpan>" : "System.TimeSpan"); case _Types.t_smalldatetime: return((c.Nullable) ? "Nullable<DateTime>" : "DateTime"); case _Types.t_image: return("byte[]"); case _Types.t_money: case _Types.t_smallmoney: return((c.Nullable) ? "Nullable<decimal>" : "decimal"); case _Types.t_uniqueidentifier: return((c.Nullable) ? "Nullable<Guid>" : "Guid"); case _Types.t_char: if (_Context.IsMySql && c.Spec == "char(36)") { // char(36) 被认为是 MySql 的一个标志性实现 return((c.Nullable) ? "Nullable<Guid>" : "Guid"); } return("string"); case _Types.t_varchar: case _Types.t_tinytext: case _Types.t_text: case _Types.t_mediumtext: case _Types.t_longtext: case _Types.t_set: case _Types.t_enum: case _Types.t_nchar: case _Types.t_nvarchar: case _Types.t_ntext: case _Types.t_xml: return("string"); case _Types.t_binary: case _Types.t_varbinary: case _Types.t_tinyblob: case _Types.t_blob: case _Types.t_mediumblob: case _Types.t_longblob: return("byte[]"); case _Types.t_spatial_geometry: return((c.Nullable) ? "Nullable<System.Data.Spatial.DbGeometry>" : "System.Data.Spatial.DbGeometry"); case _Types.t_spatial_geography: return((c.Nullable) ? "Nullable<System.Data.Spatial.DbGeography>" : "System.Data.Spatial.DbGeography"); case _Types.t_sql_variant: return("object"); } return(string.Empty); }; var now = DateTime.Now; var projects = (Array)_App.ActiveSolutionProjects; if (projects.Length > 0) { foreach (Project p in projects) { ProjectItem folder = p.ProjectItems .AddFolder("___ENTITIES", Constants.vsProjectItemKindPhysicalFolder); List <MBTable> tables = _Context.Tables.Where(_Filter).OrderBy(t => t.Name).ToList(); // _App Configure // Start typing _BatchIndex = -1; ProjectItem file = null; Window win = null; TextSelection ts = null; var index = 0; var count = -1; for (int i = 0; i < tables.Count; i++) { index = i / _BatchSize; count++; if (index != _BatchIndex) { // New file and insert at the end line file = folder.ProjectItems.AddFromTemplate( DefaultTemplateFile, string.Format("{0}.{1}.cs", _Identifier, index.ToString("D2"))); win = file.Open(Constants.vsViewKindCode); win.Activate(); win.Document.Activate(); ts = _App.ActiveDocument.Selection as TextSelection; ts.EndOfDocument(); _BatchIndex = index; // Update timestamp ts.Insert(@"/// <summary>"); ts.NewLine(); ts.Insert(string.Format(@"{0}", now.ToString())); ts.NewLine(); ts.Insert(@"</summary>"); ts.NewLine(); ts.SelectLine(); ts.Insert(" "); // namespace ts.Insert("namespace " + _Namespace); ts.NewLine(); ts.Insert("{"); ts.NewLine(); } MBTable t = tables[i]; List <string> keys = new List <string>(); if (! string.IsNullOrEmpty(t.KeyInfo)) { foreach (string part in t.KeyInfo.Split(',')) { if (part.Trim().Length > 0) { keys.Add(part.Trim()); } } } var columns = _Context.Columns .Where(c => c.TableId == t.TableId).OrderBy(c => c.Name).ToList(); var properties = _Context.Properties .Where(d => d.TableId == t.TableId).ToList(); // summary if (_Context.IsMySql) { if (!string.IsNullOrEmpty(t.Caption)) { ts.Insert(@"/// <summary>"); ts.NewLine(); ts.Insert(string.Format(@"{0}", t.Caption.ToStringEx())); ts.NewLine(); ts.Insert(@"</summary>"); ts.NewLine(); ts.SelectLine(); ts.Insert(" "); } } else { properties.SingleOrDefault(d => d.TableId == t.TableId && d.Field == string.Empty && d.Name == FIELD_SUMMARY && !string.IsNullOrEmpty(d.Value)).IfNN(d => { ts.Insert(@"/// <summary>"); ts.NewLine(); ts.Insert(string.Format(@"{0}", d.Value)); ts.NewLine(); ts.Insert(@"</summary>"); ts.NewLine(); ts.SelectLine(); ts.Insert(" "); }); } // tableName ts.Insert("[Serializable]"); ts.NewLine(); ts.Insert(string.Format("[Table(\"{0}\")]", t.Name)); ts.NewLine(); ts.Insert(string.Format("public partial class TB_{0}:TBObject<TB_{0}>{{", t.Name)); ts.NewLine(); //ts.Insert(string.Format("public partial class ET_{0} {{", t.Name)); //ts.NewLine(); columns.ForEach(c => { if (_Context.IsMySql) { if (!string.IsNullOrEmpty(c.Caption)) { ts.Insert(@"/// <summary>"); ts.NewLine(); ts.Insert(string.Format(@"{0}", c.Caption)); ts.NewLine(); ts.Insert(@"</summary>"); ts.NewLine(); ts.SelectLine(); ts.Insert(" "); } } else { // 说明 properties.SingleOrDefault(d => d.TableId == t.TableId && d.Field == c.Name && d.Name == FIELD_SUMMARY && !string.IsNullOrEmpty(d.Value)).IfNN(d => { ts.Insert(@"/// <summary>"); ts.NewLine(); ts.Insert(string.Format(@"{0}", d.Value)); ts.NewLine(); ts.Insert(@"</summary>"); ts.NewLine(); ts.SelectLine(); ts.Insert(" "); }); } if (t.KeyInfo.ToStringEx(string.Empty).Contains(c.Name)) { //var singleKey = !t.KeyInfo.ToStringEx(string.Empty).Contains(","); //if (singleKey && c.Type.Contains("int")) //{ // ts.Insert(@"[Key*]"); // 人为编译不成功,mySql 的问题 //} //else //{ // ts.Insert(@"[Key]"); //} ts.Insert(@"[Key]"); ts.NewLine(); } ts.Insert(string.Format(@"[Column(Order = {0})]", c.Ordinal)); ts.NewLine(); if (c.CharMaxLength.HasValue && !c.Type.Contains("blob") && !c.Type.Contains("long") && !c.Type.Contains("text") //!c.Spec.Contains("char(36)") // guid ) { ts.Insert(string.Format(@"[MaxLength({0})]", c.CharMaxLength)); ts.NewLine(); } var s = "public "; s += _getType(c) + " "; s += c.Name; s += " { get; set; }"; ts.Insert(s); ts.NewLine(); }); ts.Insert("}"); ts.NewLine(); if (doneToConfirmContinue != null) { if (!doneToConfirmContinue(t.Name)) { break; } } if (count == _BatchSize - 1) { ts.Insert("}"); ts.NewLine(); ts.SelectAll(); _App.ExecuteCommand("Edit.FormatDocument"); win.Close(vsSaveChanges.vsSaveChangesYes); count = -1; } } // closing if (count != -1) { ts.Insert("}"); ts.NewLine(); ts.SelectAll(); _App.ExecuteCommand("Edit.FormatDocument"); win.Close(vsSaveChanges.vsSaveChangesYes); count = -1; } } } }
/// <summary> /// Runs custom wizard logic when a project has finished generating. /// </summary> /// <param name="project"></param> public void ProjectFinishedGenerating(Project project) { // Iterate through the project items and // remove any files that begin with the word "Placeholder". // and the Rates class unless it's the Telescope class // done this way to avoid removing items from inside a foreach loop List <string> rems = new List <string>(); foreach (ProjectItem item in project.ProjectItems) { if (item.Name.StartsWith("Placeholder", StringComparison.OrdinalIgnoreCase) || item.Name.StartsWith("Rate", StringComparison.OrdinalIgnoreCase) && !this.DeviceClass.Equals("Telescope", StringComparison.OrdinalIgnoreCase)) { //MessageBox.Show("adding " + item.Name); rems.Add(item.Name); } } foreach (string item in rems) { //MessageBox.Show("Deleting " + item); project.ProjectItems.Item(item).Delete(); } // Special handling for VB and C# driver template projects to add the interface implementation to the core driver code try { // Check the name of each item in the project and execute if this is a driver template project (contains Driver.vb or Driver.cs) foreach (ProjectItem projectItem in project.ProjectItems) { TL.LogMessage("ProjectFinishedGenerating", "Item name: " + projectItem.Name); if ((projectItem.Name.ToUpperInvariant() == "DRIVER.CS") | (projectItem.Name.ToUpperInvariant() == "DRIVER.VB")) { driverTemplate = projectItem; // Save the driver item // This is a driver template // Get the filename and directory of the Driver.xx file string directory = Path.GetDirectoryName(projectItem.FileNames[1].ToString()); TL.LogMessage("ProjectFinishedGenerating", "File name: " + projectItem.FileNames[1].ToString() + ", Directory: " + directory); TL.LogMessage("ProjectFinishedGenerating", "Found " + projectItem.Name); projectItem.Open(); // Open the item for editing TL.LogMessage("ProjectFinishedGenerating", "Done Open"); Document itemDocument = projectItem.Document; // Get the open file's document object TL.LogMessage("ProjectFinishedGenerating", "Created Document"); itemDocument.Activate(); // Make this the current document TL.LogMessage("ProjectFinishedGenerating", "Activated Document"); TextSelection documentSelection = (TextSelection)itemDocument.Selection; // Create a document selection TL.LogMessage("ProjectFinishedGenerating", "Created Selection object"); const string insertionPoint = "//INTERFACECODEINSERTIONPOINT"; // Find the insertion point in the Driver.xx item documentSelection.FindText(insertionPoint, (int)vsFindOptions.vsFindOptionsMatchWholeWord); TL.LogMessage("ProjectFinishedGenerating", "Done INTERFACECODEINSERTIONPOINT FindText:" + documentSelection.Text); // Create the name of the device interface file to be inserted string insertFile = directory + "\\Device" + this.DeviceClass + Path.GetExtension(projectItem.Name); TL.LogMessage("ProjectFinishedGenerating", "Opening file: " + insertFile); documentSelection.InsertFromFile(insertFile); // Insert the required file at the current selection point TL.LogMessage("ProjectFinishedGenerating", "Done InsertFromFile"); // Remove the top lines of the inserted file until we get to #Region // These lines are only there to make the file error free in the template develpment project and are not required here documentSelection.SelectLine(); // Select the current line TL.LogMessage("ProjectFinishedGenerating", "Selected initial line: " + documentSelection.Text); while (!documentSelection.Text.ToUpperInvariant().Contains("#REGION")) { TL.LogMessage("ProjectFinishedGenerating", "Deleting start line: " + documentSelection.Text); documentSelection.Delete(); // Delete the current line documentSelection.SelectLine(); // Select the new current line ready to test on the next loop } // Find the end of file marker that came from the inserted file const string endOfInsertFile = "//ENDOFINSERTEDFILE"; documentSelection.FindText(endOfInsertFile, (int)vsFindOptions.vsFindOptionsMatchWholeWord); TL.LogMessage("ProjectFinishedGenerating", "Done ENDOFINSERTEDFILE FindText:" + documentSelection.Text); // Delete the marker line and the last 2 lines from the inserted file documentSelection.SelectLine(); TL.LogMessage("ProjectFinishedGenerating", "Found end line: " + documentSelection.Text); while (!documentSelection.Text.ToUpperInvariant().Contains("#REGION")) { TL.LogMessage("ProjectFinishedGenerating", "Deleting end line: " + documentSelection.Text); documentSelection.Delete(); // Delete the current line documentSelection.SelectLine(); // Select the new current line ready to test on the next loop TL.LogMessage("ProjectFinishedGenerating", "Found end line: " + documentSelection.Text); } // Reformat the document to make it look pretty documentSelection.SelectAll(); TL.LogMessage("ProjectFinishedGenerating", "Done SelectAll"); documentSelection.SmartFormat(); TL.LogMessage("ProjectFinishedGenerating", "Done SmartFormat"); itemDocument.Save(); // Save the edited file readyfor use! TL.LogMessage("ProjectFinishedGenerating", "Done Save"); itemDocument.Close(vsSaveChanges.vsSaveChangesYes); TL.LogMessage("ProjectFinishedGenerating", "Done Close"); } } // Iterate through the project items and remove any files that begin with the word "Device". // These are the partial device implementations that are merged in to create a complete device driver template by the code above // They are not required in the final project // Done this way to avoid removing items from inside a foreach loop rems = new List <string>(); foreach (ProjectItem item in project.ProjectItems) { if (item.Name.StartsWith("Device", StringComparison.OrdinalIgnoreCase)) { //MessageBox.Show("adding " + item.Name); rems.Add(item.Name); } } foreach (string item in rems) { TL.LogMessage("ProjectFinishedGenerating", "Deleting file: " + item); project.ProjectItems.Item(item).Delete(); } } catch (Exception ex) { TL.LogMessageCrLf("ProjectFinishedGenerating Exception", ex.ToString()); // Log any error message MessageBox.Show(ex.ToString(), "ProjectFinishedGenerating Wizard Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // Show an error message } TL.LogMessage("ProjectFinishedGenerating", "End"); TL.Enabled = false; }
// Collapses all regions in the current document public static void CollapseAllRegions(DTE dte, Language language, MainPackage package, bool showErrors = true) { if (IsSupportedLanguage(language)) { dte.SuppressUI = true; // Disable UI while we do this try { // Outling must be enabled. If Outlining is turned off then the rest of this method will get stuck in an infinite loop. // It can be turned off by default from the C# advanced text editor properties, or it can be turned off by running // the Edit.StopOutlining command (e.g., in the Command window or via Edit -> Outlining -> Stop Outlining). // If the Edit.StartAutomaticOutlining command is available, then that means outlining needs to be turned back on. const string StartOutliningCommand = "Edit.StartAutomaticOutlining"; EnvDTE.Command command = dte.Commands.Item(StartOutliningCommand); if (command.IsAvailable) { dte.ExecuteCommand(StartOutliningCommand); } const string ToggleOutliningExpansion = "Edit.ToggleOutliningExpansion"; command = dte.Commands.Item(ToggleOutliningExpansion); const int MaxAttempts = 3; int maxAttempts = command.IsAvailable ? MaxAttempts : 0; string regionBeginRegex = GetRegionBeginRegex(language); // Sometimes VS can't collapse some regions, so we'll try the whole operation a few times if necessary. bool failedToCollapse = true; for (int attempt = 1; attempt <= maxAttempts && failedToCollapse; attempt++) { failedToCollapse = false; ExpandAllRegions(dte, language); // Force the expansion of all regions TextSelection selection = (TextSelection)dte.ActiveDocument.Selection; // Hook up to the ActiveDocument's selection selection.EndOfDocument(); // Shoot to the end of the document // Find the first occurence of #region from the end of the document to the start of the document. int currentFindOffset = 0; int previousFindOffset = int.MaxValue; const int FindOptions = (int)vsFindOptions.vsFindOptionsBackwards + (int)vsFindOptions.vsFindOptionsMatchCase + (int)vsFindOptions.vsFindOptionsRegularExpression; while (selection.FindText(regionBeginRegex, FindOptions)) { currentFindOffset = selection.TopPoint.AbsoluteCharOffset; if (currentFindOffset >= previousFindOffset) { // I don't want to get stuck in an infinite loop. I'd rather throw if something unexpected happens. throw new InvalidOperationException(string.Format( "FindText did not go backward! Previous offset: {0}; Current offset: {1}.", previousFindOffset, currentFindOffset)); } // We can ignore matches where #region is used inside a string or single line comment. // However, this still won't detect if it's used inside a multiline comment with the opening // delimiter on another line. selection.SelectLine(); string lineText = selection.Text ?? string.Empty; // Make sure the region begin token is the first non-whitespace on the line. Match match = Regex.Match(lineText.TrimStart(), regionBeginRegex); if (match.Success && match.Index == 0) { // The SelectLine call above will leave the end anchor on the next line. If there's no blank line between // a #region line and an XML doc comment after it, then having the end anchor on the line with the // XML doc comment will cause the comment to collapse instead of the #region. So we'll avoid that // by moving back to the find offset. selection.MoveToAbsoluteOffset(currentFindOffset); // Try to increase the chances that the ToggleOutliningExpansion command will be available. selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText); // Collapse this #region. Sometimes VS reports that the Edit.ToggleOutliningExpansion command // isn't available even though it should be. Poke it and give it a little bit of time to sync up. if (!command.IsAvailable) { const int WaitMilliseconds = 20; System.Threading.Thread.Sleep(WaitMilliseconds); int tempOffset = selection.TopPoint.AbsoluteCharOffset; selection.CharRight(); selection.MoveToAbsoluteOffset(tempOffset); System.Threading.Thread.Sleep(WaitMilliseconds); } if (command.IsAvailable) { // If #region is found in a multiline comment, then this will collapse the enclosing block. dte.ExecuteCommand(ToggleOutliningExpansion); } else { // We couldn't collapse a #region. failedToCollapse = true; } } // Move to the start of the last FindText match, so we can continue searching backward from there. selection.MoveToAbsoluteOffset(currentFindOffset); previousFindOffset = currentFindOffset; } selection.StartOfDocument(); // All done, head back to the start of the doc } if (failedToCollapse && package != null && showErrors) { package.ShowMessageBox( "Some regions couldn't be collapsed because Visual Studio's Edit.ToggleOutliningExpansion command wasn't available.", true); } } finally { dte.SuppressUI = false; // Reenable the UI } } }
public static void ApplyPrefeence(DTE2 dte, string region, string controller, string field, string property, string preferredValue) { //string preferredValue = GetMostPreferredValue(region, controller, field, property); List <PreviousPropertyValue> listDefault = new List <PreviousPropertyValue>(); foreach (ProjectItem pi in dte.Solution.Projects.Item(1).ProjectItems) { if (pi.ProjectItems != null) { foreach (ProjectItem p in pi.ProjectItems) { if (p.Name.EndsWith(".Designer.cs")) { p.Open(EnvDTE.Constants.vsViewKindCode); p.Document.Activate(); TextSelection ts = (TextSelection)dte.ActiveDocument.Selection; TextSelection ts2 = (TextSelection)dte.ActiveDocument.Selection; string srchPattern1 = "new System.Windows.Forms.Button();"; EnvDTE.TextRanges textRanges = null; ts.StartOfDocument(false); int count = 0; string nameLine = ""; string name = ""; string[] np = new string[50]; while (ts.FindPattern(srchPattern1, 0, ref textRanges)) { ts.SelectLine(); nameLine = ts.Text; count++; string[] sp = nameLine.Split('.'); string spi = sp[1]; string[] sp2 = spi.Split('='); name = sp2[0]; np[count] = name; } int i = 1; while (ts2.FindPattern(".BackColor = System.Drawing.Color", 0, ref textRanges)) { PreviousPropertyValue def = new PreviousPropertyValue(); ts2.SelectLine(); string codeLine = ts2.Text; codeLine = codeLine.Trim(); foreach (string s in np) { string ss = s; if (ss != null) { ss = ss.Trim(); if (codeLine.Contains(ss) == true) { ts2.ReplacePattern(codeLine, "this." + s + ".BackColor = System.Drawing.Color." + preferredValue + ";", 0, ref textRanges); np = np.Where(w => w != s).ToArray(); def.FileName = p.Name; def.ControllerType = controller; def.Property = property; def.ControllerName = ss; def.DefaultValue = codeLine; listDefault.Add(def); } //else //{ // ts2.LineDown(); // ts2.NewLine(); // ts2.Insert("this." + np[i] + ".BackColor = System.Drawing.Color." + preferredValue + ";"); //} //def.FileName = p.Name; //def.ControllerType = controller; //def.Property = property; //def.ControllerName = ss; //def.DefaultValue = codeLine; //listDefault.Add(def); } } //i++; } if (np != null) { foreach (string s in np) { if (s != null) { ts2.EndOfLine(); ts2.NewLine(); ts2.Insert("this." + np[i] + ".BackColor = System.Drawing.Color." + preferredValue + ";"); np = np.Where(w => w != s).ToArray(); } } } SaveDefaultValues(listDefault); dte.ActiveDocument.Save(p.Document.FullName); dte.ActiveDocument.Close(vsSaveChanges.vsSaveChangesNo); } } } } }
public static bool ChangeToPreveiousValue(DTE2 dte, string controller, string property) { List <PreviousPropertyValue> listDefault = new List <PreviousPropertyValue>(); List <PreviousPropertyValue> list = LoadDefaultValues(); if (list == null) { return(false); } else { foreach (ProjectItem pi in dte.Solution.Projects.Item(1).ProjectItems) { if (pi.ProjectItems != null) { foreach (ProjectItem p in pi.ProjectItems) { if (p.Name.EndsWith(".Designer.cs")) { p.Open(EnvDTE.Constants.vsViewKindCode); p.Document.Activate(); TextSelection ts2 = (TextSelection)dte.ActiveDocument.Selection; EnvDTE.TextRanges textRanges = null; ts2.StartOfDocument(false); //Find2 findWin = (Find2)dte.Find; int count = 0; //c = findWin.FindReplace(vsFindAction.vsFindActionFindAll, "button1", 0); string s = ""; string name = ""; string[] np = new string[50]; // Advance to the next Visual Basic function beginning or end by // searching for "Sub" with white space before and after it. //while //while (ts.FindPattern(srchPattern1, 0, ref textRanges)) //{ // // // Select the entire line. // count++; // ts.SelectLine(); // s = ts.Text; // string[] sp = s.Split('.'); // string spi = sp[1]; // string[] sp2 = spi.Split('='); // name = sp2[0]; // np[count] = name; // //ts.FindPattern("this." + name + ".BackColor = System.Drawing.Color", 0, ref textRanges); // //ts.SelectLine(); // //s = ts.Text; // //ts2.StartOfDocument(false); // //while (ts.FindText("this." + name + ".BackColor = System.Drawing.Color", 0)) // //{ // // ts.SelectLine(); // // string sd = ts.Text; // // bool t = ts.ReplacePattern(sd, "this.button1.BackColor = System.Drawing.Color.Red;", 0, ref textRanges); // //} //} int i = 1; //for(int i=1; i<=5;i++) //{ //ts2 = null; while (ts2.FindPattern(".BackColor = System.Drawing.Color", 0, ref textRanges)) { ts2.SelectLine(); string sd = ts2.Text; sd = sd.Trim(); foreach (PreviousPropertyValue dfcon in list) { if (dfcon.FileName == p.Name && sd.Contains(dfcon.ControllerName) && dfcon.Property == property && dfcon.ControllerType == controller) { ts2.ReplacePattern(sd, dfcon.DefaultValue, 0, ref textRanges); } i++; //} } } //ts.NewLine(1); dte.ActiveDocument.Save(p.Document.FullName); dte.ActiveDocument.Close(vsSaveChanges.vsSaveChangesNo); } } } } return(true); } }
/// <summary> /// Removes the header. /// </summary> /// <param name="instance">The instance.</param> public static void RemoveHeader(this ProjectItem instance) { TraceService.WriteLine("ProjectItemExtensions::RemoveHeader Name=" + instance.Name); if (instance.IsCSharpFile()) { Window window = instance.Open(VSConstants.VsViewKindCode); if (window != null) { try { window.Activate(); } catch (Exception exception) { ///// i think this happens when i am debugging (i could be wrong!) TraceService.WriteError("Cant Remove Header Window Activate wont work exception=" + exception.Message); return; } TextSelection selection = (TextSelection)instance.Document.Selection; bool continueLoop = true; int loopCounter = 0; do { //// just in case we get infinity loop problem! if (loopCounter > 100) { TraceService.WriteLine("breaking out of loop"); continueLoop = false; } selection.GotoLine(1, true); selection.SelectLine(); TraceService.WriteLine("text=" + selection.Text); if (selection.Text.TrimStart().StartsWith("//")) { TraceService.WriteLine("*** deleting selection"); selection.Delete(); loopCounter++; } else { TraceService.WriteLine("*** NOT deleting selection"); continueLoop = false; } }while (continueLoop); } } //// don't forget sub items. if (instance.ProjectItems != null) { IEnumerable <ProjectItem> subProjectItems = instance.GetCSharpProjectItems(); foreach (ProjectItem subProjectItem in subProjectItems) { subProjectItem.RemoveHeader(); } } }
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { try { if (VsShellUtilities.IsInAutomationFunction(m_provider.ServiceProvider)) { return(m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut)); } // make a copy of this so we can look at it after forwarding some commands uint commandID = nCmdID; char typedChar = char.MinValue; // make sure the input is a char before getting it if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR) { typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); } if (m_dte != null) { string currentLine = m_textView.TextSnapshot.GetLineFromPosition( m_textView.Caret.Position.BufferPosition.Position).GetText(); // check for the Javadoc slash and two asterisk pattern while compensating for visual studio's block comment closing generation if (typedChar == '*' && currentLine.Trim() == "/**/") { // Calculate how many spaces string spaces = currentLine.Replace(currentLine.TrimStart(), ""); TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection; //Remember where the cursor was when command was triggered int oldLine = ts.ActivePoint.Line; int oldOffset = ts.ActivePoint.LineCharOffset; ts.LineDown(); ts.EndOfLine(); ts.SelectLine(); //Detect and skip over Unreal Engine Function Macros string trimmedFuncLine = ts.Text.Trim(); if (trimmedFuncLine != "" && trimmedFuncLine.StartsWith("UFUNCTION(")) { ts.EndOfLine(); } else { ts.MoveToLineAndOffset(oldLine, oldOffset); ts.LineDown(); ts.EndOfLine(); } CodeElement codeElement = null; FileCodeModel fcm = m_dte.ActiveDocument.ProjectItem.FileCodeModel; if (fcm != null) { codeElement = fcm.CodeElementFromPoint(ts.ActivePoint, vsCMElement.vsCMElementFunction); } if (codeElement != null && codeElement is CodeFunction) { CodeFunction function = codeElement as CodeFunction; StringBuilder sb = new StringBuilder("*"); bool isNoArgsNoReturn = true; foreach (CodeElement child in codeElement.Children) { CodeParameter parameter = child as CodeParameter; if (parameter != null) { sb.AppendFormat("\r\n" + spaces + " * @param {0} ", parameter.Name); isNoArgsNoReturn = false; } } if (function.Type.AsString != "void") { isNoArgsNoReturn = false; if (function.Type.AsString == "bool") { sb.AppendFormat("\r\n" + spaces + " * @return true \r\n" + spaces + " * @return false "); } else { sb.AppendFormat("\r\n" + spaces + " * @return "); } } //If function has a return type or parameters then we generate them and return, otherwise we skip to generate a single line comment if (!isNoArgsNoReturn) { sb.Insert(1, "\r\n" + spaces + " * "); sb.AppendFormat("\r\n" + spaces + " "); ts.MoveToLineAndOffset(oldLine, oldOffset); ts.Insert(sb.ToString()); ts.MoveToLineAndOffset(oldLine, oldOffset); ts.LineDown(); ts.EndOfLine(); return(VSConstants.S_OK); } } //For variables and void functions with no parameters we can do a single line comment ts.MoveToLineAndOffset(oldLine, oldOffset); ts.Insert("* "); ts.MoveToLineAndOffset(oldLine, oldOffset + 2); return(VSConstants.S_OK); } else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN) { //Get text on current line before and after cursor TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection; int oldLine = ts.ActivePoint.Line; int oldOffset = ts.ActivePoint.LineCharOffset; ts.EndOfLine(true); string afterCursor = ts.Text; ts.MoveToLineAndOffset(oldLine, oldOffset); ts.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, true); string beforeCursor = ts.Text; string beforeCursorTrimmed = beforeCursor.TrimStart(); ts.MoveToLineAndOffset(oldLine, oldOffset); // Calculate how many spaces string spaces = beforeCursorTrimmed == "" ? beforeCursor : beforeCursor.Replace(beforeCursorTrimmed, ""); bool hasAsteriskBeforeCursor = beforeCursorTrimmed == "" ? false : beforeCursorTrimmed.StartsWith("* "); bool hasBlockTerminatorAfterCursor = afterCursor == "" ? false : afterCursor.EndsWith("*/"); bool hasBlockTerminatorDirectlyAfterCursor = hasBlockTerminatorAfterCursor && afterCursor.Trim() == "*/"; //Add a space to maintain correct asterisk alignment if needed if (beforeCursorTrimmed != "" && beforeCursorTrimmed.StartsWith("/*")) { hasAsteriskBeforeCursor = true; spaces += " "; } if (hasAsteriskBeforeCursor) { ts.Insert("\r\n" + spaces); if (!hasBlockTerminatorAfterCursor) { ts.Insert("* "); } else if (hasBlockTerminatorDirectlyAfterCursor) { ts.Delete(afterCursor.Length); ts.Insert("*/"); ts.MoveToLineAndOffset(ts.ActivePoint.Line, ts.ActivePoint.LineCharOffset - 2); } return(VSConstants.S_OK); } else if (hasBlockTerminatorAfterCursor) { ts.Insert("* \r\n" + spaces); if (hasBlockTerminatorDirectlyAfterCursor) { ts.Delete(afterCursor.Length); ts.Insert("*/"); ts.MoveToLineAndOffset(ts.ActivePoint.Line, ts.ActivePoint.LineCharOffset - 2); } return(VSConstants.S_OK); } } } // pass along the command so the char is added to the buffer return(m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut)); } catch { } return(VSConstants.E_FAIL); }
private bool handleStackUrl(WebBrowserNavigatingEventArgs e) { string line = e.Url.ToString(); if (line.StartsWith(STACKLINE_URL_TYPE) && line.LastIndexOf(STACKLINE_LINE_NUMBER_SEPARATOR) != -1) { List <ProjectItem> files = new List <ProjectItem>(); string file = line.Substring(STACKLINE_URL_TYPE.Length, line.LastIndexOf(STACKLINE_LINE_NUMBER_SEPARATOR) - STACKLINE_URL_TYPE.Length); foreach (Project project in solution.Projects) { matchProjectItemChildren(file, files, project.ProjectItems); } if (files.Count == 0) { MessageBox.Show("No matching files found for " + file, "Error"); Debug.WriteLine("No matching files found for " + file); } else if (files.Count > 1) { MessageBox.Show("Multiple matching files found for " + file, "Error"); Debug.WriteLine("Multiple matching files found for " + file); } else { string lineNoStr = line.Substring(line.LastIndexOf(STACKLINE_LINE_NUMBER_SEPARATOR) + 1); try { int lineNo = int.Parse(lineNoStr); if (lineNo < 0) { throw new ArgumentException(); } Debug.WriteLine("opening file " + file + " at line number " + lineNo); Window w = files[0].Open(Constants.vsViewKindCode); w.Visible = true; w.Document.Activate(); TextSelection sel = w.DTE.ActiveDocument.Selection as TextSelection; if (sel != null) { sel.SelectAll(); sel.MoveToLineAndOffset(lineNo, 1, false); sel.SelectLine(); } else { throw new Exception("Cannot get text selection for the document"); } } catch (Exception ex) { MessageBox.Show("Unable to open the specified file: " + ex.Message, "Error"); Debug.WriteLine(ex); } } e.Cancel = true; return(true); } return(false); }