Tuesday, May 12, 2009

WPF Colors, static classes and reflection in .Net

Today I wanted to know the definitions of the colors in WPF's static Colors class. A two-minute web search didn't turn anything up so I decided to write a quick and dirty little program to emit them. It should have been simple enough; I should have known better.

Using reflection, I wanted to cycle through each property of the Colors class and output its name and RGB value. To this end, I typed this into Visual Studio:
foreach (var prop in typeof(Colors).GetProperties())
{
    var propColor = (Color)prop.GetValue();
}

Then I hit a snag: GetValue wanted an instance of the class. However, Colors is static and I could not create an instance of it. In looking through the interface, I found GetConstantValue method. That sounded promising. I tried it. It compiled but threw an exception at run-time indicating it wasn't going to work.

I read the PropertyInfo documentation and didn't see anything more promising than GetValue. I searched the web some more but the only thing I could find talked about calling static methods on normal classes with instances of them created. I went back to the documentation where the description for the first parameter still said "The object whose property value will be returned." Reading on, the second parameter was the index value and said, "This value should be null for non-indexed properties."

Hmm... What happens if the first parameter is null?

Having nothing to lose, I tried it with both parameters passed as null. It compiled. A breakpoint set after the assignment and then inspection of propColor indicated it worked as expected. Cool!

I put a WrapPanel in the XAML file and named it ColorItems. Then I fleshed out my for loop:
foreach (var prop in typeof(Colors).GetProperties())
{
    var propColor = (Color)prop.GetValue(null, null);
    var desc = string.Format("{0} ({1})", prop.Name, propColor);
    Console.WriteLine(desc);
    ColorItems.Children.Add(new Grid
        {
            Width = 20,
            Height = 20,
            Margin = new Thickness(2),
            ToolTip = desc,
            Background = new SolidColorBrush(propColor)
        });
}

This gave me a nice little window with squares of color. Each square showed a tool tip with the name and color. Moreover, I had the table shown below in the Output window of the IDE.

Download the zipped project with compiled application.

