views:

31

answers:

3

Is their a way to exclude a block of code when you use the publish feature in visual studio. In other words say I had a log in button that did something like:

// Start Exclude when publishing
if (txtUserName.Text == "" && txtPassword.Password == "")
{             
  lp = new System.ServiceModel.DomainServices.Client.ApplicationServices.LoginParameters("UserName", "Password");
}
else
// Stop Exclude when publishing
{
  lp = new System.ServiceModel.DomainServices.Client.ApplicationServices.LoginParameters(txtUserName.Text, txtPassword.Password);
}

This way when I am debugging I can just leave the username and password field blank and just click login and the application will log me on. But when the application is published the compiler woudl ignore that code and not compile it in to the application.

A: 

you can use the DEBUG constant, which should be active on the project preferences.

Then, you can just wrap your code on the following:

 #if DEBUG
    // some code here
 #else
    //other code here
 #endif

If there is no need for an else, don't use it.

jpabluz
+1  A: 

You can use the Conditional attribute along with the DEBUG constant and assuming that you only publish code in the Release configuration that by default does not define the DEBUG constant you could do something like this:

static void Main(string[] args)
{
    Login("John", "Doe");
}

public static void Login(string username, string password)
{
    SetDebugCredentials(ref username, ref password);

    // Login here
    Console.WriteLine("Credentials: {0} | {1}", username, password);
}

[Conditional("DEBUG")]
public static void SetDebugCredentials(ref string username, ref string password)
{
    username = "User";
    password = "Password";
}

This code will print User and Password in the Debug configuration and John Doe in the Release configuration.

João Angelo
A: 

While conditional compilation and #if switches work correctly in this case, I think you are actually looking for the ApplicationDeployment.IsNetworkDeployed property.

// Check if the application was published via ClickOnce.
if (!ApplicationDeployment.IsNetworkDeployed) {
Marek