Tag Archives: Visual Studio

Presenting templates for int and string ValueObjects

Most ValueObjects that i have implemented were wrappers around an int or a string. Apart from the domain specific rules, there is a lot of repetitive work in implementing operator overloads, IEquatable<T>, IComparable<T>, … Thus i decided to create a couple of Item templates that generate this code (and related tests).

Simply save IntValueObject.zip and StringValueObject.zip under %My Documents%\Visual Studio 2005\Templates\ItemTemplates and click on “Add New Item” in your project:

screenshot of add new item dialog in visual studio

Add the bottom of the dialog you can choose one of the templates:

screenshot of add new item dialog in visual studio

Here is the result of adding an International Standard Book Number class:

screenshot of generated artificates for isbn

Visual Studio 2008 (SP1) crashes when opening ViewPage in designer

Visual Studio 2008 (SP1) crashed every time i tried to open a ViewPage with the Web Form Editor (designer). Kudos go to eniac who suggested the removal of the Power Commands add-in. This made the crashes disappear.

Error loading testrunconfig: Failed to instantiate type Microsoft.VisualStudio.TestTools.WebStress.WebTestRunConfig

Earlier this week i ran into the following exception when opening a solution: “Error loading TestRunConfig1.testrunconfig: Failed to instantiate type Microsoft.VisualStudio.TestTools.WebStress.WebTestRunConfig”.

screenshot of testrunconfig not expected format dialog box

Apparently (here and here) the VS2005 Developer edition is missing a couple of libraries that the VS2005 Tester edition adds to the testrunconfig. If your tests don’t depend on these, the simplest way to solve this problem is to remove all the values nodes, and their childnodes, where the type is defined in the Microsoft.VisualStudio.QualityTools.LoadTest, Microsoft.VisualStudio.QualityTools.WebTest and Microsoft.VisualStudio.QualityTools.LoadTest.WebStress assemblies.

Easily switching between configuration files with MSBuild

A couple of days ago i wrote about Easily switching between App.Config files with MSBuild. Christophe Gijbels, a fellow compuwarrior, pointed out that developers usually need to copy more than a single App.Config file… I would propose to add a Folder for each Customer that contains all the specific configuration files. Eg:

screenshot of solution explorer with proposed folder structures

Now i have to configure MSBuild so that the right files are copied into the OutDir:

<!-- Define the CustomerPath depending on the choosen Configuration -->
<propertyGroup  Condition=" $(Configuration) == 'Customer1 Debug' ">
 <customerPath>Customer1</customerPath>
</propertyGroup>
<propertyGroup  Condition=" $(Configuration) == 'Customer2 Debug' ">
 <customerPath>Customer2</customerPath>
</propertyGroup>

<!-- Define AppConfig in the CustomerPath  -->
<propertyGroup>
 <appConfig>$(CustomerPath)\App.config</appConfig>
</propertyGroup>

<!-- Find all files in CustomerPath, excluding AppConfig -->
<itemGroup>
<customerFiles Include="$(CustomerPath)\*.*" Exclude="$(CustomerPath)\App.config" />
</itemGroup>

<target Name="AfterBuild">
<copy SourceFiles="@(CustomerFiles)" DestinationFolder="$(OutDir)" SkipUnchangedFiles="true"/>
</target>

Why doesn't Visual Studio display my MSBuild message texts?

In order to debug an MSBuild script i added a couple of <Message> tasks, but when i asked Visual Studio to Build i didn’t get to see the output… By default Visual Studio will use “Minimal” as verbosity level. You can change this via Tools -> Options -> Projects and Solutions -> Build and Run.

screenshot of configuration dialog in visual studio that allows the user to set the verbosity of msbuild

Easily switching between App.Config files with MSBuild

Imagine the following situation: One codebase, two customers with different Application Configuration files. How can we easily switch between the different configurations? By taking advantage of the Build Configurations functionality in Visual Studio we can easily switch between different configurations:

screenshot of the configuration manager in visual studio