ColorValueSample
AliceBlue#F0F8FF 
AntiqueWhite#FAEBD7 
Aqua#00FFFF 
Aquamarine#7FFFD4 
Azure#F0FFFF 
Beige#F5F5DC 
Bisque#FFE4C4 
Black#000000 
BlanchedAlmond#FFEBCD 
Blue#0000FF 
BlueViolet#8A2BE2 
Brown#A52A2A 
BurlyWood#DEB887 
CadetBlue#5F9EA0 
Chartreuse#7FFF00 
Chocolate#D2691E 
Coral#FF7F50 
CornflowerBlue#6495ED 
Cornsilk#FFF8DC 
Crimson#DC143C 
Cyan#00FFFF 
DarkBlue#00008B 
DarkCyan#008B8B 
DarkGoldenrod#B8860B 
DarkGray#A9A9A9 
DarkGreen#006400 
DarkKhaki#BDB76B 
DarkMagenta#8B008B 
DarkOliveGreen#556B2F 
DarkOrange#FF8C00 
DarkOrchid#9932CC 
DarkRed#8B0000 
DarkSalmon#E9967A 
DarkSeaGreen#8FBC8F 
DarkSlateBlue#483D8B 
DarkSlateGray#2F4F4F 
DarkTurquoise#00CED1 
DarkViolet#9400D3 
DeepPink#FF1493 
DeepSkyBlue#00BFFF 
DimGray#696969 
DodgerBlue#1E90FF 
Firebrick#B22222 
FloralWhite#FFFAF0 
ForestGreen#228B22 
Fuchsia#FF00FF 
Gainsboro#DCDCDC 
GhostWhite#F8F8FF 
Gold#FFD700 
Goldenrod#DAA520 
Gray#808080 
Green#008000 
GreenYellow#ADFF2F 
Honeydew#F0FFF0 
HotPink#FF69B4 
IndianRed#CD5C5C 
Indigo#4B0082 
Ivory#FFFFF0 
Khaki#F0E68C 
Lavender#E6E6FA 
LavenderBlush#FFF0F5 
LawnGreen#7CFC00 
LemonChiffon#FFFACD 
LightBlue#ADD8E6 
LightCoral#F08080 
LightCyan#E0FFFF 
LightGoldenrodYellow#FAFAD2 
LightGray#D3D3D3 
LightGreen#90EE90 
LightPink#FFB6C1 
LightSalmon#FFA07A 
LightSeaGreen#20B2AA 
LightSkyBlue#87CEFA 
LightSlateGray#778899 
LightSteelBlue#B0C4DE 
LightYellow#FFFFE0 
Lime#00FF00 
LimeGreen#32CD32 
Linen#FAF0E6 
Magenta#FF00FF 
Maroon#800000 
MediumAquamarine#66CDAA 
MediumBlue#0000CD 
MediumOrchid#BA55D3 
MediumPurple#9370DB 
MediumSeaGreen#3CB371 
MediumSlateBlue#7B68EE 
MediumSpringGreen#00FA9A 
MediumTurquoise#48D1CC 
MediumVioletRed#C71585 
MidnightBlue#191970 
MintCream#F5FFFA 
MistyRose#FFE4E1 
Moccasin#FFE4B5 
NavajoWhite#FFDEAD 
Navy#000080 
OldLace#FDF5E6 
Olive#808000 
OliveDrab#6B8E23 
Orange#FFA500 
OrangeRed#FF4500 
Orchid#DA70D6 
PaleGoldenrod#EEE8AA 
PaleGreen#98FB98 
PaleTurquoise#AFEEEE 
PaleVioletRed#DB7093 
PapayaWhip#FFEFD5 
PeachPuff#FFDAB9 
Peru#CD853F 
Pink#FFC0CB 
Plum#DDA0DD 
PowderBlue#B0E0E6 
Purple#800080 
Red#FF0000 
RosyBrown#BC8F8F 
RoyalBlue#4169E1 
SaddleBrown#8B4513 
Salmon#FA8072 
SandyBrown#F4A460 
SeaGreen#2E8B57 
SeaShell#FFF5EE 
Sienna#A0522D 
Silver#C0C0C0 
SkyBlue#87CEEB 
SlateBlue#6A5ACD 
SlateGray#708090 
Snow#FFFAFA 
SpringGreen#00FF7F 
SteelBlue#4682B4 
Tan#D2B48C 
Teal#008080 
Thistle#D8BFD8 
Tomato#FF6347 
Transparent#FFFFFF 
Turquoise#40E0D0 
Violet#EE82EE 
Wheat#F5DEB3 
White#FFFFFF 
WhiteSmoke#F5F5F5 
Yellow#FFFF00 
YellowGreen#9ACD32 

Thursday, April 30, 2009

WPF DataGrid binding weirdness

Recently I had an object with a read-only property that I wanted to bind to a WPF DataGrid column. I expected an easy Binding="{Binding Path=MyProperty}" to accomplish it. However, when I made this change and tried to display the data at run-time, I got a bunch of exceptions:
A TwoWay or OneWayToSource binding cannot work on the read-only property 'MyProperty' of type 'MyObject'.
"Ok," I thought, "just change the binding's Mode."

So I assigned the value OneWay to Mode in the binding: Binding="{Binding Path=MyProperty, Mode="OneWay"}.

Same thing. No difference. Huh!?!?

After a bit of head scratching and digging through search results, I set the IsReadOnly property on the column to true.[1] That worked!

I removed the Mode assignment from the binding. It still worked!

Apparently, the DataGrid ignores the binding mode and sets it to what it thinks it should be, regardless of what it's told. Frustrating.
1. This post on GenericError.com pointed me in the right direction.

Tuesday, March 31, 2009

Bug free software?

A little while ago, my wife and I purchased a new version of Adobe Photoshop CS4. About a week later, she came to me complaining that we spent several hundred dollars for a software package that crashes on her. It's not frequent; she's had one occurrence in many, many hours of operation. But still, when it happened she lost some work and was frustrated.

Over the last several months, I noticed the separator between the minutes and seconds on the front panel of my treadmill did not display. I thought it odd, because there were times I knew it did. One day I watched it more closely during my workout and I determined when it showed and when it didn't. The combination of conditions were such that I'm sure it was not intended behavior.

