Archive for December, 2007

0 == 0 … well, usually it does

December 20, 2007

So when does 0 not equal 0? When it is -0 and even then it depends on who you ask. According the C# specification, -0 is an acceptable value and is treated the same as positive zero in most situations and they seem to be correct because it is very hard to tell that you have a negative 0 value. Take a look at the following set of comparisons:

double zero = 0.0;

double negZero = -0.0;

 

// following all result in true values

bool areSame = zero.Equals(negZero);

bool areEqual = zero == negZero;

bool sameSign = Math.Sign(zero) == Math.Sign(negZero);

bool sameString = zero.ToString() == negZero.ToString();

When you execute the code above, the results of all the tests is true – that for these tests 0 and -0 are considered the same. However, there are cases where they are not treated the same. For example:

bool sameResult =

    Math.Atan2(zero, -1.0) == Math.Atan2(negZero, -1.0);

This is the scenario that Mike, a friend of mine at work, came across the other day. It was a bit more difficult to detect though because the values were coming from variables that were part of a series of calculations. We looked at the value of the variables in the watch window and executed the same method (Math.Atan2) in the watch window explicitly with those values (instead of the variables) and got a different result.

In this particular case, the issue may actually be a bug in that method. We’ve logged it with Microsoft so you can check the status if you’re interested. The point though is that the CLR does support this and that the values could be treated differently. So how can you tell that you are in this situation? One way is to use the BitConverter.GetBytes. If you check the bytes, you will see that the sign bit for the value is actually set indicating that its negative.

byte[] zeroBytes = BitConverter.GetBytes(zero);

byte[] negZeroBytes = BitConverter.GetBytes(negZero);

 

bool sameBytes = zeroBytes[7] == negZeroBytes[7];

One other interesting point is how you can arrive at this value without explicitly creating a negative zero as I did in the tests above. If you do calculations using doubles, it does not appear that the value will result in a -0. For example:

double one = 1.0d;

double negOne = -one + one;

double posOne = one – one;

 

byte[] negOneDBytes = BitConverter.GetBytes(negOne);

byte[] posOneDBytes = BitConverter.GetBytes(posOne);

 

// these both result in positive 0

bool sameSignBit = negOneDBytes[7] == posOneDBytes[7];

In this case, both values are positive 0. However, if you perform the same test with decimal values:

decimal one = 1.0m;

decimal negOne = -one + one;

decimal posOne = one – one;

 

double dblNegOne = Convert.ToDouble(negOne);

double dblPosOne = Convert.ToDouble(posOne);

 

byte[] negOneDBytes = BitConverter.GetBytes(dblNegOne);

byte[] posOneDBytes = BitConverter.GetBytes(dblPosOne);

 

// these have different sign bits

bool sameSignBit = negOneDBytes[7] == posOneDBytes[7];

The sign bit is set for the value that moved from a negative value towards zero and that sign bit is maintained when the value is converted to a double.

Alt Codes

December 15, 2007

This is kind of silly but I thought I’d share it anyway. Sometime yesterday afternoon I locked my system and went to talk with a colleague about an issue. I was in for a little surprise when I got back. I pressed Ctrl-Alt-Delete and went to type in my password as I always do when I come back to my system. However, it wasn’t accepting it. I checked the caps lock but it was off. My keyboard was working because I could see the password character symbols as I typed.

I started to think that  someone in the office was fooling with me. Maybe I hadn’t locked my system and someone came along and changed my password. A friend in the office had a little program he used to install a long time ago on people’s system and send random messages so it wasn’t far fetched that someone would be playing a practical joke. But when I thought about it, it couldn’t be – they would have to know my current password to change it.

I then expanded the options section of the login dialog and I noticed that the lower left corner of the dialog read “AR”. This area is supposed to indicate the current keyboard layout so my keyboard layout was setup for Arabic. When you have multiple layouts installed, you’re supposed to be able to click on this area and choose a different keyboard layout but it wasn’t showing me a list so I guess I only had 1 keyboard layout installed at the time. Earlier that day, I was testing some right-to-left functionality and I had change my system keyboard – actually I think I changed the shell using XP’s MUI. When I was finished, I thought I had changed it back but I must have done something wrong.

I didn’t want to hard boot because I had Visual Studio running, as well as some other apps, and I didn’t think I had saved all the changes. For some reason, I remembered how you used to be able to type in characters by pressing Alt plus the character code. I played around with typing it in in the user name textbox so I could verify the characters and then finally typed in my password using the alt key codes and was able to get back into my system. To make things worse, instead of fixing the problem immediately – resetting the keyboard layout and rebooting – I had to get something finished first so I worked on that and got called away again – instinctively locking my system and having to type it in using the alt codes all over again when I got back.

Internal And Protected Virtual

