Sharepoint debugging – process terminated by IIS
”The web server process that was being debugged has been terminated by IIS”
When debugging Sharepoint components you’re likely to come across this error message. It is easily fixed by turning off the ping IIS is sending the worker process at regular intervals to keep it alive.
Go to IIS Manager, select the Application Pool used by your Sharepoint app, choose advanced settings and turn the “Ping Enabled” setting under “Process Model” to FALSE:
Executing commands and programs on a remote machine – Part 2
One month a ago my friend Njål blogged about executing commands and programs on a remote machine using powershell.
Njål wrote about PsExec and Invoke-WmiMethod and I will present some more ways to do this. First one is through MSDeploy.exe and the second, my preferred way of doing it, using WinRM, - and then WinRS. I won't give pros and cons merely inform about the different techniques.
Msdeploy
Msdeploy has two properties that can be set when calling the executable which is called preSync and postSync. MsDeploy is build around a synchronization from source to destination and the commands given in preSync will be executed before the actual synchronization and postSync after. This comes in handy when for example deploying a Windows Service. If the services isn't stopped before new files are synchronized then you might have seen that a "File(s) in use exception" is thrown.
Example:
Msdeploy.exe –verb:sync –source: -dest: -preSync: runCommand="net stop " –postSync:runCommand="net start "
When executed this command will first stop the service on the remote machine, then synchronize all the files and then start the service when done. (when actually doing this live you might add waitInterval and waitAttempts since the stopping of the service might take a while).
The value in "runCommand" can contain all sorts of script executing and you can also add "&&" and execute two commands after each other directly.
WinRM
To be able to use WinRM it must be installed and started on the remote computer. Open powershell and run "winrm qc" (qc=quickconfig) and everything should be fixed ready for use. If it’s a test server and you don’t care that much about security you can enable the listener on port 80 (will not interfere with IIS) running this command:
winrm set winrm/config/service @{EnableCompatibilityHttpListener="true"}
You can enable unencrypted messaging setting "allowunencrypted = true". You can do this almost like the command above or you can browse to the setting and set it specific:
cd wsman:\localhost\client\ set-item .\allowunencrypted $true
The above settings have to be executed on the server. On the client (buildserver when running automated deploys) you might have to enable AllowUnencrypted and also add the server as a TrustedHosts:
winrm s winrm/config/client '@{TrustedHosts="RemoteComputer"}'
Everything should now be set up for running unencrypted remote commands. This can be done through Invoke-Command:
Invoke-Command -Session $ps -ScriptBlock {
Unzip-File x y
Copy-Item x y
…
}
Within the ScriptBlock you can add all the commands you want and they will all be executed on the remote macine
The $ps variable above is a session which I create and remove like this:
$ps = new-pssession -Computername $computername -Port 80 -credential $cred Invoke-Command…… Remove-PSSession $ps
If your script got the password in cleartext you can not put it directly into a parameter in the new-pssession command but you can write is as a SecureString to variable and then use this as Credential:
$secureString = ConvertTo-SecureString $password -AsPlainText –Force $cred = new-object -typename System.Management.Automation.PSCredential ` -argumentlist $usernameAndDomain, $secureString
WinRS
I am not sure, but I think WinRS only a wrapper for the Invoke-Command used in the examples above. Atleast it simplifies the whole process. I have actually not used this command I just saw it when "browsing around" and I haven't botherd changing my current scripts.
But as an example you can write
winrs –r:http://remotemachine <command>
The <command>
IsNullOrEmpty() extension for generic lists (List<T>)
The .IsNullOrEmpty() and .IsNullOrWhitespace() utility methods for string objects really helps cleaning up the code compared to the old fashion
if (myString == null || myString.Trim().Equals("")) ...
This should definately have been implemented for other classes as well, like the List or the Dictionary. But until that happens, add your own extensions:
public static class Extensions { public static bool IsNullOrEmpty<T>(this List<T> list) { return list == null || !list.Any(); } public static bool IsNullOrEmpty<TKey, TValue>(this Dictionary<TKey, TValue> dictionary) { return dictionary == null || !dictionary.Any(); } }
Then you’ll be able to check whether your List is null or empty in a single statement:
List<long> myNumericValues = new List<long>(); if (myNumericValues.IsNullOrEmpty()) { ... }
Downloading blobs from Windows Azure
Enabling users to download files (blobs) in Windows Azure can be done in 4 ways ;
(as Microsoft evangelist Sean Harris explains in this blogpost)
- Direct Download – Set the Access of the Container to Public Read Access or Full Public Read Access and expose the URL to the end user. The drawback of this method is obviously security – you have no way of controlling access when the URL is exposed. There is also no way of detecting downloads, and to execute code before/after the download.
- API Download – The user must run a Windows App, Silverlight etc. Also – the app must contain the store account name and key – which might compromise security. Especially if you have several customers using the same account (they can still have their own containers of course).
- Proxy Download – Have the user access a URL on YOUR server – which then retrieves the file from Azure and sends it to the user. The advantage of this is that you have full control of downloads, you can execute code before/after downloading and you don’t have to expose any Azure URL’s / account info. In fact – the end user will not even see that the file is stored in Azure. You can also override the filename this way. A downside is that all traffic passes through your server – so you' might get a bottleneck here.
- Pass-through Download (Azure Shared Access Signature) – Creates a signature and inserts this signature in a URL where the user is redirected to Azure. The signature enables the user to access the file for a limited period of time. This is most likely your best option. It enables custom code to be executed before downloading, it will ensure max download speed for your users, and a good level of security is also ensured.
Our client has files stored as Guids in Azure – and we keep track of files (names, sizes etc) and folders in a MS Sql database. This is the reason we have to use the Proxy Download option – when users are downloading files.
Sean Harris has developed such a proxy which streams the file directly from Azure to the end user. This code however requires a third party framework, and seems to overcomplicate things a lot. Here’s a version which does the job just as well (.ashx generic handler):
//Retrieve filenname from DB (based on fileid (Guid)) // *SNIP* string filename = "some file name.txt"; //IE needs URL encoded filename. Important when there are spaces and other non-ansi chars in filename. if (HttpContext.Current.Request.UserAgent != null && HttpContext.Current.Request.UserAgent.ToUpper().Contains("MSIE")) filename = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8).Replace("+", " "); context.Response.Charset = "UTF-8"; //Important to set buffer to false. IIS will download entire blob before passing it on to user if this is not set to false context.Response.Buffer = false; context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); context.Response.AddHeader("Content-Length", "100122334"); //Set the length the file context.Response.ContentType = "application/octet-stream"; context.Response.Flush(); //Use the Azure API to stream the blob to the user instantly. // *SNIP* fileBlob.DownloadToStream(context.Response.OutputStream);
Presenting the Degree Blog Team
Thank you for following our Blog – Presenting the bloggers from Degree Consulting Group
From the left: Aage, Njål, Kirsti, Stian, Andreas and Joakim
Delete ReSharper Test Results on “Clean Solution”
On my local dev machine, I can see no reason for keeping old test results (on a build server it’s another matter completely though). You usually run your tests quite often when developing, and thus you get a lot of “test result”-folders cluttering up your hard drive. Some test runners have options for configuring how many old test results you would like to keep, but this is not the case for ReSharper’s test runner (afaik).
To remedy this I’ve created a new target in the project file for my test project, that will delete the test result folder when I right-click the solution Visual Studio’s solution explorer and select “Clean Solution” (or on a project and select “Clean”). By default ReSharper creates the test results in “<ProjectFolder>/bin/<Configuration>/TestResults”, you can however change this (and therefore need to modify the config below accordingly).
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> . . . <PropertyGroup> <TestResultsFolderPath>bin\$(Configuration)\TestResults</TestResultsFolderPath> </PropertyGroup> <Target Name="AfterClean"> <RemoveDir Directories="$(TestResultsFolderPath)" Condition="Exists('$(TestResultsFolderPath)')" /> </Target> </Project>
This target will check if there is a test results folder, and if there is, it will delete it (and it will only run when you clean the solution/project).
If you have more than one test project (i.e. one for unit tests and one for integration tests, etc.) you need to add it the project file for each project. Also beware that adding this target will affect everyone working on the project, not just you!
This solution should work for other test runners as well, just modify the “TestResultsFolderPath” above to reflect where the test results are created.
As I said in the beginning, some test runners allow you to configure how many old test results should be kept at any time, making this a non-issue. E.g. if you’re using the test runner found in Visual Studio out of the box, you could go to “Tools –> Options –> Test Tools –> Test Execution” and specify a number for the “Limit number of old Test Results to”-setting.
TeamCity: Executing commands and programs on a remote machine using Powershell

Windows Sysinternals has a range of pretty neat tools. My favorite is PsExec – which lets me execute programs on a remote computer. It's like Remote Desktop – but with the console. Or you could think of it as a Windows alternative of SSH – if you’re a *NIX guy.
It’s perfect when you need to restart a server where Remote Desktop Services is fubar.
I can execute
psexec \\myWebServer cmd.exe
and I am now running a console window on the webserver.
It is also handy when scripting/automating tasks – such as building, deploying and making backups of software projects.
But invoking PsExec from TeamCity isn’t a walk in the park, to say the least. PsExec does some funky things with the standard input/output, and invoking this from Java (which TeamCity is built on) raises all kinds of problems and stability issues.
Luckily - Powershell takes care of business.
The script below stops an IIS 7 ApplicationPool on a remote server.
[string]$HostName = "myWebServer"
[string]$Cmd = "C:\Windows\System32\inetsrv\appcmd.exe stop apppool MyMainAppPool”
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ($Cmd) -ComputerName $HostName
Change $HostName and $Cmd in order to run other commands.
Monicas kjøttgryte/suppe

Etter en laaang dag med MVC, CSS og Java script, smaker det ekstra godt med denne gryta
- 2 ss smør
- 1-2 løk
- 7-8 sjampinjong
- 1-2 fedd hvitløk
Grovdelses og stekes på middels varme til løken blir blank. Bruk en stor gryte som skal romme hele suppen til slutt. 1 kg kjøttdeig stekes og tilsettes gryten med løk og sjampinjong. En pakke Salami, chorizo eller bacon deles i passe store biter og stekes sprøtt før det blandes i den store gryten. Har du noen rester av pølser eller annet kjøtt er det også godt i suppen.
- 2 bokser med skoldede tomater helst Mutti
- 2-3 bokser med vann (tilpass mengden vann til ønsket tykkelse på suppen).
- 2 bokser med tomatbønner helst Heinz
- 1-2 ts buljong
- Salt, pepper, cayennepepper og Tabasco elle lignende etter smak
La det putre i minimum 20 min. Kos dere!!!
Automatic Config Transformations
My fellow blogger here on the Degree Blog, Thor Halvor, had a blog post not too long ago titled “Don’t let the Configuration transform your Configs” where he recommends that people don’t transform their config files based on the solution configuration, and he points out a lot of things which is important to keep in mind. I, however, think that using the solution configurations to control which transformation files are applied to your config files works quite well.
As Thor Halvor points out in his blog post, you get a few extra config files when you create a web application in Visual Studio, namely Web.Debug.config, and Web.Release.config. These files are the XML transform files for Web.config, and when you build you application locally, they do exactly nothing (no matter if you have selected the debug or release solution configuration). If you use the “Build Deployment Package” or the “Publish” functionality in Visual Studio however, they are applied to your web.config file based on the currently selected solution configuration. Now this might work fine for a small personal project like your own homepage etc., but I doubt many people use this on large work projects. Another problem with this functionality (as Thor Halvor points out), is that it only works for Web.config, and in larger projects you often have more than one config-file (connection strings in a separate file, etc.).
So how can we use xml transform files for more than Web.config, and have the transformation be performed as part of an automated build on a build server? By adding a new target to the Web Application’s project file (.csproj) which will run as a part of the build (You need to right click on the project and choose “Edit project file”).
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> . . . <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <Target Name="TransformConfigFiles" AfterTargets="AfterBuild" Condition="'$(TransformConfigFiles)'=='true'"> <ItemGroup> <DeleteAfterBuild Include="$(WebProjectOutputDir)\Web.*.config" /> <DeleteAfterBuild Include="$(WebProjectOutputDir)\ConnectionStrings.*.config" /> </ItemGroup> <TransformXml Source="Web.config" Transform="$(ProjectConfigTransformFileName)" Destination="$(WebProjectOutputDir)\Web.config" /> <TransformXml Source="ConnectionStrings.config" Transform="ConnectionStrings.$(Configuration).config" Destination="$(WebProjectOutputDir)\ConnectionStrings.config" /> <Delete Files="@(DeleteAfterBuild)" /> </Target> . . . </Project>
This new target will run after the “AfterBuild”-target, and it will transform both Web.config and ConnectionStrings.config, given that you specify the property “TransformConfigFiles” to be “true” (because we don’t want this be be done when we’re developing the application and building it in Visual Studio. As you can see above it uses the “Configuration”-property to decide which xml transform file to use (this property will contain the name of the selected solution configuration). After performing the transformation, it will clean-up/delete the xml transform files.
As you can see, I have created an additional config file, namely ConnectionStrings.config, as well as xml transform files for it (ConnectionStrings.Debug.config and ConnectionStrings.Release.config). The transformation files I’ve created aren’t group under the actual config file like Web.config'’s xml transformation files are, but if you wanted to you could edit the project file to do this.
You need to have xml transformation files for each solution configuration for those config files you want to transform, and they must all be named as <ConfigFileName>.<SolutionConfigurationName.config. I.e. if you create a new solution configuration called “Production” you would need to create a xml transform file called ConnectionString.Production.config (for Web.config you would just need to right click on it and select “Add Config Transforms”.
Inside my transformation files I’ve just put some simple transformations that will allow me to see that the config files are actually being transformed.
Web.config: <configuration> <connectionStrings configSource="ConnectionStrings.config" /> <appSettings> <add key="Configuration" value="" /> ... </appSettings> ... </configuration> Web.Release.config: <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <appSettings> <add key="Configuration" value="Release" xdt:Transform="Replace" xdt:Locator="Match(key)" /> </appSettings> </system.web> </configuration> ConnectionStrings.config: <connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(local);Initial Catalog=dbMVC4;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> ConnectionStrings.Release.config: <connectionStrings xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <add name="DefaultConnection" connectionString="Data Source=PreProdDatabaseServer;Initial Catalog=dbMVC4;Integrated Security=True" providerName="System.Data.SqlClient" xdt:Transform="Replace" xdt:Locator="Match(name)" /> </connectionStrings>
In order to build the Web Application and have the config transformations take place we must run msbuild and specify the solution configuration we want to use, and that TransformConfigFiles should be true.
Running msbuild manually from the Visual Studio command prompt:
msbuild "C:\...\Testing.sln" /p:Configuration=Release /p:TransformConfigFiles=true /p:OutDir=C:\Temp\Testing_Release\
Under “C:\Temp\Testing_Release\_PublishedWebsites\MVC4” one should be able to find the Web Application with transformed config-files.
Now for the cool part, this approach will also work on your TFS build server, in your build definition just specify the build configuration and add TransformConfigFiles=true to the MSBuild Arguments.
On the project I’m currently working on, we have successfully been using this solution with TFS 2010 to automatically build and deploy our web application to the different testing environments for the better part of a year now! ![]()
Powershell returns exitcode 0 instead of 1
I am currently setting up buildscripts in Teamcity for a website I am working on. I use Ctt.exe to transform my web.config files and this program is invoked through PowerShell. But my problem is that that Ctt.exe in some cases has an error or something else is wrong in my ps1-script but the Teamcity buildstep returns "Process exited with code 0" and the build Succeeds instead of failing.
Since this blogpost might be boring and badly written I will start with the solution:
$ErroActionPreference = 'Stop'
My scenario is that I have a script, ConfigTransform.ps1, which is invoking the ctt.exe file. This script file takes one parameter which is the Environment (Test/Production). If an error occurs in the script I need the hole build to fail.
To force an error while testing I have set my script to invoke the file "DoesNotExist.exe" instead of the Ctt.exe.
My script (ConfigTransform.ps1)
param($Environment)
Write-Host Environment is $Environment
..\DoesNotExist.Exe
In Teamcity there are many different alternatives for you to call the script.
Script=File and Executionmode = -FILE
Since I have a predefined powershell script with all the logic and I need to pass a parameter to it, - I first choose the PowerShell-runner with Script=File and Executionmode to –File. As you can see below the parameter is passed on but this process exits with code 0 and therefore the Build won't fail.
[13:51:05][Step 1/5] Starting: (…)cmd.exe /c (…)powershell.exe -NonInteractive -File (…) ConfigTransform.ps1 -Environment Test && exit /b %ERRORLEVEL% [13:51:06][Step 1/5] Environment is Test [13:51:06][Step 1/5] The term '..\DoesNotExist.Exe' is not recognized as the name of a cmdlet, funct [13:51:06][Step 1/5] ion, script file, or operable program. Check the spelling of the name, or if a [13:51:06][Step 1/5] path was included, verify that the path is correct and try again. [13:51:06][Step 1/5] At C:\TeamCity\buildAgent\work\7100e0a13f6ca7b6\BuildToolsAndScripts\Scripts\Co [13:51:06][Step 1/5] nfigTransform\ConfigTransform.ps1:4 char:20 [13:51:06][Step 1/5] + ..\DoesNotExist.Exe <<<< [13:51:06][Step 1/5] + CategoryInfo : ObjectNotFound: (..\DoesNotExist.Exe:String) [], [13:51:06][Step 1/5] CommandNotFoundException [13:51:06][Step 1/5] + FullyQualifiedErrorId : CommandNotFoundException [13:51:06][Step 1/5] [13:51:06][Step 1/5] Process exited with code 0
Script=File and Executionmode = -Command
Then I try setting the Executionmode to "-Command". The exit code is now correct and the Build is not failing but it is not possible to pass on script parameters.
[13:51:07][Step 1/5] Starting: (…)cmd.exe /c (…)powershell.exe -NonInteractive -Command (…) ConfigTransform.ps1 && exit /b %ERRORLEVEL% [13:51:07][Step 1/5] Environment is [13:51:07][Step 2/5] The term '..\DoesNotExist.Exe' is not recognized as the name of a cmdlet, funct [13:51:07][Step 2/5] ion, script file, or operable program. Check the spelling of the name, or if a [13:51:07][Step 2/5] path was included, verify that the path is correct and try again. [13:51:07][Step 2/5] At line:1 char:20 [13:51:07][Step 2/5] + ..\DoesNotExist.Exe <<<< [13:51:07][Step 2/5] + CategoryInfo : ObjectNotFound: (..\DoesNotExist.Exe:String) [], [13:51:07][Step 2/5] CommandNotFoundException [13:51:07][Step 2/5] + FullyQualifiedErrorId : CommandNotFoundException [13:51:07][Step 2/5] [13:51:07][Step 2/5] Process exited with code 1
Script=Source code and Executionmode = -Command
Since executionmode –File does not return correct errorcode I need to use "-Command" but also pass on my parameter. This can be done PowerShell-runner with Script=Source code. In the Script Source field I am now adding the full path to my script including my parameter.
The output is:
[13:51:05][Step 1/5] Starting: (…)cmd.exe /c (…)powershell.exe -NonInteractive -Command (…) powershell3439435836265.ps1 && exit /b %ERRORLEVEL% [13:51:06][Step 1/5] Environment is Test [13:51:06][Step 1/5] The term '..\DoesNotExist.Exe' is not recognized as the name of a cmdlet, funct [13:51:06][Step 1/5] ion, script file, or operable program. Check the spelling of the name, or if a [13:51:06][Step 1/5] path was included, verify that the path is correct and try again. [13:51:06][Step 1/5] At C:\TeamCity\buildAgent\work\7100e0a13f6ca7b6\BuildToolsAndScripts\Scripts\Co [13:51:06][Step 1/5] nfigTransform\ConfigTransform.ps1:4 char:20 [13:51:06][Step 1/5] + ..\DoesNotExist.Exe <<<< [13:51:06][Step 1/5] + CategoryInfo : ObjectNotFound: (..\DoesNotExist.Exe:String) [], [13:51:06][Step 1/5] CommandNotFoundException [13:51:06][Step 1/5] + FullyQualifiedErrorId : CommandNotFoundException [13:51:06][Step 1/5] [13:51:06][Step 1/5] Process exited with code 0
My script is runtime wrapped in a temporary ps1-file "powershell3439435836265.ps1 ", the parameter Environment is Test BUT exit code is now 0 again! So what now…
Solution:
Powershell is by default continuing when "minor" error occurs. I guess the Powershell-runner has done something with that and therefore it works using the –Command switch. I also guess they have forgotten that errorhandling when creating the –File switch. When setting Script=SourceCode all the code is wrapped in a temporary script and you have to take care of the errors yourself. One solution that at first glance worked for me was to wrap my script in a try catch and then just have a 'throw' in my errorhandling. What was not so good about this is that the exception itself was suppressed and therefore not visible in the build output.
So the best solution I found is to add the following code (see the first line) in Team City's Source Code-field:
$ErrorActionPreference = 'Stop'
(…)/ConfigTransform.ps1 –Enviroenment Test
And then finally everything worked as I wanted. I got exit code 1 in the examples above. ![]()