A brute-force solution would be to add a Post-build Event that copies the desired App.Config file to the destination directory. In the Microsoft.Common.targets file (usually at C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727) around line 725 you can read how MSBuild chooses the App.Config that is copied to the destination folder:

Choose exactly one app.config to be the main app.config that is copied to the destination folder.

The search order is:

  1. Choose the value $(AppConfig) set in the main project.
  2. Choose @(None) App.Config in the same folder as the project.
  3. Choose @(Content) App.Config in the same folder as the project.
  4. Choose @(None) App.Config in any subfolder in the project.
  5. Choose @(Content) App.Config in any subfolder in the project.

Thus, simply setting $(AppConfig) should be enough to make sure that MSBuild chooses the appropriate App.Config file. Here is an example of a csproj section that defines $(AppConfig) as App.Customer1.Config or App.Customer2.Config depending on the choosen Build configuration:

<propertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug Customer1|AnyCPU' ">
 <debugSymbols>true</debugSymbols>
 <debugType>full</debugType>
 <optimize>false</optimize>
 <outputPath>bin\Debug\</outputPath>
 <defineConstants>DEBUG;TRACE</defineConstants>
 <errorReport>prompt</errorReport>
 <warningLevel>4</warningLevel>
 <appConfig>App.Customer1.Config</appConfig>
</propertyGroup>
<propertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug Customer2|AnyCPU' ">
 <debugSymbols>true</debugSymbols>
 <outputPath>bin\Debug Customer2\</outputPath>
 <defineConstants>DEBUG;TRACE</defineConstants>
 <debugType>full</debugType>
 <platformTarget>AnyCPU</platformTarget>
 <codeAnalysisUseTypeNameInSuppression>true</codeAnalysisUseTypeNameInSuppression>
 <codeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</codeAnalysisModuleSuppressionsFile>
 <errorReport>prompt</errorReport>
 <appConfig>App.Customer2.Config</appConfig>
  </propertyGroup>

Bending the code generation of IExtenderProvider to your will

In Exploring CodeDomSerializer i already explained how we can modify the code that the Visual Studio designer generates for us. With a typical IExtenderProvider the designer generates an initializer, SetXXX methods and a variable declaration, which looks like:

this.constantsExtenderProvider1 = new WindowsApplication1.ConstantsExtenderProvider();

this.constantsExtenderProvider1.SetConstants(this.button1, new string[] {
 "Operation1",
 "Operation5"});

this.constantsExtenderProvider1.SetConstants(this, null);

private ConstantsExtenderProvider constantsExtenderProvider1;

Now, what if we’re not happy with those generated SetXXX methods on each Component? The problem is that this code is not generated by the serializer for the ConstantsExtenderProvider but by the serializers for the Components. An easy workaround for this problem is to set the DesignerSerializationVisibilityAttribute on the GetXXX method in our IExtenderProvider to Hidden.

With those ugly SetXXX methods out of the way it’s up to us to do it better. We do this by implementing a custom serializer for our ConstantsExtenderProvider:

class ConstantsSerializer<t> : CodeDomSerializer
{
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
  ConstantsExtenderProvider provider = value as ConstantsExtenderProvider;

  CodeDomSerializer baseClassSerializer = manager.GetSerializer(typeof(ConstantsExtenderProvider).BaseType, typeof(CodeDomSerializer)) as CodeDomSerializer;
  CodeStatementCollection statements = baseClassSerializer.Serialize(manager, value) as CodeStatementCollection;

  IDesignerHost host = (IDesignerHost)manager.GetService(typeof(IDesignerHost));
  ComponentCollection components = host.Container.Components;
  this.SerializeExtender(manager, provider, components, statements);

