How do I set specific environment variables when debugging in Visual Studio? - visual-studio

On a class library project, I set the "Start Action" on the Debug tab of the project properties to "Start external program" (NUnit in this case). I want to set an environment variable in the environment this program is started in. How do I do that? (Is it even possible?)
EDIT:
It's an environment variable that influences all .NET applications (COMplus_Version, it sets the runtime version) so setting it system wide really isn't an option.
As a workaround I just forced NUnit to start in right .NET version (2.0) by setting it in nunit.exe.config, though unfortunately this also means all my .NET 1.1 unit tests are now also run in .NET 2.0. I should probably just make a copy of the executable so it can have its own configuration file...
(I am keeping the question open (not accepting an answer) in case someone does happen to find out how (it might be useful for other purposes too after all...))

In Visual Studio 2008 and Visual Studio 2005 at least, you can specify changes to environment variables in the project settings.
Open your project. Go to Project -> Properties... Under Configuration Properties -> Debugging, edit the 'Environment' value to set environment variables.
For example, if you want to add the directory "c:\foo\bin" to the path when debugging your application, set the 'Environment' value to "PATH=%PATH%;c:\foo\bin".

In Visual Studio for Mac and C# you can use:
Environment.SetEnvironmentVariable("<Variable_name>", "<Value>");
But you will need the following namespace
using System.Collections;
you can check the full list of variables with this:
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
Console.WriteLine(" {0} = {1}", de.Key, de.Value);

In Visual Studio 2019 right-click your project, choose Properties. In the project properties window, select the Debug tab. Then, under Environment variables change the value of your environment from Development to Production or other environments. For .Net Core and .Net 5 the property is called ASPNETCORE_ENVIRONMENT.

Visual Studio 2003 doesn't seem to allow you to set environment variables for debugging.
What I do in C/C++ is use _putenv() in main() and set any variables. Usually I surround it with a #if defined DEBUG_MODE / #endif to make sure only certain builds have it.
_putenv("MYANSWER=42");
I believe you can do the same thing with C# using os.putenv(), i.e.
os.putenv('MYANSWER', '42');
These will set the envrironment variable for that shell process only, and as such is an ephemeral setting, which is what you are looking for.
By the way, its good to use process explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx), which is a sysinternals tool. You can see what a given process' copy of the environment variables is, so you can validate that what you set is what you got.

Starting with NUnit 2.5 you can use /framework switch e.g.:
nunit-console myassembly.dll /framework:net-1.1
This is from NUnit's help pages.

If you are using VS 2019, Go to Project-> Properties->Debug. check here
Add key and value for your variables. Then it is done. Check launchSettings.json in properties folder you should see your variable there.

If you can't use bat files to set up your environment, then your only likely option is to set up a system wide environment variable. You can find these by doing
Right click "My Computer"
Select properties
Select the "advanced" tab
Click the "environment variables" button
In the "System variables" section, add the new environment variable that you desire
"Ok" all the way out to accept your changes
I don't know if you'd have to restart visual studio, but seems unlikely. HTH

Set up a batch file which you can invoke. Pass the path the batch file, and have the batch file set the environment variable and then invoke NUnit.

As environments are inherited from the parent process, you could write an add-in for Visual Studio that modifies its environment variables before you perform the start. I am not sure how easy that would be to put into your process.

In Visual Studio 2022, go to solution explorer, right click to project file. Then, click on the Debug link at the left side. Then, click on the Open debug and launch profiles UI. Then, you can add new variables into the field in Environment Variables section.
Environment Variables

In VS 2022 for .NET 5 and 6 you can set environment variables under properties of project -> Debug -> under General click on 'Open debug launch profiles UI' and scroll down to 'Environment variables'

I prefer to keep all such definitions in the make files, i.e. in the .*proj or .props - because these are under SCM.
I avoid the VS-Gui-Property-Dialogs. A lot of the config you write there goes into some .user, .suo or so, which is usually not under SCM.
E.g. in case of environment variables you could write (using a text editor) something like the following in your .vcxproj:
<PropertyGroup>
<LocalDebuggerEnvironment Condition="'$(Configuration)'=='Debug'">
ANSWER=42
RUNTIME_DIR="$(g_runtime_dir)"
COLOR=octarin
</LocalDebuggerEnvironment>
</PropertyGroup>
NOTE that you can use MSBuild Conditions and other build properties to define the environment variables.
NOTE: this works for me with VS2013 and VS2019. I think it is the same for other VS + MSBuild versions.