Bugs exist, whether its in a large, complex package with probably several million lines of code or in an embedded controller with around three orders of magnitude fewer lines. Nevertheless it is frustrating, particularly for uses like my wife because, not knowing the incredible complexity of software, their expectations are higher than mine.

All this to introduce tongue-in-cheek, long time favorite quote that basically says software bugs are a way of life:
Every program has at least one bug and can be shortened by at least one instruction - from which, by induction, one can conclude that every program can be reduced to one instruction that doesn't work. -- Unknown

Saturday, February 7, 2009

Microsoft's OfficeUI Ribbon: Adding non-button controls

There are quite a few controls included with the new Microsoft OfficeUI Ribbon library. I recently wanted to incorporate this into a prototype application I was working on. All the examples I found showed how to use it with a button but I wanted a richer UI than just buttons on the ribbon. I did some web searching and found precious little information on using other controls and I did not find any documentation. Using the little information I did find, a lot of reverse engineering and some trial and error, I finally came up with something that works. Therefore, in an effort to help someone else, here are some things I discovered.

First, I wanted a simple mini-form for doing text searches. All it needed was an edit box, a go button and a couple check boxes in a ribbon group. Here is a screen shot of what I wanted:
Ribbon panel specification

In my first attempt, I knew I needed a group to put the controls in, so I naively added one to my ribbon and added the desired controls. The designer immediately became unstable. I was able to compile after stopping and restarting the IDE. However, when running the application, I got a null reference exception loading the form.

Through some routine diagnostic sleuthing, I determined the cause: having multiple groups without assigning GroupSizeDefinitions. If there is only one group, it will work properly without defining a GroupSizeDefinition. However, with more than one group, each group must have a GroupSizeDefinition assigned. I hope that Microsoft will fix this bug before the final release.

In spite of fixing the null reference problem, the layout did not work as desired. Things did not size appropriately. Controls did not position the way I wanted. It was a UI mess.

I had gone to a session at PDC2008 where they demonstrated the control so I went to find that presentation. A bit of information was gleaned from slide 36 [pptx] of session PC45 where the ItemsPanel property was discussed. Unfortunately it was entirely too brief and ended up somewhat misleading. It did give me a clue to start looking for other things though.

After a bit of searching, reading blog articles and forum posts, I found the key to figuring this out in a short post by Mike Cook. I found it best to add an ItemsPanel to the RibbonGroup containing a UniformGrid. The controls then went in this container.

In order to get the controls formatted the way I wanted, I needed to put each row in a DockPanel. However, the only things that can go in a RibbonGroup are things that implement IRibbonControl. To handle this, I created two of my own controls that extend DockPanel and implement IRibbonControl. This ended up working well because I needed to add additional code to each one to work the way I wanted and this helped encapsulate this code.

In formatting the top line, the first thing I found was the RibbonButton, used for the Go function, always assumes there is an image associated with it. For the purposes of this form, I wanted the image to the left of the label, associated with the entire line, not over on the right associated with the button. In order to turn this off, I had to find the image in the button's template and set its Visibility to Collapsed.

After getting the button's image removed, the next thing I found was the RibbonTextBox sizes the text box to its content. This seemed ugly to me and I did not find any way of altering this behavior with simple property settings so I started investigating the VisualTree for the control. After some trial and error, I found I could set the Width of a Border inside the RibbonTextBox and the internal TextBox would remain that size. This strikes me as a pretty ugly and fragile hack, but it works. I hope that this will improve before the final release.

The second row is more straightforward with just two RibbonCheckBoxes on it. It does have a slight oddity though. The Executed property must have a method assigned to it for the check box to be active. The issue is, in this particular use case, I did not need to have anything happen when the user checks the box so there is a required method that has nothing in it. This seems silly to me.

At the end of the day, I was able to get what I wanted out of the library. I think it looks nice for the user and functions well. But, it is not terribly pretty for the programmer and there was quite a bit of frustration getting it to work as I intended, mostly due to poor and lacking documentation. I hope someone else finds this useful. If there are any errors or omissions, please leave a comment to let me know and I will do my best to correct it.

