Документ взят из кэша поисковой машины. Адрес оригинального документа : http://old.hcs.cmc.msu.ru/lectures/OOPS_01_2008_04_23.pdf
Дата изменения: Fri Apr 25 00:30:41 2008
Дата индексирования: Mon Oct 1 22:21:24 2012
Кодировка:
- Visual Studio
1.
, . .. romsrcc@rom.srcc.msu.su, vladimir.romanov@gmail.com


Visual Studio.


Visual Studio. ,


: , UML ,


Visual Studio
: , , ...

Extensibility :: IDTExtensibility2 EnvDTE :: DTE_ EnvDTE :: IDTCommandTarget

application EnvDTE80 :: DTE2

Connect

addInInst EnvDTE :: AddIn

Visual Studio




IDTExtensibility2.
: , , ...

Extensibility :: IDTExtensibility2 EnvDTE :: DTE_ EnvDTE :: IDTCommandTarget

application EnvDTE80 :: DTE2

Connect

addInInst EnvDTE :: AddIn

Visual Studio




IDTExtensibility2.
void OnConnection(object Application, ext_ConnectMode ConnectMode, object AddInInst, ref Array custom); VisualStudio void OnDisconnection(ext_DisconnectMode RemoveMode, ref Array custom); VisualStudio void OnAddInsUpdate(ref Array custom); void OnBeginShutdown(ref Array custom); VisualStudio void OnStartupComplete(ref Array custom); VisualStudio


VisualStudio
using using using using System; Extensibility; EnvDTE; EnvDTE80;

Visual Studio

namespace LoadingTrace { public class Connect : IDTExtensibility2 private DTE2 _applicationObject; private AddIn _addInInstance; {



public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE2) application; _addInInstance = (AddIn) addInInst; } public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom) {} // ... }


OutputWindow
private OutputWindowPane output; Output public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE2) application; LoadingTrace _addInInstance = (AddIn) addInInst; try { this.output = _applicationObject.ToolWindows.OutputWindow. OutputWindowPanes.Item("LoadingTrace"); } catch { this.output = _applicationObject.ToolWindows.OutputWindow. OutputWindowPanes.Add("LoadingTrace"); } this.output.OutputString("OnConnection event fired\n"); } LoadingTrace

public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom) { this.output.OutputString("OnDisconnection event fired\n"); }


. Output
Output

LoadingTrace Output


. (1)
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE2) application; Visual Studio _addInInstance = (AddIn) addInInst; if (connectMode == ext_ConnectMode.ext_cm_UISetup) { Commands2 commands = (Commands2) _applicationObject.Commands; CommandBar menuBarCommandBar = ((CommandBars)_applicationObject.CommandBars) ["MenuBar"]; CommandBarControl toolsControl = menuBarCommandBar.Controls["Tools"];

Visual Studio

Tools

Tools
CommandBarPopup toolsPopup = (CommandBarPopup) toolsControl;


. (2)
try { string name = "Build"; // . string text = "Build Zonnon Project"; // . string tooltip = "Compile project files with the znn file extention"; int status = (int) vsCommandStatus.vsCommandStatusSupported + (int) vsCommandStatus.vsCommandStatusEnabled; int style = (int) vsCommandStyle.vsCommandStylePictAndText;

vsCommandControlType controlType = vsCommandControlType.vsCommandControlTypeButton; object []contextGUIDS = new object[] { }; Command command = commands.AddNamedCommand2 (_addInInstance, name, text, tooltip, true, 59, // 59- ­ ! ref contextGUIDS, status, style, controlType); if ((command != null) && (toolsPopup != null)) command.AddControl(toolsPopup.CommandBar, 1); }


Tools

59


Tools

3


IDTCommandTarget
: , , ...

Extensibility :: IDTExtensibility2 EnvDTE :: DTE_ EnvDTE :: IDTCommandTarget

application EnvDTE80 :: DTE2

Connect

addInInst EnvDTE :: AddIn

Visual Studio




IDTCommandTarget.

public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status, ref object commandText) { if (neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone) { if (commandName == "CommandExecution.Connect.Build") { status = (vsCommandStatus) vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusEnabled; } } }


IDTCommandTarget.

public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, // ref object varOut, // . ref bool handled) { handled = false; if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault) { if (commandName == "CommandExecution.Connect.Build") { handled = true; MessageBox.Show("command: " + commandName, "Trace", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }


IDTCommandTarget.



ToolWindow.
(1)
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE2) application; _addInInstance = (AddIn) addInInst; string string string string guidstr = "{858C3FCD-8B39-4540-A592-F31C1520B174}"; assemblyPath = typeof(Panel).Assembly.Location; classname = "System.Windows.Forms.Panel"; caption = "Window with empty panel";

object ctlobj = null; Windows2 windows2 = (Windows2)_applicationObject.Windows; Window toolWindow = windows2.CreateToolWindow2 (_addInInstance, assemblyPath, classname, caption, guidstr, ref ctlobj);


ToolWindow.
(2)
Panel panel = ctlobj as Panel; panel.BackColor = Color.CadetBlue; panel.Dock = DockStyle.Fill; panel.BorderStyle = BorderStyle.FixedSingle; _windowToolWindow.Visible = true; }

