Friday, March 27, 2009

Visual Studio Macros for source control.

Visual Studio allows for users to customize the environment by writing macros. With Visual Studio 2008 the macros can be written in VB.Net. VB.Net is a very powerful language as it can use any of the standard .NET object, and in addition it has access to Visual Studios ENVDTE object.

The following set of macros replace the buggy Perforce source control plugin.


Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics

Public Module MiscCommands
Sub P4Add()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "add " + filename)
End Sub

Sub P4Edit()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "edit " + filename)
End Sub

Sub P4Diff()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "diff " + filename)
End Sub

Sub P4Revert()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "revert " + filename)
End Sub

Sub P4Opened()
ChDir("c:\p4")
ExecuteCommand("p4.exe", "opened")
End Sub

Sub P4History()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "filelog " + filename)
End Sub

Public Sub ExecuteCommand(ByVal filename As String, ByVal arguments As String)

Dim p As New System.Diagnostics.Process
p.StartInfo.UseShellExecute = False
p.StartInfo.FileName = filename
p.StartInfo.Arguments = arguments
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.RedirectStandardError = True
p.Start()
p.WaitForExit()


WriteToMyNewPane(filename + " " + arguments, p.StandardOutput.ReadToEnd + p.StandardError.ReadToEnd)


End Sub

Public Sub WriteToMyNewPane(ByVal command As String, ByVal results As String)
Dim win As Window = _
DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
Dim ow As OutputWindow = win.Object
Dim owPane As OutputWindowPane
Dim cnt As Integer = ow.OutputWindowPanes.Count
owPane = ow.OutputWindowPanes.Item(1)
owPane.OutputString(command & vbCrLf)
owPane.OutputString(results & vbCrLf)
owPane.Activate()
End Sub


Sub OpenFile()
Dim fileName As String = InputBox("Open file:")
If String.IsNullOrEmpty(fileName) Then
Return
End If
Dim item As EnvDTE.ProjectItem = DTE.Solution.FindProjectItem(fileName)
If item Is Nothing Then
MsgBox("File not found", MsgBoxStyle.Exclamation)
Return
End If
item.Open()
item.Document.Activate()
End Sub

End Module

No comments: