Getting Started with iTunes

July 19, 2008 by agsmith

I’ve been thinking about getting an iPod for a while but I’ve held off for one reason or another. Well my wife got me an iPod Nano for my birthday recently so I’ve been digging through my cd’s - many of which still haven’t been unpacked since we moved into the house a couple of years ago.

One of the first things I had to do was to install iTunes. I try to be careful about the applications I install on my system. I didn’t have any worries about malware or anything like that but one of the requirements for iTunes is to install QuickTime. I had gotten a bad taste from previous experiences using QuickTime so I was looking to avoid installing that if possible. Luckily I found some posts like this one that talk about using a QuickTime alternative with iTunes.

One of the things I really liked about the iPod was the cover flow display - both within iTunes but also within the iPod itself. The problem that I’ve found though (and apparantly others have as well) is that iTunes sometimes gets the wrong album artwork or fails to find the artwork. I searched around to try and find a solution and thought I had found one named iTunes Art Importer but most of the links I found were broken. When I had finally found the application and installed it, it didn’t work - every search I tried returned right away with a message that no matches were found. I did some more searching to try and find another utility when I came across another page where Garett Harnish modified iTunes Art Importer to work again - apparantly the original version was written against an older version of the Amazon web service.

I’m sure there are lots of utilities out there for iTunes but this is all I’ve needed so far. There’s even an SDK for it.

ElementName Binding In ToolTips (Borrowing a NameScope)

July 17, 2008 by agsmith

I had previously seen mention of the limitation that you cannot use ElementName binding within a ToolTip but I never bothered to investigate it since I didn’t have need to use it. Yesterday Josh asked me about it so I decided to look into it further. I’m going to deal with ToolTip here since that was the one he asked me about but I believe the same technique could apply to ContextMenu.

First let’s take a look at the various ways you can define a tooltip that uses ElementName in a binding and see which work.

<Window.Resources>
    <!– Shared tooltip –>
    <ToolTip x:Key=”sharedTT”>
        <TextBlock Text=”{Binding ElementName=txt, 
           Path=Text}” />
    </ToolTip>
</Window.Resources>
<DockPanel>
    <TextBox Text=”This is the tooltip text” 
            x:Name=”txt” DockPanel.Dock=”Top” />
   
    <!– 1 - explicitly provide a tooltip instance where
        the content is bound –>
    <Button Content=”Explicit ToolTip” DockPanel.Dock=”Top” >
        <ToolTipService.ToolTip>
            <ToolTip Content=”{Binding ElementName=txt, 
               Path=Text}” />
        </ToolTipService.ToolTip>
    </Button>
   
    <!– 2 - Set the tooltip to a binding –>
    <Button DockPanel.Dock=”Top” Content=”Binding”
           ToolTipService.ToolTip=”{Binding ElementName=txt, 
           Path=Text}”/>

 

    <!– 3- Set the tooltip to an object that tries to
        bind to an element outside the tooltip –>
    <Button DockPanel.Dock=”Top” Content=”Element ToolTip”>
        <ToolTipService.ToolTip>
            <TextBlock Text=”{Binding ElementName=txt, 
               Path=Text}” />
        </ToolTipService.ToolTip>
    </Button>

 

    <!– 4- Set the tooltip to an element that tries to bind
        to the value of another element within the tooltip –>
    <Button DockPanel.Dock=”Top” >
        <ToolTipService.ToolTip>
            <StackPanel>
                <TextBlock x:Name=”ttText” Text=”Foo” />
                <TextBlock Text=”{Binding ElementName=ttText, 
                   Path=Text}” />
            </StackPanel>
        </ToolTipService.ToolTip>
        Normal ToolTip
    </Button>

 

    <!– 5 - Bind to a ToolTip in Resources –>
    <Button DockPanel.Dock=”Top” 
           Content=”SharedResource ToolTip”
           ToolTipService.ToolTip=”{StaticResource sharedTT}”/>
</DockPanel>

Of all of these the only one that actually works is #2 where the ToolTip property is set to a Binding instance. Suprisingly, at least to me, is that even #4 where we are trying to bind to another element within the tooltip itself does not work.

In order to understand why these aren’t working, we need to understand how ElementName binding works. Basically, when an ElementName is used in a binding, the NameScope of the target object is used to locate the element with the specified name. If that element doesn’t have a NameScope specifically on it, the FrameworkElement.FindScope method continues up the logical tree and falls back to the inheritance context if there is no logical parent. The name scope is the object in which all named objects have been registered. So in this example, there is a NameScope created for the Window itself implicitly. Other objects also provide a namescope to prevent conflicts between names - e.g. ControlTemplate and Style. Actually in those cases, the objects themselves implement INameScope.

The ToolTip however is not part of the logical nor visual tree of the element on which it is being set. Instead, it is just the value of a property and as such it doesn’t have a way to reach the NameScope of the Window in which it was created. The reason that #2 worked is because we just set the value of the ToolTip property to a binding. Since that is a property set directly on the element, that binding has access to the namescope just as you can use in a binding for any other dependency property on the element.

So the issue we have to overcome is how to provide a way for the ToolTip to get to the NameScope of the Window. My solution was to set the NameScope of the ToolTip to a custom INameScope implementation that would get to the NameScope of the element for which the ToolTip was being used. To accomplish this, I defined a new attached property named BindableToolTip. When set, it would set the NameScope property of the tooltip (and create a tooltip if the value wasn’t a tooltip instance such as the case where you are just providing the elements that make up the content of the tooltip) to my custom INameScope implementation that would “borrow” the namescope of the element on which the tooltip was being set. I then set the real ToolTipService.ToolTip property to that tooltip instance.

I did hit one glitch along the way. The BamlRecordReader class which is used to process the compiled baml uses a stack to manage the namescopes it encounters. By the time that the BindableToolTip property change is invoked, the BamlRecordReader has already processed the ToolTip instance (through its PushContext method). So when it gets to the point where it wants to clean up its namescope stack (in its PopContext method), it finds that the tooltip now has a namescope and tries to pop an item off its stack which results in an exception because it tries to pop off more items then it pushed. To get around this, I remove the namescope from the tooltip in the Initialized event of the tooltip.

To use the new functionality, you would just replace any place you are setting the ToolTip property with the BindableToolTip property. After doing so with the sample above, every case now works. I’ve attached the sample project that defines and uses this new attached property.

Who set the DataContext?

July 14, 2008 by agsmith

In the course of the last month or so, several people have asked why the DataContext that they set on the form level wasn’t carried down deeper into their element tree. Since I haven’t seen any documentation going into this I’d like to go over when/why the DataContext may be explicitly set in the WPF framework.

The DataContext is an inherited property defined on FrameworkElement and on FrameworkContextElement (the latter is actually an AddOwner of the former but I’ll discuss AddOwner another day). Suffice it to say that if you set the DataContext on an element, it should/will get inherited by its descendant elements. So naturally some people will assume that if they set it on their Window/Page, that all elements within that Window/Page will get that DataContext value. Afterall they are not setting it anywhere else. Well, that is the problem. While they may not be setting it, the WPF framework does in certain situations and if you look at it you can understand why. So if anything, including within the WPF framework itself, sets the DataContext on one of the descandants of that Window/Page, then all its descandants will get its locally set DataContext instead of the one set on one of its ancestors.

Ok so when will the WPF framework actually set the DataContext? There are actually two situations that I know of in which a class in the WPF framework will set the DataContext and both relate to when it automatically generates an element for you. One is in the ItemsControl - or more accurately by the ItemContainerGenerator of an ItemsControl when a container element is generated for an element in the list. The other is in the ContentPresenter when an element is generated for its Content (e.g. based on a DataTemplate). This makes perfect sense since after all the element generated for the ItemsControl and the elements within the DataTemplate need to get access to the thing that that element is supposed to represent.

The reason this may not be noticed in normal usage is because inherited properties prefer the logical tree and therefore can “skip” over the elements that have had their DataContext set further up the visual tree between it and its logical parent. So for example, if you were to put a TextBlock into a ListBox:

    <Grid DataContext=”Foo”>
        <ListBox>
            <TextBlock Text=”{Binding}” />
        </ListBox>
    </Grid> 

At runtime, a ListBoxItem would be created to contain the TextBlock within the ListBox. The DataContext of that ListBoxItem is the TextBlock (i.e. the object it represents within the listbox). However, the DataContext of the TextBlock ends up being Foo since that is the DataContext of its logical parent (i.e. the ListBox) and would show “Foo” as its Text.

If the TextBlock were not a logical child of the listbox (e.g. if it were added to the listbox via its ItemsSource) then it would inherit the DataContext of its visual parent - which ultimately would come from the ListBoxItem.

    <Grid DataContext=”Foo”>
        <Grid.Resources>
            <x:Array x:Key=”arr” Type=”sys:Object”>
                <TextBlock Text=”{Binding}” />
            </x:Array>
        </Grid.Resources>
        <ListBox ItemsSource=”{StaticResource arr}” />
    </Grid> 

In this case, the TextBlock would have a Text value of “System.Windows.Control.TextBlock” - the ToString of the TextBlock itself since it is the DataContext of the ListBoxItem and therefore that is its DataContext.

PropertyDescriptor AddValueChanged Alternative

April 7, 2008 by agsmith

I’ve been meaning to write about this for a while since I’ve seen this approach mentioned lots of times on the newsgroups but have seen no mentions about the caveats. Just today I saw the same problem in some code from one of the disciples. The scenario is that you want to know when the value of a dependency property changes but you don’t have a one to one relationship with the object. For example, you have a list of items and you want to know when the IsSelected property of an item has changed.

The solution that I have seen given for this is to get to the PropertyDescriptor and use its AddValueChanged method to provide an EventHandler to receive a notification when the property has changed. Sometimes, the reply will mention/use DependencyPropertyDescriptor directly but its the same thing since that is just a derived PropertyDescriptor that provides additional information about the underlying DependencyProperty it represents. You  can get to this property descriptor in a few ways but the most common are to get it from the TypeDescriptor.GetProperties method or using the DependencyPropertyDescriptor.FromProperty.

The issue with this approach is that it will root your object so it will never get collected by the GC. There have been plenty of discussions about how hooking events (particularly static events) can root your object so I won’t go into great detail there. While it does not seem that you are hooking a static event in this case, in essence you are. When you add a handler to a property descriptor, that property descriptor stores the delegate in a hashtable keyed by the object whose property you are hooking. A delegate/handler is basically a pointer to a method on an object (or no object if its for a static method) so that means the property descriptor has a reference to your object as well as the object whose value you are watching (since that is the key into the hashtable). The property descriptors themselves are cached statically so the hashtable is kept around and therefore your object and the one you are watching are as well.

I personally like to use the Scitech memory profiler (or you can use the Microsoft CLR Profiler) when debugging memory leak issues but you can see the issue manifest itself pretty easily in this case. First we’ll do a benchmark to make sure that we can check whether the object was collected.

ListBoxItem i = new ListBoxItem();
WeakReference wr = new WeakReference(i);
i = null;
GC.Collect();
bool isAlive = wr.IsAlive;

If you run this code and check isAlive, you will see that it returns false indicating that the ListBoxItem was not referenced and was able to be collected. Now let’s try using the AddValueChanged method.

ListBoxItem i = new ListBoxItem();
WeakReference wr = new WeakReference(i);
PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(ListBoxItem))["IsSelected"];
// the following yields the same pd
//PropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ListBoxItem.IsSelectedProperty, typeof(ListBoxItem));
prop.AddValueChanged(i, new EventHandler(this.OnValueChanged));
i = null;
GC.Collect();
bool isAlive = wr.IsAlive;

This time isAlive returns true because the property descriptor is maintaining a reference to the ListBoxItem. Now, let’s try an alternative approach that involves creating a helper class to listen for the property change.

ListBoxItem i = new ListBoxItem();
WeakReference wr = new WeakReference(i);
PropertyChangeNotifier notifier = new PropertyChangeNotifier(i, “IsSelected”);
notifier.ValueChanged += new EventHandler(OnValueChanged);
i = null;
GC.Collect();
bool isAlive = wr.IsAlive;

In this case isAlive is false indicating that the object can be collected even though we’re still maintaining an explicit reference to the notifier. The implementation for the class - PropertyChangeNotifier - is listed below. The class is basically a simple DependencyObject that exposes 2 properties - Value returns the value of the property of the object that it is watching and PropertySource returns the object whose property it is watching. The constructor for the object takes the object whose property is to be watched for changes and the property that should be watched. This class takes advantage of the fact that bindings use weak references to manage associations so the class will not root the object who property changes it is watching. It also uses a WeakReference to maintain a reference to the object whose property it is watching without rooting that object. In this way, you can maintain a collection of these objects so that you can unhook the property change later without worrying about that collection rooting the object whose values you are watching.

