In "Properties" of my project I have the following:
I want to check if TEST
symbol exists, and only then, do some things.
So I did what you see in the picture below and in the class it works. However this does not work in the views.
The text in this block is gray even if TEST
is defined!
How can I cause it work if TEST
is defined?
Right-click the project > Properties. Go in the Build tab. Select the Configuration and Platform you want to define the symbol for. In the Conditional compilation symbols textbox, put the symbols you want to define (if you have more than one, separate them with a semicolon).
Conditional compilation provides a way of including or omitting selected lines of source code depending on the values of literals specified by the DEFINE directive. In this way, you can create multiple variants of the same program without the need to maintain separate source streams.
Rather than specify the compiler flag in web.config as per the accepted answer (which also requires specifying the compiler version in web.config, which is a non-standard location) I went with the following:
Add a method to a base class shared by my models
public bool IsDebugBuild
{
get
{
#if DEBUG
return true;
#else
return false;
#endif
}
}
Use that method in my views
if (mm.IsDebugBuild) {
<div class="debug">
// Do Stuff
</div>
}
The problem is related to the fact that views are only compiled when you run your application so the TEST
symbol that you defined is no longer applied by the compiler because it has no knowledge of it.
Assuming that you are using C# you need to configure the compiler to use the TEST
symbol when building the views and for this you need to override its configuration in Web.config
using the following:
<system.codedom>
<compilers>
<compiler
language="c#;cs;csharp"
extension=".cs"
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
compilerOptions="/define:TEST"
warningLevel="1" />
</compilers>
</system.codedom>
The important part is that you define compilerOptions="/define:TEST"
. The rest of the configuration you need to adapt to your specific needs, for example switch between .NET 2.0 or .NET 4.0.
If you apply this directly in the Web.config
it will work but will define TEST
every time. So what you should really do is use Web.config transformations so that the symbol is only applied for the correct build configurations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With