code depending on build-type? - c#

I'm using Visual c# Express 2008. I want to have a special command executed just in "Release" builds - this command should not be executed while I'm creating and running Debug versions. Is it possible to implement code depending on my build-type (Debug or. Release)?
For example:
if(??buildtype?? == "Release")
{
//... special command ...
MessageBox.Show("RELEASE version");
}
else
{
//... normal command ...
MessageBox.Show("debug release");
}

#if DEBUG
// Commands that should run in debug builds.
#else
// Commands that should run in release builds.
#endif

Related

Detect DEBUG, RELEASE and my own mode C#

I have DEBUG, RELEASE and MYMODE configuration modes. How can I detect them?
#if DEBUG
#endif
detect only DEBUG and anything else, but not difference between RELEASE and MYMODE.
How can I do it?
MORE INFO:
I was thinking about something like this:
#if DEBUG
#elif RELEASE
#elif MYMODE
but if I have RELEASE or MYMODE, all parts of code are gray, only for DEBUG mode the DEBUG part is colorful. I also tried
#define MYMODE
but for this, MYMODE is true all the time doesn't metter what mode is set.
First you can use boolean operators in #if:
#if DEBUG || MYMODE
…
#endif
Second you can use #else and #elif to break up things...
#if DEBUG
// Debug only
#elif MYMODE || RELEASE
// In either release or MYMODE
#else
// Otherwise
#endif
The combination of these two covers most use cases.
MyMode is a configuration. But, in and of itself, that doesn't define any conditional compilation symbols.
You change these through the projects compilation settings1 or by passing the -define option to csc. If you look through the Debug configuration's compilation settings, you'll find that the DEBUG conditional compilation symbol was already defined2, but there's no RELEASE symbol defined in the Release configuration.
There is no requirement (as you'll find above) that there be any relation between configurations and the symbols that they define.
#if (and family) is defined to work with conditional compilation.
1Project -> Properties -> Build -> General.
2In some versions of Visual Studio, there's a dedicated checkbox for it rather than it being listed in the Conditional Compilation symbols, but the effect is the same. If you unload the project and examine the XML, you'll find that all constants are stored in the <DefineConstants> element.
The same:
#if MYMODE
#endif
#if RELEASE
#endif
Or more complex:
#if (DEBUG && MYMODE)
#endif
#if (!RELEASE && MYMODE)
#endif
I found the solution also thanks by you guys. I used this code:
#if DEBUG
#elif MYMODE
#else
but first I needed to put the name MYMODE to the Properties > Build > Conditional Compilation Symbols. I didn't do it before so there was the problem.

Compiler directive (DEBUG) work wrong for publishing

I have simple code with compiler directive in my WPF app:
#if (DEBUG)
MySettings.Default.Host = "http://localhost:63372/";
#else
MySettings.Default.Host = "http://example.com/";
#endif
All works fine in the Visual Studio. When I switch to Release or Debug then Host filled properly. But when I make publish, in the decompiler I see that Host is equal to "http://localhost:63372/" string.
Where is a problem?
Have you tried:
#if (DEBUG)
MySettings.Default.Host = "http://localhost:63372/";
#endif
#if (!DEBUG)
MySettings.Default.Host = "http://example.com/";
#endif
I have found the anwser. When you publish with clickOnce it uses current selected mode. So, I need to switch to release and then click Publish.

Running NUnit test depending on a condition

I'm writing a project using Win7 x64. Some part of my tests requires using SQLServer CE which only represents support for x86. I'm using Visual Studio 2010 Express and I gotta change platform target for my projects manually editing *.cproj files to run, for example, schema export test (NHibernate). Howcome I run a part of my tests depending on a platform target.
Thanks!
I don't know if there's a built-in mechanism in NUnit to handle this scenario, but at the very least you can use preprocessor directives.
For instance, create a "Debug x86" solution configuration, targeting x86. Then define the DEBUG_X86 conditional compilation symbol (in the properties of the project). Finally, surround your unit test with preprocessor directives:
#if DEBUG_X86
[Test]
public void Test()
{
// This test will only run when compiled with Debug x86
}
#endif
Edit: Actually, you don't even have to create a new solution configuration, as it's possible to define the conditional symbols depending on the platform (https://stackoverflow.com/a/1313450/869621). So define a WIN32 compilation symbol, and surround your test with it:
#if WIN32
[Test]
public void Test()
{
// This test will only run when compiled for x86
}
#endif

Different configuaration string for specific build configuration

how can i configure my Visual Studio 2010 C# solution/project so
that when i select a Debug configuration - ConnectionString#1 would be used
Release - Connection string #2
and
"Myconfiguarion1" (which was copied from debug) -> Connection string #3
I got to it work with debug in such a way:
if (ConfigurationManager.ConnectionStrings["ConnectionString1"] != null)
{
winApplication.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
}
#if DEBUG
if(ConfigurationManager.ConnectionStrings["ConnectionString2"] != null)
{
winApplication.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
}
#endif
but this doesn't work with "MybuildConfiguration"
If you're trying to do this for the web.config file of an ASP.NET project in Visual Studio 2010, it's built-in via XML Transformations for web.config.
Web Deployment: Web.Config Transformations
If you're trying to do this for an app.config file, you can use the same transformations but working with them is a bit of a hack:
Visual Studio App.config XML Transformations
Both boil down to actually using separate config files for the different environments you are going to be running your app in. That allows you to supply different values for any of the keys based on what environment you're running in.
I think you can use conditional compilation constants. To define them,
you have to open project property window, select compilation tab, and define a name in the conditional constants field, e.g. CONN1.
This constants get defined only for your active build configuration, so you can define CONN1 for Debug configuration,CONN2 for Release configuration,CONN3 for your custom configuration etc.
then, in your code, you can use:
#ifdef CONN1
//use connection 1
#else
#ifdef CONN2
//use connection 2
#else
//use connection 3
#endif
#endif

Detecting if a program was run by Visual Studio, as opposed to run from Windows Explorer

Is there a way to detect if your program was loaded through Visual Studio vs. whether it was started as a standalone executable?
Our software has a bug reporting feature to handle unhandled exceptions -- we need to be able to distribute debug builds to our beta testers, but we don't want the bug report to go off when we are in the middle of development, because the Exceptions are a lot more useful if VS catches them with a full stack trace, etc.
Right now, I'm disabling the bug report if Application.ExecutablePath includes bin\Debug or bin\Release, but I figure there is probably a more robust way of detecting whether the program was loaded through VS.
Obviously, we could set up a different build with some preprocessor macros, but for the sake of the question, assume that isn't a possibility -- I don't mind adding code, but I'm trying to make the fewest modifications to the build process, which is why command-line options are kind of a last resort as well.
If it matters, I'm using VS2003/.NET 1.1.
If you're doing this to determine if it is in any debugger (clarified by #JaredPar), you can use Debugger.IsAttached in the exception handler.
try
{
// ...
}
catch(Exception ex)
{
if (!Debugger.IsAttached)
{
ExceptionHandler.Frob(ex);
}
else
{
throw;
}
}
Alternatively:
public static void Frob(Exception ex)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
I don't do .net development, but in java I have done this by passing a flag into the startup options of the application. So you could pass a debug flag into the app from the IDE, and then check for that, when the app is run as an executable the flag would not be present. I would be surprised if .net didn't have something similar.
I know this is old but the provided solutions are not very satisfying.
I used the following class instead:
using System.IO;
using System.Reflection;
public static class Program
{
public static string ExecutablePath
{
get;
private set;
}
static Program()
{
var assemblyPath = Assembly.GetEntryAssembly().Location;
var assemblyDirectory = Path.GetDirectoryName(assemblyPath);
if (assemblyDirectory.EndsWith(#"\Debug") || assemblyDirectory.EndsWith(#"\Release"))
{
string projectFile = Path.GetFileNameWithoutExtension(assemblyPath) + ".csproj";
var root = new DirectoryInfo(assemblyDirectory);
while (root.Parent != null)
{
if (File.Exists(Path.Combine(root.FullName, projectFile)))
break;
root = root.Parent;
if (root.Parent == null) // we could not find it (should not happen)
ExecutablePath = assemblyDirectory;
}
ExecutablePath = root.FullName;
}
else
{
ExecutablePath = assemblyDirectory;
}
}
}
Then you can just use Program.ExecutablePath. If you already have a class named Program you can just extend it by those properties and methods.
If running from Visual Studio it will give you the project path where the csproj-file resides. This is the executable path without the "bin\*\Debug" or "bin\*\Release" stuff.
If not running from Visual Studio it will give you the path where the executable resides.
The solution is independent of debug settings, other attached debuggers or build configurations. The only important thing is, that your configurations are named "Release" and "Debug".
Note: As Troy Gizzi mentioned in the comments, this solution only works if you run the executable from another directory than the output directory. For my use case (simulate the deployment directory structure with the project directory as the root directory), this is a suitable solution. In general I copy my executable later to the deployment directory and expect the same behavior as if I run my program from within Visual Studio. Content and other dependencies are located relative to the project directory in my case.
Have you considered command line arguments? Run the program from Visual Studio with a --no-exception-handling flag (or whatever sounds appropriate), and don't handle exceptions if that argument is passed in. When you start the program elsewhere, without this argument, it'll behave normally.
Instead of tracking by process tree, I would add a configuration flag that enables the reporting feature. The flag can always default to "true" unless you are in your DEV environment then you set it to "false".
Sometimes the application is started outside the debugger and the debugger gets attached later. (Doubleclick on a file where the application is assigned to ...) I use this code to wait for the debugger attach.
using System.Diagnostics;
Process[] procName = Process.GetProcessesByName("devenv");
if(procName.Length > 0)
MessageBox.Show("Wait for debugger attach");

Categories