Showing posts with label tfs. Show all posts
Showing posts with label tfs. Show all posts

Monday, September 6, 2010

Team Build 2008 to 2010 – Notes on the side of migration

Here are just my few notes in a very raw format, hope someone might find it useful. The context – trying to run builds as they are without transforming them or modifying build type .proj file anyhow.

Environment: Windows 2008 x64 VM, Team build 2008 installed, newly installed Team build 2010. Projects do build under team build 2008.

From build log following is used by the agent to invoke msbuild:

Run TfsBuild for Configuration Folder

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe /nologo /noconsolelogger "C:\xyz\BuildType\TFSBuild.proj" /m:1 "@C:\xyz\BuildType\TfsBuild.rsp"

So we can see the x64 msbuild is picked up and later on few issues raise from it.

But first stop was at the System.Workflow.xyz family. Build started to pick version 4.0 from innocently looking references in the csproj:

    <Reference Include="System.Workflow.Activities" />
    <Reference Include="System.Workflow.ComponentModel" />
    <Reference Include="System.Workflow.Runtime" />

That was easy to fix by providing the stronger references, like:

<Reference
Include="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

<Reference 
Include="System.Workflow.ComponentModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<Reference 
Include="System.Workflow.Runtime, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

Next stop – sgen for binaries compiled as x86:

C:\yuy\x64\sgen.exe /assembly:"zzz.exe" /proxytypes ....
.....
Could not load file or assembly 'file:///C:\XYZ\zzz.exe' or one of its dependencies.
An attempt was made to load a program with an incorrect format.

Why on earth would you have your code compiled specifically as x86? Here is the point: because of nasty x86 specific dependencies like Infragistics or Oracle.DataAccess.dll of certain versions. So when you run your any cpu binaries, they get into x64 loader and fail then on your unfortunate x86 only dependencies.

Anyway this is solved easily by just giving up the compile time serialization assembly generation and letting .NET to generate it during runtime. Just put:

<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>

To a PropertyGroup of your project corresponding to the target configuration (or the top one to affect all configurations).

This is what I have gathered for a moment.

Monday, April 6, 2009

CI - Failed tfs team build watcher. Part II - the code.

Code follows, as promised in the first installment on this subject.

What is required to develop?

1. Resolve the "windows" name of the build requestor in CI to the Display Name and email address. This requires a call to the TFS API, as name comes in the format "domain\windowsusername".
That is done by the ResolveUser build task: http://code.google.com/p/toolsdotnet/source/browse/trunk/Tools.Net/src/Tools.TeamBuild.Tasks/ResolveUser.cs

2. Keep a build and requestor names (email address) for the first broken build following the successful one. Again I decided not to use build API for that because of its chatty character of retrieving all build records and only then filtering through them. This is achieved by the BuildGateKeeper task: http://code.google.com/p/toolsdotnet/source/browse/trunk/Tools.Net/src/Tools.TeamBuild.Tasks/BuildGateKeeper.cs

Pardon me all the surrounding files for achieving the better test coverage, you can get the dll (.exe) straight here: http://cid-c651f6a9f36fb87d.skydrive.live.com/self.aspx/Public/tools.tfs.utils.exe. Reason for having it as an exe was ability to use ResolveUser task as a console utility.

First, get those tasks imported (change path to yours):

<UsingTask AssemblyFile="$(MSBuildExtensionsPath)\SitronicsTeamBuild.Quick\tools.tfs.utils.exe" TaskName="Tools.TeamBuild.Tasks.ResolveUser" />   
<UsingTask AssemblyFile="$(MSBuildExtensionsPath)\SitronicsTeamBuild.Quick\tools.tfs.utils.exe" TaskName="Tools.TeamBuild.Tasks.BuildGateKeeper" /> 

Then use ResolveUser in some place before the build:

<ResolveUser WindowsAccountName="$(RequestedFor)"> 
  <Output TaskParameter="DisplayName" PropertyName="Requestor" />
  <Output TaskParameter="MailAddress" PropertyName="MailAddress" />
