Tuesday, June 24, 2008

Watch Out: Window.ObjectKind is UPPER CASE!

Using Windows2.CreateToolWindow2() to create a VisualStudio addin tool window? If you do, then maybe you want to check how often it is called during the life cycle of your addin. And if you notice that you create it twice, you may want to avoid that by checking the collection EnvDTE80.Windows. If your tool window is already contained you don't want to create a second instance of your tool window. There is a possible surprise, though. Windows2.CreateToolWindow2() expects as the fifth parameter a guid. The online documentation (see here) says it is the "GuidPosition". This is a little misleading since it doesn't really refer to a position. In reality it is the type of the tool window, e.g. the Solution Explorer. Now, when you create the boiler plate code you may just use the example given there. If you do, then change the content of the variable guidpos given in the code to all upper case. So the important bit is the following change:
string guidpos = "{426E8D27-3D33-4fc8-B3E9-9883AADC679F}";
string guidpos = "{426E8D27-3D33-4FC8-B3E9-9883AADC679F}";
                              =====

I've highlighted the important bit with red color, bold, and a larger font. In addition I have underlined it. I think you got the idea. Why is this change important? Assume you iterate over the collection as follows:
foreach(Window2 toolWin in toolWins) {
string toolWinKind = toolWin.ObjectKind;
if( toolWinKind.Equals(guidString) ) {
 _toolWindow = toolWin;
 break;
}
}
The Equals() call may always result in 'false' even if you think you are looking at the correct tool window. The reason is that ObjectKind returns the guid all upper case. The example code has two lower case characters in the guidpos variable. The same can also happen when you use "Create GUID" from the "Tools" menu in Visual Studio. It may generate a guid for you with one or more lower case digits ('a' through 'f') as well. It's unfortunate that the online documentation doesn't mention that some time between calling CreateToolWindow2() and calling ObjectKind everything is made upper case. The example code leads to potentially incorrect behavior of your addin as well. This post gives you the heads-up. It took me quite some time to spot this little difference. In my case it was 'f' versus 'F' and only when Equals() insisted on returning false I took a closer look. Maybe this helps you saving some development time. And maybe someone from Microsoft is reading this. I tried to add it as Community Content at MSDN. It wasn't possible. So I rated the article and left a comment adding the suggestions for improvement. This would have been ideal for "Community Content". MSFT, you mind updating the online material? Thank you!

Thursday, June 19, 2008

csUnit: What's Next?

csUnit 2.5 is very well received but since we are always trying to find improvements I'd like to share a couple of items that we plan for the next version. For one, the performance has slightly slipped. Some new features resulted in an runtime penalty which we believe has become too high. So we did some performance analysis and have found ways to get a performance improvement of about 10% to 30% of the next version over version 2.5. Both the command line version and the GUI version benefit from this improvement. The other area we didn't like too much was the slightly cluttered user interface on the test hierarchy tab, which is the most frequently used view in the tool. In addition the search feature on the test hierarchy tab worksfor the test hierarchy only. This is a limitation. So we decided to revisit the search feature. The next version will therefore have a new search feature that works across all tabs. And at the sime time we were able to remove the related buttons from the test hierarchy page and replace them with a single button in the already existing toolbar. This freed up screen real estate for the important information and also simplified the appearance. These are just two of the improvements you will see in the upcoming version 2.6 of csUnit, which we are planning for August. Stay posted. If you'd like to participate in determining the future of csUnit then please don't hesitate to contact me or anybody else of the csUnit team.

Saturday, June 14, 2008

Vista: Finding Encrypted Files

