Specify Machine Name in Web.Config Transform - msbuild

I am using Web.config transforms to successfully create debug and release versions of the my web.config - this is working correctly.
I am interested to know whether there is a 'machine name' property to specify the current machine name which I can use in a debug URL, rather than hard-coding a specific machine name (using localhost isn't an option in the case), e.g.
<add name="XrmService" connectionString="http://$(ComputerName):5555/Service.svc" />
Are there any properties available using Web.config transforms? Similar to MSBuild's $(ComputerName) property?

I faced a similar issue, what I ended up doing is :
1) Added the following build target to the project file. (Which is an MSBuild script effectively)
<Target Name="AfterBuild">
<TransformXml Source="Web.config" Condition="Exists('Web.$(Computername).config') " Transform="Web.$(Computername).config" Destination="Web.config" />
</Target>
2) Added a Web.MyMachineName.config config transform file to the project. In your case it should look like this:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="XrmService"
connectionString="http://MyMachineName:5555/Service.svc"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)"/>
</connectionStrings>
</configuration>
This has the benefit of running different transformations based on the machine name, without creating a separate build configuration. You can configure it to be debug only by specifying Condition="'$(Configuration)' == 'Debug'".

There is an Environment Variable that you can use. It is $(COMPUTERNAME).
Open a command window, type "set" (without the double quotes) and press Enter. You will see this Environment Variable somewhere at the top of the screen.

Related

Replace config value in teamcity build step

I have a build step in teamcity which allows me to replace web.config values with web.release.config values. I would like to add one more step - pass some parameter from teamcity to web.config. In my case it will be release version, which is part of connection string. The best idea I have is just to have some powershell script which will replace text in some file (web.config). Are there any better options?
Example web config
<add key="Version" value="Replace me, please from teamcity"/>
<add key="some key" value="example 2. version as part of some value #VERSION"/>
You could use File Content Replacer.
Instead of making the creation of the web.config in release dependent of TeamCity, you can use the web.config transformation syntax
ie: To create a specific connection string:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="MyDB"
connectionString="value for the deployed Web.config file"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
</configuration>