</ResolveUser>

I used a default for our own tfs, but there is an extra parameter TfsUrl that is the best to set to the full url as http://tfsname:port.

Note that it is $(RequestedFor) that is used as $(RequestedBy) gives something like "System Build Account", while $(RequestedFor) gives user windows name. This way we are getting from mine domain\sdvoychenko to Stanislav Dvoychenko and "yours truly" email address.

If build is successful build I reward the lucky guy with the grateful email:

<CreateProperty          Value="Success" >
 <Output TaskParameter="Value" PropertyName="BuildStatus" />
</CreateProperty>
<BuildGateKeeper BuildStatus="$(BuildStatus)" StateFilePath="c:\Build\$(BuildDefinition).txt" RequestorMailAddress="$(MailAddress)" RequestorDisplayName="$(Requestor)">
</BuildGateKeeper>
<Mail SmtpServer="YourSmtpServer" IsBodyHtml="true" Username="xxx\xxx" Password="xxx" To="$(MailAddress)" CC="controlfreak@controlfreakdomain.com" From="build@controlfreakdomain.com" Body="Successful check-in! Your checkin to SP5 Dev branch was built successfuly. Check-in number and comments to be provided soon. Build log: %3CBR%2F%3E $(DropLocation)\$(BuildNumber)\BuildLog.txt;" Subject="Your checkin to SP5 Dev branch was built successfuly."></Mail>           