December 15, 2007

I was thinking about it this morning and the approach that I mentioned in my last post wouldn’t work if you used this from a virtual member and that member was overriden. Here’s the class structure that demonstrates this problem when using yesterday’s approach:

    public class Base

    {

        internal virtual void OnlyCallFromDerivedClasses()

        {

            Utilities.VerifyCallerIsFamily();

 

            // do something

        }

    }

 

    public class Derived : Base

    {

        internal sealed override void OnlyCallFromDerivedClasses()

        {

            base.OnlyCallFromDerivedClasses();

 

            // do something

        }

    }

 

    public class NotDerived

    {

        public void VerifyCannotCallMethod()

        {

            Derived d = new Derived();

            d.OnlyCallFromDerivedClasses();

        }

    }

Note, for brevity I will not repeat yesterday’s implementation of Utilities.VerifyCallerIsFamily. The problem can be seen if you create an instance of NotDerived and it calls OnlyCallFromDerivedClasses on an instance of B; in that case an exception will not be raised. The reason is that the direct caller of the Utilities.VerifyCallerIsFamily is override of the OnlyCallFromDerivedClasses method in class B so it appears that everything is ok.

Here’s a modified version of Utilities.VerifyCallerIsFamily that gets around this issue:

    public static class Utilities

    {

        [MethodImpl(MethodImplOptions.NoInlining)]

        [Conditional(“DEBUG”)]

        public static void VerifyCallerIsFamily()

        {

            // get the method doing the check

            StackFrame sfCallee = new StackFrame(1, false);

            MethodBase calleeMethod = sfCallee.GetMethod();

 

            int callerIndex = 2;

            StackFrame sfCaller = new StackFrame(callerIndex, false);

            MethodBase callerMethod = sfCaller.GetMethod();

 

            MethodBase callerPrevious = calleeMethod;

 

            // if the callee – the method checking whose is calling it – is

            // virtual then we need to make sure that the caller we are

            // verifying is the external method and not the derived classes

            // override of the callee method

            if (calleeMethod.IsVirtual)

            {

                while (callerMethod.IsVirtual && callerMethod is MethodInfo)

                {

                    MethodInfo baseMethod = ((MethodInfo)callerMethod).GetBaseDefinition();

 

                    // break out once we find a method that is not an override

                    // of the callee method

                    if (null == baseMethod ||

                        baseMethod.MethodHandle != callerPrevious.MethodHandle)

                        break;

 

                    callerPrevious = callerMethod;

                    callerIndex++;

                    sfCaller = new StackFrame(callerIndex, false);

                    callerMethod = sfCaller.GetMethod();

                }

            }

 

            Debug.Assert(calleeMethod.IsAssembly, “This method is meant to try and implement a scope of ‘Assembly And Family’ so the calling method should be internal.”);

 

            if (false == calleeMethod.DeclaringType.IsAssignableFrom(callerMethod.DeclaringType))

            {

                // if the caller is a nested type of the callee then

                // this is an acceptable call since nested types always have

                // access to all the members of the declaring type. this also

                // will handle the case where an anonymous method that captures

                // a local is used.

                Type callerMethodType = callerMethod.DeclaringType;

                while (callerMethodType.IsNested)

                {

                    if (calleeMethod.DeclaringType.IsAssignableFrom(callerMethodType.DeclaringType))

                        return;

 

                    // move up the declaring chain

                    callerMethodType = callerMethodType.DeclaringType;

                }

 

                const string Format = “The ‘{0}.{1}’ method is being called from ‘{2}.{3}’. It should only be called by derived types.”;

                string message = string.Format(Format,

                    calleeMethod.DeclaringType.Name,

                    calleeMethod.Name,

                    callerMethod.DeclaringType.Name,

                    callerMethod.Name);

                throw new InvalidOperationException(message);

            }

        }

    }

[Note: The section above has been modified from the original posting for this article. The loop dealing with IsNested was added to address the fact that nested classes are supposed to be allowed full access to all members defined by its nesting class.]

Now after we get the caller method, we verify that it is not an override of the callee method. If it is then we continue up the call stack until we hit a method that is not an override of the callee and perform the verification as we had been with that method.

Note, this assumes that the overriden of the member is calling the base. If it is not then it will be up to the override to make the call to VerifyCallerIsFamily.

Internal And Protected

December 15, 2007

I like to make sure that the members of the types (and the types themselves) that I define are only available to the types that need it. This is done by providing the appropriate scope. C# and VB.Net define 5 possible scopes – public, private, protected, internal (friend in VB) and internal protected (protected friend in VB). I’ll give a brief background on each so if you already know this stuff you can skip ahead:

Public

Public members are visible to all types whether they are defined in the same assembly or within another assembly. So given a class A, anyone that has an instance of A can call its Foo method.

