Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Note: This blog has moved to omervk.wordpress.com.

Omer van Kloeten's Facebook profile

Omer has been professionally developing applications over the past 8 years, both at the IDF’s IT corps and later at the Sela Technology Center, but has had the programming bug ever since he can remember himself.
As a senior developer at NuConomy, a leading web analytics and advertising startup, he leads a wide range of technologies for its flagship products.

Get Firefox


powered by Dapper 

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

August 2004 - Posts

Cutting The Branch

Following the contest, I've been getting some emails from people about the Object Model Generator.
Most questions I got were in the line of "Why doesn't OMG support feature X of XSDs" and "Why does my XSD cause OMG to throw an exception?"
I am the first to admit that OMG is not a finished piece of work, but rather an experimental tool I have created for personal use and decided to release to the general public, hence the immediate release of the code (for you to be able to debug into it) and the eternal beta status.

Since the current codebase was created rather in a hurry, without proper design or testing, it is relatively unmaintainable and so I have decided to cut the current development branch and start over, learning the lessons I had learned from the current versions. This time, the tool will not be for my own personal use, and as such, it will be written condierably better. :P

If any of you want to help out, just kick the can.

Implicit Type Casting - The Is Question

I'll start this post with an example:

public class MyClass
{
    private int m_HeldInteger = 0;

    public MyClass()
    {
    }

    public static implicit operator int(MyClass myClass)
    {
        return myClass.m_HeldInteger;
    }

    public static void Main(string[] args)
    {
        MyClass c = new MyClass();

        bool b = c is int;
    }
}
What have we here? We have the type MyClass which holds an integer field and has an implicit conversion to an integer.

Now let's look at the Main method. In it, we instantiate the variable c to be of type MyClass. We then inquire the runtime to whether c is of type int or any of its descendants.
It's pretty obvious that the answer will be no, so we will get a false assigned to the boolean variable b.

What I find wrong with this is that, effectively, c could indeed be of type int, because we can implicitly convert it to that type.
In this particular case, the compiler chooses to not translate our object to int prior to the execution of this expression, causing it to always return false. Was I to explicitly cast c into int, no exception would be thrown (since a call would be made to the implicit operator) and the value returned would be true.
This is correct behavior because, yes, the object c is indeed not of type int. On the other hand, this is not correct beahvior, since it could be of type int.

What do you think? Should this stay like it is or should it be changed?

Singleton Unit Testing - A Different Approach

Peli has posted a tip concerning singleton objects and how them being singletons interferes with the testing itself. He also added a solution to this problem. Respect to Peli for this very cool post. :)

At first, I failed to understand his method, so I debated him a bit in his comments. Eventually, I understood what he meant - he created an instance manually each time he set-up his tests.

Here's another way of doing this, if you have some instantiation code in your get accessor for Instance: Just nullify the static instance.

Here's some code that shows how:

public class Singleton
{
    private static Singleton m_Instance;

    private Singleton()
    {
        // Do Initialization Magic
    }

    public static Singleton Instance
    {
        get
        {
            if (m_Instance == null)
            {
                m_Instance = new Singleton();

                // Do Instance Getting Magic
            }

            return m_Instance;
        }
    }
}

[TestFixture]
public class MyTests
{
    [TearDown]
    public void TearDown()
    {
        System.Reflection.FieldInfo fi =
            typeof(Singleton).GetField("m_Instance",
            System.Reflection.BindingFlags.Static |
            System.Reflection.BindingFlags.NonPublic);

        Assert.IsNotNull(fi);

        fi.SetValue(null, null);
    }
}

An added bonus for this method is the ability to use the Singleton class as it was intended for it to be used. There might be some code in the get accessor that should run whenever it is accessed, regardless for the value of the private instance.

MSBuild's Fix

I was reading John Lam's excellent A Practical Developers’ Guide to MSBuild article which is contained in the second installment of his Practical Eye for the .NET Guy newsletter when I realized that this could be a great opportunity to try out my Object Model Generator on MSBuild's project files. This could be a first step towards the creation of a tool that edits these files.

I took the msbuild.xsd schema that came with Visual C# 2005 Express Edition Beta 1 and dumbed it down a little to this version, so that the current version of OMG could handle it. I ran it through OMG to get this output.
Let's look a little bit at how to work with what we got.

I took John's example of a valid project file:

<Project DefaultTargets="Build">

    <PropertyGroup>
        <Property DebugSymbols="True"/>
        <Property Optimize="False"/>
        <Property OutputType="exe"/>
    </PropertyGroup>

    <ItemGroup>
        <Item Type="Compile" Include="App.cs"/>
    </ItemGroup>

    <Target Name="Build">
        <Task Name="Csc"
            Sources="@(Compile)"
            EmitDebugInformation="$(DebugSymbols)"
            Optimize="$(Optimize)"
            DefineConstants="DEBUG"
            TargetType="$(OutputType)"/>
    </Target>

</Project>
The example gives us a couple of the features exposed by MSBuild.