Programmatically (using C#) determine current Visual Studio build configuration

My Visual Studio 2013 C# app needs to programmatically determine if another Visual Studio solution has been saved in "build mode" or "release mode". Is there an API for accomplishing this?
Alternatively, I was thinking of using the MSBuild API to build the solution and then check to see if the app has debug symbols. Is there a way of doing this?
Debug, Release or any other custom configuration are just names, anyone can make one to look like the other one in Advanced Build Settings of Project Properties or by tweaking properties in the .csproj directly. Those flags will dictate how you identify a "debug" assembly and how much of "debug" debug really means. That said, the difference in output for default combination of properties is in Debuggable assembly attribute, both default configurations have it and you can see it for yourself using ILSpy.
Debug
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default
| DebuggableAttribute.DebuggingModes.DisableOptimizations
| DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints
| DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
Release
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
On how to read this Debuggable attribute value -- see #MobyDisk answer.
When you build an assembly in debug mode, the compiler adds the [assembly: DebuggableAttribute] automatically. You can use reflection to see if that attribute is present on the assembly. Take a look here for details on how to read attributes from an assembly: How to read assembly attributes
I'm currently solving the same problem using Web.config:
My Web.config (as default this will be equivalent to Web.Debug.config and Web.Development.config) file contains (using your naming above):
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="mode" value="build"/>
<add key="anotherKey" value="another value"/>
</appSettings>
</configuration>
My Web.Test.config and Web.Release.config files contain:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="mode" value="release" xdt:Transform="Replace" xdt:Locator="Match(key)"/>
</appSettings>
</configuration>
Then you can access the 'mode' using:
WebConfigurationManager.AppSettings.Get("mode");
[you don't have to use 'mode' for the key, as long as you are consistent]

Msbuild just produces a package but does not deploy it when using a publish profile. Why?

MSBuild really seems to like me.
Recently I am trying out the different possibilities to build and deploy from command line.
However I am experiencing some seemingly strange behaviour when I pass a publish profile to MSBuild.
Here is an example of what I just did:
I deploy to a local IIS for the moment with a command such as this:
msbuild D:\PathToFile\DeployDBVariation01\DeployDBVariation01\DeployDBVariation01.csproj
/p:Configuration=Release;
Platform=AnyCpu;
DeployOnBuild=true;
DeployTarget=MSDeployPublish;
MSDeployServiceURL="localhost";
DeployIisAppPath="DeployApp/DeployThis";
MSDeployPublishMethod=InProc;
Username=thisIsNotActuallyMyUsername;
password=guesswhat;
AllowUntrustedCertificate=true
And this works! After that it is successfully deployed and I can call it in a browser.
However, since Visual Studio gives us the comfort of using publishing profiles I wanted to try that in conjunction with MSBuild over command line and tried the following command:
msbuild D:\PathToFile\DeployDBVariation01\DeployDBVariation01\DeployDBVariation01.csproj
/p:DeployOnBuild=true;
AllowUntrustedCertificate=true;
PublishProfile=ReleaseLocal
ReleaseLocal is a profile I created in Visual Studio and it looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>MSDeploy</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<ExcludeApp_Data>False</ExcludeApp_Data>
<MSDeployServiceURL>localhost</MSDeployServiceURL>
<DeployIisAppPath>DeployApp/DeployThis</DeployIisAppPath>
<RemoteSitePhysicalPath />
<SkipExtraFilesOnServer>True</SkipExtraFilesOnServer>
<MSDeployPublishMethod>InProc</MSDeployPublishMethod>
<EnableMSDeployBackup>False</EnableMSDeployBackup>
<UserName />
<_SavePWD>False</_SavePWD>
<PublishDatabaseSettings>
<Objects xmlns="">
<ObjectGroup Name="DefaultConnection" Order="1" Enabled="False">
<Destination Path="Data Source=.\SQLEXPRESS;Initial Catalog=HorstDataProductive;User ID=sa;Password=GuessWhat" />
<Object Type="DbDacFx">
<PreSource Path="Data Source=.\SQLEXPRESS;Initial Catalog=HorstData;User ID=sa;Password=GuessWhat" includeData="False" />
<Source Path="$(IntermediateOutputPath)AutoScripts\DefaultConnection_IncrementalSchemaOnly.dacpac" dacpacAction="Deploy" />
</Object>
<UpdateFrom Type="Web.Config">
<Source MatchValue="Data Source=.\SQLEXPRESS;Initial Catalog=HorstData;User ID=sa;Password=GuessWhat" MatchAttributes="$(UpdateFromConnectionStringAttributes)" />
</UpdateFrom>
</ObjectGroup>
</Objects>
</PublishDatabaseSettings>
</PropertyGroup>
<ItemGroup>
<MSDeployParameterValue Include="$(DeployParameterPrefix)DefaultConnection-Web.config Connection String">
<ParameterValue>Data Source=.\SQLEXPRESS;Initial Catalog=HorstDataProductive;User ID=sa;Password=GuessWhat</ParameterValue>
</MSDeployParameterValue>
</ItemGroup>
</Project>
As you can see I have some additional connection string replacement there that I want to test.
So I execute that last MSBuild-command that I have shown you and it executes without any errors. Instead it says that the web deployment task was successful and that a package has been created in a certain path. Now that is actually the right package. When I import that manually in my IIS it is the result I expect, also the connection string replacement has been done.
But I do not understand why it actually is just creating the package but not deploying it in one run, like in my first command.
Can someone explain?
(Or even better, what do I have to do to make it also deploy that package immediately)
You need to specify the VS version.
http://www.asp.net/mvc/tutorials/deployment/visual-studio-web-deployment/command-line-deployment
msbuild /P:DeployOnBuild=True /P:VisualStudioVersion=11.0 /P:PublishProfile=Dev.pubxml
Don't forget to allow untrusted certs if you're using a 'fake' internal certificate
Looks like you're missing the deploy target.. it's got all the necessary info, but doesn't know what you want it to do. Try this;
msbuild D:\PathToFile\DeployDBVariation01\DeployDBVariation01\DeployDBVariation01.csproj
/p:DeployOnBuild=true;DeployTarget=MSDeployPublish;AllowUntrustedCertificate=true;PublishProfile=ReleaseLocal

MSBuild Web Deploy not updating connection strings

I am currently trying to get my deployment process up and running on my production server. Currently I am using the web deploy and publish profiles to achieve this, and I have everything working correctly, apart from the updating of connection strings to suit the production server.
I am using:
msbuild myProj.csproj /p:DeployOnBuild=true;PublishProfile=myProfile;Configuration=Release
to create the publish package, and the:
call myProj.deploy.cmd /Y /M:http://myServer/MSDeployAgentService -allowUntrusted /U:user /:Password
So this is working, it packages and then sends it to the server fine, and configures IIS correctly, but points to the wrong database.
My publishing profile looks like:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>MSDeploy</WebPublishMethod>
<SiteUrlToLaunchAfterPublish />
<MSDeployServiceURL>http://myserver</MSDeployServiceURL>
<DeployIisAppPath>Website</DeployIisAppPath>
<RemoteSitePhysicalPath />
<SkipExtraFilesOnServer>True</SkipExtraFilesOnServer>
<MSDeployPublishMethod>RemoteAgent</MSDeployPublishMethod>
<UserName>user</UserName>
<_SavePWD>True</_SavePWD>
<PublishDatabaseSettings>
<Objects xmlns="">
<ObjectGroup Name="DBContext" Order="1" Enabled="False">
<Destination Path="Data Source=server;Initial Catalog=ProductionDB;User ID=user;Password="password"" Name="" />
<Object Type="DbCodeFirst">
<Source Path="DBMigration" DbContext="myproj.Repositories.DBContext, myproj.Repositories" MigrationConfiguration="myproj.Repositories.Migrations.Configuration, myproj.Repositories" Origin="Configuration" />
</Object>
</ObjectGroup>
<ObjectGroup Name="DefaultConnection" Order="2" Enabled="False">
<Destination Path="Data Source=server;Initial Catalog=ProductionDB;User ID=user;Password="password"" Name="" />
<Object Type="DbDacFx">
<PreSource Path="Data Source=localhost;Initial Catalog=devDB;User ID=user;Password="password"" includeData="False" />
<Source Path="$(IntermediateOutputPath)AutoScripts\DefaultConnection_IncrementalSchemaOnly.dacpac" dacpacAction="Deploy" />
</Object>
<UpdateFrom Type="Web.Config">
<Source MatchValue="Data Source=localhost;Initial Catalog=devDB;User Id=user;Password=password" MatchAttributes="$(UpdateFromConnectionStringAttributes)" />
</UpdateFrom>
</ObjectGroup>
</Objects>
</PublishDatabaseSettings>
</PropertyGroup>
<ItemGroup>
<MSDeployParameterValue Include="$(DeployParameterPrefix)DBContext-Web.config Connection String">
<ParameterValue> Data Source=server;Initial Catalog=ProductionDB;User ID=user;Password="password"</ParameterValue>
</MSDeployParameterValue>
<MSDeployParameterValue Include="$(DeployParameterPrefix)DefaultConnection-Web.config Connection String">
<ParameterValue>Data Source=server;Initial Catalog=ProductionDB;User ID=user;Password="password"</ParameterValue>
</MSDeployParameterValue>
</ItemGroup>
</Project>
Annoyingly this works fine when Publishing directly from VS2012, just not via command line. Is there a switch or option I am missing from my msbuild call maybe?
It is not working correctly as in my myProj.SetParameters.xml file, the connection strings shown in there are wrong. If I manually change these to the correct connection strings, then the web.xml file is correct on the production server once deployed. How do I get the correct string into my SetParameters file? Any help would be greatly appreciated.
In the end to get around this, in Visual Studio I created a Parameters.xml file in the root of project which holds the values of the connection strings to be used on the production server. These are picked up and used instead of the default values.
The Parameters.xml file looks like:
<?xml version="1.0" encoding="utf-8" ?>
<parameters>
<parameter name="DefaultConnection-Web.config Connection String"
description=""
defaultValue=""tags="" />
Just add as many as you require and obviously populate the attributes as required
My DefaultConnection was not updating either. It turned out that I had to delete the MyProject > PublishProfiles .pubxml file.
Then when attempting to publish the newly built project it asked me to connect to azure and download the publishing profile.
Even though that wizard has a checkbox with the option to turn off overriding the DefaultConnection string with the one pulled down with the publishing profile, unchecking it had no effect. It continued to overwrite the string.
So in the azure control panel (portal) I clicked Websites > My Website > Configure
Scroll down to connection strings and you can show the hidden connection string. I just removed it by hitting the x and then hardcoded the correct one in my web config.
I then removed the .pubxml again and went through the wizard again. Now there is not connectionstring being pulled down with the publish profile.
My Publish Profile .pubxml file (found in Project\Properties\PublishProfiles) had become corrupt with extra duplicate "DefaultConnection-Web.config Connection String" nodes. The connection string updated correctly after I deleted the extra nodes.

Why is msbuild duplicating entries in web.config transformations?

I am using web.config transformations to insert entries into the web.config for certain build configurations.
E.g. my Web.Test.config has this entry:
<elmah>
<errorMail from="me#me.com" to="me#me.com" async="false" smtpPort="25" smtpServer="mail" subject="test.senegal.co.uk Exception" xdt:Transform="Insert" />
</elmah>
This works absolutely fine building from visual studio.
However when creating a deployment package using msbuild, the entry is duplicated in the web.config. This obviously causes an exception.
Any ideas?
UPDATE
My "master" config is Web.Master.config not Web.config. The web.config file gets overwritten on build in visual studio. I think it must have something to do with this.
What I think is happening is msbuild is transforming web.config rather than using the Web.Master.config.
The question is how to tell it to use the right master.
I added /p:TransformWebConfigEnabled=false to the msbuild parameters, as my web.config was already being transformed in a BeforeBuild target like so:
<Target Name="BeforeBuild">
<TransformXml Source="$(MSBuildProjectDirectory)\Web.Master.config" Transform="$(MSBuildProjectDirectory)\Web.$(Configuration).config" Destination="$(MSBuildProjectDirectory)\Web.config" />
</Target>
In my case duplication was caused by xdt:Transform="Insert". If remove it from Web..config and leave the rest it will work properly, e.g.:
<!-- doesn't work -->
<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="My"
xdt:Transform="Insert" />
vs.
<!-- works -->
<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="My"
/>