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.