Now let's see how this structure is achieved by means of using the code generated by OMG:

ProjectElement project = new ProjectElement();

ProjectElement.PropertyGroupElement propGroup =
    new ProjectElement.PropertyGroupElement();

ProjectElement.PropertyGroupElement.PropertyElement debugSymbols = new
    ProjectElement.PropertyGroupElement.PropertyElement();
debugSymbols.CustomAttributes.Add("DebugSymbols", "True");
propGroup.Propertys.Add(debugSymbols);

ProjectElement.PropertyGroupElement.PropertyElement optimize =
    new ProjectElement.PropertyGroupElement.PropertyElement();
optimize.CustomAttributes.Add("Optimize", "False");
propGroup.Propertys.Add(optimize);

ProjectElement.PropertyGroupElement.PropertyElement outputType =
    new ProjectElement.PropertyGroupElement.PropertyElement();
outputType.CustomAttributes.Add("OutputType", "exe");
propGroup.Propertys.Add(outputType);

project.PropertyGroups.Add(propGroup);

ProjectElement.ItemGroupElement itemGroup =
    new ProjectElement.ItemGroupElement();

ProjectElement.ItemGroupElement.ItemElement item =
    new ProjectElement.ItemGroupElement.ItemElement();
item.Include = "App.cs";
item.CustomAttributes.Add("Type", "Compile");
itemGroup.Items.Add(item);

project.ItemGroups.Add(itemGroup);

ProjectElement.TargetElement target =
    new ProjectElement.TargetElement();

target.Name = "Build";

ProjectElement.TargetElement.TaskElement cscTask =
    new ProjectElement.TargetElement.TaskElement();

cscTask.CustomAttributes.Add("Name", "Csc");
cscTask.CustomAttributes.Add("Sources", "@(Compile)");
cscTask.CustomAttributes.Add("EmitDebugInformation", "$(DebugSymbols)");
cscTask.CustomAttributes.Add("Optimize", "$(Optimize)");
cscTask.CustomAttributes.Add("DefineConstants", "DEBUG");
cscTask.CustomAttributes.Add("TargetType", "$(OutputType)");

target.Tasks.Add(cscTask);

project.Targets.Add(target);

ProjectDocument doc = ProjectDocument.FromDOM(project);

doc.Save("c:\\app.proj");

Let's examine the code brought here.
First, we create the root Project element. We then create a PropertyGroup element that contains the three Property elements we need. Note that these properties are untyped and as such can not have members declared for them.
Next comes the ItemGroup element which contains an Item element. The Include attribute was already declared and as such, a property on the Item class was generated for it.
The last two lines translate our typed DOM to an XmlDocument and then save it to a file with the creative name app.proj.
Needless to say, the output file is similar to the file we wished to create.

The next step would be to build a graphical user interface for this, binding properties to fields, etc.
I'd love to see that happen. :)

The Case Of The Busy Contact

I use the Windows Messenger, as well as I do ICQ, for my instant messaging needs (if you want my contact, drop me a line).

Playing with some anonymous methods in C# Express on my laptop, I used the good old full screen mode, since my screen can only get as high as 1024x768 and using Visual Studio sucks on resolutions lower than 1280x1024 ever since the 2002 version.

When I went to click on a taskbar button, I noticed something quickly change in my Messenger tray icon. I became suspicious and tried that again.

It appears that our friends at Microsoft decided that they will automatically change your status to Busy, whenever you go and work in fullscreen mode.

Looking for an option to disable this intrusive behavior has been in vain. What gives?

Conditional Attributes vs. Conditional Sections