Source code

The ribbon control is publicly available on the OfficeUI web site after agreeing to a long, overwhelming license. (Here are the how-to-get instructions.) As I understand it, this is going to be bundled into the base System.Windows name space with CLR 4.0, so I'm not quite sure why there's such an onerous license on it at this point.

Here is complete source code [zip] for this article. Note that it does contain a reference to RibbonControlsLibrary, the package containing the Ribbon controls, which is not included due to licensing restrictions. In order for this to compile, you need to get this library from Microsoft (see links above) and then update this project to point to your copy of it.

Wednesday, December 10, 2008

C# odditiy: Object initializer scope

I was reviewing some code today and ran across something that looked like this:
SomeProperty = SomeProperty

Odd, I thought that doesn't do anything, probably not what the writer intended. I sort of ignored it since I was doing some refactoring that removed that line anyway and went on. When I realized I didn't have any tests covering this bit of code, I saved my changes, reverted the unit, wrote a test and ran it, expecting a failure. Much to my surprise, it worked.

In context, the function looked sort of like this:
public class SomeClass
{
    public string SomeProperty { get; set; }

    public object Clone()
    {
        return new SomeClass { SomeProperty = SomeProperty };
    }
}

Looking at this, I expected both the SomeProperty properties to be in the scope of the object initializer and end up not doing anything, essentially assigning the property to itself. The test seemed to indicate otherwise. Thinking I had a problem with my test, I set some breakpoints and did some evaluation at run-time. I didn't see anything wrong with the tests and everything seemed to be working.

Still convinced something had to be wrong, I did some searching on the web trying to find somebody who talked about scoping rules in object initializers. Of course, I may not have hit on the correct search terms, but in any case I didn't find anything. So I wrote the following console application:
namespace TestObjectInitializerScopeConsole
{
    public class TestClass
    {
        public string TestText { get; set; }
    }

    class Program
    {
        public static string TestText { get; private set; }

        static void Main(string[] args)
        {
            TestText = "Some random text";
            Console.WriteLine("this.TestText = \"{0}\" (initially)", TestText);

            var test1 = new TestClass();
            Console.WriteLine("test1.TestText = \"{0}\" (without initializer)", test1.TestText);

            var test2 = new TestClass { TestText = TestText };
            Console.WriteLine("test2.TestText = \"{0}\" (with initializer)", test2.TestText);

            Console.WriteLine("Enter to finish...");
            Console.ReadLine();
        }
    }
}

According to this test, it seems to indicate the scope for items on the left hand of the assignment are the new object and those on the right hand are what you'd normally expect for the method. It seems pretty odd and anti-intuitive to have different scope like this.

Any comments? Am I missing something? Is this defined somewhere that I've missed? Does it seem weird to anyone else?

Friday, December 5, 2008

How to show WWSGD text in Blogger

I've been doing quite a bit of reading regarding the ins and outs of blogging, search engine optimization and building readership. In the course of this, I read 21 Ways to Make Your Blog or Website Sticky. In that article, Darren Rowse mentioned a WordPress plug-in by Richard Miller called What Would Seth Godin Do. Based on an observation by Seth Godin, this plug-in allows customized messages to viewers based on the number of times they visit your site.

Intrigued by this idea, I set off to find something similar for Blogger (a.k.a. Blogspot) based sites. After a lot of searching, I failed to find anything. I figured it couldn't be too hard; I'd just roll my own. It took a bit more work than I expected, but I finally came up with my own variation. There is no code shared at all with the WordPress plug-in; it's simply similar functionality inspired by Seth's observation and Richard's implementation. The following explains how to configure a Blogger site display different text based on a user's visit count.

