Website publish failing due to file path being too long - asp.net

I am trying to publish a Website project from a vendor that has ridiculously long paths to some of its files. When publishing, the error is:
The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
When I publish, Visual Studio 2012 Update 3 is attempting to write to a temp directory, and the prefix is quite long:
C:\Users\cuser\AppData\Local\Temp\WebSitePublish\MidasCMS400v9-1580334405\obj\Debug\Package\PackageTmp\
I thought I might be able to redirect VS to a different temporary directory at c:\tem by following this SO answer: Temp path too long when publishing a web site project
I create my publication profile, and as soon as I open it, there is an error indicating that WebPublishMethod is not an element of PropertyGroup. Regardless, I updated the file so it looks like this:
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>FileSystem</WebPublishMethod>
<LastUsedBuildConfiguration>Debug</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<ExcludeApp_Data>False</ExcludeApp_Data>
<publishUrl>C:\Sites\MidasPublish</publishUrl>
<DeleteExistingFiles>False</DeleteExistingFiles>
<AspnetCompileMergeIntermediateOutputPath>c:\tem\</AspnetCompileMergeIntermediateOutputPath>
</PropertyGroup>
</Project>
When I try to publish, I get the a modal box pop-up entitled "File Modification Detected", with the message "The project YourWebsite has been modified outside the environment", and it asks me if I want to reload. In my error list, I continue to get the error about the path being too long, as it is not attempting to use the c:\tem directory I identified.
I need to put this bloody thing onto a server, I am up for any solution that allows me to publish the bloody thing. I don't know much about the Website project template, so please let me know if there is a better way.