To find encrypted files on Windows Vista do this:
  1. Open a command prompt and switch to a directory in which you have write permissions.
  2. Run the command: "cypher /s:c:\ /N /U > filelist.txt" and wait until finished (this example searches the entire volume c:
  3. When finished open the file filelist.txt. It contains a list of all files that are encrypted.
  4. In the Explorer window navigate to each file and though "Properties" -> "Advanced..." goto to the "Advanced Attributes" page and remove the checkmark from "Encrypt contents to secure data"

Tuesday, June 10, 2008

Addin Command Names

What is the name of a command when you register it for an addin? Typically you use Commands.AddNamedCommand() to register a command. The second parameter is the command name. Now, when you want to look up a command you can use _DTE.Commands using the name you used for AddNamedCommand() and you're done. Right? Wrong! Let's take the csUnit addin for Visual Studio as an example. The addin has the name csUnit.csUnit4VS2005.Connect. This is the class that implements the interface Extensibility.IDTExtensibility2. This interface includes members such as OnConnection(), OnDisconnection(), etc. This full name - 'csUnit.csUnit4VS2005.Connect' - is also used in the addin file (see node Extensibilily / Addin / FullClassName). What VS 2005 and VS 2008 do is this: When you register a command, the name of the command will be automatically prefixed with the name of the addin. So in this case a csUnit command named Foo would turn into csUnit.csUnit4VS2005.Connect.Foo. Be aware of this. Otherwise your code may not be able to find your command in _DTE.Commands.

Saturday, May 31, 2008

Custom Installer Creating Folder, Setting Permissions

When implementing custom installers you sometimes may want to created directories when the setup is executed. This may not be sufficient since you may also want to set sufficient permissions on those new directories so that users have access to the directories and the files in them.

The first thing to know is that an installer typically runs with elevated rights as the discussion on Chris Jackson's blog indicates. This means that your installer has sufficient rights to create directories but also to set appropriate permissions.

And here is the code for creating a directory and setting permissions:

public static void CreateWithReadAccess(string targetDirectory) {
try {
if(!Directory.Exists(targetDirectory)) {
Directory.CreateDirectory(targetDirectory);
}
DirectoryInfo info = new DirectoryInfo(targetDirectory);
SecurityIdentifier allUsersSid =
new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid,
null);
DirectorySecurity security = info.GetAccessControl();
security.AddAccessRule(
new FileSystemAccessRule(allUsersSid,
FileSystemRights.Read,
AccessControlType.Allow));
info.SetAccessControl(security);
}
catch(Exception ex) {
Debug.WriteLine(ex.ToString());
}
}

This code checks for existence of the directory first. If the directory doesn't exist yet it is created. Then the security settings are applied. In this case the Read permissions are granted to all members of the group BUILTIN\Users.

By selecting another member of the WellKnownSidType enumeration you can grant permissions to a different group. Alternatively, if you'd like to grant permissions to a specific user, have a look at the NTAccount class. An instance of it can be passed into the FileSystemAccessRule constructor as a first parameter as well.

Tuesday, May 27, 2008

ReSharper 3.1 and Empty Constructor

ReSharper has this nice feature to make you aware of code that are not necessarily required. I like this feature since it allows me to reduce the number of characters that I have to read and as a consequence I can process more of them at a time. As a result I can work faster. However, I just came across an item where this feature doesn't work as I hoped. I have a class publicly visible from outside the assembly. For the constructor I have added a number of XML documentation tags. The constructor itself doesn't take parameters and it doesn't do anything. But I want to keep the constructor for the XML documentation. Since the compiler automatically generates the same constructor, ReSharper emits that as a warning and also suggests to remove the constructor. If I followed that suggestion it would also remove the XML documentation along with it. Alternatively ReSharper offers to supress the warning. So I did that. ReSharper is now happy. But my compiler isn't since it sees the following (the pragma was added by ReSharper):
#pragma warning disable EmptyConstructor
The compiler now complains about 'EmptyConstrutor' not being a valid number. Fair enough it is not. So I removed the pragma since any other pragma would get ReSharper complaining again. To keep ReSharper quiet the constructor now looks as follows:
public class Foo() {
  // ... the XML markup for documentation
  public Foo() {
    ; // to shut up ReSharper
  }
}
Now both, the compiler and ReSharper, are happy! :-) No big issue but the better solution would have been if ReSharper would modify the code only in such a way that it doesn't cause additional warnings. Update This applies to essentially all such pragma's ReSharper inserts, including but not limited to:
  • UnusedMemberInPrivateClass
  • PossibleNullReferenceException

As stated before: Best option would be if the code inserted by ReSharper would not cause additional warnings from the C# compiler. Or in other words: The added code should be "compatible" with the compiler. One option could be to use comments instead. The compiler ignores them.