public sealed class PropertyChangeNotifier :
DependencyObject,
IDisposable
{
#region Member Variables
private WeakReference _propertySource;
#endregion // Member Variables
 
#region Constructor
public PropertyChangeNotifier(DependencyObject propertySource, string path)
: this(propertySource, new PropertyPath(path))
{
}
public PropertyChangeNotifier(DependencyObject propertySource, DependencyProperty property)
: this(propertySource, new PropertyPath(property))
{
}
public PropertyChangeNotifier(DependencyObject propertySource, PropertyPath property)
{
if (null == propertySource)
throw new ArgumentNullException(“propertySource”);
if (null == property)
throw new ArgumentNullException(“property”);
this._propertySource = new WeakReference(propertySource);
Binding binding = new Binding();
binding.Path = property;
binding.Mode = BindingMode.OneWay;
binding.Source = propertySource;
BindingOperations.SetBinding(this, ValueProperty, binding);
}
#endregion // Constructor
 
#region PropertySource
public DependencyObject PropertySource
{
get 
{
try
{
// note, it is possible that accessing the target property
// will result in an exception so i’ve wrapped this check
// in a try catch
return this._propertySource.IsAlive
? this._propertySource.Target as DependencyObject
: null;
}
catch
{
return null;
}
}
}
#endregion // PropertySource
 
#region Value
/// <summary>
/// Identifies the <see cref=”Value”/> dependency property
/// </summary>
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(“Value”,
typeof(object), typeof(PropertyChangeNotifier), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnPropertyChanged)));
 
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PropertyChangeNotifier notifier = (PropertyChangeNotifier)d;
if (null != notifier.ValueChanged)
notifier.ValueChanged(notifier, EventArgs.Empty);
}
 
/// <summary>
/// Returns/sets the value of the property
/// </summary>
/// <seealso cref=”ValueProperty”/>
[Description("Returns/sets the value of the property")]
[Category("Behavior")]
[Bindable(true)]
public object Value
{
get
{
return (object)this.GetValue(PropertyChangeNotifier.ValueProperty);
}
set
{
this.SetValue(PropertyChangeNotifier.ValueProperty, value);
}
}
#endregion //Value
 
#region Events
public event EventHandler ValueChanged;
#endregion // Events
 
#region IDisposable Members
public void Dispose()
{
BindingOperations.ClearBinding(this, ValueProperty);
}
#endregion
}

Another possible approach would be to implement your own derived WeakEventManager but I’ll leave that as an exercise for the reader. For those that choose to go this route, there is such a class - except its internal - in the PresentationFramework assembly.

SyncHashtable is not enumerable…

January 19, 2008 by agsmith

One of the things I really like about working on Mole is that I get to debug some obscure issues that I haven’t come across before. Today, Karl mentioned that there was an issue when dealing with collections - specifically with a synchronized hashtable. Mole was dealing with collections using one of the base collection interfaces - ICollection. He fixed the issue correctly by iterating the IDictionaryEnumerator you get from the IDictionary implementations of a hashtable but I wanted to see what was go on so I decided to look into this further.

The problem can be reproduced with the following snippet:

Hashtable ht = new Hashtable();

Hashtable syncedTable = Hashtable.Synchronized(ht);

IEnumerator enumerator = ((ICollection)syncedTable).GetEnumerator();

Or more likely it would be something like this:

Hashtable ht = new Hashtable();

Hashtable syncedTable = Hashtable.Synchronized(ht);

syncedTable.Add(“Foo”, “Bar”);

EnumerateCollection(syncedTable);

Where EnumerateCollection was something like the following:

private void EnumerateCollection(IEnumerable enumerable)

{

    foreach (object value in enumerable)

    {

        // do something

    }

}

I took at a look at MS’ code for the Hashtable class using Reflector and there is an obvious bug in their implementation. I did a quick internet search and it seems like people have been bitten by this same issue for a while so its hard to believe that it still exists within the framework today. In case anyone encounters the issue, I’ll explain what’s going on.