From http://forums.asp.net/t/1944241.aspx?Website+publish+failing+due+to+file+path+being+too+long
Add the following line in default PropertyGroup of web project file.
<IntermediateOutputPath>..\Temp\</IntermediateOutputPath>
You can likely make the above path C:\temp or ......\Temp (as needed to get it as close to root of the drive as possible.
In my case, there was no .csproj or .vbproj (website project file) but there was a website.publishproj file that warns you not to edit it, but I did anyway, and it did the trick.

Thanks to Stelvio, from http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2156195-fix-260-character-file-name-length-limitation , there is a solution :
Well, I found a workaround that ALLOW work with path with more than 260 chars.
Disclaimer: I've tried this trick only on Windows 8 x64 and Visual Studio 2013
So, to make it work I've just create a junction to the folder with the mklink command:
Assume this is the original path: d:\very\very\long\path\to\solution\folder, you can obtain a short link as d:\short_path_to_solution_folder just jaunching this command from a dos shell as administrator:
mklink /J d:\short_path_to_solution_folder d:\very\very\long\path\to\solution\folder
change source and destination path to you needs
Best Regards!
Stelvio
from this link :
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2156195-fix-260-character-file-name-length-limitation

While moving the project closer to the root file does work. I found a link to a solution that did work for me. The site also does a great job at discussion the issue as well as the details behind his solution.
Sayed Hashimi's solution to long path issue
EDIT:
To Summarize the provided link:
You can update your publish profile file, which is used by MSBuild, to include a replace rule that will shorten the path of your output when publishing to a web deploy package (Zip file).
For example, let's say publishing using the default profile created by Visual Studio, we get the following paths in the zip file:
archive.xml
Content\C_C\Temp\package\WebApplication1\obj\Release\Package\PackageTmp
Content\C_C\Temp\package\WebApplication1\obj\Release\Package\PackageTmp\bin
Content\C_C\Temp\package\WebApplication1\obj\Release\Package\PackageTmp\bin\WebApplication1.dll
Content\C_C\Temp\package\WebApplication1\obj\Release\Package\PackageTmp\index.html
Content\C_C\Temp\package\WebApplication1\obj\Release\Package\PackageTmp\Web.config
parameters.xml
systemInfo.xml
The trick is to replace all of the path defined after Content with a shorter path. In this particular example, replace the path with "website" in the PackagePath element.
One can edit the publishing profile file (.pubxml) and add the follow lines near the end of the file, just before the Project element is terminated.
<PropertyGroup>
<PackagePath Condition=" '$(PackagePath)'=='' ">website</PackagePath>
<EnableAddReplaceToUpdatePacakgePath Condition=" '$(EnableAddReplaceToUpdatePacakgePath)'=='' ">true</EnableAddReplaceToUpdatePacakgePath>
<PackageDependsOn>
$(PackageDependsOn);
AddReplaceRuleForAppPath;
</PackageDependsOn>
</PropertyGroup>
<Target Name="AddReplaceRuleForAppPath" Condition=" '$(EnableAddReplaceToUpdatePacakgePath)'=='true' ">
<PropertyGroup>
<_PkgPathFull>$([System.IO.Path]::GetFullPath($(WPPAllFilesInSingleFolder)))</_PkgPathFull>
</PropertyGroup>
<!-- escape the text into a regex -->
<EscapeTextForRegularExpressions Text="$(_PkgPathFull)">
<Output TaskParameter="Result" PropertyName="_PkgPathRegex" />
</EscapeTextForRegularExpressions>
<!-- add the replace rule to update the path -->
<ItemGroup>
<MsDeployReplaceRules Include="replaceFullPath">
<Match>$(_PkgPathRegex)</Match>
<Replace>$(PackagePath)</Replace>
</MsDeployReplaceRules>
</ItemGroup>
</Target>
Now, the publish profile paths should look something like the following:
archive.xml
Content\website
Content\website\bin
Content\website\bin\WebApplication1.dll
Content\website\index.html
Content\website\Web.config
parameters.xml
systemInfo.xml

The answer of Jason Beck worked to me with a small change. To avoid the error "The IntermediateOutputPath must end with a trailing slash." use the "\" at the end of the path:
..\Temp\
Your "CONFIG_PUBLISH_FILE.pubxml" should look like this (The "..." omits other configuration that you file may have):
...
...
..\Temp\
...

At the time of publishing the project, the visual studio compiler checks the size of the files that are part of the project.
So I searched for long names in files.
I found and renamed those files.
Did Work perfectly

In my case it was because the default legacy string length limitation of windows. This was still set to 256-character limit.
To fix this, from an admin powershell session I ran the following command
New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" `
-Name "LongPathsEnabled" -Value 1 -PropertyType DWORD -Force
I needed to reboot the system for the changes to take effect.
Microsoft reference document link here

This error comes because of long path name....U just cut your folder from current location to D drive or F drive. suppose your project folder name is "myproject", and you should cut this folder and paste to D drive of F drive,that your current path name will be D:\myproject or F:\myproject. Then you publish again......It will work...

Related

Removing comments from web.config on build

Is it possible to remove the commented lines from a web.config on build?
xml transform is fine to remove some elements but I couldn't find any syntax to clean the comments from the file.
We are using TFS 2010 build server for our builds.
<add xdt:Transform="RemoveAll" xdt:Locator="XPath(//comment())" />
Put this node within the root node of your transform file. "XPath(//comment())" selects all XML comment nodes to delete.
UPDATE: See actual and working answer below.
It's not possible to do with xml transformation.
But you can do it with your own console app or msbuild task.
See example code here Remove XML comments using Visual Studio 2010 Web Config Transformation
I had a similar problem where I wanted to remove dev comments from the config files before I published to the web site. I wrote an app that will recursively remove comments from config files in the directory I specify on the command line. The sample below assumes YourCommentRemover will do the same.
I included the comment remover project as part of my solution and referenced it in the web app I plan to deploy. You can just add the executable as a reference if you want. Since I didn't want the comment remover to get deployed, I added a task to delete it from the bin directory where it was being staged for deploy, (ProjectDir)obj\$(Configuration)\Package\PackageTmp\.
Open your project file in a text editor (You can right-click on the project file in the solution explorer and select 'Edit Project File').
Go to the very end of the project file and insert the following before </Project>:
<Target Name="BeforePublish" BeforeTargets="MSDeployPublish">
<Exec Command="$(ProjectDir)bin\YourCommentRemover $(ProjectDir)obj\$(Configuration)\Package\PackageTmp" />
<Exec Command="del $(ProjectDir)obj\$(Configuration)\Package\PackageTmp\bin\YourCommentRemover.*" />
</Target>
This target will run before any files are copied to the web application location on publish.

Specifying folders not to sync in Web Deploy

I use the following script to deploy my ASP.NET MVC app to our web server:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe MySolution.sln^
/p:Configuration=TeamCity-Test^
/p:OutputPath=bin^
/p:DeployOnBuild=True^
/p:DeployTarget=MSDeployPublish^
/p:MsDeployServiceUrl=https://mywebserver.com:8172/msdeploy.axd^
/p:username=MyDomain\MyUser^
/p:password=MyPassword^
/p:AllowUntrustedCertificate=True^
/p:DeployIisAppPath=mywebsitename.com^
/p:MSDeployPublishMethod=WMSVC
Now I need to specify to not sync the /uploads folder. Can I specify that in this script? Thanks!
Clarification:
I have the Uploads folder in my project. I'd like for Web Deploy to create the folder. I do not want it to delete the folder/subfolders/files from my web server because it contains user-uploaded content.
Clarification #2:
I just found the SkipExtraFilesOnServer=True option. However, I don't want this to be global. I'd like to set it to a single folder.
UPDATE:
Apparently, what you really want is prevent web deploy from removing existing directory on the destination server, but still have the folder created in case it's not there. You can accomplish this as follows:
create YourWebProjectName.wpp.targets file next to you the project file with the following content:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<MsDeploySkipRules Include="SkipELMAHFolderFiles">
<SkipAction></SkipAction>
<ObjectName>filePath</ObjectName>
<AbsolutePath>$(_DestinationContentPath)\\NameOfYourFolder\\.*</AbsolutePath>
<Apply>Destination</Apply>
<XPath></XPath>
</MsDeploySkipRules>
<MsDeploySkipRules Include="SkipELMAHFolderChildFolders">
<SkipAction></SkipAction>
<ObjectName>dirPath</ObjectName>
<AbsolutePath>$(_DestinationContentPath)\\NameOfYourFolder\\.*\\*</AbsolutePath>
<Apply>Destination</Apply>
<XPath></XPath>
</MsDeploySkipRules>
</ItemGroup>
</Project>
Change NameOfYourFolder and YourWebProjectName accordingly. This assumes, you have it in the root, I believe, you can use relative path if it's not the case.
The first MsDeploySkipRules entry tells webdeploy not to remove any files in Name_OfYourFolder.
The second MsDeploySkipRules tells webdeploy not to remove any child folders in Name_OfYourFolder.
Also, to have the folder created if it's not present on the destination server, you have to do the following:
include the folder into the project
add a dummy DeployemntPlaceholder.txt file into it and include it into the project as well
DeployemntPlaceholder.txt is required to tell MSBUild to add the folder into the package: empty folders are ignored.
I've tested this approach and it works fine when you run publish in the manner you've shown. I've used this answer to get the msbuild items syntaxt right. I believe, this is a MSBuild way to customize flags, passed to webdeploy by MSBuild Deployment Pipeline.
If you ran MSDeploy directly, you could use skip arguments in the following manner:
-skip:objectname='filePath',absolutepath='logs\\.*\\someNameToExclude\.txt'
UPDATE 2
You might also want to have ACL write permissions set on your \Uploads folder - there's a complete guide to do this: Setting Folder Permissions On Web Publish
Conserning the original question "Specifying folders not to sync in Web Deploy", the easiest way to do this is as follows:
You can create a publish profile and add the following lines:
<PropertyGroup>
<ExcludeFilesFromDeployment>
File1.aspx;File2.aspx
</ExcludeFilesFromDeployment>
<ExcludeFoldersFromDeployment>
Folder1;Folder2
</ExcludeFoldersFromDeployment>
</PropertyGroup>
I've tested this approach for excluding files using publish profiles. An easy guide is here (scroll to Edit the .pubxml file to exclude robots.txt section).
You can also do this in .wpp.targets file or edit you csproj. See more information at Web Deployment FAQ for Visual Studio and ASP.NET

Temp path too long when publishing a web site project

I am trying to publish an ASP.NET web site project using the Publish Web Site tool but get this error:
ASPNETCOMPILER(0,0): Error ASPRUNTIME: The specified path, file name,
or both are too long. The fully qualified file name must be less than
260 characters, and the directory name must be less than 248
characters.
I see that it is trying to copy the files to a very long path in AppData:
Copying all files to temporary location below for package/publish:
C:\Users\imx0\AppData\Local\Temp\1\WebSitePublish\BMW.Web-424993535\obj\Debug\AspnetCompileMerge\Source.
c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v /BMW.Web -p C:\Users\imx0\AppData\Local\Temp\1\WebSitePublish\BMW.Web-424993535\obj\Debug\AspnetCompileMerge\Source C:\Users\imx0\AppData\Local\Temp\1\WebSitePublish\BMW.Web-424993535\obj\Debug\AspnetCompileMerge\TempBuildDir
I couldn't find anything about this temp directory in my .pubxml publish profile. How can I change the temporary directory that Visual Studio copies the files to?
Add this to your publish profile to modify the temporary directory for package/publish:
<AspnetCompileMergeIntermediateOutputPath>c:\shortPath\</AspnetCompileMergeIntermediateOutputPath>
Go to your web project folder, navigate to Properties\PublishProfiles folder.
open your profile file profile_name.pubxml (not the profile_name.pubxml.user)
copy/past <AspnetCompileMergeIntermediateOutputPath>c:\shortPath\</AspnetCompileMergeIntermediateOutputPath> under the <PropertyGroup> tag
save your file, you would be able to publish your website using this profil
This is sort of an aside answer, but I ran into this problem when trying to MSBuild a solution that depended on nodeJS and gulp. The problem was that the gulp dependency tree became very deep and the aspnet_compiler was trying to copy that tree to a deeper directory, resulting in this error. I tried everything noted in here but nothing worked.
As it so happened, I was building with TFS, so my solution was to run an attrib +h node_modules\* /S /D before msbuild to hide the directory tree and then attrib +h node_modules\* /S /D. That did it for me.
Sure would be nice if the error thrown in this situation by the compiler revealed the path that caused the write to fail...
try adding this
<IntermediateOutputPath>..\Temp</IntermediateOutputPath>
to the default <propertyGroup />
None of the other answers worked for me.
Visual Studio 2013 Community Edition.
I changed the TMP and TEMP environment variable to a short folder name and it worked.
We identified the lengthy files/folders using this solution, then corrected the issue from there:
Run this script at the command prompt: dir /s /b | sort /r /+261 > out.txt it will output all file paths into the out.txt file
Copy the output to an Excel file
In the next column over from what you pasted in add this Excel function: =LEN(A1) where "A1" is the cell, copy this against every file length so you can see how long the paths are
Sort in Excel by the path length
Identify the lengths over the recommended limit
I know this is a bit long-winded but if you have several files that are resulting in this issue you'll be able to see them all.
Even though the content of node_modules was not included in neither version control not in the *.csprojfile itself Deleting the whole node_modules folder did the trick for me.
You can try the selected solution for correcting the long file path issue.
Still if not able to publish due to some other issue, You can try below method.
=> If the 'Solution Configuration' is in 'Debug' mode, please change the same to 'Release' mode and Publish the files.
=> If the Solution Configuration is in Release mode, and if the problem still persists, please try to delete the dll generated earlier in the 'Release' folder of our project and Publish the project once again.
Any of the above method will solve the issue.
For me, using Visual Studio 2019, the only change to the publish profile .pubxml file that worked was:
<WPPAllFilesInSingleFolder>c:\shortPath\</WPPAllFilesInSingleFolder>
I discovered this property at line 484 of Microsoft.Web.Publishing.targets file. Full path was C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\VisualStudio\v16.0\Web.

MSDeploy Package has Missing Files

I'm using MSBuild to build a web application project and adding parameters to create the package file. All of that is good. I get two folders in the _PublishedWebSites output:
AppName
AppName_Package
In the ApplicationName folder, the entire site is there and I can simply copy this folder over to the website and it will run.
In the Package folder I've got the expected 5 files:
AppName.deploy.cmd
AppName.-readme.txt
AppName.SetParameters.xml
AppName.SourceManifest.xml
AppName.zip
When deploying the package however, the web application dll (AppName.dll) is missing, as are a few other important referenced dependencies.
Inspecting the package itself does reveal that the files are in fact missing from the web applications bin directory.
This is very odd, considering the files are all in the root AppName folder, but not in the package found in AppName_Package folder.
The only MSDeploy related modification I've made is that I am overriding the CopyAllFilesToSingleFolderForPackageDependsOn target to copy in some handlers from a library project, and this all works nicely.
<PropertyGroup>
<CopyAllFilesToSingleFolderForPackageDependsOn>
CustomCollectFiles;
$(CopyAllFilesToSingleFolderForPackageDependsOn);
</CopyAllFilesToSingleFolderForPackageDependsOn>
</PropertyGroup>
<Target Name="CustomCollectFiles">
<ItemGroup>
<_CustomFiles Include="..\Libraries\CodeLibrary1\**\*.ashx" />
<FilesForPackagingFromProject Include="%(_CustomFiles.Identity)">
<DestinationRelativePath>$(ProjectDir)%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
</FilesForPackagingFromProject>
</ItemGroup>
</Target>
So, I'm not able to determine why the web application's DLL, and only a few other (referenced)DLLs are removed from the bin directory during the package creation process (but not all - maybe 3%).
Any ideas what I should be looking for in the log file?
EDIT: (Response to Sayed):
I truly appreciate you answering my post. Unfortunately I’m not sure we are on the same page. Like I said, I might not have explained my problem well enough to actually clue others in on exactly what my issue is. Let me try once more to clarify
Getting external files copied into my web application was not the problem. I understand that scanning over my post and seeing the all too common “CopyAllFilesToSingleFolderForPackageDependsOn” element set off a few red flags, alarms, bells and whisles. . It seems to be a common thing people are struggling with, and as you point out, there have been some issues with it being executed. That worked OK for me.
My problem has more to do with project referenced DLLs, AND most importantly the application DLL itself not being copied.
More tweaking around today has revealed something I was not aware of. For instance:
Kicking off a Build on TFS outputs a couple things:
The source from TFS is output to the Source Directory (SourceDir)
This only contains the output what is checked into TFS
This does not include project or file references, only what is committed in TFS
The output of the build is into two folders
Binaries (includes project and file references)
Sources (only what is included/committed in TFS)
Inside Binaries I find the _publishedWebsites folder, as well as all project and file references, while inside Sources there are just the files that are checked into TFS.
My problem, or confusion, was thinking that when I pass in the following parameters to MSBuild Arguments, it would take the output from the build (_PublishedWebsites) and use those files to create the package. It does not do that.
The actual process builds a package based on the files in the SOURCES folder. So, here is my dilemma/confusion, because I did not commit my application dll into source, it was not being included in the package, and therefore was not being sent off to the test site on the test server.
/p:DeployOnBuild=True /p:DeployTarget=MsDeployPublish /p:CreatePackageOnPublish=True /p:MSDeployPublishMethod=RemoteAgent /p:MSDeployServiceUrl=http://<mytestsite> /p:DeployIisAppPath="<AppName>" /p:UserName=<domain\user> /p:Password=<mypassword> /p:SkipExtraFilesOnServer=false /p:AllowUntrustedCertificate=True
To wrap this up, once I “checkout for edit” my application DLL on my dev machine, and them compile the solution, and finally commit the application DLL to source control, then it is included in the package because it is included as just another source item.
So, I guess this becomes my fault for not understanding how to get the output of the TFS BUILD into the sources folder, and get that included into the package used by msdeploy.
There is probably something very fundamental that I missed or just skimmed over - and not understood, that the package creation is from the Sources folder and not the _PublishedWebsites folder. Nor do I understand how to get the MSBuild compiled application dll, and project referenced dlls, into my package – replacing the committed source items in source control.
I hope this isn’t a complete waste of your time because I missed a
source=<some-parameter>
somewhere.
I appreciate it you can direct me to any existing sources out that already explain this to where I should be able to get my head around it and get this working. Or if it’s so easy to just tell me here.
The issue here is that the CopyAllFilesToSingleFolderForPackage target itself is not getting called from the VS2012 targets. We made a lot of changes and this may be a regression on our side. I will look into this to see if there is anything that we can do. Fortunately it should be pretty straight forward to update this to get the behavior that you are looking for. Instead of using CopyAllFilesToSingleFolderForPackageDependsOn you should be able to use PipelineCollectFilesPhaseDependsOn as an alternative. You should be able to change what you have above to
<PropertyGroup>
<PipelineCollectFilesPhaseDependsOn>
CustomCollectFiles;
$(PipelineCollectFilesPhaseDependsOn);
</PipelineCollectFilesPhaseDependsOn>
</PropertyGroup>
<Target Name="CustomCollectFiles">
<Message Text="Inside of CustomCollectFiles" Importance="high"/>
<ItemGroup>
<_CustomFiles Include="C:\Temp\_NET\WAP-AfterPublish\MvcApplication1\additional files\**\*" />
<FilesForPackagingFromProject Include="%(_CustomFiles.Identity)">
<DestinationRelativePath>additional files\%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
</FilesForPackagingFromProject>
</ItemGroup>
</Target>
I just tried this for both VS2012 as well as VS2010 so this seems like a better to solution then the CopyAllFilesToSingleFolderForPackageDependsOn approach. Can you try that out and let me know what you find out?

Make Web.config transformations work locally

I want to get web.config transformations working locally but apparently the transformations only occur when doing deployments.
Does anybody know of a way to run the msbuild target "TransformWebConfig" without it going through the "rebuild" process and also specify and output directory where to spit out the transformed web.config?
EDIT: Using Sayed's answer, I created a .bat file to do run the task for me:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Msbuild.exe "D:\Demo\Transformation.proj" /t:TransformWebConfig
copy /Y "D:\Demo\Web.config" "D:\MyProject\Web.config"
del ""D:\Demo\Web.config"
the "Transformation.proj" is a copy of Sayed's code snippet in the answer below. Just specify the source, target, and destination for the transformation. The new file, in this case, the transformed "web.config" will be in the "D:\Demo" directory. I am simply copying it over to overwrite my project's web.config and, finally, deleting the generated file in the "demo" folder.
Also, I created a macro to run this batch file and perform the tranformation for me:
Public Module DoTransform
Sub RunTransformBatchFile()
Try
Process.Start("D:\Demo\RunTransform.bat")
Catch ex As System.Exception
MsgBox(ex.Message)
End Try
End Sub
End Module
You can also add a button on your toolbar to run this batch and/or assign a shortcut key to execute.
if you want to transform a config file without using the Web Publishing Pipeline then you just use the TransformXml task manually. I've written a detailed blog post on this at http://sedodream.com/2010/04/26/ConfigTransformationsOutsideOfWebAppBuilds.aspx, but here are the high lights:
<Project ToolsVersion="4.0" DefaultTargets="Demo" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask TaskName="TransformXml"
AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>
<Target Name="Demo">
<TransformXml Source="app.config"
Transform="Transform.xml"
Destination="app.prod.config"/>
</Target>
</Project>
Here I manually transform the app.config file using transform.xml file and the destination file is app.prod.config.
One thing that you mentioned was being able to do transformation locally when running the app. The reason why we only perform the transform on package/publish is because if we transformed web.config itself then next time you debug your app the web.config gets transformed again. So for example if in your web.debug.config you have the transformation to add a value to config, everything is OK the first time you add that but then the next time your run/debug your app it will get added again. So it is best to avoid that.
If you are using Visual Studio 2015, you can just right click on the transform of the desired environment, and click "View Preview" ... It will then generate the transform, and you can copy and paste that into the normal Web.config file for debugging purposes. Just don't commit it!
If you are using Visual Studio 2013, you can install the SlowCheetah - XML Transforms extension

Resources