What BuildGateKeeper does at this moment is to delete the state file (if any), that keeps exactly who was the first to break the build.
After that, email sending follows for which you might need to add the following usage if you have not been using community tasks (http://msbuildtasks.tigris.org/) in your project already:

<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />

Now, lets see what to do if build breaks.

<Copy Condition="Exists('$(MSBuildProjectDirectory)\build.errors.txt')"                SourceFiles="$(MSBuildProjectDirectory)\build.errors.txt" DestinationFolder="$(DropLocation)\$(BuildNumber)\" />
<ReadLinesFromFile Condition="Exists('$(DropLocation)\$(BuildNumber)\build.errors.txt')"            File="$(DropLocation)\$(BuildNumber)\build.errors.txt" >
  <Output TaskParameter="Lines"  ItemName="BuildErrorLines"/>
</ReadLinesFromFile>
<CreateProperty Value="Failure" >
  <Output TaskParameter="Value" PropertyName="BuildStatus" />
</CreateProperty>
<BuildGateKeeper BuildStatus="$(BuildStatus)" StateFilePath="c:\Build\$(BuildDefinition).txt" RequestorMailAddress="$(MailAddress)" RequestorDisplayName="$(Requestor)">
  <Output TaskParameter="BreakerMailAddress" PropertyName="BreakerMailAddress" />
  <Output TaskParameter="BreakerDisplayName" PropertyName="BreakerDisplayName" />
  <Output TaskParameter="BreakTimeStamp" PropertyName="BreakTimeStamp" />
</BuildGateKeeper>
<Mail SmtpServer="YourSmtpServer" IsBodyHtml="true" Username="xxx\xxx" Password="xxx" To="$(MailAddress)" CC="controlfreak@controlfreakdomain.com;$(BreakerMailAddress)" From="build@controlfreakdomain.com" Body="You got this email message because the code you checked in recently was not compiled successfully during verification build. Changeset number and comments to be provided soon. &lt;br/&gt; The build was broken first by $(BreakerDisplayName) at $(BreakTimeStamp). &lt;br/&gt;&lt;br/&gt; Errors log: &lt;br/&gt; &lt;b&gt; @(BuildErrorLines) &lt;/b&gt; &lt;br/&gt; &lt;br/&gt; More detailed info: &lt;a href='file:///$(DropLocation)\$(BuildNumber)\BuildLog.txt' &gt; $(DropLocation)\$(BuildNumber)\BuildLog.txt &lt;/a &gt;. &lt;br/&gt; If you believe this informatin is false positive or need help with fixing check-in, please reply to the Dvoychenko Stanislav." Subject="FAILURE! Build - $(BuildNumber) - changes your checked in were not compiled successfuly."></Mail>

The line I owe here is an update to the .rsp build file in the BuildTypes folder. That is to log build errors only to the separate file. I'll add this snippet asap.
What we do then is to copy that error file to the drop location and then we read its lines into the $(BuildErrorLines) property which we use then in the body of our email.

We then use BuildGateKeeper to create a break state file if there is no such yet. If there is already one, then task uses it to populate Breaker details which we use again in our Mail community task to send the email to the check-in initiator and CC to the guy who First Broke The Build (and the control freak who is me by the way:).

This is very spartan and I'll share the improvements as I progress in the evenings :).

Happy hunting my fellow control freaks!

P.S. Full solution including nunit tests is available here:  http://code.google.com/p/toolsdotnet/source/browse/trunk/Tools.Net/Tools.Build.sln

Monday, March 30, 2009

CI - Failed team build watcher. Part I - main ideas.

This is my DIY activity, so sorry if something like this already exists, I have not been searching that long. I'd highly recommend to look at the buddy build http://www.codeplex.com/BuddyBuild as well as gated check-ins feature in Team System 2010 http://blogs.msdn.com/jimlamb/archive/2009/01/23/coming-soon-gated-check-in.aspx will make this quite obsolete.

Problem definition:

1. First Developer check-ins files, breaking the build
Action required: Send notification email with build errors list and link to the detailed log file.

BuildGateKeeperFile1

2. Second Developer check-ins files, his check-in doesn't build as build is broken by the First Developer
Action required: Send notification email to the Second Developer saying build can't be verified. CC the First Developer on it (knock-knock on his conscious).

BuildGateKeeperFile2

3. Third Developer check-ins -> same as the second.

4. Corrective check-ins -> team build builds
Action required: Notify the check-in author of successful check-in

BuildGateKeeperFile3

*Names of all devs in the sreenshots are mine as an implication of testing on myself. As well as error message is faked in the team build target so I don't need to wait for the compilation to complete.

Implementation ideas:

1. Don't use the Team Build API as its query ability is quite limited. In this case we need the first build breaker after the last successful build.
2. Even if possible to code completely with bunch of msbuild and community build tasks http://msbuildtasks.tigris.org/, still I decided to go with custom task(s), except for sending email I used Email community task and for reading error logs I used msbuild ReadLines task.
Main reason for this decision was ability to provide unit/integration tests instead of taming/tuning a bunch of xml (Still there is enough xml left :))
3. Introduce failure state file to keep the data of the build breaker immediately following the successful build. That is to compensate the absence of the "build query language" already referred to in point #1.

Implementation time required - 5 hours
Test coverage achieved at the moment - 60%
Lines of code - to be counted
Implementation guide, source and binaries - coming in the next post

Thursday, October 18, 2007

Sample scripts for backing up all TFS related databases

 

Powershell part:

# Set sql server
[string] $SqlServerName = "[TFSSQLServerName]"