First, go into the Layout tab for your site and then the Page Elements sub-tab. Click on Add a Gadget. Select the HTML/JavaScript option. In the Content section, place something like this:
<div id="NewVisitor" style="display: none;">Thanks for visiting! Use the RSS feed or e-mail subscription to keep up to date on what's happening on this site.</div>
<div id="ReturningVisitor" style="display: none;">Welcome back! We're glad you enjoy our writing. If you especially like a particular article, please consider casting a Digg vote. Thanks!</div>
I'm no copywriter and obviously you'll want different text, but the important thing is to have two div sections with IDs of NewVisitor and ReturningVisitor, and with a style attribute for both set to display: none;. When the page is loaded, one section or the other will be changed to visible based on the result of a cookie.

Except for the limitations of ID and style, the rest is normal HTML. You can put things that are common to both text sections outside the div sections. Inside the div sections, put things you want displayed for the context identified by the ID attribute.

Save the gadget. Since the text is inside a gadget, you can move it to where you want it to display.

Next, select the code below and copy it to the clipboard. Then go to the Edit HTML section of your blog configuration and scroll down through the template code until you find the line that says <body>. Just above this line, there will be one that says </head>; paste the copied code just above the </head> line.

<!-- Start of script for "WWSGD" div manipulation -->
<script type='text/javascript'>
function getCookie(c_name)
{
  if (document.cookie.length > 0)
  {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start != -1)
    {
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  return "";
}

function setCookie(c_name,value,expiredays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+
      ((expiredays==null)
        ? ""
        : "; expires="+exdate.toGMTString()+
      "; path=/");
}

function checkCookie()
{
  wwsgd_count=getCookie('wwsgd_count');
  if (wwsgd_count == null || wwsgd_count == "")
  {
    wwsgd_count = 0;
  }
  else
  {
    wwsgd_count = parseInt(wwsgd_count);
  }
  setCookie('wwsgd_count',wwsgd_count+1,365);
  visibleTag = 'ReturningVisitor';
  <!-- This will show the "new visitor" text three times.
      Change 3 to the desired value. -->
  if (wwsgd_count &lt; 3)
  {
    visibleTag = 'NewVisitor';
  }
  divToSee = document.getElementById(visibleTag);
  if (divToSee != null)
  {
    divToSee.style.display = "block";
  }
}
</script>
<!-- End of script for "WWSGD" div manipulation -->

(For those with sharp eyes, JavaScript's less than operator is encoded above. This is by intent. It needs to be encoded in the Blogger template when it is saved. It gets converted to a real less than sign and used properly when it is sent to the client's browswer.)

Finally, on the <body> line, before the closing ">", add onLoad='checkCookie()'. When done, this line will look like:
<body onLoad='checkCookie()'>

When these three things are finished, the site should show the items inside the NewVisitor div section the first three times it is visited. After that, the items inside the ReturningVisitor should be displayed. If you want a different count for the first message, change the numeral 3 in the script (indicated by a comment) to the desired number. If cookies aren't enabled, then nothing will be displayed.

Leave a comment if you have any thoughts or find this useful. Thanks!

Resources

Thanks to the following for information found useful in the development of this tool:

Monday, November 24, 2008

Microsoft's OfficeUI Ribbon: Application template

I've been working with the recently released Ribbon control from Microsoft's Office UI group. There are several cookie-cutter setup steps to get an application ribbon aware. In order to facilitate setting up a new application, I made a Visual Studio 2008 template that creates a blank application containing a ribbon bar with some empty controls.

Here is the template file. Copy this zip file to My Documents\Visual Studio 2008\Templates\ProjectTemplates\Visual C#. When Visual Studio is started, the New project dialog displayed when File | New | Project... will have a new Ribbon Application option under My Templates. Select this to create a skeleton ribbon application.

When the application is created, an error will be displayed indicating the ribbon control library cannot be found. This is because this library needs to be acquired directly from Microsoft. To get it you need to go to the OfficeUI web site. (Here are the how-to-get instructions.)

Once the library is downloaded and installed on your computer, go to the new ribbon application's References, remove RibbonControlsLibrary and then add it in again, pointing to the location on your computer.

The skeleton application contains a Close option on the application menu to stop the application. There is a single tab with a single group containing a single button. Finally, there is a single button on the quick access toolbar. These all can be used as templates to easily add more.

More information on creating Visual Studio templates can be found on the MSDN site. (Thanks to paranoid ferret for the pointers on to how to create templates.)