Saturday, June 14, 2008

Harnessing Post-Build-Events in Visual Studio

In class library development, we need to add an assembly to GAC. One way is to open Visual Studio command prompt. And type the command for gacutil /i "DLL" or gacutil /u "DLL".
The disadvantage of the approach is that after every successful build we have to do it manually uninstall the prev version and install the correct version.

In my todays post, we will harness Visual Studio Post-Buil Events to automate this process.

On every successful build the DLL will be automatically added to the GAC.

To begin with,
1. Open any existing class library project to be deployed to the GAC.
2. Right click on the project, add new item-> Text File. Rename the file as PostBuildActions.bat
3. Paste the following content:

@ECHO OFF
SET DEPLOY=%3
ECHO DEPLOY: %DEPLOY%
:: Extract the deploye variable value from the command line
SET DEPLOYVALUE=DEPLOY
ECHO DEPLOYVALUE: %DEPLOYVALUE%

IF NOT %DEPLOY%==%DEPLOYVALUE% (ECHO Skipping deployment & GOTO QUIT)
SET TARGETDIR=%1
:: Fix the extra slashes the the path
echo %TARGETDIR:~0,-2%
:: Fix the extra slashes the the path
SET TARGETDIR=%TARGETDIR:~1,-2%
ECHO TARGETDIR: %TARGETDIR%
SET TARGETNAME=%2
:: Fix the extra slashes the the path
SET TARGETNAME=%TARGETNAME:~1,-1%
ECHO TARGETNAME: %TARGETNAME%
IF EXIST "%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" (SET GACUTIL="%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" & GOTO DEPLOY)
IF EXIST "%programfiles% (x86)\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" (SET GACUTIL="%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe") ELSE (ECHO Gacutil.exe could not be found! & GOTO QUIT)

:DEPLOY
ECHO.
ECHO Adding assemblies to the GAC...
ECHO.
ECHO.
%GACUTIL% -uf %TARGETNAME%
ECHO.
ECHO.
%GACUTIL% -if "%TARGETDIR%\%TARGETNAME%.dll"
ECHO.
:QUIT
ECHO.
ECHO Assembly added to GAC
ECHO.

4. Right click on solution-> Go to properties -> Build Events -> Post-build events command line and
Paste the following
call "$(ProjectDir)\PostBuildActions.bat" "$(TargetDir)" "$(TargetName)" DEPLOY

(Replace DEPLOY with NODEPLOY to skip adding to GAC)

1 comment:

Unknown said...

Great Stuff Dinar... but do get in touch with me
sandeep_senjit@infosys.com