Move intermediates directory on C# projects in Visual Studio - c#

I'm currently in the process of stripping down, refactoring and cleaning up a medium sized (15 ish projects) Visual Studio solution. The solution contains projects in both C++ and C#.
I'm keen to keep things as neat as possible in terms of output - seperating anything compiler created from source code, as it helps subversion (okay, I can tell it to ignore files, but I still feel it's messy) from freaking out.
The output I would like to achieve is as follows:
SolutionDir/
SolutionDir/src/project1/{ Code here }
SolutionDir/int/project1/configuration/{.obj files and other misc compiler junk here}
SolutionDir/bin/project1/configuration/{The fun stuff goes here}
This seems trivial with C++ projects as you can specify both the output and the intermediates directory. However with C#, at least through the Visual Studio 2008 User Interface it seems impossible to move the obj directory?
After doing some digging, I added
<IntermediateOutputPath>..\..\int\ProjectName\Debug\</IntermediateOutputPath>
to the C# .csproj
This appears to work, sort of. It's true the intermediates appear to end up there, but a directory 'obj' and under it a configuration directory (e.g. 'debug') and then a 'TempPE' directory are created in the old location - all of which are empty.
This isn't really a big deal, but it would be nice to know the cause of this behavior and if possible a way to fix it.
Thanks in advance!

If you add both of the following lines to each build configuration then the "obj" folder is not created by default and there is no need for a post-build action:
<IntermediateOutputPath>Assembly\obj\Debug\</IntermediateOutputPath>
<BaseIntermediateOutputPath>Assembly\obj\Debug\</BaseIntermediateOutputPath>
SVN / SCC ignore properties are also useful if desired

I've been searching for a solution for this problem myself, and came up with something less intrusive.
Create a bat file named "CleanSrcDir.bat" somewhere (i placed mine in my project path) with the following contents:
rmdir /S /Q %1obj
SET %ERRORLEVEL%=0
After this, add something similar to the C# project's post-build events:
$(ProjectDir)CleanSrcDir.bat $(ProjectDir)
(This assumes you placed your bat file in the project directory, of course.)
Then change the post-build settings to "Always", and you're done.
It's a little hackish, but sure makes the version control problem go away.

I'd recommend adding directories that you want to ignore to an SVN ignore property one-level-up. Also, when you do an initial commit and don't add bin and obje directories, SVN clients won't freak. On another note, consider placing generated files into GeneratedFiles subdirectory of your project, and not checking that directory into SVN.

Related

What is TempAssemblyInfo.cs?

My question is pretty basic, I understand what AssemblyInfo.cs is, but why is there a Temp version generates in the same Properties folder? What is it used for? Do people usually add it to their .gitignore?
I believe it's what is generated from the MSBuild/csproj build. I'm not sure what process would be generating that otherwise - check for nuget packages and other things in your csproj that might be generating it.
Generally should should add bin/ and obj/ (where this file is placed) to your .gitignore.

How to copy additional files on build?

I have a WebApi2 application and it references other projects within the solution. One of these includes some files that I want copied on build. These files have their Copy to Output Directory property set to true.
The files are correctly located in the bin folder of their assembly.
However:
After the build I need them to be copied to the App_Data folder of the web application
Included in the files that get published to IIS
Is it possible?
From my experience you are going to have to get your hands dirty with MSBuild. Its been ages since I've used it but you will need to use the Move Task
This is what Visual Studio uses in the background to build the projects. It may seem daunting but is actually pretty simple once you get used to it. There are tons of tutorials online.
Alternatively, and the most straightforward way, is that you include the files in the APP_DATA folder from within the solution.
EDIT: As mentioned by robor78 you will need to call the Move Task in the Post-Build event
Add build events
In Visual Studio -> Solution Explorer -> right click the project -> properties -> go to build events.
Use something like xcopy
Also if click on "Edit Post-Build" you will see a list of useful folders and file names which you can use e.g. $(OutDir)
You can use Xcopy from the Post build event. It is pretty straight forward but will not run if code not changed. So if you update configs etc. you must force the build I beleive.
See here for how to use xcopy.
http://commandwindows.com/xcopy.htm
There are wild cards and all kinds of useful features, but your situation is pretty simple. Just copy from $(ProjectDir)/bin or something like that to a path.

Visual Studio Rebuilds unmodified projects