The C# preprocessor is not as powerful and flexible as the C/C++ one. The latter allows your extensions by ignoring unknown ones. The C# version does not have that "back door" but checks them for validity as well. In essence you can't define your own. (Or at least you shouldn't if you don't want to cause compiler warnings.)

Thursday, May 15, 2008

Outlining/collapsing Comments in VS2005/VS2008

A minor issue but still it might bother you while working with your code. The C# editor (and possibly others) of Visual Studio offers collapsing and expanding classes name spaces, methods, blocks, etc. And comments. Most of the times this works as expected. But then it doesn't work for comments at the beginning of a file. Then it works often, and sometimes it doesn't. I can't reproduce it but it usually doesn't work when I want to collapse the comment, and it works if I don't need to collapse. Why is this annoying? Well at the beginning of files by default I add my company's copyright statement. It has about 10 lines. Not much but if you consider that generally I can see about 30 lines on my laptop display then it basically means that 33% of the real estate on the screen is consumed by a piece of text that has no value to me while editing code (rather than comments). You still think 10 lines is not much? If you really want to optimize the use of your time you are happy about every single contribution. A mouse click here, a key press there, some scrolling, waiting time, etc. it all adds up. I don't know whether this exists in other versions as well. I have observed the issue in both Visual Studio 2005 and Visual Studio 2008. It's not really an issue; more like a nuisance. So this is another item I'd like to ask to get fixed. Just in case someone from Redmond is ready this. The workaround I'm using is to surround those comments with #region/#endregion. This can be reliably collapse expanded even at the beginning of a source file.

Tuesday, May 13, 2008

SerializationException - "The constructor to deserialize an object of type 'foo' was not found."

Some classes need to be serializable. Even if you use the SerializableAttribute to mark it up you may run into the issue that a SerializationException is thrown. To fix it you need to put the following things in place. As a running example I'll use a class named Foo. The items you need to put in place are:
  1. Add the SerializableAttribute to the class.
  2. Have the class implement the ISerializable interface.
  3. Request sufficient privileges for your GetObjectData() implementation.

In essence you are rolling custom serialization. And here is how Foo would look like with all these in place:

using System.Runtime.Serialization;
using System.Security.Permissions;
...
[Serializable]
public class Foo : ISerializable {
  protected Foo(SerializationInfo info,
                StreamingContext context) {
    _barString = info.GetString("_barString");
    _barInteger = info.GetInt32("_barInteger");
  }

  [SecurityPermissionAttribute(
                SecurityAction.Demand,
                SerializationFormatter = true)]
  public virtual void GetObjectData(SerializationInfo info,
                                    StreamingContext context) {
    info.AddValue("_barString", _barString);
    info.AddValue("_barInteger", _barInteger);
  }
  private string _barString;
  private int _barInteger;
}
Note that the constructor is protected. This way it cannot be called except from the serialization code within .NET. It is however accessible by code in subclasses. If your class is derived from a class that implements ISerializable, then you need to call the base class in both the constructor and the GetObjectData() implementation as follows:
[Serializable]
public class Foo : Base { // Base implements ISerializable
  protected Foo(SerializationInfo info,
                StreamingContext context)
    : base(info, context) {
    // your deserialization code
  }

  [SecurityPermissionAttribute(
                SecurityAction.Demand,
                SerializationFormatter = true)]
  public virtual void GetObjectData(SerializationInfo info,
                                    StreamingContext context) {
    base.GetObjectData(info, context);
    // your serialization code
  }
}
For more information please check MSFT's web site here.

Sunday, May 11, 2008

Weakness in VS Debugger

This time I' d like to make you aware of a wee weakness of the Visual Studio debugger. Suppose you have overloaded the Equals() method for one of your classes. And it looks similar to this:
public class ProjectElement {
  ...
  public override bool Equals(object obj) {
    if( obj != null
      && obj.GetType().Equals(GetType())) {
      ProjectElement otherObject = 
                          (ProjecElement)obj;
      return _assemblyPathName.Equals(
                otherObject._assemblyPathName);
    }
  }
  ...
}
During a debugging session you can use the QuickWatch as a convenient way to examine variables. However, be aware of the following. When you use QuickWatch on '_assemblyPathName' in the above example then QuickWatch does not consider the context. E.g. even if you hover over the '_assemblyPathName' part of the expression 'otherObject._assemblyPathName' QuickWatch will just use the member variable of 'this', which not in all cases will have the same value. If you want to be on the safe side then select the entire expression you would like to inspect, e.g. all of 'otherObject._assemblyPathName'. After that select QuickWatch. I think this is a shortcoming of the QuickWatch feature since it displays the content of a variable that you didn't want to look at, and you might not even notice that you are looking at something different of a similar name. If one of you Microsofties are reading this maybe you could consider this as an improvement for the next release of Visual Studio? Thank you!