I posted a riddle yesterday for my readers (I know there's at least two of you ;).

Let's compare the two methods:

Conditional Attribute Conditional Section
Compile Time The call is compiled No No
The method is compiled Yes No
Compiler errors for any calls during compilation No Yes
Run Time The call is made No No
The method is JITed No No

The conclusion is that while using the Conditional Attribute may look better on your code, using the #if directive is more secure and slims down your file size (unwanted code is not compiled into the output file).

Keep this in mind the next time you need to add code that is called only if a certain symbol is defined.
I think I'll stick to #if directives.

ConditionalAttribute

Eric Gunnerson has posted about the ConditionalAttribute attribute and its use, in comparison to the #if directive.
In his example, he has two methods, each is called from a third method. The call to the first is in a #if DEBUG block and the second method is marked with a Conditional("DEBUG") attribute. He then says that neither call will be made if DEBUG is not defined.

This is true (not that he needs my approval ;).

Here's a riddle for you all. What is the difference between the two following code segments, both at compile time and at run time (considering DEBUG is defined/not defined for each case):

  1. public class Program
    {
        public static void Main(string[] args)
        {
            CallMethod();
        }

        [Conditional("DEBUG")]
        static void CallMethod()
        {
            Console.WriteLine("I'm in! w00t!");
        }
    }
  2. public class Program
    {
        public static void Main(string[] args)
        {
            #if DEBUG
            CallMethod();
            #endif
        }

        #if DEBUG
        static void CallMethod()
        {
            Console.WriteLine("I'm in! w00t!");
        }
        #endif
    }

Operators in Interfaces

An interface, as we all know, is a way of declaring members that a class must implement. This allows other classes that may only recognize the interface, to use a polymorphed version of the class and invoke the members that were defined in the interface.
One thing you can not declare inside an interface are operators. This makes perfect sense, because operators are declared as static and static members are defined per class (never you mind that apparently they can be inherited - a subject on which I posted before).
On the other hand, why can't I do that? Take the following code for example:

public interface IIntegerHolder
{
    int Value { get; }
}

public class IntegerHolderImpl
{
    private int m_Value;

    public int Value { get { return m_Value; } };

    // More members...
}

public class Main
{
    static void Main(string[] args)
    {
        IntegerHolderImpl impl1 = new IntegerHolderImplementation(), impl1 = new IntegerHolderImpl();

        Console.WriteLine(Add(x, y));
    }

    static int Add(IIntegerHolder x, IIntegerHolder y)
    {
        return x.Value + y.Value;
    }
}
What happens if I want to implicitly convert an IIntegerHolder into an integer? Nope, you can't do that, my compiler tells me.

Fine, I say, so I go and implement an implicit conversion on my implementing class:

public static implicit operator int(IIntegerHolder value)
{
    return value.Value;
}
After trying to build that, I get an error that the implicit conversion must convert to or from the enclosing type (IntegerHolderImpl).

So I change the code:

public static implicit operator int(IntegerHolderImpl value)
{
    return value.Value;
}
I also change the Add method so that it would look like this:
static int Add(IIntegerHolder x, IIntegerHolder y)
{
    return x + y;
}
And then I get an error that there is no implicit conversion from IIntegerHolder to int.

So our conclusion is that you can't declare an operator per interface, no matter what. This pretty much sucks, because I would have expected one of these ways to work, even though they both have their flaws (the first defies the law that all operator must explicitly have a connection to the enclosing type; the second defies the laws of polymorphism).

Posted: Aug 13 2004, 11:43 PM by Omer van Kloeten
Filed under:
Nested Using Statements Redux

Many people have been responding to my previous post on the subject, this way or another.
What seems to be a reoccurring complaint is that you can't put two resource acquisitions of different types in the same line.
So I sat down and found a way to do this.

Let's take Sean's code:

using(TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
using(MemoryStream ms = new MemoryStream(inBytes.Length))
using(CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(__desKey, __desIV), CryptoStreamMode.Read))
{
    ms.Write(inBytes, 0, inBytes.Length);
    ms.Position = 0;  
    string outString = new StreamReader(cs).ReadToEnd();
    cs.Close();
    outBytes = ASCIIEncoding.ASCII.GetBytes(outString);
    return outBytes;
}
The above code can use only one using statement, using the currently available language features.
However, it would look like this:
TripleDESCryptoServiceProvider des; MemoryStream ms; CryptoStream cs;

using (IDisposable ides = des = new TripleDESCryptoServiceProvider(),
       ims = ms = new MemoryStream(inBytes.Length),
       ics = cs = new CryptoStream(ms, des.CreateDecryptor(__desKey, __desIV), CryptoStreamMode.Read))
{
	ms.Write(inBytes, 0, inBytes.Length);
	ms.Position = 0;  
	string outString = new StreamReader(cs).ReadToEnd();
	cs.Close(); // By the way, you don't need this. Dispose for stream closes them.
	outBytes = ASCIIEncoding.ASCII.GetBytes(outString);
	return outBytes;
}

Well, you got what you wanted, didn't you?

Base Constructor Calls With Out Parameters

I've thought about this for a while, but I can't figure out the answer. Maybe someone can help me with this.
One note before we start, I'd like to ask everyone to not comment about whether the design looks good or not, but on the specific language features that I find lacking.

Take the class MyBaseClass which is as follows:

public class MyBaseClass
{
    public MyBaseClass(out int myParameter)
    {
        // Do initialization on myParameter.
        // Do magic...
    }
}
This class takes one parameter to its instance constructor, which is an out parameter.
Instace creation may look like this:
int i;
MyBaseClass myInstance = new MyBaseClass(out i);
Everything's peachy, Right?

Now take the class MyDerivedClass which derives from MyBaseClass:

public class MyDerivedClass : MyBaseClass
{
    private int m_MyInteger;

    public MyDerivedClass() : base(out m_MyInteger)
    {
        // Do magic...
    }
}
Oh, but wait. There's a compiler error in there! You can't pass an instance member to the call to the base constructor, even though it makes complete sense!
What you can pass is a type (static) member.

Now, my question is this: Why can't I pass an instance member as an out parameter to a call to a base constructor?

[Update: My original meaning was not why it was not allowed to send an instance member to the base constructor (I do understand that), but why it is not allowed to send an instance member specifically with an out modifier to the base constructor. There is no need for the value to be set into that member yet. Also, Ron Buckton has a good workaround for this, if anyone requires it.]

More Posts Next page »