日期:2013-08-06  浏览次数:20622 次


运行环境: Visual Studio .NET


介绍
我们每一个从原有的开发环境转移到VS.NET下的用户,都遭遇到不少的阻碍.我所碰到的一个障碍就是:我原有的那些macro无法继续工作了.

现在的这个编译序列号自动增长工具是从很多人的代码片断组合而成的,虽然它并不完善,而且缺乏一些特性,但它至少为进一步开发提供了一个坚实的基础.

目标
这里是自动编译序列号的需求:

1. 在每一次release编译的时候,自动增加保存在一个单独文件中的编译序列号,这个文件将被加入到我的项目中.

2. 自动记录编译的日期和序列号.



代码分析
我的第一个任务是找到一个能够替代VS 6中.Application_BeforeBuildStart()的事件,VS.NET的设计者为我们提供了非常容易使用的编译事件:

OnBuildBegin
OnBuildDone
OnBuildProjConfigBegin
OnBuildProjConfigDone
这些事件句柄的命名规则有一点误导.我们不希望使用OnBuildBegin,因为即使我们同时针对多种配置(release, debug等等)进行编译,它也只会被执行一次.这使得难以只在编译release版本的时候增加编译序列号.OnBuildProjConfigBegin就能够在针对每一种配置编译的时候被执行,并且还提供一个名为ProjectConfig的字符串参数来描述当前所进行的编译使用的是哪一种配置.

大部分的任务是在OnBuildProjConfigBegin事件处理函数中完成的, 它还使用了两个辅助macro:

WriteToLogFile
WriteToOutputBuildPane
这两个宏都可以被写入到OnBuildProjConfigBegin事件处理函数中,或者在不用时删除.



代码
' ------------------------------------
' OnBuildProjConfigBegin event handler
' ------------------------------------

Private Sub BuildEvents_OnBuildProjConfigBegin(
ByVal Project As String,
ByVal ProjectConfig As String,
ByVal Platform As String,
ByVal SolutionConfig As String)
Handles BuildEvents.OnBuildProjConfigBegin

' abort if build type is debug

If InStr(1, ProjectConfig, "Debug", 1) Then Exit Sub

' get ver filename

Dim res_filename As String

res_filename = DTE.Solution.FullName
res_filename = Path.ChangeExtension(res_filename, ".ver")

' open VERSION FILE and increment build number

Dim msg_text As String

If File.Exists(res_filename) Then

Dim line As String

Try

Dim sr As StreamReader = New StreamReader(res_filename)
line = sr.ReadLine()
sr.Close()

Catch ex As Exception

Module1.WriteToOutputBuildPane(vbCrLf & _
"Version file read failed : " &
ex.Message & vbCrLf)

End Try

line = Right(line, line.Length - 18)

Try

Dim sw As StreamWriter = File.CreateText(res_filename)
sw.WriteLine("#define BUILD_NUM {0}", line + 1)
sw.Close()

Catch ex As Exception

Module1.WriteToOutputBuildPane(vbCrLf & _
"Version file write failed : " &
ex.Message & vbCrLf)

End Try

msg_text = "Build number : " & line + 1 & ", " & Now

Module1.WriteToOutputBuildPane(vbCrLf & msg_text & vbCrLf)
Module1.WriteToLogFile(msg_text)

Else

Try

Dim sw As StreamWriter = File.CreateText(res_filename)
sw.WriteLine("#define BUILD_NUM 1")
sw.Close()

Catch ex As Exception

Module1.WriteToOutputBuildPane(vbCrLf & _
"Version file write failed : " &
ex.Message & vbCrLf)

End Try

msg_text = "Build number : 1, " & Now

Module1.WriteToOutputBuildPane(vbCrLf & msg_text & vbCrLf)
Module1.WriteToLogFile(msg_text)

End If

End Sub




' ----------------------------------
' write text message to a log file
' ----------------------------------

Sub WriteToLogFile(ByVal msg_text As String)

Dim log_filename As String

log_filename = DTE.Solution.FullName
log_filename = Path.ChangeExtension(log_filename, ".log.txt")

Try

Dim sw As StreamWriter = File.AppendText(log_filename)
sw.WriteLine(msg_text)
sw.Clos