­ Panel


ToolWindow.




ToolWindow.




ToolWindow.




.
(1)
BuildEvents buildEvents; SolutionEvents solutionEvents; public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE2) application; _addInInstance = (AddIn) addInInst; buildEvents = _applicationObject.Events.BuildEvents; buildEvents.OnBuildBegin += new _dispBuildEvents_OnBuildBeginEventHandler(buildEvents_OnBuildBegin); solutionEvents = _applicationObject.Events.SolutionEvents; solutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(solutionEvents_Opened); }


.
(2)
void solutionEvents_Opened() { MessageBox.Show(_applicationObject.Solution.FullName, "Solution Opened trace", MessageBoxButtons.OK, MessageBoxIcon.Information); } void buildEvents_OnBuildBegin(vsBuildScope Scope, vsBuildAction Action) { MessageBox.Show(_applicationObject.Solution.FullName, "Build Begin trace", MessageBoxButtons.OK, MessageBoxIcon.Information); }


.


WindowsCreate


.


WindowsCreate


.

namespace ProjectBrowser { class SolutionBrowser { public OutputWindowPane output; public void iterateSolution(Solution solution) { if (solution == null) return; string sFileName = solution.FileName; foreach (Project pr in solution.Projects) iterateProject(pr); } // IterateSolution


.

public void iterateProject(Project project) { String name = project.Name; String fileName = project.FileName; String fullName = project.FullName; ProjectItems pis = project.ProjectItems; if (pis == null) return; foreach(ProjectItem pri in pis) iterateProjectItem(pri); } // iterateProject


.

public void iterateProjectItem(ProjectItem projectItem) { string priName = projectItem.Name; Property FullPath = projectItem.Properties.Item("FullPath"); string fullPath = FullPath.Value as string; ProjectItems pis = projectItem.ProjectItems; if (pis == null) return; foreach (ProjectItem pri in pis) iterateProjectItem(pri); output.OutputString(fullPath + "\n"); } }





.

UML



MenuBar


. Tools
ErrorListDemo

UML



Tools


.




.




.

string menuBar = "MenuBar"; string commandName = "GetAllCommandBars"; l string commandText = "UML"; Visual Studio object[] contextGUIDS = new object[] { }; Commands2 commands = (Commands2)vs.Commands; try { Command command = commands.AddNamedCommand2 (_addInInstance, commandName, commandText, "Executes the command for GetAllCommandBars", true, 41, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); _CommandBars cmdBars = (_CommandBars)vs.CommandBars; CommandBar cmdBar = cmdBars[menuBar]; command.AddControl(cmdBar, 4);


.

UML



MenuBar


.

_CommandBars cmdBars = (_CommandBars)vs.CommandBars; List bars = new List(); IEnumerator e = cmdBars.GetEnumerator(); while (e.MoveNext()) { CommandBar cmb = (CommandBar) e.Current; bars.Add(cmb.Name); } bars.Sort(); try { outputWin = vs.ToolWindows.OutputWindow. OutputWindowPanes.Item("All Command Bars"); } catch { outputWin = vs.ToolWindows.OutputWindow. OutputWindowPanes.Add("All Command Bars"); } foreach (string s in bars) outputWin.OutputString(s + Environment.NewLine);


.




.

string commandText = "Zonnon Refactoring"; string menuBar = "Code Window"; object[] contextGUIDS = new object[] { }; Commands2 commands = (Commands2)vs.Commands; try { Command command = commands.AddNamedCommand2(_addInInstance, "CodeWinContextMenuCS", commandText, "Executes the command for CodeWinContextMenuCS", true, 40, // .... ); _CommandBars cmdBars = (_CommandBars)vs.CommandBars; CommandBar cmdBar = cmdBars[menuBar]; command.AddControl(cmdBar, 2); }


.



.

public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled) { if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault) { if (commandName == "CodeWinContextMenuCS.Connect.CodeWinContextMenuCS") { handled = true; Window w = vs.ActiveDocument.ActiveWindow; TextWindow textWindow = (TextWindow) w.Object; TextPane textPane = textWindow.ActivePane; string selectedText = textPane.Selection.Text; MessageBox.Show(selectedText + " is selected in the file: " + vs.ActiveDocument.Name, "Command: " + "Zonnon Refactor");


.



.

string commandText = "Project Item update"; string menuBar = "Item"; object[] contextGUIDS = new object[] { }; Commands2 commands = (Commands2)vs.Commands; try { Command command = commands.AddNamedCommand2(_addInInstance, "CodeWinContextMenuCS", commandText, "Executes the command for CodeWinContextMenuCS", true, 42, // .... ); _CommandBars cmdBars = (_CommandBars)vs.CommandBars; CommandBar cmdBar = cmdBars[menuBar]; command.AddControl(cmdBar, 2); }


.



. (ErrorList)


. (Output Window)


VS.
private OutputWindowPane output; private TaskListEvents list; public MessageHandlerOutput(DTE2 dte, string tabName) { this.dte = dte; OutputWindow window = dte.ToolWindows.OutputWindow;



try { output = window.OutputWindowPanes.Item(tabName); } catch { output = window.OutputWindowPanes.Add(tabName); } Events events = dte.Application.Events; list = (TaskListEvents) events.get_TaskListEvents(""); list.TaskNavigated += new _dispTaskListEvents_TaskNavigatedEventHandler(list_TaskNavigated); }


VS.
public void outError(string fileName, int line, vsTaskPriority priority, string outputMessage, string errorListMessage) { FileInfo fi = new FileInfo(fileName); string mess = "" + fi.Name + ": [" + line + "] " + outputMessage + "\n"; output.OutputTaskItemString (mess, priority, "cocor", EnvDTE.vsTaskIcon.vsTaskIconNone, fileName, line, errorListMessage, true); }



VS.
void list_TaskNavigated(TaskItem taskItem, ref bool NavigateHandled) { if (taskItem.FileName == "") return; Window fileWindow = dte.Application.ItemOperations.OpenFile (taskItem.FileName, Constants.vsViewKindTextView); TextWindow textWindow = (TextWindow) fileWindow.Object; TextPane textPane = textWindow.ActivePane; textPane.Selection.MoveTo(taskItem.Line, 1, false); textPane.Selection.SelectLine(); NavigateHandled = true; } // list_TaskNavigated




VS.

SolutionBrowser sb = new SolutionBrowser(); sb.iterateSolution(vs.Solution); MessageHandlerOutput mho = new MessageHandlerOutput(vs, "ErrorListDemo"); foreach (string fileName in sb.files) { mho.outError(fileName, 1, vsTaskPriority.vsTaskPriorityHigh, "Error message in error list", "Error message in output window"); mho.outError(fileName, 1, vsTaskPriority.vsTaskPriorityMedium, "Warning message in error list", "Warning message in output window"); mho.outError(fileName, 1, vsTaskPriority.vsTaskPriorityLow, "Info message in error list", "Info message in output window"); } // foreach


.


.


.
-
Window CreateEmptyWindow(string caption, ref Panel panel, string guid) { string assemblyPath = typeof(Panel).Assembly.Location; string classname = "System.Windows.Forms.Panel"; object ctlobj = null; Windows2 windows2 = (Windows2)vs.Windows; window = windows2.CreateToolWindow2(_addInInstance, assemblyPath, classname, caption, guidstr, ref ctlobj); panel = ctlobj as Panel; panel.BackColor = Color.CadetBlue; panel.Dock = DockStyle.Fill; panel.BorderStyle = BorderStyle.FixedSingle; window.Visible = true; return window; }


.

void CreateMetricsWindow() { Panel panel = null; string caption = "File Metrics Window"; string guidstr = "{BB91E243-3D2B-4609-A98F-23CE95FDA33D}"; window = CreateEmptyWindow(caption, ref panel, guidstr); ListView lv = new ListView(); lv.Parent = panel; lv.Dock = DockStyle.Fill; lv.View = View.Details; - -

lv.Columns.Add("Name", 100, HorizontalAlignment.Left); lv.Columns.Add("Length", 100, HorizontalAlignment.Right); lv.Columns.Add("LOC", 100, HorizontalAlignment.Right); lv.Columns.Add("Path", 100, HorizontalAlignment.Left); LoadFileMetrics(lv);


.
(1)
private void LoadFileMetrics(ListView lv) { SolutionBrowser sb = new SolutionBrowser(); sb.iterateSolution(this.vs.Solution); foreach (string pe in sb.files) { if (!pe.EndsWith(".cs")) continue; if (!File.Exists(pe)) continue;

­

FileInfo fi = new FileInfo(pe); ListViewItem lvi = new ListViewItem(fi.Name); // ---- Length ---lvi.SubItems.Add("" + fi.Length); ­


.
(2)
StreamReader sr = fi.OpenText(); string text = sr.ReadToEnd(); int loc = 0; foreach (char c in text) if (c == '\n') loc++; // ---- Lines of code ---lvi.SubItems.Add("" + loc); // ---- Path ---lvi.SubItems.Add("" + fi.FullName); lv.Items.Add(lvi); } // foreach } // CreateMetricsWindow

­


.


.

lv.Click += new EventHandler(lv_Click); lv.ColumnClick += new ColumnClickEventHandler(lv_ColumnClick); void lv_ColumnClick(object sender, ColumnClickEventArgs e) { string text = lv.Columns[e.Column].Text; MessageBox.Show(text + "[" + e.Column + "]", "ColumnClick", MessageBoxButtons.OK, MessageBoxIcon.Information); } void lv_Click(object sender, EventArgs e) { foreach(ListViewItem lvi in lv.SelectedItems) { MessageBox.Show(lvi.Text + " is selected!", "Click", MessageBoxButtons.OK, MessageBoxIcon.Information); } }


.


.



RichTextBox rtb; public void CreateLanguageWindow(string fileName) { Panel panel = null; string caption = "File " + fileName; string guidstr = "{46319E9B-E144-438c-A8DC-683DD55F84B9}"; window = CreateEmptyWindow(caption, ref panel, guidstr); rtb = new RichTextBox(); rtb.Parent = panel; rtb.Dock = DockStyle.Fill; rtb.LoadFile(fileName, RichTextBoxStreamType.PlainText); ZonnonPainter zp = new ZonnonPainter(rtb); zp.paint(); } // CreateLanguageWindow


. Zonnon
public class ZonnonPainter { private List keywords = new List(); private RichTextBox rtb; private int pos = 0; private string text; public ZonnonPainter(RichTextBox rtb) { this.rtb = rtb; keywords.Add( keywords.Add( keywords.Add( keywords.Add( keywords.Add( } "begin"); "end"); "string"); "module"); "var"); Zonnon


.
private bool stepOnIdent(ref int idPos, ref int idLen) { while ((pos < text.Length) && (!Char.IsLetter(text[pos]))) pos++; if (pos >= text.Length) return false; idPos = pos; idLen = 0; while ((pos < text.Length) && (Char.IsLetterOrDigit(text[pos]))) { pos++; idLen++; } return true; } // stepOnIdent


.
private bool stepOnString(ref int idPos, ref int idLen) { while ((pos < text.Length) && (text[pos] != '"')) pos++; if (pos >= text.Length) return false; idPos = pos; idLen = 1; pos++; // " while ((pos < text.Length) && (text[pos] != '"')) { pos++; idLen++; } pos++; idLen++; // " return true; } // stepOnString


.
public void paint() { text = rtb.Text; int idPos = 0, idLen = 0; pos = 0; while (stepOnIdent(ref idPos, ref idLen)) { if (keywords.Contains( text.Substring(idPos, idLen)) ) { rtb.Select(idPos, idLen); rtb.SelectionColor = Color.Blue; } // if } // while int sPos = 0, sLen = 0; pos = 0; while (stepOnString(ref sPos, ref sLen)) { rtb.Select(sPos, sLen); rtb.SelectionColor = Color.Red; } // while } // paint


Zonnon


UML .
Label node1, node2; public void CreateGraphWindow() { Panel panel = null; string caption = "Diagram Editor "; string guidstr = "{46319E9B-E144-438c-A8DC-683DD55F84B9}"; window = CreateEmptyWindow(caption, ref panel, guidstr); panel.BackColor = Color.White; node1 = new Label(); node1.Parent = panel; node2 = new Label(); node2.Parent = panel;


UML .
node1.BackColor = Color.Yellow; node1.Top = 20; node1.Left = 30; node1.Text = "Point"; node1.BorderStyle = BorderStyle.FixedSingle; node1.TextAlign = ContentAlignment.MiddleCenter; node2.BackColor = Color.Yellow; node2.Top = 120; node2.Left = 130; node2.Text = "Rectangle"; node2.BorderStyle = BorderStyle.FixedSingle; node2.TextAlign = ContentAlignment.MiddleCenter; panel.Paint += new PaintEventHandler(panel_Paint); }


UML .
void panel_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawLine( Pens.Blue, (node1.Left + node1.Right) / 2, (node1.Top + node1.Bottom) / 2, (node2.Left + node2.Right) / 2, (node2.Top + node2.Bottom) / 2); } // CreateLanguageWindow





.
public class Node : Label { public Node(string name) { Text = name; BackColor = Color.Yellow; BorderStyle = BorderStyle.FixedSingle; TextAlign = ContentAlignment.MiddleCenter; } }


.
public class Edge { Node n1, n2; public Edge(Node n1, Node n2) { this.n1 = n1; this.n2 = n2; } public void draw(Graphics g) { g.DrawLine( Pens.Blue, (n1.Left + n1.Right) / 2, (n1.Top + n1.Bottom) / 2, (n2.Left + n2.Right) / 2, (n2.Top + n2.Bottom) / 2); } }


.
public class Graph { public List nodes = new List(); public List edges = new List(); public void draw(Graphics g) { foreach(Edge e in edges) e.draw(g); } public Node getNode(int x, int y) { foreach (Node n in nodes) { if (n.Top < y) continue; if (n.Bottom > y) continue; if (n.Left < x) continue; if (n.Right > x) continue; return n; } return null; } // getNode } // class Graph


. (1)
Node n1 = new Node("View"); Node n2 = new Node("Node"); Node n3 = new Node("Edge"); n1.Parent = panel; n2.Parent = panel; n3.Parent = panel; graph.nodes.Add(n1); graph.nodes.Add(n2); graph.nodes.Add(n3);


. (2)
n1.Top = 100; n2.Top = 200; n3.Top = 200; n1.Left = 200; n2.Left = 100; n3.Left = 300; graph.edges.Add(new Edge(n1, n2)); graph.edges.Add(new Edge(n1, n3)); panel.Paint += new PaintEventHandler(panel_Paint2); } void panel_Paint2(object sender, PaintEventArgs e) { graph.draw(e.Graphics); }