So, as the title reads, I have a VS2010 solution with ~50 projects in it right now. If I make a change to a "top level" project that nothing references then VS still rebuilds all 50 projects. I'm running Visual Studio 2010 Ultimate without any add-ons. I am using ILMerge to consolidate all of the projects into a single file.
I have verified this by checking the time stamps of the lower level dlls and see that they are indeed rebuilt even though their code wasn't touched.
I've read all responses and comments for:
Visual Studio 2008 keeps rebuilding
Visual studio keeps building everything
Strange VS2010 build glitch occurs in my solution
Reasons for C# projects to rebuild in Visual Studio
But most of them just offer suggestions on unloading projects to speed up build times but nothing concrete as to a fix. I'm trying to figure out why VS thinks these dependent projects need to be rebuilt when they don't and fix it.
I've turned on 'Tools > Options > Projects and Solutions > Build and Run > Only build startup projects and dependencies on run' but with no effect.
Also, if I just rebuild a "mid-level" project that only has 8 (in)direct dependencies then it still builds all 8 projects even though ILMerge isn't invoked and none of the dependent projects have been modified.
Thank you everyone for any insight you may be able to provide.
Added
To test some of the suggestions I created a new WinForms project from scratch. I then created two new projects inside that solution. I copied all of the code and resources (not project file) from my two 'lowest level' projects into the two brand new projects (I did this by dropping the files and folders from Explorer onto the project in Visual Studio).
The lowest project, let's call it B, did not reference any other project. The next project, A, referenced B only. So once I added the required .NET and external assembly references to the projects then the solution would build.
I then had my new WinForm project reference A and did a full build. So the ref chain is:
WinForm -> A -> B
I then modified WinForm only and did a standard build (F6). As before, Visual Studio rebuilt all three projects.
After some systematic eleminiation of source files in project B I found that if I removed my Resources.Designer.cs and Resources.resx (and commented out the code that made use of the .Properties.Resources object of those resources) then a modification of WinForm would no longer rebuild the entire solution and would only rebuild WinForm.
Adding the Resources.resx and Resources.Designer.cs back to project B (but leaving the referenced code commented out so that nothing was making use of the resources) would re-introduce the full build behavior.
To see if perhaps my resource files were corrupted, I deleted them again and then created a new one (via Project Properties -> Resources) and re-added the same resource as before, which was a single Excel file. With this setup the full rebuild would still occur.
I then removed the single resource, but left the resource file in project B. Even with no resources added, but the resource file still in the project, the full (unneeded) rebuild would occur.
It appears that just having a resource file added to a (.NET 3.5) project will cause Visual Studio 2010 to always rebuild that project. Is this a bug or intended/expected behavior?
Thanks all again!
Open Tools - Options, select Projects and Solutions - Build and Run in tree, then set "MSBuild project build output verbosity" to Diagnostic.
This will output the reason for building a project, i.e.
Project 'ReferencedProject' is not up to date. Project item
'c:\some.xml' has 'Copy to Output Directory' attribute set to 'Copy
always'.
or
Project 'MyProject' is not up to date. Input file
'c:\ReferencedProject.dll' is modified after output file
'c:\MyProject.pdb'.
In this case the fix is to copy some.xml only if newer.
Pre and post build events can trigger build as well.
While I don't think this is a fix, it is a workaround that has worked for my situation...
I originally had about 5 projects out of 50 that contained a Resources section. These projects would always be rebuilt and thus anything that they depended on would also be rebuilt. One of those 5 projects was a "base" level library that 48 of the other projects referenced, thus 96% of my project would be rebuilt every time even if it didn't need it.
My workaround was to use dependency injection, interfaces, and a dedicated "Resources" project. Instead of having those 5 projects reference their own Resources object, I created an interface in each project that would supply the desired resources. Then, the classes that needed those resources would require that interface be passed in during their creation in the constructor (constructor injection).
I then created a separate "Resources" project that had an actual Resources section like normal. This project only contained the resources themselves, and a class for each interface that was needed to provide those resources via an interface. This project would reference every other project that had a resource dependency and implement the interface that the project needed.
Finally, in my "Top Level" project which nothing referenced (and where the exe was actually built and my composition root lives) I referenced the "Resources" project, wired up the DI, and away we went.
This means that only two projects (the "Resources" and the "Top Level") will be rebuilt every time, and if I do a partial build (Shift-F6) then they won't get rebuilt at all.
Again, not a great work around, but with 48 projects being built every time a build would take about 3 minutes, so I was losing 30 to 90 minutes a day with needless rebuilds. It took awhile to refactor, but I think it was a good investment.
Here is a simplified diagram. Note that the dependencies from Main.exe to Proj1 and Proj2 are not shown in order to reduce clutter.
With this design, I can do a build of Proj1 or Proj2 without triggering a full rebuild, since they don't have any dependencies on a Resources section. Only Main knows about the Resources implementation.
This happens when a project has a file that doesn't really exist.
The project can't determine if the file was changed (because it's not there) so it rebuilds.
Simply look at all the files in the project, and search for the one that doesn't have an expandable arrow near it.
I had the same issue in VS 2015.
What did the trick for me is:
One project was referencing itself copy in some other project bin (magic, yes). This kind of stuff could be found when switching to diagnostic build output (in build options) and then trying to build projects one by one from the top of projects hierarchy - if you see the project that rebuilds even if nothing has been changed then see it's references.
I've changed all "copy always" files in all projects to "copy if newer". Basically, in all .csproj files replace <CopyToOutputDirectory>Always</CopyToOutputDirectory>
to <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
Then I've disabled NTFS tunneling as described in this article with this powershell script:
New-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name "MaximumTunnelEntries" -Value 0 -PropertyType "DWord"
After that I needed on rebuild and it seems working for now.
In my case the culprit was "Copy Local" setting of a referenced dll set to true and "Copy to Output Directory" setting a file set to Copy always.
For .Net Core Projects, all solutions above are not working.
I've found the solution. In case you are using Visual Studio 2019:
Build the solution twice
Turn on Tools -> Options -> Projects and Solutions -> SDK-Style Projects -> Logging Level -> Verbose
Clear the output window
Build your start project
Inspect the output window. All the string starting with FastUpToDate
You will find some project items that are making your project not up to date.
Fix these issues and try again from step 1. If your fixes are correct, you will achieve Build: 0 succeeded, 0 failed, {n} up-to-date, 0 skipped in the last string of build output.
The MSBuild team is collecting documentation about investigating build incrementality issues here:
https://github.com/Microsoft/MSBuild/wiki/Rebuilding%20when%20nothing%20changed
UPDATED LINK: https://github.com/dotnet/msbuild/blob/main/documentation/wiki/Rebuilding-when-nothing-changed.md
Based on your observations, it sounds like you have projects expressing dependencies to other projects in a way that isn't obvious. It is possible for orphaned dependencies to remain in project files without being apparent in the UI. Have you looked through a misbehaving project file after opening it in a text editor? Checked solution build dependencies?
If you're not able to spot anything, try recreating one of your projects from scratch to see if the new project exhibits the same problem. If the clean project builds correctly, you'll know that you have unwanted dependencies expressed somewhere. As far as I know, these would have to be in the project file(s) or the solution file, unless you have makefiles or other unusual build steps.
Another problem that frequently happens is when some item in your solution has a modified stamp that is in the future. This can happen if you set your clock forward, and then set your clock to the correct time. I had this happen while installing Linux.
In this case you can recursively touch all the files using git bash (yes, in Windows):
find . -exec touch {} \;
I've finally found one more culprit that I had hard time finding by increasing the build log verbosity.
In some cases, MSBuild looks for vc120.pdb in the output folder, and if this file doesn't exist, it will rebuild the entire project. This occurs even if you have disabled debug symbol generation.
The workaround here is to enable debug symbols and let this file get generated, then disable the setting again without deleting the PDB file.
I had this same problem and it turned out to be related to a couple of project that had a copy local reference to a dll in their own output directory.
The key to finding this was having diagnostic output set for the build output, but also knowing what to look for in the log. Searching for: 'not up to date' was the key.
Here is an answer from VS2010 always rebuilds solution?
This issue is solved by changing the project files, cleaning solution,
deleting all bin folders by hand, restarting Visual studio and
rebuilding everything.
I had the same issues with you.
I found that it came from some deleted files.
When I had removed the files from my project, the issues was gone.
Regards.
For this category of build problems setting MSBuild output verbosity to 'diagnostic' is indeed a necessary first step. Most of the time the stated reason for the re-builds would be enough to act upon, BUT occasionally MSBuild would erroneously claim that some files are modified and need to be copied.
If that is the case, you'd need to either disable NTFS tunneling or duplicate your output folder to a new location. Here it is in more words.
I had the problem of Visual Studio rebuilding projects when upgrading from Visual Studio 2015 to 2017 and I add this answer for the benefit of those who might experience similar problems, as it does not seem to be documented anywhere.
In my case, the problem was that all projects in the solution had the same intermediate Output path (obj). The file GeneratedInternalTypeHelper.cs gets generated by all projects containing XAML. Up to Visual Studio 2015, the build process apparently did not check for the file date of this file and thus no problem with it occurred. With VS2017 the file date of this file is checked and because a later project in the build process will overwrite it (with the same content), the earlier project will re-build, re-triggering the later build, ad infinitum.
The solution in this case is to ensure that all projects have differing intermediate output directories, which will make the problem go away.
In my case (mixed C#, C++/CLI and native C++ solution) , some C++ projects were being re-linked even if nothing had changed. I spent ages trying to work out what was happening. In the end I worked out from the "Command Line" option that the PDB output path (option /Fd) could not handle the folder setting $(IntDir). I removed that - an empty value will do the default correctly - and my issue went away.
As others have noticed, a likely reason is that CopyToOutputDirectory is set to Always. This can be fixed simultaneously in all project files by applying the powershell script below:
$folder = "C:\My\Solution\Folder"
$csvFiles = Get-ChildItem $folder *.csproj -rec
foreach ($file in $csvFiles)
{
(Get-Content $file.PSPath -Encoding UTF8 -Raw) |
Foreach-Object { $_ -replace "<CopyToOutputDirectory>Always</CopyToOutputDirectory>", "<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>" } |
Set-Content $file.PSPath -Encoding UTF8 -NoNewline
}
Files that do not exist are a problem and obviously files producing no output as well. That can happen, wenn you have a resource file in a static library. (C++)

Visual Studio (C#) Build Output path using environmental variables

Is it possible to use environmental variables in the build output path in VS 2008 (et al)/ I'm trying to find a solution where several developers on my team using both Windows XP & 7 and all with different Windows logons, can all modify projects and common referenced dll's (source held on Source Safe) and not screw up the relative paths? I've tried such things as %userprofile% and $(userprofile).
I've looked into post build events but these do not really seem to provide an anawer to my problem. Sadly I'm not in the position to use 3rd party add-ons either as these will be non-commercial and it's nearly impossible to get authorization for any licences for them.
(Similar unanswered question at Output path for build in visual studio 2010)
You need to open the csproj file in a text editor and manually enter your environment variables in the OutputPath section. Visual Studio escapes the '$', '(' and ')' when you try to do this from the IDE.
I've used the subst command to accomplish this sort of thing in the past. Essentially all project references define paths in relation to a known drive letter like R:\MyProject\outputs.
Then every developer can map the R: drive (or whatever) to the folder structure particular to their environment. As long as the folder structure beneath the mapped drive is the same, the location of that mapped folder can vary between machines, builds, and users.
This works well as developers can then set up their environment with a simple batch file and easily switch between branches, projects etc and relative pathing within the projects is not broken.
PaulTee,
Is it a longshot to ask you try directory replication? Like Dropbox/Synctoy and other tools that invokes a file-copy from choosen location to the expected shared location?
In your situation, I would love to use the built-in environment variables. Probably there are a way to make it work, but until then i would go for such a solution. I would also have in mind that different users compiling to same directory, would make conflicts with both file versions and file locks (used by other user).
If you don't mind the extra copies, you could add post-build event that copies the project outputs to a commonly-agreed location for shared dlls, and everyone uses a non-relative reference to that location. It would still, though, require standardization of that target location, so maybe it is not what you are looking for. (example below would allow for drive letter independence at least)
copy $(TargetPath) \dependencies
While I don't quite understand what you're asking for, it sounds like symlinked directories will help -- you can configure the solution to output to some folder that will be symlinked to arbitrary locations on each individual box.
http://en.wikipedia.org/wiki/NTFS_symbolic_link
ghost edit - mklink is apparently new in 7, but older versions still support it (Russinovich to the rescue once again):
http://technet.microsoft.com/en-us/sysinternals/bb896768

How to return the Visual Studio currently open soution directory

I have a Visual Studio solution that comprises of several projects and are separated into different directories.
In my C# or VB.NET code, I want to determine the base directory (or the directory that the solution is in).
A dirty solution would be to call the directory parent.parent.parent until I find a file *.sln, but I also have several solutions in other directories that I don't want to be returned.
I am just wondering if there is a cleaner method, maybe part of System.Diagnostics.Debugger or similar?
I look forward to your reply, thanks.
As the sln file does not need to be deployed on the target machine - why are you trying to find it at all?
If you still want to use the sln- try at EnvDTE Namespace
EnvDTE.DTE dte = (EnvDTE.DTE) System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
string folder = System.IO.Path.GetDirectoryName(dte.ActiveDocument.FullName);
Even though you have solutions in other directories, presumably those aren't directories within your original solution, are they? What situation do you envisage where the "recurse up until you find a .sln file" would fail (other than running from the wrong directory)?
One alternative would be to pass the solution directory as a command line argument.
What do you need this for, out of interest?
Thank you for your answers. All were very helpful. I worked with the answer from Dror and with a little modification to the following line solved this problem, thanks.
string folder = System.IO.Path.GetDirectoryName(dte.Solution.FullName);
The reason I want to do this is whilst running the code in the IDE I determine the current Subversion revision of the project so that I can embed this into the running software version.
This is done automatically. See the article I wrote at codeproject:
link text
If you look at the code you will see I perform the following:
dirinfoSourceWorkingDir = dirInfo.Parent().Parent().Parent();
I need to determine the directory of the solution currently open in Visual Studio but want a cleaner way (and if I change the directory structure this would break the code).
Hope this makes sense!
Is the code being run from within the solution, i.e. within the IDE debugger? If so you can pass the solution directory as $(SolutionDir) from the IDE to the command line.

Categories

Resources