Hashtable implements the IDictionary interface which derives from ICollection and therefore IEnumerable. Both IDictionary and IEnumerable define a GetEnumerator method. For IDictionary this returns an IDictionaryEnumerator and for IEnumerable this returns an IEnumerator. Hashtable’s implementation of the IDictionary method is a public virtual GetEnumerator method. Its implementation of the IEnumerable method is an explicit implementation of the interface method.

e.g. IEnumerator IEnumerable.GetEnumerator();

The Hashtable class exposes a public static method named Synchronize that is supposed to take a hashtable and return a thread safe hashtable. There are actually flaws in the thread safety aspect of the implementation but that is another matter outside the issue we were dealing with. The Synchronize methods returns an instance of a private nested class named SyncHashtable which derives from Hashtable and is basically a thin wrapper around the Hashtable you pass to the Synchronize method. SyncHashtable overrides the virtual methods on the base Hashtable class and attempts to make dealing with the hashtable thread safe by using locks around edits.

SyncHashtable correctly overrides the public virtual GetEnumerator method and returns the IDictionaryEnumerator of the hashtable its wrapping. However, and herein lies the problem, it does not reimplement the IEnumerable.GetEnumerator method. Therefore, you get the base Hashtable’s implementation which returns an enumerator (HashtableEnumerator) for the SyncHashtable itself. This enumerator class assumes that the buckets member variable of the Hashtable it is to enumerate is non-null but the SyncHashtable specifically uses an overload of the Hashtable constructor that does not initialize this member (and others normally initialized for a Hashtable). It makes sense that they would not want to initialize these values since the SyncHashtable doesn’t store its own values - remember its just a thin wrapper around the Hashtable you provided to the Synchronize method - but then they should have reimplemented the IEnumerable.GetEnumerator method.

So if you’re writing any code that enumerates collections using the IEnumerable interface (directly or indirectly) with an object where you’re not in control of the source, you may want to consider dealing with the IDictionary’s enumerator first.

So you could fix the EnumeratorCollection method above as follows:

private void EnumerateCollection(IEnumerable enumerable)

{

    IEnumerator enumerator;

 

    // SyncHashtable has a bug where its IEnumerable

    // returns an enumerator whose ctor causes a crash.

    // instead, we can get around the problem using its 

    // IDictionary.GetEnumerator impl

    Hashtable table = enumerable as Hashtable;

 

    if (null != table)

        enumerator = table.GetEnumerator();

    else

        enumerator = enumerable.GetEnumerator();

 

    while (enumerator.MoveNext())

    {

        object value = enumerator.Current;

 

        // do something

    }

}

Compare Property & Field Values with Mole

January 15, 2008 by agsmith

As seems to happen with Mole, a suggestion quickly snowballed into a feature implementation. Mole now has the ability to save the members (properties/fields) of the selected element to an xml file and allow you to load that xml file back in to allow property comparison. This will be extremely helpful when you’re trying to debug a problem where something works for one element but doesn’t for another instance. There’s even an option to filter out members with the same value so you can see just the properties that differ.

 You can download the latest version here.

In addition, Karl has been posting some videos on YouTube that show how to use Mole. You can view those videos here.

Editing Properties and Fields with Mole

January 1, 2008 by agsmith

When debugging there are often times when you need to manipulate the value of a property or field within the watch window. Mole is a great visualizer that lets inspect the properties/fields of other objects in the visual/logical tree but if you saw something that needed to be changed, you would have to come out of the visualizer, change the value (assuming you could easily write the code necessary in the watch window Name column to locate the appropriate object) and then continue debugging.

Well, one of the things that I really wanted to see in Mole was editing capability similar to that of Snoop so we took the time and added it in. I wrote the editing infrastructure making use of .NET’s TypeConverters and Karl wrote the editors making it easy to edit common data types like fonts, colors, enums, etc. You can check it out here.

Note, there are some limitations to what can be done. For example, you can’t create new instances of classes as you might be able to do with the watch window. Since we’re using typeconverters, the editing is limited to the typeconverter associated with the property/field type. Maybe this is something we can look to add in a future version.

0 == 0 … well, usually it does

December 20, 2007 by agsmith

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 by agsmith

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 by agsmith

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.