public class A

{

   public void Foo() {}

}

Protected

Protected is sometimes referred to as Family in the CLR documentation. Basically protected means that only derived classes can access that member. So given a class A, only classes that derive from A can call its Foo method.

public class A

{

   protected void Foo() { }

}

Private

Private members are only available within that class. So given a class A, only class A can call its Foo method.

public class A

{

   private void Foo() { }

}

Assembly

Assembly scope is referred to as internal in C# and Friend in VB.Net. Assembly scoped members can be accessed by any type defined within the same assembly. So if you have assembly 1 with a class defined as follows, any other type defined within assembly 1 may access the Foo method but types defined in other assemblies cannot.

public class A

{

   internal void Foo() { }

}

Assembly Or Protected

Assembly Or Protected combines the scopes of Assembly and Protected. In C# this would be defined as internal protected and in VB.Net the member would be defined as Protected Friend. Members with this scope can be access by any type within the same assembly or types in other assemblies that derive from this type. So if you have assembly 1 with a class defined as follows, any other type defined within assembly 1 may access the Foo method and also any type that derives from A (including types defined in an assembly other than assembly 1) may access the Foo method.

public class A

{

   internal protected void Foo() { }

}

But there’s actually another scope – Assembly And Family. I used the terminology that’s used in the CLR documentation because it’s not available in C# or VB.Net. This scope is supposed to limit member access to only derived types within that assembly. Outside of that assembly or to non-derived types in the same assembly, it is as if that member doesn’t exist.

So if you have class A in assembly 1 that has a method named Foo with this scope, only classes within assembly 1 that derive from class A may access the Foo method. Personally I think this would be a useful scope to support. I even asked Jeffrey Richter at the PDC about the possibility of supporting it and he basically told me it wouldn’t happen and that I was the only person that had asked him that question. I was a little suprised by this. I spend a lot of time in reflector and there seem to be lots of cases where they could have used this type of functionality themselves.

Without this scope, you are forced to use internal instead and try to manage this via guidelines/standards. I can think of a couple of possible approaches that you could use to verify that this is the case – you could write an fxcop/static analysis rule that does the check or you could use reflection. The following method is a simple take on the latter. I’ll list the code first and then explain how it works.

    public static class Utilities

    {

        [MethodImpl(MethodImplOptions.NoInlining)]

        [Conditional(“DEBUG”)]

        public static void VerifyCallerIsFamily()

        {

            // get the method doing the check

            StackFrame sfCallee = new StackFrame(1, false);

            MethodBase calleeMethod = sfCallee.GetMethod();

 

            StackFrame sfCaller = new StackFrame(2, false);

            MethodBase callerMethod = sfCaller.GetMethod();

 

            Debug.Assert(calleeMethod.IsAssembly, “This method is meant to try and implement a scope of ‘Assembly And Family’ so the calling method should be internal.”);

 

            if (false == calleeMethod.DeclaringType.IsAssignableFrom(callerMethod.DeclaringType))

            {

                const string Format = “The ‘{0}.{1}’ method is being called from ‘{2}.{3}’. It should only be called by derived types.”;

                string message = string.Format(Format,

                    calleeMethod.DeclaringType.Name,

                    calleeMethod.Name,

                    callerMethod.DeclaringType.Name,

                    callerMethod.Name);

                throw new InvalidOperationException(message);

            }

        }

    }

The following will be our test scenario classes:

    public class Base

    {

        internal void OnlyCallFromDerivedClasses()

        {

            Utilities.VerifyCallerIsFamily();

 

            // do something

        }

    }

 

    public class Derived : Base

    {

        public void VerifyCanCallMethod()

        {

            this.OnlyCallFromDerivedClasses();

        }

    }

 

    public class NotDerived

    {

        public void VerifyCannotCallMethod()

        {

            Base b = new Base();

            b.OnlyCallFromDerivedClasses();

        }

    }

We could then test this out:

    Derived d = new Derived();

    d.VerifyCanCallMethod();

 

    NotDerived not = new NotDerived();

    not.VerifyCannotCallMethod();

The call to VerifyCanCallMethod on d will pass because Derived is a derived class and has the rights to make this call. The second call will result in an exception – “The ‘Base.OnlyCallFromDerivedClasses’ method is being called from ‘NotDerived.VerifyCannotCallMethod’. It should only be called by derived types.” – which is the behavior that we want.

Ok so how does this work. The majority of the code relies upon the use of the StackFrame class to obtain the information about the method requesting the verification (the callee) and the method that is calling that method (the caller). We have to pass in 1, since this is implemented as a helper method. Passing in 0 would return the VerifyCallerIsFamily method which we do not want.