# Set date and time driven variables
$date = get-Date
[string] $DateSuffix = $date.ToString("yyyyMMdd")
[string] $DateTimeSuffix = $date.ToString("yyyyMMddTHHmmssfffz").Replace("+", "U");
[string] $RootPath = "E:\DBBackups\"
[string] $BackupSqlScriptPath = "C:\....\BackupAllTfsDatabases.sql"
[string] $TargetPath = $RootPath + $DateSuffix + "_"
[int] $i = 0
do
{
    $i++
    $directoryExists = test-Path ($TargetPath + $i + "\")
}
while ($directoryExists -eq $true)

$TargetPath = $TargetPath + $i + "\";

if ($dir -eq $null)
{
    Write-Output "Directory created: $TargetPath"
    new-item -path $TargetPath -type directory
}
else
{
    Write-Output "Directory already existed: $TargetPath"
}

Write-Output "Generating set of backups to disk: $TargetPath, with datetime siffix of $DateTimeSuffix"
[string] $TargetPathForCmd = '"' +  $TargetPath + '"' #Simply putting qoutes around in the command line itself doesn't work

$sqlCmdOutput = sqlcmd -S $SqlServerName -E -p -i $BackupSqlScriptPath -v RootPath=$TargetPathForCmd DateSuffix=$DateSuffix DateTimeSuffix=$DateTimeSuffix 2>&1

$sqlCmdOutput

SQL Part: 

SET NOCOUNT ON

DECLARE @DateSuffix nvarchar(30),
        @DateTimeSuffix nvarchar(30),
        @RootPath nvarchar(200),
        @BackupName nvarchar(100),
        @BackupFile nvarchar(255),
        @TodaysDirectory nvarchar(30),
        @DBName nvarchar(30)

DECLARE @databases table (DBName nvarchar(30))
-- Add an insert here for any new database to backup
INSERT INTO @databases (DBName) VALUES (N'ReportServer')
INSERT INTO @databases (DBName) VALUES (N'STS_Config_TFS')
INSERT INTO @databases (DBName) VALUES (N'STS_Content_TFS')
INSERT INTO @databases (DBName) VALUES (N'TfsActivityLogging')
INSERT INTO @databases (DBName) VALUES (N'TfsBuild')
INSERT INTO @databases (DBName) VALUES (N'TfsIntegration')
INSERT INTO @databases (DBName) VALUES (N'TfsVersionControl')
INSERT INTO @databases (DBName) VALUES (N'TfsWarehouse')
INSERT INTO @databases (DBName) VALUES (N'TfsWorkItemTracking')
-- Set day and time based parameters
SET @DateSuffix = N'$(DateSuffix)'
SET @DateTimeSuffix = N'$(DateTimeSuffix)'
SET @RootPath = N'$(RootPath)' --N'E:\DBBackups\'
SET @TodaysDirectory = @RootPath -- + @DateSuffix + N'\'

-- Setup and run a cursor
DECLARE CursorOverDatabases CURSOR FOR SELECT DBName FROM @databases

OPEN CursorOverDatabases

FETCH NEXT FROM CursorOverDatabases INTO @DBName

WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @BackupName = @DBName + N'_' + @DateTimeSuffix
        SET @BackupFile = @TodaysDirectory + @BackupName + N'.bak'

        BACKUP DATABASE @DBName TO  DISK = @BackupFile
            WITH NOFORMAT, NOINIT,  NAME = @BackupName, SKIP, REWIND, NOUNLOAD,  STATS = 10

        DECLARE @backupSetId as int
        SELECT @backupSetId = position from msdb..backupset where database_name=@DBName and backup_set_id=(select max(backup_set_id) from msdb..backupset where database_name=@DBName)
        IF @backupSetId is null
            BEGIN RAISERROR(N'Verify failed. Backup information for database %s not found.', 16, 1, @DBName) END

        RESTORE VERIFYONLY FROM  DISK = @BackupFile
            WITH  FILE = @backupSetId,  NOUNLOAD,  NOREWIND

        FETCH NEXT FROM CursorOverDatabases INTO @DBName
    END
CLOSE CursorOverDatabases
DEALLOCATE CursorOverDatabases

Monday, September 10, 2007

Problems connecting to TFS.


Fiddler or other http proxy tool is running.

Shut them down or the bellow info may help:
Beginning with the December CTP, there is an optional registry setting that you can use to tell the Team Foundation client to bypass the proxy server without changing your IE settings.  In HKCU (per user) or HKLM (global), you can create the registry entry Software\Microsoft\VisualStudio\8.0\TeamFoundation\RequestSettings\BypassProxyOnLocal of type string with the value "true" to get the improved performance.

Client-side tracing enabled in the devenv.exe.config for the level higher than 2.

You may be able to connect to tfs by invoking the url in the browser or via sidekicks. But when connecting via VS you may get the following error message.

---------------------------
Microsoft Visual Studio
---------------------------
TF31002: Unable to connect to this Team Foundation Server: kara.
Team Foundation Server Url: http://kara:8080.
Possible reasons for failure include:
- The Team Foundation Server name, port number or protocol is incorrect.
- The Team Foundation Server is offline.
- Password is expired or incorrect.
For further information, contact the Team Foundation Server administrator.

I was not getting any stack trace information as in case of this link: http://manicprogrammer.com/cs/blogs/michaelruminer/archive/2007/07/13/windows-update-net-2-0-update-may-impact-team-system.aspx

That is why I decided to debug and came to the same exception:

-        $exception    {"Index and length must refer to a location within the string.\r\nParameter name: length"}    System.Exception {System.ArgumentOutOfRangeException}

Thrown in the line:
string str2 = request.RequestUri.Segments[1].Substring(0, 3);

of the following code:

private void TraceWebMethodRequest(WebRequest request)
{
    if (ProxyTracing.TraceInfo)
    {
        if (this.m_callStartTimes == null)
        {
            this.m_callStartTimes = new Dictionary<int, long>();
            this.m_timer = new Stopwatch();
            this.m_timer.Start();
        }
        this.m_callStartTimes[request.GetHashCode()] = this.m_timer.ElapsedMilliseconds;
        StackTrace trace = new StackTrace();
        string name = trace.GetFrame(3).GetMethod().Name;
        if (name.Equals("BeginInvoke", StringComparison.OrdinalIgnoreCase))
        {
            name = "{AsyncSharepoint}";
        }
        string str2 = request.RequestUri.Segments[1].Substring(0, 3);
        if (str2.Equals("sit", StringComparison.OrdinalIgnoreCase) || str2.Equals("_vt", StringComparison.OrdinalIgnoreCase))
        {
            str2 = "Wss";
        }
        Trace.WriteLine("Web method running: [" + request.RequestUri.AbsoluteUri + "] " + (name + "[" + str2 + "]"));
    }
}
which brought me to the following links that helped to resolve the problem:
http://manicprogrammer.com/cs/blogs/michaelruminer/archive/2007/07/13/windows-update-net-2-0-update-may-impact-team-system.aspx
http://support.microsoft.com/kb/936210

I didn't call to MS though, but just set the tracing level values to be less than 3:

<switches>
  <add name="TeamFoundationSoapProxy" value="2" />
  <add name="VersionControl" value="2" />
</switches>

Technorati Tags: ,

Thursday, August 30, 2007

Optimizing the Team Build - getting less source code


Mission: Optimize Team Build bringing sources for all of the branches while it builds either the head or one of the branches.
Current time to build: 30 minutes of average solution of 50 medium sized projects.

Solution:
Customize the team build project file to initialize the build workspace differently so server source control (tfs) binding is pointing directly to the branch/head folder not the root one.
For example our root would be: $/Project/Apps which corresponds to the head. Then branches are: $/Project/Apps_RB_1, $/Project/Apps_RB_1. When building the head it was getting the source for the whole $/Project/. Very slow and expensive IO for our TFS.

TODO: Add samples.

At the end, having solution implemented but not progressing here with any more info, as team build 2008 seems to have this problem resolved and you can narrow what you get to what you really need (at least as announced).

Technorati Tags: ,

Tuesday, June 19, 2007

Note to self: troubleshooting workspaces in tfs and deleting the wrong one(s)

Sample to troubleshoot:

tf workspaces /server:ServerName /format:detailed /computer:ComputerName /owner:*

Sample to delete (WorkspaceName;UserName taken from the above command running)

tf workspace /server:ServerName /delete WorkspaceName;UserName

Sample to undo pending check-ins from the other workspace (the guy who left without checkin/undo):

tf undo /workspace:WorkspaceName;Owner /server:ServerName /recursive $\SourceControlPath\*.*

Technorati Tags: ,