Macro to Toggle MvcBuildViews Property

I really like the MvcBuildViews property included in ASP.NET MVC projects. When set to true, the views are compiled and any errors are noted. This feature does bring with it the trade-off of a longer compile time every time you run the app.

In order to avoid the longer compile time, I leave the property set to its default of false and only change it periodically to test the views. The steps involved are:

  • Unload the project
  • Edit the project file xml and set MvcBuildViews to true
  • Save the project file
  • Reload the project
  • Rebuild the project

When you are done, repeat the steps and set MvcBuildViews to false.

Rather than constantly performing theses steps manually, I’ve written a Visual Studio macro to toggle the MvcBuildViews value. Here is the macro:

Sub ToggleMvcBuildViews()
    DTE.ExecuteCommand("Project.UnloadProject")
    DTE.ExecuteCommand("OtherContextMenus.StubProject.EditProjectFile")

    Dim wasSetToTrue As Boolean = SetMvcBuildView(True)
    Dim wasSetToFalse As Boolean
    If Not wasSetToTrue Then
        wasSetToFalse = SetMvcBuildView(False)
    End If

    If (wasSetToTrue Or wasSetToFalse) Then
        DTE.ActiveDocument.Save()
    End If

    DTE.ActiveDocument.Close()
    DTE.ExecuteCommand("Project.ReloadProject")

    Dim msgBoxTitle As String = "Toggle MvcBuildViews"
    If wasSetToTrue Then
        MsgBox("MvcBuildViews property was set to True", Title:=msgBoxTitle)
    ElseIf wasSetToFalse Then
        MsgBox("MvcBuildViews property was set to False", Title:=msgBoxTitle)
    Else
        MsgBox("Unexpected Error: Unable to toggle MvcBuildViews property", Title:=msgBoxTitle)
    End If
End Sub

Function SetMvcBuildView(ByVal value As Boolean) As Boolean
    DTE.ExecuteCommand("Edit.Replace")

    Dim findResult As vsFindResult
    findResult = DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
        FindWhat:="<MvcBuildViews>" & IIf(value, "false", "true").ToString() & "</MvcBuildViews>", _
        vsFindOptionsValue:=(vsFindOptions.vsFindOptionsFromStart Or vsFindOptions.vsFindOptionsMatchCase), _
        ReplaceWith:="<MvcBuildViews>" & IIf(value, "true", "false").ToString() & "</MvcBuildViews>", _
        Target:=vsFindTarget.vsFindTargetCurrentDocument, _
        ResultsLocation:=vsFindResultsLocation.vsFindResultsNone)

    SetMvcBuildView = True
    If (findResult = vsFindResult.vsFindResultNotFound) Then
        SetMvcBuildView = False
    End If

    ' close find/replace dialog
    DTE.Windows.Item("{CF2DDC32-8CAD-11D2-9302-005345000000}").Close()
End Function

see colorized code on CodePaste.NET

I don’t write macros very often, so please let me know if you have any thoughts that would improve this.

(I haven’t installed any comments on here yet so please reply or dm me @algonzalez on twitter)

Comments
blog comments powered by Disqus

Notes

  1. dubai-homes reblogged this from algonzalez
  2. algonzalez posted this