Constant in Eclipse and in Visual Studio

Java naming conventions states that constants, declared as static and final, must be named all uppercase. Eclipse will automatically turn these guys in blue and italic. Here is an example of what it will look like in Eclipse:

public class Sandbox {
    public static final String CONSTANT_VALUE = "Hello World!";

    public static void main(String[] args) {
        System.out.println(CONSTANT_VALUE);
    }
}

That’s pretty neat. You cannot miss a constant, even if it is not fully qualified (it has to be if it is from another class, of course).

According to Microsoft’s naming conventions, constants in C# (that use the const keyword, being compile time constants) have to be named using Pascal Case. Visual Studio doesn’t color it any special way, meaning that if it is not qualified, you cannot know if it is a constant, a propertie, a variable…

Here is what it looks like:

class Sandbox
{
    const String ConstantValue = "Hello World!");

    static void Main(string[] args)
    {
        Console.WriteLine(ConstantValue);
    }
}

I find this a bit disturbing, as constant should always be easy to recognize. Well, at least that what I think. I was not able to find any option in Visual Studio to change this. A good start is to always fully qualify constants, in this case using Sandbox.ConstantValue (same advice goes for this keyword, I always use it, even when unnecessary).

You can find some more details on this subject here on stackoverflow.

Encrypt App.config section using PowerShell as a Post-build event

It is very easy to encrypt a section of the Web.config file using Aspnet_regiis.exe tool, but there is no equivalent tool to encrypt a section of an application configuration file (App.config). It can be done very easily in code, as explained in this post, but there is now way to do that automatically. So I decided to write a PowerShell script that would encode a section of the given application’s configuration file.

Here is what it looks like:

param(
  [String] $appPath = $(throw "Application exe file path is mandatory"),
  [String] $sectionName = $(throw "Configuration section is mandatory"),
  [String] $dataProtectionProvider = "DataProtectionConfigurationProvider"
)
 
#The System.Configuration assembly must be loaded
$configurationAssembly = "System.Configuration, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a"
[void] [Reflection.Assembly]::Load($configurationAssembly)
 
Write-Host "Encrypting configuration section..."
 
$configuration = [System.Configuration.ConfigurationManager]::OpenExeConfiguration($appPath)
$section = $configuration.GetSection($sectionName)
 
if (-not $section.SectionInformation.IsProtected)
{
  $section.SectionInformation.ProtectSection($dataProtectionProvider);
  $section.SectionInformation.ForceSave = [System.Boolean]::True;
  $configuration.Save([System.Configuration.ConfigurationSaveMode]::Modified);
}
 
Write-Host "Succeeded!"

Some explanation on the script:

Believe it or not, that was the easy part.

The next step is to run this script automatically as a Post-build event in Visual Studio, so the .config file that is "built" is encrypted. Sounds very easy, but is actually tricky, I had to try many times to get it right.

I will give it straight away, here is the command to put in the Post-build event:

powershell "& ""C:\Documents and Settings\VlericP\My Documents\WindowsPowerShell\EncryptAppConfigSection.ps1""" '$(TargetPath)' 'connectionStrings'

There are lot of quotes, but this is the only way to get it working. For detailed explanations on why, see this post: Invoking a PowerShell script from cmd.exe (or Start | Run).

Using this, you can have your App.config file unencrypted in your solution, and when you build the output .config file is encrypted.

Two Quick Tips on Web Setup in Visual Studio

How to change the name of the Virtual Directory

By default, when you create a Web Setup Project in Visual Studio, the name of the Virtual Directory it will deploy to is the name that you gave to the Web Setup Project. This can be changed in the property window of the "Web Application Folder" element. At the bottom of the property window, there is a property called VirtualDirectory. If you want the setup to install your application in a subdirectory, you can specify directories using the / character.

WebSetupVirtualDirectory

Simple, but took me some time to find it (I don’t use Web Setup Project very often I have to say).

When I deploy (or when I run the Setup), some of the files are not copied

I had this problem lately. My web project contained a .scv file, and the file was never copied to the IIS virtual directory when using the Deploy… option of Visual Studio, nor was it copied by the Web Setup Project. Actually, this has to do with the Build Action property of the file. If it is set to "None", the file will not be copied. It has to be set to "Content" for the file to be copied as is.

FileBuildAction

When I create a .svc file in my projects, I generally select "Text File" and name it with svc extension. By default, text files have their Build Action set to "None".

Here are two links to articles that contain very useful information on Web Setup Projects:

C# Preprocessor #if directive

I only discovered lately that C# compiler had a preprocessor directives. The only one I knew was the #region and #endregion, which is only used for aesthetical reasons in Visual Studio.

The one that I was particularly interested in was the #if and #endif. When the compiler encounters a #if [symbol] statement (followed eventually by an #endif statement), the compiler will compile the surrounded code only if the symbol is defined.

Conditional (#if) directive

Let’s take a small command line example:

using System;
using System.Collections.Generic;
using System.Text;

namespace PreprocessorTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello,");

#if DEBUG
            Console.WriteLine("This is a debug line");
#endif

            Console.WriteLine("Goodbye.");

            Console.ReadLine();
        }
    }
}

This code, when ran, will only execute the second Console.WriteLine statement only if the DEBUG symbol is defined.

For obvious reasons, this is very useful. You can include debug code in the application and let the compiler sort what has to be included when you compile. This leads us to an important point: how is a symbol defined?

Symbol definition

There are two ways to define a symbol:

One last thing that is quite interesting. Visual Studio automatically defines DEBUG and TRACE symbols in Debug configuration, while it only defines TRACE symbol in Release configuration. This can, however, be changed by going in the project properties page, in the Debug section:

Visual Studio Project properties Build section

So, by default, using the DEBUG symbol means that the surrounded code will be compiled in Debug mode, but ignored in Release mode.