You can set it at Property > Configuration Properties > Debugging > Environment

Related

What's purpose of <Use64BitIISExpress /> element in csproj file

When I edit Web application project, Visual Studio 2017 (15.3.1) adds <Use64BitIISExpress /> element under Project/PropertyGroup in csproj file.
I can't find any documentation, what is the purpose and if it affects something, when presented (as it is, without any attributes).
Only result I was able to find was mention about registry value of the same name.
Does someone know what this element serves for?
Was it introduced in some of recent updates of Visual Studio 2017?
I noticed this entry, not surprisingly, after I made a change to the Properties page of the my Project. Under the Web section of the Properties page, you'll see a section called "Servers". After I changed the "Project URL" to use the correct port number for debugging, this entry appeared (not because I changed that option specifically, but it's when I noticed it appearing).
<Use64BitIISExpress />
In this section you can select either "IIS Express" or "External Host". Next to that dropdownlist, there is another dropdownlist for "Bitness". Mine was currently set to "Default", which displays the entry in the Project file as an empty element. After changing the "Bitness" to "x64", my Project file entry changed to:
<Use64BitIISExpress>true</Use64BitIISExpress>
Changing my "Bitness" to "x86" results in:
<Use64BitIISExpress>false</Use64BitIISExpress>
Returning "Bitness" to "Default" makes it again an empty element:
<Use64BitIISExpress>
</Use64BitIISExpress>
I understand this doesn't address your question of "where is the documentation?". I, too, could not find any relevant MSBuild documentation for this attribute. But, I thought it worth noting where the attribute is coming from and how it acts based on selected options from the Project properties while we anxiously await some formal, official documentation.
The purpose of that (pretty obvious) is to start IIS Express in 64bit mode. It is the equivalent of setting 64bit only on the Application pool in IIS.
If your project has a dependency on a DLL that only runs under 64bit mode then this is when you need to set it. This has been available since VS2013
Probably is useful if you prefer to do do F5 debugging instead of
process reattaching for your pure 64bit applications
This started showing up in the config files since VS2017 due to all the changes happening with Visual Studio portability. (VSCode, Visual Studio Mac, Xamarin, etc)

How to define environment variables in a VS solution and use them in csproj files?

I would like to define user environment variables in a Visual Studio solution. Then I would like to use them in the project files. For example:
<ProjectReference Include="$(MyUserVar)\MyProject.csproj">
Is it possible?
This can be done in the VS property sheet.
Go to the Property Manager tab if it's not highlighted yet.
Double click on the newly created property sheet.
Go to the User Macros node and press the Add Macro button. Insert name to the value field as you'd like and set this macro as an environment variable in the build environment.
Detailed step-by-step instructions can be referred here: https://sites.google.com/site/pinyotae/Home/visual-studio-visual-c/create-user-defined-environment-variables-macros

Setting environment variables for build in Visual Studio (2008)

I looked at some projects generated by the Qt plugin for VS and noticed that they use the environment variable QTDIR to refer for example to the Qt header files. However I failed to figure out where this variable is set. I guess it must be somewhere in the project settings, however I could not find it. Also please note that I am referring to the environment variables required during the build, not the ones for debugging.
On Windows there are two ways to set an environment variable like QTDIR: either permanently in System Properties->Advanced->Environment Variables or temporarily for a single cmd session by opening cmd.exe and executing set QTDIR=/path/to/qt; now when starting VS from that commandline (execute devenv.exe) it will use the QTDIR value just set. The second case you use mainly when you have multiple QT installations.
Apart from that, you can also use User Macros in VS Property sheets. From the build tools' point of view they are sort of equivalent to environment variables. Add a new property sheet to your project, double click on the new sheet, go to the User Macros page and click on Add Macro. Nice thing is you can share this property sheet amongst all your Qt projects.
When you install Qt through the setup wizard (i.e. not manually), the installation process sets the system environment variable QTDIR. This is not a project-specific thing, it is set for your whole system. You can check that at the location stijn described.
Hint: You can press Win+Pause to open the system properties dialog (where Win is the key between Ctrl and Alt)

Visual studio extension to redirect output files to specified folder