  return statements;
 }

 private void SerializeExtender(IDesignerSerializationManager manager, ConstantsExtenderProvider provider, ComponentCollection components, CodeStatementCollection statements)
 {
  foreach (IComponent component in components)
  {
   Control control = component as Control;
   if (control != null && (control as Form == null))
   {
    CodeMethodInvokeExpression methodcall = new CodeMethodInvokeExpression(base.SerializeToExpression(manager, provider), "SetConstants");
    methodcall.Parameters.Add(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), control.Name));

    string[] constants = provider.GetConstants(control);
    if (constants != null)
    {
     StringBuilder sb = new StringBuilder();
     sb.Append("new string[] { ");

     foreach (string constant in constants)
     {
      sb.Append(typeof(T).FullName);
      sb.Append(".");
      sb.Append(constant);
      sb.Append(", ");
     }

     sb.Remove(sb.Length - 2, 2);
     sb.Append(" }");

     methodcall.Parameters.Add(new CodeSnippetExpression(sb.ToString()));
    }
    else
    {
     methodcall.Parameters.Add(new CodePrimitiveExpression(null));
    }

    statements.Add(methodcall);
   }
  }
 }
}

And now the generated code looks like:

this.constantsExtenderProvider1.SetConstants(this.button1, new string[] { WindowsApplication1.Constants.Operation1, WindowsApplication1.Constants.Operation5 });

As always, feel free to download the ConstantsExtenderProvider source.

Debugging custom UITypeEditors

If you read this you’re probably gonna think: What a moron! Anyway, i’m sharing this in the hope that i’ll be the last to undergo the following. In order to test my custom UITypeEditor i did the following:

  1. Create a UserControl
  2. Add a property to the control
  3. Add an Editor attribute to the property
  4. Build
  5. Drag a UserControl on the designer form
  6. Test via Visual Studio’s Property Window if the UITypeEditor works as expected
  7. Everytime i changed some code: Restart Visual Studio, load the project and repeat 6.

A tedious task to say the least. Yesterday i figured out that i could drag a PropertyGrid on the designer form, and set it’s SelectedObject property to a class with a property that uses the custom UITypeEditor; Instead of having to reload visual studio i can simply start a debug session, and click on the property in the PropertyGrid. Now it’s a breeze to develop custom UITypeEditors :)

private void Form1_Load(object sender, EventArgs e)
{
 // display an instance of PersonEntry,
 // a class with a property that should use the custom UITypeEditor i want to test
 this.propertyGrid1.SelectedObject = new PersonEntry(new Person("Tim", "Van Wassenhove"));
}

public class PersonEntry
{
 ...

 // instruct the PropertyGrid to use my custom PersonUITypeEditor
 [Editor(typeof(PersonUITypeEditor), typeof(UITypeEditor))]
 public Person Person
 {
  get { return this.person; }
  set { this.person = value; }
 }
}

public class PersonUITypeEditor : UITypeEditor
{
 public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
 {
  return UITypeEditorEditStyle.Modal;
 }

 public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
 {
  Person person = value as Person;

  IWindowsFormsEditorService svc = context.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
  if (svc != null)
  {
   using (PersonEditorForm personEditorForm = new PersonEditorForm(person))
   {
    if (svc.ShowDialog(personEditorForm) == DialogResult.OK)
    {
     return personEditorForm.Person;
    }
   }
  }

  return value;
 }
}

Inserting pause to your Console Applications

When i write Console Applications i find myself to write the following two lines quite often:

Console.Write("{0}Press any key to continue...", Environment.NewLine);
Console.ReadKey();

As you already know i’m lazy so i decided to write an IntelliSense Code Snippet. When i type “pau” Intellisense show the following:

Intellisense drop down list

Next i hit the tab button twice and i get the following effect:

Intellisense code snippet

Download pause.txt and save it as Pause.snippet in your %My DocumentS\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets% folder.

I’ve made it even simpler, you can install the snippet by simply running the pause.vsi package (Visual Studio Installer).

Silly bug in Visual Studio 2005 editor

If you try to compile the code below you will see that the i in the second loop is not defined in my main function. Position your mouse over the i, click right and choose “Go To Definition” in the context menu. Why does the cursor move to the i in the struct? Btw, if you remove the first for loop this doesn’t happen.

#include "stdafx.h"
struct {
  int i;
} BLAH;

int _tmain(int argc, _TCHAR* argv[]) {
  for (int i = 0; i < 10; ++i) { ; }
  for (i = 0; i < 10; ++i) { ; }
  return 0;
}