Thursday, May 08, 2008

Implementing Properties: Basic Considerations

Not too long ago I wrote about Property Getters with bad manors (here). I suggested ways for doing better but I would like to share more of how I generally implement properties in C# (also applicable for other .NET languages). I'm not claiming that my style is the only one or the best one. However, it works good for me and it is based on 7 years .NET development experience and over 15 years experience with C++. Where to start? For this post I would like to focus on very simple things. Suppose you have a class Foo that has a field named _bar (note that I prefix all fields with and underscore; not necessarily what MS recommends but I think that it improves the readability of the code). So the code would look as follows:
public class Foo {
   private string _bar;
}
Now we want to add an accessor aka the getter:
public class Foo {
   public string Bar {
      get {
         return _bar;
      }
   private string _bar;
}
This has been the easy part. There is not really a lot that can go wrong.

It starts to become more interesting when you add a modifier aka a setter. In it's most simple form you could write:

public class Foo {
   public string Bar {
      get {
         return _bar;
      }
      set {
         _bar = value;
      }
   private string _bar;
}
Easy you think. But hang on. There is more to it. You may want to decide whether it is acceptable to pass in a null reference or not. Whether you allow for null or not is a decision that should be made based on a number of factors. One way to find out is to look at all the places in your code where the getter is used. What would happen to that code if null would be returned? For example:
Foo foo = new Foo();
...
if( foo.Bar.Length > 25 ) {
   ...
}
...
In that case if null was returned this piece of code would crash. You could fix this issue by checking for nullness:
Foo foo = new Foo();
...
if(   foo.Bar != null
   && foo.Bar.Length > 25 ) {
   ...
}
...
This certainly work but you pay the price of a slightly less readable code. In addition you may have to have this in a lot of places. So in essence you may decide that the property Foo.Bar doesn't allow for null values. The code for class Foo would then look as this:
public class Foo {
   public string Bar {
      get {
         return _bar;
      }
      set {
         if( value != null ) {
            _bar = value;
         }
      }
   private string _bar;
}
This clearly provides the benefit of Foo.Bar never being null since upon initialization _bar will be initialized with string.Empty or "".

But again this comes at a price. The setter simply swallows the attempt to set Foo.Bar to null. This might be desirable. I personally prefer that a class doesn't swallow incorrect things but instead fails fast. In this particular case I would want my code to indicated the error by throwing an exception:

public class Foo {
   public string Bar {
      get {
         return _bar;
      }
      set {
         if( value != null ) {
            _bar = value;
         }
         else {
            throw new ArgumentNullException("value");
         }
      }
   private string _bar;
}
You see that although this is a simple property implementation it can already require quite a few decisions to be made and aspects to be considered.

To close off this particular post, I'd like to also bring performance considerations into the picture. What if the setter needs to validate any new value against a remote system such as a service? Let's look at the possible code:

public class Foo {
   public string Bar {
      get {
         return _bar;
      }
      set {
         if( value != null ) {
            if( _validationService.IsPermitted(value) ) {
               _bar = value;
            }
            else {
               throw new
                  ArgumentOutOfRangeException("value");
            }
         }
         else {
            throw new ArgumentNullException("value");
         }
      }
   private string _bar;
   private ValidationService _validationService = 
                                 new ValidationService(...);
}
Calling IsPermitted() can be quite expensive. So how to avoid this? Here is one possible solution:
public class Foo {
  public string Bar {
    get {
      return _bar;
    }
    set {
      if( _bar != value ) {
        if( value != null ) {
          if( _validationService.IsPermitted(value) ) {
            _bar = value;
          }
          else {
            throw new
                    ArgumentOutOfRangeException("value");
          }
        }
        else {
          throw new ArgumentNullException("value");
        }
      }
    }
  private string _bar;
  private ValidationService _validationService = 
                                 new ValidationService(...);
}
With this implementation the validation service is called only if the value has actually changed. Certainly if the set of permitted values is dynamic this implementation would not make the cut. With this post I want to demonstrate that even property that looks like an easy thing to do already requires a lot of considerations. We even touched performance briefly. It is important that we are aware of all of these aspects when implementing and testing such a property. There are more aspects to this but I think I've made my point. Even with simple things like properties there are already a quite a few aspects to consider.

Sunday, April 27, 2008

Codeplex, IE, and Firefox

Ok, maybe my system was completely screwed up and that's why it didn't work. But to the best of my knowledge I have a Vista Ultimate installation including IE 7 maintained by Microsoft Update. It has the latest and greatest patches installed. Today I went to codeplex.com - Microsoft's answer/contribution to the open-source community - and tried to download a few Sandcastle bits. I used Internet Explorer for it since I thought "It's a Microsoft site so the Microsoft browser should be fine." Well, it wasn't. When I clicked one of the two download links for Sandcastle I was presented with an overlay window (no pop-up) containing some licensing information. Before I was able to click the "Accept" buttone the overlay disappeared, and .... nothing happened. I restarted IE, and tried multiple times, eventually I got fast enough that I could actuall click the "Accept" button. Still it didn't work. Despite my recent experience with a different Microsoft Site that serves IE only, I thought it is at least worth a try to use Firefox. From there it was a breeze. Everything was straight forward, working flawlessly. Which leaves me wondering whether the guys who maintain the Codeplex site test mainly on Firefox.... (Onto my soap box: Microsoft - in my opinion - has started to move in the right direction. At the same time I believe it has still a long way to go until it competes on merits and great products and services only.)

Saturday, April 26, 2008

Accessing Installation Properties in Custom Actions

Assume you have a custom action for your installer and you'd like to access a parameter (or call it a variable or property) from within your installer. That property might have been set by another installer, e.g. a file search, or it could be part of the set of properties that are standard during installation, e.g. "TargetDir". Let's take TargetDir as an example. When you work on your setup project within Visual Studio (2005) it offers a number of macros for properties. E.g. when you want to specify the location for a folder that you'd like to create during install you can use [PersonalFolder] and others to specify the actual location. In order to pass such a variable to your custom action, simply open the Custom Actions editor for your setup project. Then select the custom action and then add the parameter in the "CustomActionData" property using the following syntax:
/TargetDir="[TARGETDIR]\"
Please note the trailing backslash, which you only need to use when you surround the property in double quotes. However, as a safety measure I suggest making it a habit to always add the double quotes and the backslash. Remember paths can and will contain spaces! In some examples on the internet the backslash may be mentiond in the text but not be included in the code sample. If you leave the backslash out you'll see a message box containing "error code 2869". However, this article makes it clear that you must add the trailing backslash if you use the double quotes. Also, if you want to pass more than one property separate them by a single space, e.g.
/TargetDir="[TARGETDIR]\" /UserDir="[PersonalFolder]\"
Then in your custom action implementation - a class derived from System.Configuration.Install.Installer - you can access it in the following way (C# here, but similar in other .NET languages):
string targetDir = Context.Parameters["TargetDir"];
That's all.

Two More Tips for Debugging Custom Actions

As I mentioned in my previous post one of the options you have to ensure you have sufficient rights to attach to a process, I'd like to share two more suggestions for how you can debug custom actions in your setup project. At various places you will find the tip to use MessageBox.Show() to stop execution of your custom action. Then when the message box is displayed you can attach the debugger. When I tried this the list of processes showed me three instances of msiexec.exe and I couldn't identify which one I should connect to. So I decided to select all of them and attach to all of them. Then I set a break point in a line after the message box and hit F5 to continue execution. Result: Setup continued happily and the break point was ignored. So this didn't help, but here are two simple suggestions that should make your life easier: Tip 1: For the message box make sure you give it a title or caption. For instance if you use MessageBox.Show() then use the overload that takes two strings as parameters. The first is the message in the message box. The second parameter is the caption. That's the important one since this is the string that you will find in the list of processes when you want to identify the right process. Tip 2: In the dialog box for attaching the debugger to a process make sure you tick "Show processes from all users" as it might be that the msiexec.exe instance you are interested in is not displayed.

Visual Studio: Access denied when attaching debugger to process

The other day when I was working within Visual Studio 2005 on Vista, I encountered the problem that I couldn't attach the debugger to some of the processes that I wanted to run in the debugger. The solution that worked for me was pretty simple: I closed Visual Studio and then selected "Run as administrator" from the context menu for the shurtcut to the application. This is certainly not the recommended way of bypassing security but on the other hand it may come in handy when needed. Prerequisite is that you have access to an account that has administrative rights. If you don't you may need to have a nice chat with your system administrator...

Thursday, April 17, 2008

MySQL closed-source: What's the alternative?

An anonymous writer posted on Slashdot that Sun Microsystem has announced that parts of MySQL will be closed-sourced, e.g. backup solutions and some more advanced features. The post is refering to Jeremy Cole's blog entry on the subject. The decision is certainly Sun Microsystem's business, and I'm sure it makes a lot of sense from their executive view. However, the users have an opportunity to help Sun Microsystem's understand the consequences of their decision. For instance, if you want to continue using an open-source database, PostgreSQL might be an alternative worth looking at. Developing for the Microsoft platform, it offers native interfaces for C, C++, and .NET, and even the "good old" (?) ODBC is available.

Wednesday, April 16, 2008

ReSharper 3.1: More Details

I promised to provide more details about my ReSharper experience as I go. So here is an item that I perceive as a nuisance. Sometimes, when you type in code, it displays the information above the line of code, and parameter info below the line of code. As a result in some cases almost all code is covered by those nice pop-ups. That can be very challenging at times. What I definitely like is the light bulbs ReSharper shows in the left margin. It's color indicates whether a suggestion is more serious (color is red) or if it is more optional (color is yellow). When you click on the light bulb a menu with useful next actions is displayed, e.g. "Optimize Usings" or "Qualifier is redundant" or "Make readonly". Although the fun stops after a while because you have used up all the light bulbs in the code base, it definitely helps improving the code, in particular making it more readable by removing all the "noise" from the stream of information that hits your eyes. Well done! I do have the impression though that Visual Studio responds slightly slower. This is not really surprising given the functionality ReSharper provides and given the a lot of elements need to be updated as you edit your code. I think, though, that the performance hit is a good investment since you get the improved code in return. Please be aware that this applies to version 3.1. JetBrains may decide to release newer versions that exposes a different behavior. Note: I paid in full for my license, and I have no financial or other interest in JetBrains the company behind ReSharper.

Tuesday, April 15, 2008

What's next for csUnit?

Since the March '08 release of csUnit we have thought about what area we should focus on next. We have improved the performance, we have added data-driven testing, and we there were always a few features that csUnit provided first. The next area we are looking at is usability. We'd like to improve usability significantly. For instance, as test suites grow it may become more and more time consuming to locate a particular test or test fixture. The next version of csUnit will therefore feature an easy to use search capability, available for both the stand-alone GUI and the addin for Visual Studio. We are also putting quite some effort into improving the test tree view. We believe that all users will benefit from improvements in this area. And finally, csUnit has become very feature rich over time. Some people prefer a simpler UI. We want to serve both groups of users the ones who prefer the rich functionality, and the ones who prefer to keep it simple. The idea is to add some configurability to the UI so that depending on your preference more or less elements become visible. Stay tuned! And if there is a feature you'd like to see, don't hesitate to visit csUnit's web site and follow the link to "Suggest a feature" that you can find on most pages.

ReSharper 3.1 in Visual Studio

For quite some time I have been using ReSharper now, currently version 3.1. Bottom line it helps creating better code and it has features that are beyond Visual Studio's capabilities. This is good mostly but has some side effects, too. I like for instance all the suggestions with regards to improving the code. It's a bit odd when you insert some code, e.g. a declaration of a variable of a type that is part of System, that ReSharper adds the fully qualified name including the name of the namespace. A few seconds later it may suggest to remove the namespace name is thinks that it is not necessary. Feels a bit like the fireman who wanted to be a hero, so he set a house on fire in order to being called for fighting the fire.... One thing that can be challenging if you use formatting features. ReSharper may decide to format items differently than Visual Studio. So depending on whether you have the settings for the two in sync you may end up with code that looks the same or that looks inconcistent. It certainly would be great if ReSharper would do some form of synchronization. There are other minor subtleties about which I'll blog as I encounter them. But by and large the product is a good complement to Visual Studio's feature set. Note: I paid in full for my license, and I have no financial or other interest in JetBrains the company behind ReSharper.

Tuesday, April 08, 2008

ControlPaint and Vista

What's ControlPaint for? Well, you can use it for different purposes, e.g. for printing a form including the controls on it properly rendered. Another reason why you would want to use ControlPaint is when you want to do some customization to controls that support ownerdraw, e.g. the TreeView control. Be aware, however, that ControlPaint doesn't support visual styles. So for instance if you use ControlPaint.DrawCheckBox you will notice that under Vista it will render the checkboxes with the XP style. That's not hat you want. In those cases where you want support for visual styles use classes such as the CheckBoxRenderer and similar classes in System.Windows.Forms. So for the checkbox you would use CheckBoxRenderer.DrawCheckBox. The difference will be that the CheckBoxRenderer supports visual styles. Your checkboxes will look as expected on Vista as well. I have tested this, and it works on Vista with .NET 2.0. Don't necessarily rely on the online information. Give it a try on your development and your target platform. Also give it a try on the .NET version you are using. The described technique should be available for all versions between 2.0 and 3.5. The online documentation is contradictory on this. It doesn't seem to be supported on the compact framework. But who runs Vista on his portable device....

Wednesday, April 02, 2008

Property Getters with Bad Manors

In the sources of a 3rd party library that I'm using I found the following code:
public static int Counter {
   get {
      int cnt = counter;
      counter = 0;
      return cnt;
   }
}
Ok, the documentation says that calling this getter will reset the counter. However... Still, in my opinion this is bad coding practice. Getters shouldn't modify the object. The reason for that is that some IDE's use the getters for displaying object data in debugging sessions. As a consequence debugging code and looking at the member of this object influences the outcome of the debugging session. I call this bad manors of that getter. The better approach would have been to use a method with a more intuitive name for example "ReadAndResetCounter()". That would a) avoid accidental modification during debugging sessions, b) follow the good coding practice of getters being non-modifying accessors, and c) would express the actual functionality of the code in a more understandable way. Some recommendations as a take-away:
  • Don't implement getters that modify the object
  • Instead use a method with a descriptive name

That way you will make it easier for other engineers to use your code and/or library.

(Now I'm wondering how long it will take until Charlie reads this. I'm sure he will agree with me!)

Monday, March 31, 2008

"Location is not available" on Vista

Ok, this is not exactly a .NET issue but I still thought it is worth mentioning it here since I assume there is a sufficient number of people currently using Vista for development who may have encountered this issue. You may have experienced one or more of the following:
  • "Preparing your desktop..." for an extended period of time
  • "Location is not available" after you log in
  • Desktop looks more like XP and has lost the Aero look-and-feel

I don't know what the reason for this was. Maybe it was relating to my Vodem to not being able to survive stand-by and/or hibernate. Maybe it was because Vista decided to run some lengthy checks, like CHKDSK. The event logs don't give a clue.

Resolution: Reboot another time.

Monday, March 24, 2008

csUnit 2.3 available

Just in case you are a regular reader of this blog: csUnit 2.3 has just been made available. With this release we have focused on improving the quality by fixing a few defects. On behalf of the csUnit team: Happy testing!

unresolved external symbol ?.cctor@@$$FYMXXZ

This error is usually related to upgrading Managed C++ project from Visual Studio 2003 to Visual Studio 2005. It is easy to resolve by removing a few options from both the compiler and linker, then recompiling the project. For the compiler remove the /ZI flag (don't confuse with /Zi). In the project properties pages choose "Configuration Properties", then "C/C++", then "Command Line". In the bottom part of the page you'll see "Additional Options". Remove /ZI from there if you have it at all. Next, go to "Linker", then "Command Line". Remove /NOENTRY and /NODEFAULTLIB from there if you have it at all. In all cases make sure you do this for all configurations not just the debug or the release configuration. More details about the context and background are available here.

Monday, March 17, 2008

csUnit, Visual Studio 2008, Vista, .NET 3.x

Maybe you have wondered about whether csUnit is supported on Vista and/or Visual Studio 2008. So in this post I'd like to give a few details for csUnit 2.2. Microsoft Windows Vista is not an issue. csUnit installs and runs just fine. This is also true for Visual Studio 2005 on Vista. The add-in registers properly and the context menus work, too. Visual Studio 2008 is a different story. The add-ins don't install and neither do the context menus. This is an item that we'll address in one of the next csUnit releases. If you are building for .NET 2.0 in VS 2008 you can still use csUnitRunner as a stand-alone application and run all tests. This mode works on both XP and Vista. If you are building an application for .NET 3.0 or .NET 3.5 that's fine, too. Simply include the reference to the csUnit 2.2 runtime assemblies as before and run your tests within csUnitRunner (or the add-in in VS 2005 if you managed to modify VS2005 to use .NET 3.x). If you encounter an issue with any of the above combinations, or if you find a combination that doesn't work, we would be very interested to hear about it. Please log a bug report at csUnit's but tracker at SourceForge and include as many details about your specific configuration as possible. Happy testing! (Note: All of the tests mentioned above were conducted using the English language version of the mentioned software components, all of them on the latest patch level as of the date of publication.)

Thursday, March 13, 2008

csUnit Sources About To Be Moved to Subversion

Since the beginning csUnit has used Sourceforge's CVS repository. In the meantime Subversion has become very stable and provides a number of benefits over CVS. As a consequence we will stop using the CVS repository. All committed source code that was available in CVS will continue to be available via CVS. Access is also possible via the internet and ViewVC. As of the conversion date all new commits will go into the Subversion repository. We have no plans to migrate old commits to the new repository. Details for accessing the new repository are available here.

Visual Studio: "Unable to find manifest signing certificate in the certificate store"

I just moved a Visual Studio project from one computer to a different one. When I then tried to rebuild the solution I received the following error:
"Unable to find manifest signing certificate in the certificate store"
As I was sure that I wasn't using any certificate to sign the assembly I couldn't understand the reason for this error message and the integrated help system for Visual Studio wasn't a big help either. It turned out that I had to manually go into the *.csproj file and remove the following three lines that were apparently left over from some past experiments with signing using a certificate:
<manifestcertificatethumbprint>...</manifestcertificatethumbprint> <manifestkeyfile>...</manifestkeyfile> <generatemanifests>...</generatemanifests> <signmanifests>...</signmanifests>
After I had removed those lines I reloaded the project and the solution rebuilt just fine. There is more information on this subject at a Microsoft Forum.

Wednesday, January 30, 2008

const == static?

Sometimes it can be the simple things that surprise. Ok, maybe you are one of those geniuses who knew it all the time. If that is the case don't bother reading this post. For all mere mortals go ahead. When writing code in C# on the surface you would assume that const and static mean two different things. But in reality there is a connection. As soon as you declare a field to be const it becomes static. The explanation is actually quite simple. If a field is declared const then its value is the same in all instances of that class. If that is the case a conceptual optimization can take place by simply declaring such a field static. If the value is the same it can be share across all instances. Sounds a bit confusing but it actually makes sense. This is not necessarily obvious at face value. Having worked with C++, Java, and C# over years it just became apparent when working with the type system and reflection in .NET. What I learn from that? There is always a little gem waiting to be discovered! Now here is some food for an additional thought: Can a static field be automatically const? If so, why? If not, why not?

Friday, January 11, 2008

csUnit in 2008

csUnit continues to enjoy good download and visitor numbers on its web site. In particular the interest in (introductory) tutorials remains very strong. Therefore we are assessing what options we have with regards to improving the tutorials that already exist, and whether there are opportunities for additional tutorials. As for csUnit we are looking into options with regards to increasing the functional footprint again this year without increasing the burden on user who don't need some of the new features (yet). The data-driven testing features are likely to move out of the experimental stage. Also, there are a few smaller improvements for supporting generics. And then we certainly want to make sure that csUnit also works with Vista, .NET 3.5 and Visual Studio 2008.