Usually, visual studio puts output files to bin/debug or bin/release.
When solution contains a large number of projects its not easy to modify each project output manually.
Also edits in csproj files no desirable, because some of them is shared between solutions..
My questions: Is anybody knows a tool, which can quickly configure output path ?
UPDATE: my problem solved by TFS Build
Presumably you have at least one project in each solution that is unique to that solution. In the Post-Build event of that, copy the contents of each project's output to the required location.
We often to this using a batch file. It's crude but effective. In our project that's unique to the solution we create a Release.bat file. This contains a number of file copies to copy all of the required components from the various output directories of the other projects. You can then just run the batch file in the post build event. We usually copy everything to a "Latest Release" fodler when the solution is built. If this becomes a proper release we will rename the Latest Release folder to the actual release number.
If you have multiple build configurations, or even just use the Debug and Release configurations, you can use an If statement in the Post-Build event to decide which batch file to run. So you could create a Debug.bat, Release.bat etc which do what you need. It can be tedious to set them up and get them working correctly at first, but they are very useful once fully implemented.
Customize your project using the msbuild properties which you can do if you follow these steps:
Go to the solution explorer and unload one project by right clicking on it and select Unload Project.
Then right click again on the unloaded project and select Edit Project. This will open the XML definition of your project, and you will have intellisense for the layout which will help you perform the next steps.
In the visual studio editor find the first PropertyGroup tag and add these lines near or at the end of the closing PropertyGroup tag:
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<BuildDirectory Condition="$(BuildDirectory) =='' or $(BuildDirectory) == '*Undefined*'">$(SolutionDir)\build\</BuildDirectory>
The above SolutionDir is defined in msbuild properties which you can obtain using this answer: msbuild script using solution information and also check out the well known msbuild properties here
The next step is to find the OutputPath tag for each configuration and edit it like this:
<OutputPath>$(BuildDirectory)\x86\AutomatedDebug\</OutputPath>
The example above assumes you have a configuration named AutomatedDebug with destination platform x86.
The output will be
x:\projects\whereever-your-solution-is\build\x86\AutomatedDebug\
Repeat for each project.
To unload more than one project, collapse all projects in the solution explorer and shift click or ctrl click to select all or some projects, then right click on the selected group to unload, unfortunately you cannot do this for editing, at least in visual studio 2010.
I am the first to admit that this is somewhat cumbersome to do for existing projects, but you could easily create a visual studio project template that has these settings changed so that new projects will use a more convenient default output directory.
You cannot edit the output directory directly in visual studio because the project properties editor escapes any $() enclosed text.
Also you could only modify the OutputPath using the name of a system environment variable enclosed in $(). This last option is to enable a global output directory.
If you build any single project modified in this way using msbuild directly in the commandline the output directory will be created one directory above from where you ran msbuild
..\build\x86\AutomatedDebug
If you are in a team, you should warn them not to edit the output directory directly by hand, as this action will overwrite any customization.
Hope this info is useful.
Greetings.

Error when running projects on Expression Blend 4

Whenever I try to run a project on Expression Blend 4 an error always appear.
The specified solution configuration "Debug|MCD" is invalid.Please specify a valid solution configuration using the Configuration and Platform properties (e.g. MSBuild.exe Solution.sln /p Configuration=Debug / p:Platform="Any CPU" or leave those properties blank to use the default solution configuration )
In some forums I've read that by deleting something on the registry will solve this issue but what I want to know is if it's safe to do that or if there are other ways to solve this error.
It turns out that HP machines from the factory come with several global variables set for it’s own update software, including things such as “PCBRAND”. One of those variables are, you guessed it, PLATFORM.
In VS 2010 RC the build environment started respecting “Platform” as a compile time System variable. Therefore, because no such platform exists in your deployment configuration, it fails.
It’s a pretty simple fix, just delete the PLATFORM variable.
You need to do the following steps:
Right-mouse click "Computer"
Go to "Properties"
Click "Advanced System Settings"
Click "Environment Variables"
Under "System Variables" find "PLATFORM" and delete it.
Restart Visual Studio
Here’s hoping I saved you some time.
If you mean:
http://social.expression.microsoft.com/Forums/en/blend/thread/f664d317-2415-4369-b461-a22eb0a2f023
&
http://social.expression.microsoft.com/Forums/en-US/blend/thread/71496590-a9ec-4e3a-8353-3ced345f78dc/#18af3654-2ee7-4e61-a1e1-321d430026eb
Then yes. It's to do with HP and the way they package up the extra applications on the machine. I found that the MCD platform key was in the registry in a few places, I deleted them and then restarted and now blend builds great.

Resources