Once we have the stackframes, we can get the MethodBase instances. These are reflection objects that provide information about the method being called. We can then use the IsAssignableFrom method to ensure that the caller is either the same type as the callee or a derived class. If it is not we raise an appropriate exception.

You may notice that I decorated the VerifyCallerIsFamily with 2 attributes. The MethodImpl attribute is used to ensure that the jitter will not inline the execution of the method. The method is a little large so its unlikely that it would but its best to make sure. We need to do this because we’re relying on getting the methods using specific indexes in the stack frame. The Conditional attribute is used to indicate that calls to this method should not be included unless the code is being compiled with the DEBUG compilation constant. In other words, we only want to do this check in a debug version. My main reason for doing this is that using a StackFrame has overhead and once we release our assembly, its really not necessary to do this check since the callee method is internal and our testing can be limited to checking calls within the same assembly.

I still hope they implement that scope in a future version of C# and VB.Net but until then this approach may help you to get close.

Mole for Visual Studio

December 15, 2007

Karl is at it again. He extended Mole to allow it to be used for other types of objects including WinForms Controls, ASP.Net controls, etc. You can read about it on Mole’s home page or on codeproject.

Karl is very kind in his mentions of my involvement. I did help more with this version but Karl is the main one to thank for this round of enhancements. In any case, I highly advise you to try it out. If you have any comments or suggestions, be sure to send them to molefeedback@yahoo.com.

Where are my fields?

December 13, 2007

Recently Karl added the ability to view the non-public fields of objects in our Mole visualizer, a feature he termed BlackOps. However when reviewing it, I noticed that some fields that I know exist were not being displayed. What we were doing – targetType.GetFields(BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.DeclaredOnly) – seemed to be right but it didn’t return the results expected.

So lets take a look at an example.

    public class A

    {

        private string _private;

        internal string _internal;

        protected string _protected;

        internal protected string _internalProtected;

    }

 

    public class B : A

    {

 

    }

If we check the results of GetFields for these two types:

int aFieldCount = typeof(A).GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Length;

int bFieldCount = typeof(B).GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Length;

When you execute this code, you will find that aFieldCount is 4 but bFieldCount is 3. This is obviously not what we want for Mole since we’re looking to display all the field values (including those not visible to the type itself). The problem is that GetFields will only return Private fields if they are defined by that type – it will not return the private fields of any base classes. The solution is pretty simple – only get the fields defined by each type and walk up the BaseType chain. To get only the fields defined on the type, we add in the BindingFlags.DeclaredOnly flag and then we just use a loop to walk up the base types.

    Type type = typeof(B);

    int fieldCount = 0;

 

    while (null != type)

    {

        fieldCount += type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).Length;

        type = type.BaseType;

    }

Mole II

December 13, 2007

Josh Smith and I worked together at the Infragistics WinForms development lab and since I’m now working on WPF, I keep an eye on his blog. I also tend to read through the articles on codeproject. So when I saw that he posted a visualizer for wpf, I was naturally curious. I sent him a couple of thoughts about how he might want to change the visualizer.

If you’re not familiar with visualizers, you can check out this page on Microsoft’s site. Basically a visualizer is a tool used for debugging in Visual Studio. It allows you to provide a “visualization” or representation – hence the name – of an object in the program being debugged. They’re actually very powerful because they allow you to send information back and forth between the debugger and debuggee side.

Anyway, Josh then moved on to work on Mole with Karl Shifflett. I posted a bunch of performance related improvements as well as a number of suggestions (delving/drilling into the properties of objects, viewing the logical tree, etc). In the communications with Josh and Karl that followed, I was asked if I wanted to participate in the development with them.

Karl and Josh worked long hours in developing Mole II. I tried to help out where I could but given my schedule (work and personal) I couldn’t help as much as I would have liked. That aside, Josh and Karl were kind enough to include me as an author on the article. I have to say that both Josh and Karl are talented developers. Since I had worked with Josh before I knew he was intelligent and motivated. I hadn’t had the opportunity to work with Karl before but I must say that he is one of the most enthusiastic and driven developers that I have come across. I think the outcome is a great visualizer for inspecting WPF objects.

First Post

December 9, 2007

I’ve been meaning to blog for a long time but I could never find the time. Recently I had the opportunity to work with Josh Smith and Karl Shifflett on Mole II, a Visual Studio Visualizer for inspecting WPF objects, and I decided to make the time.

My available time nowadays is pretty limited – my wife and I have a young daughter with a very late sleeping schedule – that occupies much of what would previously have been my free time. I wouldn’t trade it for the world but it does mean that the time I can devote to a blog will be limited. When I do post, I expect that the majority of my posts will be related to C#, .NET, VS, WinForms and WPF as those are the areas I concentrate on the most. I sometimes help my wife with some PHP work so I may on occassion go off on a tangents into that area although it is far from my current areas of expertise.